Skip to content
Verified contractExactUNLICENSED

EvalPurchase

Address0x3e2761d572bc2e4beeb1741de78646321df875a7
Balance

0 ETH

 

Transactions

4

 

Compiler

solc 0.8.31

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.31+commit.fd3a2265
Language
solidity
Optimization
Yes, 200 runs
EVM version
osaka
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,492,567
Creation transaction
0x6f5a5a23db…8c4d98cedc

src/EvalPurchase.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {PropPool} from "./PropPool.sol";
import {EvalQueue} from "./EvalQueue.sol";

/// @title EvalPurchase — achat d'une évaluation en USDC
/// @notice Prix du jour P = Pmax - (Pmax - Pmin) * x, marge firme M = Pmin * x (x = PropPool.level()).
///         Mode test : P = testPrice (1 USDC), marge au même ratio M/P.
///         Si le pool a la marge (solde libre >= seuil) et la file est vide : revenu versé au pool tout de suite
///         (EvalPurchased, queued = false -> l'API crée le compte d'éval). Sinon l'éval part en file (queued = true) :
///         - amorçage (PropPool.bootstrapping : 0 siège et solde libre < seuil) : prix entier versé au pool,
///           marge firme 0 (prepaid = true), activée quand le seuil est atteint ;
///         - sinon (sièges ouverts, capacité dépassée) : USDC bloqué dans EvalQueue jusqu'à l'activation.
///         Décision Léo 24/11 : un achat d'évaluation n'est jamais remboursable (aucune fonction de remboursement).
/// @dev    Code NON audité.
contract EvalPurchase is AccessControl, Pausable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    bytes32 public constant PRICER_ROLE = keccak256("PRICER_ROLE");
    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
    uint256 public constant WAD = 1e18;
    uint256 public constant MAX_PRICE = 10_000e6; // garde-fou de configuration

    struct Offer {
        uint256 priceMax; // prix à pool vide (x = 0)
        uint256 priceMin; // prix à pool plein (x = 1) = marge firme max
        uint16 traderBps; // 8000 ou 9000
        bool active;
    }

    IERC20 public immutable usdc;
    PropPool public immutable pool;
    EvalQueue public immutable queue;

    mapping(uint8 => Offer) public offers; // 0 = 80/20, 1 = 90/10
    bool public testMode;
    uint256 public testPrice;
    uint256 public autoProcess = 10; // évals de la file tentées après un achat mis en file
    uint256 public nextEvalId = 1;
    mapping(uint256 => address) public buyerOf;

    event EvalPurchased(
        uint256 indexed evalId,
        address indexed buyer,
        uint8 indexed offerId,
        uint16 traderBps,
        uint256 price,
        uint256 firmMargin,
        bool queued,
        bytes32 ref,
        bool prepaid
    );
    event OfferSet(uint8 indexed offerId, uint256 priceMax, uint256 priceMin, uint16 traderBps, bool active);
    event TestModeSet(bool enabled, uint256 testPrice);
    event AutoProcessSet(uint256 n);

    error OfferInactive();
    error PriceAboveMax(uint256 price, uint256 maxPrice);
    error BadOffer();

    constructor(IERC20 usdc_, PropPool pool_, EvalQueue queue_, address admin, bool testMode_, uint256 testPrice_) {
        usdc = usdc_;
        pool = pool_;
        queue = queue_;
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(PRICER_ROLE, admin);
        _grantRole(PAUSER_ROLE, admin);
        _setTestMode(testMode_, testPrice_);
    }

    // ---------------------------------------------------------------- vues
    /// @notice Prix et marge firme du moment, et si l'achat partirait en file.
    function quote(uint8 offerId) public view returns (uint256 price, uint256 firmMargin, bool wouldQueue) {
        Offer memory o = offers[offerId];
        if (!o.active) revert OfferInactive();
        uint256 x = pool.level();
        uint256 pFull = o.priceMax - ((o.priceMax - o.priceMin) * x) / WAD;
        uint256 mFull = (o.priceMin * x) / WAD;
        if (testMode) {
            price = testPrice;
            firmMargin = pFull == 0 ? 0 : (testPrice * mFull) / pFull;
        } else {
            price = pFull;
            firmMargin = mFull;
        }
        if (pool.bootstrapping()) firmMargin = 0; // 0 siège : tout au pool
        wouldQueue = queue.queuedCount() > 0 || !pool.canActivateEval();
    }

    // ---------------------------------------------------------------- achat
    /// @notice Achète une éval. Approbation USDC préalable de `price` (lire `quote`). `maxPrice` = protection.
    function buy(uint8 offerId, uint256 maxPrice, bytes32 ref) external nonReentrant whenNotPaused returns (uint256) {
        return _buy(offerId, maxPrice, ref);
    }

    /// @notice Achat en une transaction avec un permis EIP-2612 (USDC Base le supporte).
    function buyWithPermit(
        uint8 offerId,
        uint256 maxPrice,
        bytes32 ref,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external nonReentrant whenNotPaused returns (uint256) {
        // un permis déjà consommé (front-run) ne doit pas bloquer l'achat si l'allowance est là
        try IERC20Permit(address(usdc)).permit(msg.sender, address(this), maxPrice, deadline, v, r, s) {} catch {}
        return _buy(offerId, maxPrice, ref);
    }

    function _buy(uint8 offerId, uint256 maxPrice, bytes32 ref) internal returns (uint256 evalId) {
        (uint256 price, uint256 margin, bool toQueue) = quote(offerId);
        if (price > maxPrice) revert PriceAboveMax(price, maxPrice);
        uint16 bps = offers[offerId].traderBps;
        evalId = nextEvalId++;
        buyerOf[evalId] = msg.sender;

        if (!toQueue) {
            usdc.safeTransferFrom(msg.sender, address(this), price);
            usdc.forceApprove(address(pool), price);
            pool.receiveEvalRevenue(evalId, price, margin);
            emit EvalPurchased(evalId, msg.sender, offerId, bps, price, margin, false, ref, false);
        } else if (pool.bootstrapping()) {
            // amorçage : le prix alimente le pool tout de suite (margin = 0 via quote), l'éval attend le seuil
            usdc.safeTransferFrom(msg.sender, address(this), price);
            usdc.forceApprove(address(pool), price);
            pool.receiveEvalRevenue(evalId, price, margin);
            emit EvalPurchased(evalId, msg.sender, offerId, bps, price, margin, true, ref, true);
            queue.enqueue(evalId, msg.sender, offerId, bps, price, margin, true);
            if (autoProcess > 0 && queue.headActivatable()) queue.process(autoProcess);
        } else {
            usdc.safeTransferFrom(msg.sender, address(queue), price);
            emit EvalPurchased(evalId, msg.sender, offerId, bps, price, margin, true, ref, false);
            queue.enqueue(evalId, msg.sender, offerId, bps, price, margin, false);
            if (autoProcess > 0 && queue.headActivatable()) queue.process(autoProcess);
        }
    }

    // ---------------------------------------------------------------- administration
    function setOffer(uint8 offerId, uint256 priceMax, uint256 priceMin, uint16 traderBps, bool active)
        external
        onlyRole(PRICER_ROLE)
    {
        _setOffer(offerId, priceMax, priceMin, traderBps, active);
    }

    function setTestMode(bool enabled, uint256 price) external onlyRole(PRICER_ROLE) {
        _setTestMode(enabled, price);
    }

    function setAutoProcess(uint256 n) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (n > 50) revert BadOffer();
        autoProcess = n;
        emit AutoProcessSet(n);
    }

    function pause() external onlyRole(PAUSER_ROLE) {
        _pause();
    }

    function unpause() external onlyRole(PAUSER_ROLE) {
        _unpause();
    }

    function _setOffer(uint8 offerId, uint256 priceMax, uint256 priceMin, uint16 traderBps, bool active) internal {
        if (priceMin > priceMax || priceMax > MAX_PRICE || priceMax == 0) revert BadOffer();
        if (traderBps != 8000 && traderBps != 9000) revert BadOffer();
        offers[offerId] = Offer(priceMax, priceMin, traderBps, active);
        emit OfferSet(offerId, priceMax, priceMin, traderBps, active);
    }

    function _setTestMode(bool enabled, uint256 price) internal {
        if (enabled && (price == 0 || price > MAX_PRICE)) revert BadOffer();
        testMode = enabled;
        testPrice = price;
        emit TestModeSet(enabled, price);
    }
}

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

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

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";
import {IAccessControl} from "./IAccessControl.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /// @inheritdoc ERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * Emits a {RoleRevoked} event if the calling account had `role` and this call successfully revoked it.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

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

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

pragma solidity >=0.8.4;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted to signal this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

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

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

pragma solidity >=0.6.2;

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.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

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

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

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

pragma solidity >=0.4.16;

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

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

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

pragma solidity >=0.6.2;

import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

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

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

pragma solidity >=0.4.16;

/**
 * @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/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also applies here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

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

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

pragma solidity ^0.8.20;

import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20} from "../IERC20.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 {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

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

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

    /**
     * @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 {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 relies 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 relies 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}.
     * Oppositely, 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 Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
    function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
        bytes4 selector = IERC20Metadata.decimals.selector;
        assembly ("memory-safe") {
            mstore(0x00, selector)
            success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
            success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
            decimals := mul(success, mload(0x00))
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, 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 to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
     * @param value The amount of token to approve
     * @param bubble Behavior switch if the approve call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

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.
 *
 * IMPORTANT: Deprecated in favor of accessing `msg.sender` and `msg.data` directly. This contract, along with its
 * `_msgSender`, `_msgData` and `_contextSuffixLength` functions, will be removed in v6.0, where contracts read
 * `msg.sender` and `msg.data` directly. Contracts that override `_msgSender`/`_msgData` (e.g. to support
 * meta-transactions) will lose that extension point; plan the migration before upgrading.
 */
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/Pausable.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 *
 * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
 * by the {ReentrancyGuardTransient} variant in v6.0.
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

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

    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

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

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

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

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.sol.eta.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

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

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

pragma solidity >=0.4.16;

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

src/EvalQueue.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {PropPool} from "./PropPool.sol";

/// @title EvalQueue — file d'attente on-chain des achats d'évaluation (FIFO)
/// @notice Quand le solde libre du pool est sous `queueThreshold` (2 500 $), l'éval attend ici. Deux sortes d'entrées :
///         - prépayée (amorçage, 0 siège) : le prix est déjà au pool (marge firme 0) ;
///         - séquestre (sièges ouverts, capacité dépassée) : l'USDC reste bloqué ici jusqu'à l'activation, puis
///           part au pool / à la firme selon le partage figé à l'achat.
///         Décision Léo 24/11 : un achat d'évaluation n'est JAMAIS remboursable. Aucune fonction ne rend l'USDC à
///         l'acheteur (ni lui, ni l'opérateur, ni l'admin) : il ne sort de ce contrat que vers le pool, via `process`.
///         `process` active la tête dès que le solde libre atteint le seuil (FIFO, les deux sortes mêlées).
/// @dev    Seul le solde libre réel du pool compte pour le seuil (countEscrow = false par défaut, décision 24/11).
///         Code NON audité.
contract EvalQueue is AccessControl, Pausable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    bytes32 public constant PURCHASE_ROLE = keccak256("PURCHASE_ROLE"); // EvalPurchase
    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");

    enum Status {
        None,
        Queued,
        Activated
    }

    struct Entry {
        address buyer;
        uint8 offerId;
        uint16 traderBps;
        Status status;
        uint64 queuedAt;
        uint256 price;
        uint256 firmMargin;
        bool prepaid; // prix déjà versé au pool (amorçage) : pas de séquestre
    }

    IERC20 public immutable usdc;
    PropPool public immutable pool;

    bool public countEscrow = false;
    mapping(uint256 => Entry) internal _entries; // evalId => entrée
    uint256[] internal _order;
    uint256 public head;
    uint256 public queuedCount;
    uint256 public escrowTotal; // USDC sous séquestre
    uint256 public queuedPoolShare; // somme (prix - marge) des entrées en file

    event EvalQueued(
        uint256 indexed evalId, address indexed buyer, uint8 offerId, uint256 price, uint256 position, uint256 escrowTotal
    );
    event EvalActivated(uint256 indexed evalId, address indexed buyer, uint256 price, uint256 waitedSeconds);
    event CountEscrowSet(bool enabled);

    error Duplicate();
    error EscrowMismatch();

    constructor(IERC20 usdc_, PropPool pool_, address admin) {
        usdc = usdc_;
        pool = pool_;
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(PAUSER_ROLE, admin);
    }

    // ---------------------------------------------------------------- vues
    function getEntry(uint256 evalId) external view returns (Entry memory) {
        return _entries[evalId];
    }

    /// @notice Position (1 = tête) d'une éval en file, 0 si absente.
    function positionOf(uint256 evalId) external view returns (uint256 pos) {
        if (_entries[evalId].status != Status.Queued) return 0;
        for (uint256 i = head; i < _order.length; i++) {
            uint256 id = _order[i];
            if (_entries[id].status == Status.Queued) {
                pos++;
                if (id == evalId) return pos;
            }
        }
        return 0;
    }

    /// @notice Vrai si la tête de file peut être activée maintenant.
    function headActivatable() public view returns (bool) {
        if (queuedCount == 0 || paused() || pool.paused()) return false;
        uint256 free = pool.freeBalance();
        uint256 thr = pool.queueThreshold();
        return free >= thr || (countEscrow && free + queuedPoolShare >= thr);
    }

    // ---------------------------------------------------------------- file
    /// @notice Inscrit un achat (USDC déjà transféré ici par EvalPurchase).
    function enqueue(
        uint256 evalId,
        address buyer,
        uint8 offerId,
        uint16 traderBps,
        uint256 price,
        uint256 firmMargin,
        bool prepaid
    ) external whenNotPaused onlyRole(PURCHASE_ROLE) {
        if (_entries[evalId].status != Status.None) revert Duplicate();
        if (!prepaid) {
            escrowTotal += price;
            if (usdc.balanceOf(address(this)) < escrowTotal) revert EscrowMismatch();
            queuedPoolShare += price - firmMargin;
        }
        _entries[evalId] = Entry({
            buyer: buyer,
            offerId: offerId,
            traderBps: traderBps,
            status: Status.Queued,
            queuedAt: uint64(block.timestamp),
            price: price,
            firmMargin: firmMargin,
            prepaid: prepaid
        });
        _order.push(evalId);
        queuedCount += 1;
        emit EvalQueued(evalId, buyer, offerId, price, queuedCount, escrowTotal);
    }

    /// @notice Active les évals en tête (FIFO) tant que le pool a la marge. Appelable par tous (keeper, API).
    function process(uint256 maxCount) public nonReentrant whenNotPaused returns (uint256 activated) {
        uint256 i = head;
        uint256 n = _order.length;
        while (i < n && activated < maxCount) {
            uint256 id = _order[i];
            Entry storage e = _entries[id];
            if (e.status != Status.Queued) {
                i++;
                continue; // défensif : aucune sortie de file autre que l'activation
            }
            if (!headActivatable()) break;
            e.status = Status.Activated;
            queuedCount -= 1;
            if (!e.prepaid) {
                escrowTotal -= e.price;
                queuedPoolShare -= e.price - e.firmMargin;
                usdc.forceApprove(address(pool), e.price);
                pool.receiveEvalRevenue(id, e.price, e.firmMargin);
            }
            emit EvalActivated(id, e.buyer, e.price, block.timestamp - e.queuedAt);
            i++;
            activated++;
        }
        head = i;
    }

    // ---------------------------------------------------------------- administration
    function setCountEscrow(bool enabled) external onlyRole(DEFAULT_ADMIN_ROLE) {
        countEscrow = enabled;
        emit CountEscrowSet(enabled);
    }

    function pause() external onlyRole(PAUSER_ROLE) {
        _pause();
    }

    function unpause() external onlyRole(PAUSER_ROLE) {
        _unpause();
    }
}

src/PropPool.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

/// @title PropPool — pool USDC du parcours prop firm (chantier A, 24/11/2026)
/// @notice Tient le pool (solde libre, marges des sièges financés), la part firme et les gains dus aux traders.
///         Capte les frais : revenu des évaluations (marge firme / part pool), frais de trading 2,8 pb
///         (pool si x < x*, firme sinon), partage des retraits 80/20 ou 90/10 (part non-trader -> pool).
/// @dev    Code NON audité. Aucune sortie du pool vers la firme : la firme ne reçoit que la marge d'éval
///         et les frais de trading quand x >= x*. Montants en unités USDC (6 décimales).
contract PropPool is AccessControl, Pausable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    // ---------------------------------------------------------------- rôles
    bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); // passerelle / API : sièges, payouts, frais
    bytes32 public constant SALES_ROLE = keccak256("SALES_ROLE"); // EvalPurchase + EvalQueue
    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
    bytes32 public constant TREASURER_ROLE = keccak256("TREASURER_ROLE"); // retire la part firme

    uint256 public constant WAD = 1e18;
    uint256 public constant BPS = 10_000;
    uint256 public constant MILLION_USD = 1e12; // 1 M$ en unités USDC

    IERC20 public immutable usdc;

    // ---------------------------------------------------------------- paramètres (maths/36-37)
    uint256 public seatDeposit; // U : dépôt d'un siège financé (2 500 $)
    uint256 public queueThreshold; // file des achats d'éval sous ce solde libre (2 500 $)
    uint256 public levelSeats; // N : x = solde libre / (U * N), N = 80
    uint256 public xStar; // x* (WAD) : 2,8 pb au pool si x < x* (0,493)
    uint256 public freePerMillion; // solde libre exigé par M$ de notionnel ouvert (18 000 $)
    uint256 public notionalCap; // plafond total de notionnel (15,2 M$)
    address public custodian; // reçoit la marge des sièges en mode réel (passerelle / Lighter)
    bool public liveTrading; // désactivé par défaut : marge gardée dans le contrat
    mapping(bytes32 => uint16) public marketMaxLeverage; // levier plateforme par marché ("BTC" => 50)

    // ---------------------------------------------------------------- comptabilité
    uint256 public poolCash; // USDC du pool détenus ici (marges des sièges non réels comprises)
    uint256 public lockedMargin; // marges des sièges ouverts non réels (détenues ici)
    uint256 public deployedMargin; // marges des sièges ouverts réels (chez le custodian)
    uint256 public reservedMargin; // marges réservées aux réussis en attente de siège
    uint256 public firmBalance; // part firme, retirable par TREASURER
    uint256 public totalClaimable; // somme des gains dus aux traders
    mapping(address => uint256) public claimable;

    struct FeeStats {
        uint256 evalGross;
        uint256 evalToPool;
        uint256 evalToFirm;
        uint256 tradingToPool;
        uint256 tradingToFirm;
        uint256 payoutToTraders;
        uint256 payoutToPool;
        uint256 deposits;
    }

    FeeStats public stats;

    // ---------------------------------------------------------------- sièges
    enum SeatStatus {
        None,
        Pending,
        Open,
        Closed,
        Cancelled
    }

    struct Seat {
        address trader;
        uint64 evalId;
        uint16 traderBps; // 8000 (80/20) ou 9000 (90/10)
        SeatStatus status;
        bool live;
        uint64 requestedAt;
        uint64 openedAt;
        uint256 margin;
    }

    Seat[] internal _seats; // seatId = index + 1
    uint256[] internal _pending; // FIFO des réussis en attente
    uint256 public pendingHead;
    uint256 public pendingCount;
    uint256 public openSeats;

    // ---------------------------------------------------------------- événements (lus par l'API)
    event PoolDeposit(address indexed from, uint256 amount, uint256 freeBalance);
    event EvalRevenue(uint256 indexed evalId, uint256 gross, uint256 toPool, uint256 toFirm, uint256 freeBalance);
    event TradingFeesCaptured(address indexed from, uint256 amount, bool toPool, uint256 level);
    event SeatRequested(uint256 indexed seatId, address indexed trader, uint256 indexed evalId, uint16 traderBps);
    event SeatPending(uint256 indexed seatId, uint256 position, uint256 margin);
    event SeatOpened(uint256 indexed seatId, address indexed trader, uint256 margin, bool live);
    event SeatCancelled(uint256 indexed seatId);
    event SeatClosed(uint256 indexed seatId, uint256 returned, int256 pnl);
    event PayoutSplit(
        uint256 indexed seatId, address indexed trader, uint256 gross, uint256 traderShare, uint256 poolShare
    );
    event TraderWithdrawn(address indexed trader, uint256 amount);
    event FirmWithdrawn(address indexed to, uint256 amount);
    event ParamsUpdated(
        uint256 seatDeposit,
        uint256 queueThreshold,
        uint256 levelSeats,
        uint256 xStar,
        uint256 freePerMillion,
        uint256 notionalCap
    );
    event CustodianSet(address custodian);
    event LiveTradingSet(bool enabled);
    event MarketLeverageSet(bytes32 indexed market, uint16 maxLeverage);

    error ZeroAmount();
    error ZeroAddress();
    error BadSplit();
    error BadParams();
    error BadSeat();
    error NoCustodian();
    error InsufficientFirmBalance();

    struct Params {
        uint256 seatDeposit;
        uint256 queueThreshold;
        uint256 levelSeats;
        uint256 xStar;
        uint256 freePerMillion;
        uint256 notionalCap;
    }

    constructor(IERC20 usdc_, address admin, Params memory p) {
        if (address(usdc_) == address(0) || admin == address(0)) revert ZeroAddress();
        usdc = usdc_;
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(PAUSER_ROLE, admin);
        _grantRole(TREASURER_ROLE, admin);
        _setParams(p);
    }

    // ================================================================ vues
    /// @notice Solde libre = cash du pool - marges bloquées ici - marges réservées aux réussis (plancher 0).
    function freeBalance() public view returns (uint256) {
        uint256 used = lockedMargin + reservedMargin;
        return poolCash > used ? poolCash - used : 0;
    }

    /// @notice Pool total = cash + marges envoyées au custodian.
    function poolTotal() external view returns (uint256) {
        return poolCash + deployedMargin;
    }

    /// @notice Marge engagée dans les sièges ouverts.
    function committedMargin() public view returns (uint256) {
        return lockedMargin + deployedMargin;
    }

    /// @notice x = min(1, solde libre / (U * N)), en WAD. Fixe le prix d'éval et la route des 2,8 pb.
    function level() public view returns (uint256) {
        uint256 denom = seatDeposit * levelSeats;
        uint256 x = (freeBalance() * WAD) / denom;
        return x > WAD ? WAD : x;
    }

    function tradingFeesToPool() public view returns (bool) {
        return level() < xStar;
    }

    /// @notice Amorçage (décision Léo 24/11, option B) : aucun siège (ouvert ou en attente) et solde libre sous le seuil.
    ///         Les achats d'éval vont alors en entier au pool (marge firme 0) au lieu d'attendre en séquestre.
    function bootstrapping() public view returns (bool) {
        return openSeats == 0 && pendingCount == 0 && freeBalance() < queueThreshold;
    }

    /// @notice Vrai si un achat d'éval direct est possible (sinon il part en file).
    function canActivateEval() external view returns (bool) {
        return freeBalance() >= queueThreshold;
    }

    /// @notice Notionnel total permis = min(plafond, solde libre * 1 M$ / freePerMillion).
    function maxNotionalTotal() public view returns (uint256) {
        if (freePerMillion == 0) return notionalCap;
        uint256 byFree = (freeBalance() * MILLION_USD) / freePerMillion;
        return byFree < notionalCap ? byFree : notionalCap;
    }

    /// @notice Levier max par siège pour un marché, x100 (5000 = x50) : min(levier plateforme,
    ///         notionnel total permis / marge engagée). Lu par la passerelle avant chaque hausse.
    function maxLeverageX100(bytes32 market) public view returns (uint256) {
        uint256 cap = uint256(marketMaxLeverage[market]) * 100;
        uint256 committed = committedMargin();
        if (committed == 0) return cap;
        uint256 byPool = (maxNotionalTotal() * 100) / committed;
        return byPool < cap ? byPool : cap;
    }

    /// @notice Notionnel max d'un siège (marge U) sur un marché.
    function seatMaxNotional(bytes32 market) external view returns (uint256) {
        return (seatDeposit * maxLeverageX100(market)) / 100;
    }

    function seatCount() external view returns (uint256) {
        return _seats.length;
    }

    function getSeat(uint256 seatId) external view returns (Seat memory) {
        if (seatId == 0 || seatId > _seats.length) revert BadSeat();
        return _seats[seatId - 1];
    }

    // ================================================================ dépôts / revenus
    /// @notice Dépôt au pool (amorçage, apport). Sans part ni droit de retrait : version 1.
    function deposit(uint256 amount) external nonReentrant whenNotPaused {
        if (amount == 0) revert ZeroAmount();
        usdc.safeTransferFrom(msg.sender, address(this), amount);
        poolCash += amount;
        stats.deposits += amount;
        emit PoolDeposit(msg.sender, amount, freeBalance());
    }

    /// @notice Revenu d'une éval activée : marge -> firme, reste -> pool. Appelé par EvalPurchase / EvalQueue.
    function receiveEvalRevenue(uint256 evalId, uint256 gross, uint256 firmMargin)
        external
        nonReentrant
        whenNotPaused
        onlyRole(SALES_ROLE)
    {
        if (firmMargin > gross) revert BadParams();
        if (gross == 0) revert ZeroAmount();
        usdc.safeTransferFrom(msg.sender, address(this), gross);
        uint256 toPool = gross - firmMargin;
        poolCash += toPool;
        firmBalance += firmMargin;
        stats.evalGross += gross;
        stats.evalToPool += toPool;
        stats.evalToFirm += firmMargin;
        emit EvalRevenue(evalId, gross, toPool, firmMargin, freeBalance());
    }

    /// @notice Frais de trading reversés (part intégrateur 2,8 pb) : au pool si x < x*, sinon à la firme.
    function captureTradingFees(uint256 amount) external nonReentrant onlyRole(OPERATOR_ROLE) {
        if (amount == 0) revert ZeroAmount();
        uint256 x = level();
        bool toPool = x < xStar;
        usdc.safeTransferFrom(msg.sender, address(this), amount);
        if (toPool) {
            poolCash += amount;
            stats.tradingToPool += amount;
        } else {
            firmBalance += amount;
            stats.tradingToFirm += amount;
        }
        emit TradingFeesCaptured(msg.sender, amount, toPool, x);
    }

    // ================================================================ sièges financés
    /// @notice Un trader a réussi : ouvre son siège si le pool a la marge, sinon le met en attente
    ///         (prioritaire : sa marge est réservée et sort du solde libre, donc passe avant la file d'éval).
    function requestSeat(address trader, uint256 evalId, uint16 traderBps)
        external
        whenNotPaused
        onlyRole(OPERATOR_ROLE)
        returns (uint256 seatId)
    {
        if (trader == address(0)) revert ZeroAddress();
        if (traderBps != 8000 && traderBps != 9000) revert BadSplit();
        uint256 margin = seatDeposit;
        _seats.push(
            Seat({
                trader: trader,
                evalId: uint64(evalId),
                traderBps: traderBps,
                status: SeatStatus.Pending,
                live: false,
                requestedAt: uint64(block.timestamp),
                openedAt: 0,
                margin: margin
            })
        );
        seatId = _seats.length;
        emit SeatRequested(seatId, trader, evalId, traderBps);

        if (pendingCount == 0 && freeBalance() >= margin) {
            _open(seatId, false);
        } else {
            _pending.push(seatId);
            pendingCount += 1;
            reservedMargin += margin;
            emit SeatPending(seatId, pendingCount, margin);
        }
    }

    /// @notice Ouvre les sièges en attente (FIFO) tant que le cash le permet. Appelable par tous.
    function fundPendingSeats(uint256 maxCount) external nonReentrant whenNotPaused returns (uint256 opened) {
        opened = _fundPendingInternal(maxCount);
    }

    function cancelPendingSeat(uint256 seatId) external onlyRole(OPERATOR_ROLE) {
        Seat storage s = _seat(seatId);
        if (s.status != SeatStatus.Pending) revert BadSeat();
        s.status = SeatStatus.Cancelled;
        reservedMargin -= s.margin;
        pendingCount -= 1;
        emit SeatCancelled(seatId);
    }

    /// @notice Gains retirés par le trader (déjà rapatriés par l'opérateur) : part trader due, reste au pool.
    function payout(uint256 seatId, uint256 gross) external nonReentrant onlyRole(OPERATOR_ROLE) {
        Seat storage s = _seat(seatId);
        if (s.status != SeatStatus.Open) revert BadSeat();
        if (gross == 0) revert ZeroAmount();
        usdc.safeTransferFrom(msg.sender, address(this), gross);
        _split(seatId, s, gross);
    }

    /// @notice Clôture : en mode réel l'opérateur rend `returned` (marge restante + gains non retirés) ;
    ///         la perte reste au pool, un excédent est partagé comme un retrait. Hors mode réel la marge,
    ///         jamais sortie du contrat, est libérée en entier (`returned` ignoré).
    function closeSeat(uint256 seatId, uint256 returned) external nonReentrant onlyRole(OPERATOR_ROLE) {
        Seat storage s = _seat(seatId);
        if (s.status != SeatStatus.Open) revert BadSeat();
        s.status = SeatStatus.Closed;
        openSeats -= 1;
        uint256 m = s.margin;
        int256 pnl;
        if (s.live) {
            deployedMargin -= m;
            if (returned > 0) usdc.safeTransferFrom(msg.sender, address(this), returned);
            if (returned > m) {
                poolCash += m;
                _split(seatId, s, returned - m);
            } else {
                poolCash += returned;
            }
            pnl = int256(returned) - int256(m);
        } else {
            lockedMargin -= m;
            returned = m;
        }
        emit SeatClosed(seatId, returned, pnl);
        // un siège fermé libère de la marge : servir les réussis en attente
        if (pendingCount > 0 && !paused()) _fundPendingInternal(10);
    }

    // ================================================================ retraits
    /// @notice Le trader retire ses gains dus (même en pause).
    function withdrawTrader() external nonReentrant {
        uint256 amount = claimable[msg.sender];
        if (amount == 0) revert ZeroAmount();
        claimable[msg.sender] = 0;
        totalClaimable -= amount;
        usdc.safeTransfer(msg.sender, amount);
        emit TraderWithdrawn(msg.sender, amount);
    }

    /// @notice La firme retire sa part (marges d'éval, frais au-dessus de x*). Jamais le pool.
    function withdrawFirm(address to, uint256 amount) external nonReentrant onlyRole(TREASURER_ROLE) {
        if (to == address(0)) revert ZeroAddress();
        if (amount == 0) revert ZeroAmount();
        if (amount > firmBalance) revert InsufficientFirmBalance();
        firmBalance -= amount;
        usdc.safeTransfer(to, amount);
        emit FirmWithdrawn(to, amount);
    }

    // ================================================================ administration
    function setParams(Params calldata p) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _setParams(p);
    }

    function setCustodian(address c) external onlyRole(DEFAULT_ADMIN_ROLE) {
        custodian = c;
        emit CustodianSet(c);
    }

    function setLiveTrading(bool enabled) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (enabled && custodian == address(0)) revert NoCustodian();
        liveTrading = enabled;
        emit LiveTradingSet(enabled);
    }

    function setMarketLeverage(bytes32 market, uint16 maxLev) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (maxLev > 200) revert BadParams();
        marketMaxLeverage[market] = maxLev;
        emit MarketLeverageSet(market, maxLev);
    }

    function pause() external onlyRole(PAUSER_ROLE) {
        _pause();
    }

    function unpause() external onlyRole(PAUSER_ROLE) {
        _unpause();
    }

    // ================================================================ interne
    function _seat(uint256 seatId) internal view returns (Seat storage) {
        if (seatId == 0 || seatId > _seats.length) revert BadSeat();
        return _seats[seatId - 1];
    }

    function _open(uint256 seatId, bool fromPending) internal {
        Seat storage s = _seats[seatId - 1];
        uint256 m = s.margin;
        if (fromPending) {
            reservedMargin -= m;
            pendingCount -= 1;
        }
        s.status = SeatStatus.Open;
        s.openedAt = uint64(block.timestamp);
        openSeats += 1;
        if (liveTrading) {
            if (custodian == address(0)) revert NoCustodian();
            s.live = true;
            poolCash -= m;
            deployedMargin += m;
            usdc.safeTransfer(custodian, m);
        } else {
            lockedMargin += m;
        }
        emit SeatOpened(seatId, s.trader, m, s.live);
    }

    /// @dev FIFO ; la tête est prioritaire : seules les marges déjà bloquées comptent contre elle.
    function _fundPendingInternal(uint256 maxCount) internal returns (uint256 opened) {
        uint256 i = pendingHead;
        uint256 n = _pending.length;
        while (i < n && opened < maxCount) {
            uint256 id = _pending[i];
            Seat storage s = _seats[id - 1];
            if (s.status != SeatStatus.Pending) {
                i++;
                continue;
            }
            if (poolCash < lockedMargin + s.margin) break;
            _open(id, true);
            i++;
            opened++;
        }
        pendingHead = i;
    }

    function _split(uint256 seatId, Seat storage s, uint256 gross) internal {
        uint256 traderShare = (gross * s.traderBps) / BPS;
        uint256 poolShare = gross - traderShare;
        claimable[s.trader] += traderShare;
        totalClaimable += traderShare;
        poolCash += poolShare;
        stats.payoutToTraders += traderShare;
        stats.payoutToPool += poolShare;
        emit PayoutSplit(seatId, s.trader, gross, traderShare, poolShare);
    }

    function _setParams(Params memory p) internal {
        if (p.seatDeposit == 0 || p.levelSeats == 0 || p.levelSeats > 100_000 || p.xStar > WAD) revert BadParams();
        seatDeposit = p.seatDeposit;
        queueThreshold = p.queueThreshold;
        levelSeats = p.levelSeats;
        xStar = p.xStar;
        freePerMillion = p.freePerMillion;
        notionalCap = p.notionalCap;
        emit ParamsUpdated(p.seatDeposit, p.queueThreshold, p.levelSeats, p.xStar, p.freePerMillion, p.notionalCap);
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "osaka",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "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.