Skip to content
Verified contractPartialMIT

UserLotteryManager

Address0x9d247a82c1e645af0b6dba10785a26fa0b6552ea
Balance

0 ETH

 

Transactions

14

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,282,769
Creation transaction
0x7824b2f6b8…0ed1e24e61
Libraries
contracts/UserLotteryManager.sol:LotteryCoreLib0x82db…9a0557

contracts/UserLotteryManager.sol

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

/**
 * @title CoinLotto Protocol
 * @notice Autonomous smart contract for creating and participating in user-created token-based lotteries.
 *
 * @dev This contract is decentralized software and executes according to its immutable
 * or governance-defined logic. Game parameters are defined by their creators.
 *
 * The protocol does not take custody of assets outside the contract logic,
 * does not make decisions on behalf of users, and does not guarantee
 * any outcome, availability, or financial return.
 *
 * Users are solely responsible for:
 * - evaluating lottery parameters;
 * - complying with applicable laws and regulations in their jurisdiction;
 * - verifying supported ERC-20 tokens before participating;
 * - understanding the risks associated with blockchain transactions.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTIES OF ANY KIND,
 * EXPRESS OR IMPLIED.
 */

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

import {BaseLotteryManager} from "./abstract/BaseLotteryManager.sol";
import {ReferrerFeeLedger} from "./abstract/ReferrerFeeLedger.sol";

import {LotteryStored, LotteryState, LotteryStatus, LotteryKind, LotteryParams, PayoutModel} from "./structs/MetadataStruct.sol";
import {TicketPurchaseQuote} from "./structs/TicketPurchaseQuote.sol";

/// @title UserLotteryManager
/// @notice Manager module for `LotteryKind.USER` lotteries (all payout models).
/// @dev Hub integration:
///        • Creation: `createLotteryFromHub` — `onlyHub`, decodes `extraData`, emits {LotteryCreated}.
///        • Purchase: `quoteTicketPurchase` (view) + `registerTicketPurchase` (`onlyHub`, no transfers).
///        • Draw/claim: inherited `BaseLotteryManager` paths via Hub proxies.
///
///      Hub-pull payment (ERC-20 `params.asset` only; no CLT ticket path):
///        gross = qty × ticketPrice
///        treasuryFee = gross × protocolFeeUserLotteriesBp / BP
///        refShare = (referrer ≠ 0) ? treasuryFee × protocolFeeRevenueShareBp / BP : 0
///        netTreasury = treasuryFee − refShare
///        creatorFee = gross × params.feeBp / BP
///        prizeAmount = gross − treasuryFee − creatorFee
///        Hub pulls: netTreasury → treasury; (creatorFee + refShare + prizeAmount) → this contract
///
///      `extraData` encoding (pass to `LotteryHub.createLottery` with `USER_LOTTERY`):
///        • MULTIPLIER: `abi.encode(uint256 multiplierBp)`
///        • TIER:       `abi.encode(uint16[] tiers)`
///        • WIN_RATE:   `abi.encode(uint256 winRateBp)`
///
///      Access control:
///        • `HUB_ROLE` — Hub-only create/register/draw entry points (from `BaseLotteryCreator`).
///        • `WORKER_ROLE` — fee and treasury configuration.
///        • `DEFAULT_ADMIN_ROLE` — role admin (24h delay).
///
///      Does not implement `IRegularMissionModule` (no `CltMissions` eligibility on USER IDs).
contract UserLotteryManager is ReferrerFeeLedger {
    using SafeERC20 for IERC20;

    /* ─────────────────────────────────────── State ──────────────────────────── */

    /// @notice Protocol fee on USER ticket gross, in basis points.
    uint16 public protocolFeeUserLotteriesBp;

    /// @notice Maximum `params.feeBp` allowed at USER lottery creation; 0 = no cap.
    uint16 public creatorFeeUserLotteriesLimitBp;

    /// @notice Treasury receiving net protocol fees after referrer share.
    address public treasury;

    /// @notice Maximum `params.duration` for USER lotteries (seconds).
    uint64 public maxDurationUsers;

    /* ─────────────────────────────────────── Events ─────────────────────────── */

    /// @notice Emitted when `treasury` is updated.
    event TreasurySet(address indexed treasury);

    /// @notice Emitted when `protocolFeeUserLotteriesBp` is updated.
    event ProtocolFeeUserLotteriesBpSet(uint16 indexed value);

    /// @notice Emitted when `creatorFeeUserLotteriesLimitBp` is updated.
    event CreatorFeeUserLotteriesLimitBpSet(uint16 indexed value);

    /// @notice Emitted when `maxDurationUsers` is updated.
    event MaxDurationUsersSet(uint64 indexed value);

    /// @notice Emitted when creator fees are accrued on ticket purchase.
    event CreatorFeeAdded(uint256 indexed lotteryId, address indexed creator, address token, uint256 amount);

    /// @notice Emitted when the lottery creator withdraws accumulated creator fees post-draw.
    event CreatorFeeClaimed(uint256 indexed lotteryId, address indexed creator, address token, uint256 amount);

    /* ─────────────────────────────────────── Errors ─────────────────────────── */

    /// @notice Thrown when `createLotteryFromHub` receives a non-USER `kind`.
    error OnlyUserLotteries();

    /// @notice Thrown when `payoutModel` is not MULTIPLIER, TIER, or WIN_RATE.
    error UnsupportedPayoutModel();

    /// @notice Thrown when `claimCreatorFee` is called by an address other than `lot.creator`.
    error NotLotteryCreator();

    /// @notice Thrown when `claimCreatorFee` is called with zero accrued creator fees.
    error NoCreatorFees();

    /// @notice Thrown when draw is not finished (status not DRAW_COMPLETED / FULLY_CLAIMED).
    error NotReadyToClaim();

    /* ─────────────────────────────────────── Constructor ────────────────────── */

    /// @notice Deploys the USER creator and grants `HUB_ROLE` to `hub_`.
    ///         RndConsumer is wired post-deploy via `setRndConsumer`.
    /// @param initialDefaultAdmin `DEFAULT_ADMIN_ROLE` holder.
    /// @param hub_                `LotteryHub` address.
    constructor(address initialDefaultAdmin, address hub_) BaseLotteryManager(initialDefaultAdmin, hub_) {
        _grantRole(WORKER_ROLE, msg.sender);
    }

    /* ─────────────────────────── Configuration (WORKER_ROLE) ────────────────── */

    /// @notice Sets the maximum creator fee BP allowed on new USER lotteries.
    /// @param creatorFeeUserLotteriesLimitBp_ Cap; must be ≤ {MAX_CREATOR_FEE_BP}.
    function setCreatorFeeUserLotteriesLimitBp(uint16 creatorFeeUserLotteriesLimitBp_) external onlyRole(WORKER_ROLE) {
        if (creatorFeeUserLotteriesLimitBp_ > MAX_FEE_LIMIT_BP) revert InvalidCreatorCommission();
        creatorFeeUserLotteriesLimitBp = creatorFeeUserLotteriesLimitBp_;
        emit CreatorFeeUserLotteriesLimitBpSet(creatorFeeUserLotteriesLimitBp_);
    }

    /// @notice Sets the maximum allowed USER lottery duration.
    /// @param newDuration Seconds; must be non-zero.
    function setMaxDurationUsers(uint64 newDuration) external onlyRole(WORKER_ROLE) {
        if (newDuration == 0) revert InvalidAmount();
        maxDurationUsers = newDuration;
        emit MaxDurationUsersSet(newDuration);
    }

    /// @notice Updates the treasury address used in purchase quotes.
    function setTreasury(address treasury_) external onlyRole(WORKER_ROLE) {
        if (treasury_ == address(0)) revert ZeroAddress();
        treasury = treasury_;
        emit TreasurySet(treasury_);
    }

    /// @notice Sets the USER lottery protocol fee rate.
    /// @param protocolFeeUserLotteriesBp_ Basis points; must be ≤ `MAX_CREATOR_FEE_BP` (20%).
    function setProtocolFeeUserLotteriesBp(uint16 protocolFeeUserLotteriesBp_) external onlyRole(WORKER_ROLE) {
        if (protocolFeeUserLotteriesBp_ > MAX_CREATOR_FEE_BP) revert InvalidCreatorCommission();
        protocolFeeUserLotteriesBp = protocolFeeUserLotteriesBp_;
        emit ProtocolFeeUserLotteriesBpSet(protocolFeeUserLotteriesBp_);
    }

    /* ─────────────────────────── Creator fee claim ──────────────────────────── */

    /// @notice Withdraws accumulated creator fees for `lotteryId` after the draw completes.
    /// @dev Callable only by `lot.creator` (the `originalCaller` at Hub creation).
    function claimCreatorFee(uint256 lotteryId) external {
        LotteryStatus liveStatus = _getLotteryStatus(lotteryId);
        if (liveStatus != LotteryStatus.DRAW_COMPLETED && liveStatus != LotteryStatus.FULLY_CLAIMED)
            revert NotReadyToClaim();

        LotteryStored storage lot = _lotteries[lotteryId];
        if (lot.creator != msg.sender) revert NotLotteryCreator();

        LotteryState storage s = _state[lotteryId];
        uint256 amount = s.creatorFees;
        if (amount == 0) revert NoCreatorFees();

        s.creatorFees = 0;
        address asset = lot.asset;
        IERC20(asset).safeTransfer(msg.sender, amount);
        emit CreatorFeeClaimed(lotteryId, msg.sender, asset, amount);
    }

    /* ─────────────────────────── ILotteryCreator — creation ───────────────────── */

    /// @inheritdoc BaseLotteryManager
    /// @notice Initializes a USER lottery; decodes `extraData` per `payoutModel`.
    function createLotteryFromHub(
        uint256 lotteryId,
        address originalCaller,
        LotteryKind kind,
        PayoutModel payoutModel,
        LotteryParams calldata params,
        bytes calldata extraData
    ) external override onlyHub {
        if (kind != LotteryKind.USER) revert OnlyUserLotteries();

        _checkBase(params, maxDurationUsers);
        uint256 feeCap = creatorFeeUserLotteriesLimitBp;
        if (feeCap > 0 && params.feeBp > feeCap) revert InvalidCreatorCommission();

        _initLottery(lotteryId, kind, payoutModel, originalCaller, params);

        if (payoutModel == PayoutModel.MULTIPLIER) {
            uint256 multiplierBp = abi.decode(extraData, (uint256));
            _checkMultiplierBp(multiplierBp);
            if (params.maxTickets * BP_DENOMINATOR < multiplierBp) revert InvalidMinTicketCount();
            _setPayoutRateBp(lotteryId, multiplierBp);
        } else if (payoutModel == PayoutModel.TIER) {
            uint16[] memory tiers = abi.decode(extraData, (uint16[]));
            _checkTiersLength(tiers.length);
            if (params.maxTickets < tiers.length) revert InvalidMinTicketCount();
            _storeTiers(lotteryId, tiers);
        } else if (payoutModel == PayoutModel.WIN_RATE) {
            uint256 winRateBp = abi.decode(extraData, (uint256));
            _checkWinRateBp(winRateBp);
            _setPayoutRateBp(lotteryId, winRateBp);
        } else {
            revert UnsupportedPayoutModel();
        }

        emit LotteryCreated(lotteryId, originalCaller, kind, payoutModel);
    }

    /* ─────────────────────────── ILotteryCreator — Hub-pull purchase ─────────── */

    /// @inheritdoc BaseLotteryManager
    /// @notice Returns the ERC-20 payment breakdown for a USER ticket purchase.
    function quoteTicketPurchase(
        uint256 lotteryId,
        uint256 qty,
        address referrer
    ) external view override returns (TicketPurchaseQuote memory q) {
        LotteryStored storage lot = _lotteries[lotteryId];
        uint256 gross = qty * lot.ticketPrice;
        uint256 creatorFee = (gross * lot.feeBp) / BP_DENOMINATOR;
        uint256 treasuryFee = (gross * protocolFeeUserLotteriesBp) / BP_DENOMINATOR;

        uint256 refShare = 0;
        if (referrer != address(0) && treasuryFee > 0) {
            refShare = (treasuryFee * protocolFeeRevenueShareBp) / BP_DENOMINATOR;
        }

        uint256 netTreasury = treasuryFee - refShare;
        uint256 prizeAmount = gross - treasuryFee - creatorFee;

        q.token = lot.asset;
        q.toTreasury = netTreasury;
        q.treasuryDest = treasury;
        q.prizeAmount = prizeAmount;
        q.refShare = refShare;
        q.creatorFee = creatorFee;
        q.isUserLottery = true;
    }

    /// @inheritdoc BaseLotteryManager
    /// @notice Mints tickets and updates pools after Hub has pulled ERC-20 (no transfers here).
    /// @dev No local reentrancy guard: Hub-only entrypoint and the Hub's `buyTickets` is guarded.
    ///      Requires an open Hub settlement (`openHubSettlement`) and closes it as its last step.
    function registerTicketPurchase(
        uint256 lotteryId,
        uint256 qty,
        address ticketRecipient,
        address buyer,
        address referrer,
        TicketPurchaseQuote calldata quote
    ) external override onlyHub {
        _executeTicketPurchase(lotteryId, qty, ticketRecipient);

        address token = quote.token;
        LotteryState storage s = _state[lotteryId];
        s.creatorFees += quote.creatorFee;
        s.prizePool += quote.prizeAmount;

        if (quote.creatorFee > 0) {
            emit CreatorFeeAdded(lotteryId, _lotteries[lotteryId].creator, token, quote.creatorFee);
        }

        if (quote.refShare > 0) {
            refFees[referrer][token] += quote.refShare;
            emit ReferrerFeeAdded(lotteryId, referrer, token, quote.refShare, buyer);
        }

        _closeHubSettlement();
    }

    /* ─────────────────────────── Ticket views ───────────────────────────────── */

    /// @notice Batch metadata starting at `ticketId` (ERC721A-style contiguous run).
    /// @dev `ProtocolLotteryManager` exposes the same data through
    ///      `RegularMissionModule.getMissionBatchData`. This entry point serves USER lotteries.
    /// @param lotteryId Lottery ID.
    /// @param ticketId  1-based start of batch (must be a batch head with stored ownership).
    /// @return kind      Lottery kind.
    /// @return owner     Batch owner.
    /// @return batchSize Contiguous tickets in the batch from `ticketId`.
    function ticketBatchData(
        uint256 lotteryId,
        uint256 ticketId
    ) external view returns (LotteryKind kind, address owner, uint256 batchSize) {
        uint256 total = _lotteryIndex[lotteryId];
        if (ticketId == 0 || ticketId >= total) revert TicketDoesNotExist();
        TicketOwnership storage o = _ownerships[lotteryId][ticketId];
        if (o.owner == address(0)) revert TicketDoesNotExist();

        uint256 batchEnd = ticketId + 1;
        while (batchEnd < total && _ownerships[lotteryId][batchEnd].owner == address(0)) {
            // prettier-ignore
            unchecked { ++batchEnd; }
        }

        return (_lotteries[lotteryId].kind, o.owner, batchEnd - ticketId);
    }
}

@chainlink/contracts/src/v0.8/vrf/dev/interfaces/IVRFV2PlusWrapper.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IVRFV2PlusWrapper {
  /**
   * @return the request ID of the most recent VRF V2 request made by this wrapper. This should only
   * be relied option within the same transaction that the request was made.
   */
  function lastRequestId() external view returns (uint256);

  /**
   * @notice Calculates the price of a VRF request with the given callbackGasLimit at the current
   * @notice block.
   *
   * @dev This function relies on the transaction gas price which is not automatically set during
   * @dev simulation. To estimate the price at a specific gas price, use the estimatePrice function.
   *
   * @param _callbackGasLimit is the gas limit used to estimate the price.
   * @param _numWords is the number of words to request.
   */
  function calculateRequestPrice(uint32 _callbackGasLimit, uint32 _numWords) external view returns (uint256);

  /**
   * @notice Calculates the price of a VRF request in native with the given callbackGasLimit at the current
   * @notice block.
   *
   * @dev This function relies on the transaction gas price which is not automatically set during
   * @dev simulation. To estimate the price at a specific gas price, use the estimatePrice function.
   *
   * @param _callbackGasLimit is the gas limit used to estimate the price.
   * @param _numWords is the number of words to request.
   */
  function calculateRequestPriceNative(uint32 _callbackGasLimit, uint32 _numWords) external view returns (uint256);

  /**
   * @notice Estimates the price of a VRF request with a specific gas limit and gas price.
   *
   * @dev This is a convenience function that can be called in simulation to better understand
   * @dev pricing.
   *
   * @param _callbackGasLimit is the gas limit used to estimate the price.
   * @param _numWords is the number of words to request.
   * @param _requestGasPriceWei is the gas price in wei used for the estimation.
   */
  function estimateRequestPrice(
    uint32 _callbackGasLimit,
    uint32 _numWords,
    uint256 _requestGasPriceWei
  ) external view returns (uint256);

  /**
   * @notice Estimates the price of a VRF request in native with a specific gas limit and gas price.
   *
   * @dev This is a convenience function that can be called in simulation to better understand
   * @dev pricing.
   *
   * @param _callbackGasLimit is the gas limit used to estimate the price.
   * @param _numWords is the number of words to request.
   * @param _requestGasPriceWei is the gas price in wei used for the estimation.
   */
  function estimateRequestPriceNative(
    uint32 _callbackGasLimit,
    uint32 _numWords,
    uint256 _requestGasPriceWei
  ) external view returns (uint256);

  /**
   * @notice Requests randomness from the VRF V2 wrapper, paying in native token.
   *
   * @param _callbackGasLimit is the gas limit for the request.
   * @param _requestConfirmations number of request confirmations to wait before serving a request.
   * @param _numWords is the number of words to request.
   */
  function requestRandomWordsInNative(
    uint32 _callbackGasLimit,
    uint16 _requestConfirmations,
    uint32 _numWords,
    bytes calldata extraArgs
  ) external payable returns (uint256 requestId);

  function link() external view returns (address);
  function linkNativeFeed() external view returns (address);
}

@openzeppelin/contracts/access/AccessControl.sol

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

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.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 IERC165
    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).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * 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;
        }
    }
}

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

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

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

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

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

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.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 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 _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

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

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

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

@openzeppelin/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

/**
 * @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].
 */
abstract contract ReentrancyGuard {
    // 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;

    uint256 private _status;

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

    constructor() {
        _status = 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();
    }

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

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = 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 _status == ENTERED;
    }
}

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

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

@openzeppelin/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = 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 = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @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 {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(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 {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @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 {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 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 low / denominator;
            }

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

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

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, 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 ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, 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 high into low.
            low |= high * 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 high
            // is no longer required.
            result = low * 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 Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 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 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @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 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

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

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

contracts/LotteryTickets.sol

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

/// @title LotteryTickets
/// @notice Per-lottery ticket indexing and ERC721A-style lazy ownership tracking.
/// @dev Mixed into `BaseLotteryManager` (not deployed alone). Each `lotteryId` maintains its
///      own ticket namespace:
///
///      IMPORTANT — Tickets are NON-TRANSFERABLE. There is intentionally no transfer or
///      approval mechanism in this contract. This invariant is relied upon by
///      {ProtocolLotteryManager.claimCltReward}, which reads the live `balanceOf` at claim time
///      rather than a purchase-time snapshot. Any upgrade that adds ticket transfers MUST also
///      migrate the CLT reward logic to a per-ticket claim model.
///
///        - `_lotteryIndex[lotteryId]` — next ticket ID to mint (starts at `1` after init).
///        - `_ownerships[lotteryId][ticketId]` — sparse map: only the **first** ID of each
///          purchase batch stores `owner` and `purchaseTime`; later IDs in the batch resolve
///          by walking backward until a non-zero owner is found.
///        - `balanceOf[lotteryId][owner]` — per-owner ticket count.
///
///      Ticket IDs are **1-based**; ID `0` is unused. Tickets sold =
///      `_lotteryIndex[lotteryId] - 1` (or `0` before the lottery is initialised).
contract LotteryTickets {
    /* ------------------------------------- Types ------------------------------------- */

    /// @notice Ownership record for the first ticket in a purchased batch.
    struct TicketOwnership {
        /// @dev Owner of the batch (and all consecutive unmapped IDs after it).
        address owner;
        /// @dev `block.timestamp` when the batch was minted.
        uint64 purchaseTime;
    }

    /* ------------------------------------- State ------------------------------------- */

    /// @dev Next ticket ID to assign per lottery (equals `ticketsSold + 1` once initialised).
    mapping(uint256 lotteryId => uint256 currentIndex) internal _lotteryIndex;

    /// @dev Sparse ownership: first ticket of each batch only.
    mapping(uint256 lotteryId => mapping(uint256 ticketId => TicketOwnership))
        internal _ownerships;

    /// @notice Ticket balance per `(lotteryId, owner)`.
    mapping(uint256 lotteryId => mapping(address owner => uint256 balance)) public balanceOf;

    /* ------------------------------------- Events ------------------------------------- */

    /// @notice Emitted when a contiguous batch of tickets is minted.
    /// @param lotteryId      Lottery the tickets belong to.
    /// @param recipient      Owner of the batch.
    /// @param startTicketId  First ticket ID in the batch (1-based).
    /// @param quantity       Number of tickets minted.
    event TicketsMinted(
        uint256 indexed lotteryId,
        address indexed recipient,
        uint256 startTicketId,
        uint256 quantity
    );

    /* ------------------------------------- Errors ------------------------------------- */

    /// @notice Mint or purchase quantity is zero.
    error InvalidQuantity();

    /// @notice `ticketRecipient` or another required address is the zero address.
    error ZeroAddress();

    /// @notice Ticket ID is `0`, above the current index, or has no resolvable owner.
    error TicketDoesNotExist();

    /* ------------------------------------- External views ------------------------------------- */

    /// @notice Returns owner and purchase time for a ticket.
    /// @param lotteryId    Lottery ID.
    /// @param ticketId     1-based ticket ID.
    /// @return owner        Ticket owner.
    /// @return purchaseTime Batch purchase timestamp.
    function getTicketOwnership(
        uint256 lotteryId,
        uint256 ticketId
    ) external view returns (address owner, uint64 purchaseTime) {
        TicketOwnership memory o = _resolveOwnership(lotteryId, ticketId);
        return (o.owner, o.purchaseTime);
    }

    /* ------------------------------------- Public views ------------------------------------- */

    /// @notice Returns the owner of a ticket (ERC721-style).
    /// @param lotteryId Lottery ID.
    /// @param ticketId  1-based ticket ID.
    /// @return          Owner address.
    function ownerOf(uint256 lotteryId, uint256 ticketId) public view returns (address) {
        return _resolveOwnership(lotteryId, ticketId).owner;
    }

    /* ------------------------------------- Internal mint ------------------------------------- */

    /// @notice Mints a contiguous batch of tickets to `ticketRecipient`.
    /// @dev Writes one `TicketOwnership` at the current index and advances `_lotteryIndex`
    ///      by `quantity`. Caller must enforce `maxTickets` and lifecycle rules.
    /// @param _lotteryId       Target lottery.
    /// @param _quantity        Tickets to mint (must be > 0).
    /// @param _ticketRecipient Owner of the new batch.
    function _mintTix(uint256 _lotteryId, uint256 _quantity, address _ticketRecipient) internal {
        if (_ticketRecipient == address(0)) revert ZeroAddress();
        uint256 startTicketId = _lotteryIndex[_lotteryId];

        unchecked {
            _lotteryIndex[_lotteryId] += _quantity;
        }

        _ownerships[_lotteryId][startTicketId] = TicketOwnership({
            owner: _ticketRecipient,
            purchaseTime: uint64(block.timestamp)
        });

        emit TicketsMinted(_lotteryId, _ticketRecipient, startTicketId, _quantity);

        unchecked {
            balanceOf[_lotteryId][_ticketRecipient] += _quantity;
        }
    }

    /* ------------------------------------- Internal helpers ------------------------------------- */

    /// @dev Returns tickets sold: `_lotteryIndex - 1`, or `0` if index is still `0`.
    function _sold(uint256 _lotteryId) internal view returns (uint256) {
        uint256 idx = _lotteryIndex[_lotteryId];
        return idx > 0 ? idx - 1 : 0;
    }

    /// @dev Resolves ownership by walking backward from `ticketId` to the batch head record.
    /// @param _lotteryId Lottery ID.
    /// @param _ticketId  1-based ticket ID.
    /// @return ownership Owner and purchase time for the batch containing `ticketId`.
    function _resolveOwnership(
        uint256 _lotteryId,
        uint256 _ticketId
    ) internal view returns (TicketOwnership memory ownership) {
        if (_ticketId == 0 || _ticketId >= _lotteryIndex[_lotteryId]) {
            revert TicketDoesNotExist();
        }

        unchecked {
            for (uint256 curr = _ticketId; ; curr--) {
                ownership = _ownerships[_lotteryId][curr];
                if (ownership.owner != address(0)) return ownership;
                if (curr == 1) break;
            }
        }

        revert TicketDoesNotExist();
    }
}

contracts/abstract/BaseLotteryManager.sol

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

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

import {LotteryCoreLib} from "../libraries/LotteryCoreLib.sol";
import {LotteryPrizeLib} from "../libraries/LotteryPrizeLib.sol";
import {MultiplierPayoutModel} from "./MultiplierPayoutModel.sol";
import {TierPayoutModel} from "./TierPayoutModel.sol";
import {WinRatePayoutModel} from "./WinRatePayoutModel.sol";
import {LotteryTickets} from "../LotteryTickets.sol";
import {IRandomnessCoordinatorLike, ILotteryRandomnessConsumer} from "../interfaces/IRandomnessCoordinatorLike.sol";
import {Lottery, LotteryStored, LotteryState, LotteryStateView, LotteryStatus, LotteryKind, LotteryParams, PayoutModel} from "../structs/MetadataStruct.sol";
import {TicketPurchaseQuote} from "../structs/TicketPurchaseQuote.sol";

/// @title BaseLotteryManager
/// @notice Abstract base for lottery manager contracts (USER, REGULAR, SUPER, BATTLE variants).
/// @dev Architecture:
///
///      **LotteryHub** — Users interact through the Hub. The Hub holds `HUB_ROLE` on each creator,
///      assigns monotonic `lotteryId` values, forwards `originalCaller` (the end user), executes
///      ERC-20 transfers for ticket purchases, then calls `registerTicketPurchase`. Creation and
///      purchase entry points on creators must be Hub-gated; never use `msg.sender` for ownership
///      or fee attribution when the Hub is the caller.
///
///      **RndConsumer (VRF)** — `rndCoordinator` is the shared randomness coordinator. Draw
///      requests call `requestRandomness`; fulfillment arrives on `fulfillRandomness` from an
///      account with `RANDOMNESS_COORDINATOR_ROLE`. Single-ticket lotteries skip VRF and use
///      seed `1` instantly.
///
///      **Creator storage model** (per `lotteryId`, all on this contract):
///        - `_lotteries[lotteryId]` → static `Lottery` (kind, model, creator, `LotteryParams`).
///        - `_state[lotteryId]` → runtime `LotteryState` (status, seed, prize pool, claims bitmap).
///        - `_donations[lotteryId][donor]` → optional prize-pool top-ups before draw.
///        - Inherited ticket layer: `_lotteryIndex`, `_ownerships`, `balanceOf` (`LotteryTickets`).
///
///      **Prizes** — Paid by direct ERC-20 transfer from the creator balance. Winner slots are
///      0-based ordinals; winning ticket IDs are derived from `seed` via `LotteryPrizeLib`.
///      Claim state uses a per-winner bitmap in `LotteryState.claimedWords`.
///
///      Concrete creators implement payout math (`_calcPrize`), Hub creation
///      (`createLotteryFromHub`), quoting/payment (`quoteTicketPurchase`, `registerTicketPurchase`),
///      and may override `_prizeAsset` when the prize token differs from the ticket token.
abstract contract BaseLotteryManager is
    AccessControl,
    ReentrancyGuard,
    LotteryTickets,
    ILotteryRandomnessConsumer,
    MultiplierPayoutModel,
    TierPayoutModel,
    WinRatePayoutModel
{
    using SafeERC20 for IERC20;

    /* ─────────────────────────────────────── Constants ─────────────────────── */

    /// @notice Role for Hub-only creation and ticket registration paths.
    bytes32 public constant HUB_ROLE = keccak256("HUB_ROLE");

    /// @notice Role for protocol worker configuration setters.
    bytes32 public constant WORKER_ROLE = keccak256("WORKER_ROLE");

    /// @notice Role allowed to call `fulfillRandomness` (RndConsumer).
    bytes32 public constant RANDOMNESS_COORDINATOR_ROLE = keccak256("RANDOMNESS_COORDINATOR_ROLE");

    /// @dev Seconds after a VRF request during which a retry is blocked; once elapsed, calling
    ///      `requestDraw` again re-issues the VRF request.
    uint256 private constant VRF_TIMEOUT = 15 minutes;

    /// @notice Basis-points denominator (100.00%).
    uint256 public constant BP_DENOMINATOR = 10_000;

    /// @dev Minimum allowed ticket price (smallest units of `params.asset`).
    uint256 internal constant MIN_TICKET_PRICE = 100;

    /// @dev Maximum protocol fee on User Lottery ticket sales (20%).
    uint256 internal constant MAX_CREATOR_FEE_BP = 2_000;

    /// @dev Maximum creator fee cap and protocol lottery fee limit (30%).
    uint256 internal constant MAX_FEE_LIMIT_BP = 3_000;

    /// @dev Maximum REGULAR→SUPER feeder allocation (20%).
    uint256 internal constant MAX_ALLOCATION_BP = 2_000;

    /// @dev Maximum CLT reward per ticket (1_000 CLT, 18 decimals).
    uint256 internal constant MAX_CLT_PER_TICKET = 1_000 * 10 ** 18;

    /// @notice Public cap reference for tier count configuration.
    uint256 internal constant MAX_TIER_LENGTH = 100;

    /// @notice Protocol-wide minimum win rate (BP) for configuration bounds.
    uint256 internal constant MIN_WIN_RATE_BP = 10;

    /// @notice Protocol-wide maximum win rate (BP) for configuration bounds.
    uint256 internal constant MAX_WIN_RATE_BP = 7_500;

    /// @notice Protocol-wide minimum payout multiplier (BP) for configuration bounds.
    uint256 internal constant MIN_PAYOUT_MULTIPLIER_BP = 15_000;

    /// @dev Absolute ceiling on tickets purchasable in a single `buyTickets` call.
    ///      Immutable after compile — no role or governance mechanism can raise
    ///      `ticketLimit` above this value.
    uint256 internal constant HARD_MAX_TICKETS_PER_TX = 100;

    /* ─────────────────────────────────────── State ──────────────────────────── */

    /// @notice LotteryHub that routes creation and ticket purchases to this manager.
    address public hub;

    /// @notice Shared VRF coordinator (`RndConsumer`).
    IRandomnessCoordinatorLike public rndCoordinator;

    /// @notice Configured minimum multiplier (BP) for MULTIPLIER lotteries; `0` disables lower bound check.
    uint32 public minimumMultiplierBp;

    /// @notice Configured maximum multiplier (BP) for MULTIPLIER lotteries; `0` disables upper bound check.
    uint32 public maximumMultiplierBp;

    /// @notice Configured minimum win rate (BP) for WIN_RATE lotteries.
    uint16 public minimumWinRateBp;

    /// @notice Configured maximum win rate (BP) for WIN_RATE lotteries.
    uint16 public maximumWinRateBp;

    /// @notice Maximum tier count for TIER lotteries.
    uint16 public maximumTiers;

    /// @notice Share of protocol fee revenue paid to referrers (BP, 0–10_000).
    uint16 public protocolFeeRevenueShareBp;

    /// @notice Configurable per-tx ticket cap for this manager (1–HARD_MAX_TICKETS_PER_TX).
    ///         Each deployed manager instance holds its own independent value.
    ///         Initialized to HARD_MAX_TICKETS_PER_TX (100) in the constructor.
    uint8 public ticketLimit;

    /// @dev Immutable lottery configuration set at creation (packed, 4 slots; see `LotteryStored`).
    ///      External views unpack into the ABI-facing `Lottery` struct via `getLottery`.
    mapping(uint256 lotteryId => LotteryStored) internal _lotteries;

    /// @dev Mutable lifecycle, draw, and prize accounting.
    mapping(uint256 lotteryId => LotteryState) internal _state;

    /// @dev Per-donor amounts credited to the prize pool (withdrawable before draw).
    mapping(uint256 lotteryId => mapping(address donor => uint256 amount)) internal _donations;

    /// @dev Hub settlement lock: `1` = idle, `2` = a Hub is between its balance snapshots on this
    ///      manager. Shared by every `HUB_ROLE` holder so a nested credit through another Hub cannot
    ///      pollute an outer balance-delta check. Plain storage because the EVM target is `paris`.
    uint256 private _hubSettlement;

    /// @notice Winner slot summary for paginated views.
    struct WinnerInfo {
        /// @dev 1-based winning ticket ID.
        uint256 ticketIdx;
        /// @dev Prize amount for this winner ordinal.
        uint256 prizeAmount;
        /// @dev Owner of the winning ticket.
        address winner;
        /// @dev True when this slot's prize has already been claimed.
        bool claimed;
    }

    /* ─────────────────────────────────────── Events ─────────────────────────── */

    /// @notice Manager submitted a Chainlink VRF draw request.
    /// @param lotteryId  Lottery being drawn.
    /// @param requestId  Coordinator request ID.
    event DrawRequested(uint256 indexed lotteryId, uint256 indexed requestId);

    /// @notice Draw seed stored and lottery marked draw-complete (alias for integrators).
    /// @param lotteryId Lottery ID.
    /// @param seed      Final randomness seed.
    event DrawCompleted(uint256 indexed lotteryId, uint256 seed);

    /// @notice `hub` address updated.
    event HubSet(address indexed hub);

    /// @notice `rndCoordinator` address updated.
    event RndCoordinatorSet(address indexed rndCoordinator);

    /// @notice Old coordinator role revocation deferred because it still has pending VRF requests.
    /// @dev Emitted by `setRndConsumer` when the old consumer's `pendingRequestCount(address(this))`
    ///      is non-zero. The worker must call `finalizeConsumerRevocation(oldConsumer)` after the count
    ///      reaches zero.
    /// @param oldConsumer  Previous coordinator contract.
    /// @param pendingCount Outstanding requests from this manager on the old consumer.
    event ConsumerRevocationDeferred(address indexed oldConsumer, uint16 pendingCount);

    /// @notice Stored or virtual lifecycle status transition.
    event LotteryStatusUpdated(uint256 indexed lotteryId, LotteryStatus indexed status);

    /// @notice Donor credited `amount` of `params.asset` to the prize pool.
    event Donated(uint256 indexed lotteryId, address indexed donor, uint256 amount);

    /// @notice Worker set minimum win rate bound.
    event MinimumWinRateBpSet(uint16 indexed minimumWinRateBp);

    /// @notice Worker set maximum win rate bound.
    event MaximumWinRateBpSet(uint16 indexed maximumWinRateBp);

    /// @notice Worker set maximum tier count.
    event MaximumTiersSet(uint16 indexed value);

    /// @notice Worker set minimum multiplier bound.
    event MinimumMultiplierBpSet(uint32 indexed value);

    /// @notice Worker set maximum multiplier bound.
    event MaximumMultiplierBpSet(uint32 indexed value);

    /// @notice Worker set referrer revenue share on protocol fees.
    event ProtocolFeeRevenueShareBpSet(uint16 indexed value);

    /// @notice Worker updated the per-tx ticket cap for this manager.
    event TicketLimitSet(uint8 indexed value);

    /// @notice Donor withdrew a pre-draw donation.
    event DonationWithdrawn(uint256 indexed lotteryId, address indexed donor, uint256 amount);

    /// @notice Single winner slot claimed on the manager (includes payout amount).
    event PrizeClaimed(uint256 indexed lotteryId, uint256 indexed winnerIndex, address indexed winner, uint256 amount);

    /// @notice New lottery initialised by the Hub on this creator.
    event LotteryCreated(
        uint256 indexed lotteryId,
        address indexed originalCaller,
        LotteryKind kind,
        PayoutModel model
    );

    /// @notice Multiple winner slots claimed in one transaction.
    event PrizeClaimedBatch(
        uint256 indexed lotteryId,
        address indexed claimer,
        uint256 totalAmount,
        uint24[] winnerIndices
    );

    /* ─────────────────────────────────────── Errors ─────────────────────────── */
    /// @notice Lottery `startTime` not reached (stored status still PENDING).
    error LotteryNotStartedYet();

    /// @notice Current time is past `params.endTime`.
    error LotteryEnded();

    /// @notice Lottery is not in an open purchase state.
    error LotteryNotActive();

    /// @notice Purchase quantity exceeds remaining ticket capacity.
    /// @param ticketsLeft Tickets still available.
    error ExceedsMaxTickets(uint256 ticketsLeft);

    /// @notice Single `buyTickets` call qty exceeds the per-tx ticket cap.
    /// @param limit Active `ticketLimit` at the time of the call.
    error ExceedsBatchLimit(uint256 limit);

    /// @notice Proposed `ticketLimit` is zero or exceeds `HARD_MAX_TICKETS_PER_TX`.
    error InvalidTicketLimit();

    /// @notice Draw cannot start until sold out or past `endTime` (READY_TO_DRAW).
    error NotReadyToDraw();

    /// @notice Draw requested but no tickets were sold.
    error NoTicketsSold();

    /// @notice `LotteryState.seed` already set; duplicate fulfillment blocked.
    error SeedAlreadyAdded();

    /// @notice Draw was not requested (wrong status for fulfill/re-request).
    error DrawNotRequested();

    /// @notice `finalizeConsumerRevocation` was called with the currently active coordinator.
    ///         Revoking the active coordinator would break all ongoing and future VRF requests.
    error CannotRevokeActiveConsumer();

    /// @notice `finalizeConsumerRevocation` was called while the old consumer still has
    ///         unresolved VRF requests for this manager.
    /// @param count Outstanding pending request count on the old consumer.
    error ConsumerStillPending(uint16 count);

    /// @notice Prizes cannot be claimed until draw completes.
    error DrawNotCompleted();

    /// @notice `winnerIndex` is out of range for this lottery's winner count.
    error InvalidWinnerIndex();

    /// @notice This winner slot was already claimed.
    error PrizeAlreadyClaimed();

    /// @notice `claimer` does not own the winning ticket for this slot.
    error NotWinner();

    /// @notice ETH refund to draw requester failed.
    /// @dev Declared for ABI stability. Not thrown: draw refunds are credited in `RndConsumer`.
    error EtherRefundFailed();

    /// @notice Basis-point value is invalid for the field.
    error InvalidBp();

    /// @notice VRF re-request attempted before `drawDeadline` elapsed.
    error DrawDeadlineNotReached();

    /// @notice Caller has no donation balance to withdraw.
    error NoDonation();

    /// @notice Donations or purchases blocked after draw started or completed.
    error LotteryAlreadyDrawn();

    /// @notice Donation withdrawal is only allowed when the lottery is CANCELLED
    ///         (expired with zero ticket sales). Attempting to withdraw while the
    ///         lottery is in any other state (ACTIVE, READY_TO_DRAW, DRAW_REQUESTED,
    ///         DRAW_COMPLETED, FULLY_CLAIMED, or PENDING) reverts with this error.
    error DonationWithdrawalNotAllowed();

    /// @notice Thrown when donation is prohibited.
    error ProhibitedDonation();

    /// @notice Attempted to initialize a lottery ID that is already in use.
    ///         `_initLottery` enforces a write-once invariant: once a lottery ID has been
    ///         initialized its `_state[id].status` moves from `NONE` to `ACTIVE` or `PENDING`
    ///         and can never return to `NONE`. Any subsequent initialization of the same ID
    ///         is unconditionally rejected.
    error LotteryAlreadyExists();

    /// @notice Donation or claim amount is zero.
    error ZeroAmount();

    /// @notice Actual tokens received after a direct `donate` transfer are less than `amount`.
    ///         Indicates a fee-on-transfer or otherwise non-standard token; not supported.
    error TransferAmountMismatch();

    /// @notice Direct claim caller is not Hub and `claimer != msg.sender`.
    error InvalidClaimer();

    /// @notice Amount parameter is zero where non-zero is required.
    error InvalidAmount();

    /// @notice `params.ticketPrice` below minimum.
    error InvalidTicketPrice();

    /// @notice `params.maxTickets` is zero.
    error InvalidMaxTickets();

    /// @notice `startTime` / `endTime` ordering or window is invalid.
    error InvalidTimeRange();

    /// @notice Lottery duration exceeds creator-type `maxDuration`.
    error ExceedsMaxDuration();

    /// @notice Multiplier BP outside configured bounds.
    error InvalidPayoutMultiplier();

    /// @notice Win rate BP outside configured bounds.
    error InvalidWinRateBp();

    /// @notice Tier array empty or longer than `maximumTiers`.
    /// @param count Rejected tier count.
    error TooManyTiers(uint256 count);

    /// @notice Minimum ticket count constraint violated.
    error InvalidMinTicketCount();

    /// @notice Creator commission BP too high.
    error InvalidCreatorCommission();

    /// @notice Feeder allocation BP too high.
    error InvalidAllocation();

    /// @notice SUPER feeder link requires non-zero super lottery ID.
    error ZeroSuperLotteryId();

    /// @notice Per-ticket CLT reward exceeds cap.
    error InvalidCltTicketReward();

    /// @notice Referrer protocol-fee share exceeds 100%.
    error InvalidProtocolFeeRevenueShare();

    /// @notice Thrown when `payer` does not match `msg.sender` on a direct (non-Hub) draw call.
    error InvalidPayer();

    /* ─────────────────────────────────────── Modifiers ──────────────────────── */

    /// @dev Restricts to accounts with `HUB_ROLE` (the deployed LotteryHub).
    modifier onlyHub() {
        _checkRole(HUB_ROLE);
        _;
    }

    /* ─────────────────────────────────────── Constructor ────────────────────── */

    /// @notice Deploys the creator and wires the Hub.  RndConsumer is set post-deploy via `setRndConsumer`.
    /// @param initialDefaultAdmin Account receiving `DEFAULT_ADMIN_ROLE`.
    /// @param hub_                LotteryHub address (`HUB_ROLE`).
    constructor(address initialDefaultAdmin, address hub_) {
        if (initialDefaultAdmin == address(0)) revert ZeroAddress();

        _grantRole(DEFAULT_ADMIN_ROLE, initialDefaultAdmin);
        _grantRole(WORKER_ROLE, initialDefaultAdmin);

        _setHub(hub_);
        _grantRole(HUB_ROLE, hub_);

        ticketLimit = uint8(HARD_MAX_TICKETS_PER_TX);
        _hubSettlement = 1;
    }

    /* ─────────────────────────── Configuration (WORKER_ROLE) ──────────── */

    /// @notice Migrates to a new LotteryHub: revokes `HUB_ROLE` from the old address, grants it to the new one.
    function setHub(address hub_) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _setHub(hub_);
    }

    /// @notice Sets (or migrates) the VRF randomness coordinator.
    /// @param rndConsumer_ New RndConsumer address; must be non-zero and differ from current.
    function setRndConsumer(address rndConsumer_) external onlyRole(WORKER_ROLE) {
        if (rndConsumer_ == address(0)) revert ZeroAddress();
        address prev = address(rndCoordinator);

        if (rndConsumer_ == prev) return;

        rndCoordinator = IRandomnessCoordinatorLike(rndConsumer_);
        _grantRole(RANDOMNESS_COORDINATOR_ROLE, rndConsumer_);

        if (prev != address(0)) {
            uint16 pending = IRandomnessCoordinatorLike(prev).pendingRequestCount(address(this));
            if (pending == 0) {
                _revokeRole(RANDOMNESS_COORDINATOR_ROLE, prev);
            } else {
                // Old coordinator keeps its role until its pending requests drain.
                emit ConsumerRevocationDeferred(prev, pending);
            }
        }
        emit RndCoordinatorSet(rndConsumer_);
    }

    /// @notice Revokes `RANDOMNESS_COORDINATOR_ROLE` from a previously superseded coordinator
    ///         once all its in-flight VRF requests for this manager have been resolved.
    /// @dev Called by `WORKER_ROLE` after {ConsumerRevocationDeferred} confirms that
    ///      `oldConsumer.pendingRequestCount(address(this)) == 0`.
    ///      Reverts if `oldConsumer` is still the active coordinator (would break live draws)
    ///      or if it still has pending requests.
    /// @param oldConsumer Previous coordinator contract to revoke.
    function finalizeConsumerRevocation(address oldConsumer) external onlyRole(WORKER_ROLE) {
        if (oldConsumer == address(0)) revert ZeroAddress();
        if (oldConsumer == address(rndCoordinator)) revert CannotRevokeActiveConsumer();
        uint16 pending = IRandomnessCoordinatorLike(oldConsumer).pendingRequestCount(address(this));
        if (pending != 0) revert ConsumerStillPending(pending);
        _revokeRole(RANDOMNESS_COORDINATOR_ROLE, oldConsumer);
    }

    function _setHub(address hub_) private {
        if (hub_ == address(0)) revert ZeroAddress();
        address prev = hub;
        // Revoke the old Hub only when there is a previous Hub and it differs from the new one.
        // Skipping when prev == hub_ prevents a spurious RoleRevoked event on same-address re-sets.
        if (prev != address(0) && prev != hub_) {
            _revokeRole(HUB_ROLE, prev);
        }
        hub = hub_;
        _grantRole(HUB_ROLE, hub_);
        emit HubSet(hub_);
    }

    /// @notice Sets maximum tier count for TIER lotteries.
    /// @param newMaximumTiers New cap; must be ≤ `MAX_TIER_LENGTH`.
    function setMaximumTiers(uint16 newMaximumTiers) external onlyRole(WORKER_ROLE) {
        if (newMaximumTiers > MAX_TIER_LENGTH) revert TooManyTiers(newMaximumTiers);
        maximumTiers = newMaximumTiers;
        emit MaximumTiersSet(newMaximumTiers);
    }

    /// @notice Sets minimum win rate bound (BP).
    /// @param minimumWinRateBp_ Must be ≥ `MIN_WIN_RATE_BP` and ≤ `maximumWinRateBp` when set.
    function setMinimumWinRateBp(uint16 minimumWinRateBp_) external onlyRole(WORKER_ROLE) {
        if (minimumWinRateBp_ < MIN_WIN_RATE_BP) revert InvalidWinRateBp();
        if (maximumWinRateBp > 0 && minimumWinRateBp_ > maximumWinRateBp) revert InvalidWinRateBp();
        minimumWinRateBp = minimumWinRateBp_;
        emit MinimumWinRateBpSet(minimumWinRateBp_);
    }

    /// @notice Sets maximum win rate bound (BP).
    /// @param maximumWinRateBp_ Must be ≤ `MAX_WIN_RATE_BP` and ≥ `minimumWinRateBp` when set.
    function setMaximumWinRateBp(uint16 maximumWinRateBp_) external onlyRole(WORKER_ROLE) {
        if (maximumWinRateBp_ > MAX_WIN_RATE_BP) revert InvalidWinRateBp();
        if (minimumWinRateBp > 0 && maximumWinRateBp_ < minimumWinRateBp) revert InvalidWinRateBp();
        maximumWinRateBp = maximumWinRateBp_;
        emit MaximumWinRateBpSet(maximumWinRateBp_);
    }

    /// @notice Sets minimum payout multiplier bound (BP).
    /// @param minimumMultiplierBp_ Must be ≥ `MIN_PAYOUT_MULTIPLIER_BP` and ≤ `maximumMultiplierBp` when set.
    function setMinimumMultiplierBp(uint32 minimumMultiplierBp_) external onlyRole(WORKER_ROLE) {
        if (minimumMultiplierBp_ < MIN_PAYOUT_MULTIPLIER_BP) revert InvalidPayoutMultiplier();
        if (maximumMultiplierBp > 0 && minimumMultiplierBp_ > maximumMultiplierBp) revert InvalidPayoutMultiplier();
        minimumMultiplierBp = minimumMultiplierBp_;
        emit MinimumMultiplierBpSet(minimumMultiplierBp_);
    }

    /// @notice Sets maximum payout multiplier bound (BP).
    /// @param newMaximumMultiplierBp Must be ≥ `minimumMultiplierBp` when that is non-zero.
    function setMaximumMultiplierBp(uint32 newMaximumMultiplierBp) external onlyRole(WORKER_ROLE) {
        if (minimumMultiplierBp > 0 && newMaximumMultiplierBp < minimumMultiplierBp) {
            revert InvalidPayoutMultiplier();
        }
        maximumMultiplierBp = newMaximumMultiplierBp;
        emit MaximumMultiplierBpSet(newMaximumMultiplierBp);
    }

    /// @notice Sets referrer share of protocol fee revenue (BP).
    /// @param newProtocolFeeRevenueShareBp Value in `[0, BP_DENOMINATOR]`.
    function setProtocolFeeRevenueShareBp(uint16 newProtocolFeeRevenueShareBp) external onlyRole(WORKER_ROLE) {
        if (newProtocolFeeRevenueShareBp > BP_DENOMINATOR) revert InvalidProtocolFeeRevenueShare();
        protocolFeeRevenueShareBp = newProtocolFeeRevenueShareBp;
        emit ProtocolFeeRevenueShareBpSet(newProtocolFeeRevenueShareBp);
    }

    /// @notice Sets the per-tx ticket cap for this manager.
    /// @dev Accepts values in `[1, HARD_MAX_TICKETS_PER_TX]`.  Zero is rejected to prevent
    ///      accidentally disabling all purchases; values above the compile-time ceiling
    ///      are rejected unconditionally — no role can bypass the constant.
    /// @param newTicketLimit New cap (1–100 inclusive).
    function setTicketLimit(uint8 newTicketLimit) external onlyRole(WORKER_ROLE) {
        if (newTicketLimit == 0 || newTicketLimit > HARD_MAX_TICKETS_PER_TX) revert InvalidTicketLimit();
        ticketLimit = newTicketLimit;
        emit TicketLimitSet(newTicketLimit);
    }

    /* ─────────────────────────── Payout hooks ───────────────────────────── */

    /// @notice Computes winner slot count for `lotteryId` at a given tickets-sold snapshot.
    /// @dev When exactly one ticket is sold, all payout models yield a single winner who may
    ///      claim the entire `prizePool` (including pre-draw donations) in one claim.
    ///      MULTIPLIER uses `min(K, sold)` to prevent duplicate winner slots when K > soldTickets;
    ///      WIN_RATE min 1 when sold > 0 and rate > 0; TIER uses `min(tiers.length, sold)`.
    ///      Body lives in `LotteryCoreLib.winnerCount`, shared with `LotteryWinnerReader`.
    function _winnerCount(uint256 _lotteryId, uint256 _sold) private view returns (uint24) {
        return LotteryCoreLib.winnerCount(_lotteries, _state, _lTiers, _lotteryId, _sold);
    }

    /// @notice Number of claimable winner slots for `lotteryId` at current ticket sales.
    function _countWinners(uint256 _lotteryId) internal view virtual returns (uint24) {
        return _winnerCount(_lotteryId, _sold(_lotteryId));
    }

    /// @notice MULTIPLIER prize for one winner slot; respects the single-ticket full-pool rule.
    /// @dev Uses `min(K, soldTickets)` as the effective winner count so that prize distribution
    ///      is consistent with `_winnerCount` — prevents unclaimed funds when K > soldTickets.
    ///
    ///      Retained for duel mocks that override `_calcPrize` and call this directly. The
    ///      production managers reach the same math through `LotteryCoreLib.calcPrize`, so the
    ///      optimizer drops this from their runtime bytecode.
    function _calcMultiplierPrizeForLottery(
        uint256 _lotteryId,
        uint24 _winnerIndex,
        uint256 _sold
    ) internal view returns (uint256) {
        if (_sold == 1) return _state[_lotteryId].prizePool;
        LotteryStored storage lot = _lotteries[_lotteryId];
        uint256 pool = _state[_lotteryId].prizePool;
        uint24 k = _calcMultiplierWinnerCount(pool, lot.payoutRateBp, lot.ticketPrice);
        uint24 effectiveWinners = (k < uint24(_sold)) ? k : uint24(_sold);
        if (effectiveWinners == 0) return 0;
        if (effectiveWinners == 1) return pool;
        uint256 perWinner = pool / effectiveWinners;
        return (_winnerIndex == 0) ? perWinner + (pool % effectiveWinners) : perWinner;
    }

    /// @notice Prize amount for a 0-based winner index after the draw.
    /// @dev Uses frozen `LotteryState.prizePool` and model-specific rules.
    ///      `sold` is the caller-cached tickets-sold count, avoiding repeated `_sold` reads
    ///      when claiming multiple winner slots in one transaction.
    ///      Body lives in `LotteryCoreLib.calcPrize`, shared with `LotteryWinnerReader`, so
    ///      claimed and displayed amounts cannot diverge.
    function _calcPrize(
        uint256 _lotteryId,
        uint24 _winnerIndex,
        uint256 _sold
    ) internal view virtual returns (uint256) {
        return LotteryCoreLib.calcPrize(_lotteries, _state, _lTiers, _lotteryId, _winnerIndex, _sold);
    }

    /* ─────────────────────────── Hub entry points (virtual) ─────────────── */

    /// @notice Initialises lottery-type-specific state after the Hub assigns `lotteryId`.
    /// @dev Concrete implementations must apply `onlyHub`. Typically calls `_initLottery` then
    ///      stores model-specific fields (tiers, feeder link, etc.).
    function createLotteryFromHub(
        uint256 lotteryId,
        address originalCaller,
        LotteryKind kind,
        PayoutModel payoutModel,
        LotteryParams calldata params,
        bytes calldata extraData
    ) external virtual;

    /// @notice Off-chain quote for a ticket purchase (no state change).
    /// @dev Hub calls this before transferring tokens; concrete creators split fees/pool.
    function quoteTicketPurchase(
        uint256 lotteryId,
        uint256 qty,
        address referrer
    ) external view virtual returns (TicketPurchaseQuote memory);

    /// @notice Records a purchase after the Hub transferred tokens (no transfers here).
    /// @param lotteryId        Target lottery.
    /// @param qty              Ticket count.
    /// @param ticketRecipient  Ticket owner (may differ from payer).
    /// @param originalCaller   End user forwarded by the Hub.
    /// @param referrer         Referrer for fee sharing, if any.
    /// @param quote            Prior `quoteTicketPurchase` result.
    function registerTicketPurchase(
        uint256 lotteryId,
        uint256 qty,
        address ticketRecipient,
        address originalCaller,
        address referrer,
        TicketPurchaseQuote calldata quote
    ) external virtual;

    /* ─────────────────────────── Draw (public) ──────────────────────────── */

    /// @notice Requests a VRF draw when the lottery is ready and more than one ticket was sold.
    /// @dev **Hub path:** Hub passes `msg.sender` as `payer`. **Direct path:** caller must pass
    ///      `payer == msg.sender`. ETH refunds (overpay or single-ticket instant draw) are credited
    ///      to `payer` in `RndConsumer` (`pendingRefunds`, pulled via `withdrawRefund`); no ETH is
    ///      sent to `payer` during the draw.
    /// @dev **Retry:** if a prior request timed out without a seed, calling this again after the
    ///      `drawDeadline` re-issues the VRF request. It reverts before the deadline
    ///      (`DrawDeadlineNotReached`) or once a seed was delivered (`SeedAlreadyAdded`).
    /// @param lotteryId Target lottery.
    /// @param payer     Originating user; credited with any ETH refund in `RndConsumer`.
    function requestDraw(uint256 lotteryId, address payer) external payable nonReentrant {
        if (!hasRole(HUB_ROLE, msg.sender) && payer != msg.sender) revert InvalidPayer();
        _requestDrawBase(lotteryId, payer);
    }

    /* ─────────────────────────── Donations ───────────────────────────────── */

    /// @notice Validates that a donation is allowed and returns the asset, without writing
    ///         accounting.  The Hub calls this before the token transfer so it can measure the
    ///         actual received amount via a before/after `balanceOf` snapshot and then record it
    ///         via `recordDonationFor`.
    /// @dev **Caller:** Hub only (`HUB_ROLE`).
    ///      No local reentrancy guard: Hub-only entrypoint and the Hub's `donate` is guarded.
    /// @param lotteryId Target lottery.
    /// @param amount    Intended donation amount (used only for the zero-check; not stored here).
    /// @return asset    ERC-20 accepted for donations to `lotteryId`.
    function getDonationAsset(uint256 lotteryId, uint256 amount) external view returns (address asset, bool allowed) {
        if (amount == 0) revert ZeroAmount();
        return (_donationAsset(lotteryId), _checkDonateAllowed(lotteryId));
    }

    /// @notice Records the accounting for a Hub-routed donation after the Hub has measured the
    ///         actual received amount via a before/after `balanceOf` snapshot.
    /// @dev **Caller:** Hub only (`HUB_ROLE`), after `openHubSettlement`. Emits `Donated`.
    ///      Closes the Hub settlement as its last step.
    /// @param lotteryId     Target lottery.
    /// @param donor         Address credited as donor.
    /// @param actualReceived Tokens actually received (Hub-measured balance delta).
    function recordDonationFor(
        uint256 lotteryId,
        address donor,
        uint256 actualReceived
    ) external onlyHub nonReentrant {
        if (!_checkDonateAllowed(lotteryId)) revert ProhibitedDonation();
        _recordDonation(lotteryId, donor, actualReceived);
        _closeHubSettlement();
    }

    /// @notice Opens the Hub settlement before a Hub transfers tokens to this manager.
    /// @dev **Caller:** Hub only (`HUB_ROLE`). Reverts `ReentrancyGuardReentrantCall` while any
    ///      Hub's settlement is in flight on this manager. Closed by `recordDonationFor` /
    ///      `registerTicketPurchase` once all accounting is written.
    function openHubSettlement() external onlyHub {
        if (_hubSettlement == 2) revert ReentrancyGuardReentrantCall();
        _hubSettlement = 2;
    }

    /// @dev Must be the last statement of every Hub-routed accounting path.
    function _closeHubSettlement() internal {
        if (_hubSettlement != 2) revert ReentrancyGuardReentrantCall();
        _hubSettlement = 1;
    }

    /// @notice Withdraws the caller's pre-draw donation (direct path).
    /// @param lotteryId Target lottery.
    function withdrawDonation(uint256 lotteryId) external nonReentrant {
        _checkWithdrawDonationAllowed(lotteryId);
        _executeDonationWithdrawal(lotteryId, msg.sender);
    }

    /// @notice Hub-routed donation withdrawal; transfers asset directly to `donor`.
    /// @dev **Caller:** Hub only (`HUB_ROLE`). Hub passes original `msg.sender` as `donor`.
    ///      No local reentrancy guard: Hub-only entrypoint and the Hub's `withdrawDonation` is guarded.
    /// @param lotteryId Target lottery.
    /// @param donor     Address whose donation is cleared and refunded.
    function withdrawDonationFor(uint256 lotteryId, address donor) external onlyHub {
        _checkWithdrawDonationAllowed(lotteryId);
        _executeDonationWithdrawal(lotteryId, donor);
    }

    /// @notice Returns a donor's outstanding credited donation for `lotteryId`.
    /// @param lotteryId Lottery ID.
    /// @param donor     Donor address.
    /// @return          Amount still credited (before withdraw or draw).
    function donationOf(uint256 lotteryId, address donor) external view returns (uint256) {
        return _donations[lotteryId][donor];
    }

    /* ─────────────────────────── Donation internals ─────────────────────── */

    function _checkDonateAllowed(uint256 _lotteryId) private view returns (bool allowed) {
        LotteryStatus live = _getLotteryStatus(_lotteryId);
        return
            live != LotteryStatus.NONE &&
            live != LotteryStatus.CANCELLED &&
            live != LotteryStatus.DRAW_REQUESTED &&
            live != LotteryStatus.DRAW_COMPLETED &&
            live != LotteryStatus.FULLY_CLAIMED;
    }

    function _checkWithdrawDonationAllowed(uint256 _lotteryId) private view {
        if (_getLotteryStatus(_lotteryId) != LotteryStatus.CANCELLED)
            revert DonationWithdrawalNotAllowed();
    }

    function _recordDonation(uint256 _lotteryId, address _donor, uint256 _amount) internal virtual {
        _donations[_lotteryId][_donor] += _amount;
        _state[_lotteryId].prizePool += _amount;
        emit Donated(_lotteryId, _donor, _amount);
    }

    function _executeDonationWithdrawal(uint256 _lotteryId, address _donor) internal virtual {
        uint256 amount = _donations[_lotteryId][_donor];
        if (amount == 0) revert NoDonation();
        _donations[_lotteryId][_donor] = 0;
        _state[_lotteryId].prizePool -= amount;
        IERC20(_donationAsset(_lotteryId)).safeTransfer(_donor, amount);
        emit DonationWithdrawn(_lotteryId, _donor, amount);
    }

    /* ─────────────────────────── Prize claims ───────────────────────────── */

    /// @notice Claims one winner slot for `claimer`.
    /// @dev Hub proxy sets `claimer` to the end user; direct calls require `claimer == msg.sender`
    ///      unless caller has `HUB_ROLE`.
    /// @param lotteryId   Lottery ID.
    /// @param winnerIndex 0-based winner ordinal.
    /// @param claimer     Recipient of the prize transfer.
    function claimPrize(uint256 lotteryId, uint24 winnerIndex, address claimer) external nonReentrant {
        _assertClaimer(claimer);
        _claimPrizeBase(lotteryId, winnerIndex, claimer);
    }

    /// @notice Claims multiple winner slots in one transaction.
    /// @param lotteryId      Lottery ID.
    /// @param winnerIndices  0-based winner ordinals (non-empty).
    /// @param claimer        Prize recipient.
    /// @return totalAmount   Sum of prizes transferred in this batch.
    function claimPrizeBatch(
        uint256 lotteryId,
        uint24[] calldata winnerIndices,
        address claimer
    ) external nonReentrant returns (uint256 totalAmount) {
        _assertClaimer(claimer);

        uint256 len = winnerIndices.length;
        if (len == 0) revert InvalidWinnerIndex();

        LotteryState storage s = _state[lotteryId];
        if (s.status != LotteryStatus.DRAW_COMPLETED && s.status != LotteryStatus.FULLY_CLAIMED)
            revert DrawNotCompleted();

        uint24 winnerCount = _countWinners(lotteryId);
        uint24 sold = uint24(_sold(lotteryId));

        for (uint256 i = 0; i < len; ) {
            totalAmount += _processWinnerSlot(s, lotteryId, winnerIndices[i], winnerCount, sold, claimer);
            // prettier-ignore
            unchecked { ++i; }
        }

        _finalizeClaim(lotteryId, s, claimer, totalAmount);
        emit PrizeClaimedBatch(lotteryId, claimer, totalAmount, winnerIndices);
        return totalAmount;
    }

    /* ─────────────────────────── Views ───────────────────────────────────── */

    /// @notice Effective lifecycle status including time-based and claim exhaustion rules.
    /// @param lotteryId Lottery ID.
    /// @return          Current `LotteryStatus` (may differ from stored status near boundaries).
    function getLotteryStatus(uint256 lotteryId) external view returns (LotteryStatus) {
        return _getLotteryStatus(lotteryId);
    }

    /// @notice Owner of a 1-based ticket ID.
    /// @param lotteryId Lottery ID.
    /// @param ticketId  1-based ticket ID.
    /// @return          Owner address.
    function ticketOwner(uint256 lotteryId, uint256 ticketId) external view returns (address) {
        return ownerOf(lotteryId, ticketId);
    }

    /// @notice Returns the current draw generation for `lotteryId`.
    /// @dev Called by `RndConsumer.fulfillRandomWords` to detect stale VRF callbacks. The generation
    ///      is incremented on every new VRF request (first draw or retry),
    ///      so any pending callback whose stored generation differs from this value is stale and
    ///      must not be forwarded. Implements `ILotteryRandomnessConsumer.drawGeneration`.
    ///      Returns `0` when no draw has ever been requested for this lottery.
    /// @param lotteryId Lottery to query.
    /// @return generation Current `LotteryState.drawGeneration`.
    function drawGeneration(uint256 lotteryId) external view returns (uint32 generation) {
        return _state[lotteryId].drawGeneration;
    }

    /// @notice Static lottery configuration.
    /// @dev Unpacks the internal `LotteryStored` layout into the ABI-facing `Lottery` shape,
    ///      so external integrations see the same return type as before packing.
    /// @param lotteryId Lottery ID.
    /// @return          `Lottery` struct copy.
    function getLottery(uint256 lotteryId) external view returns (Lottery memory) {
        LotteryStored storage lot = _lotteries[lotteryId];
        return
            Lottery({
                creator: lot.creator,
                kind: lot.kind,
                model: lot.model,
                params: LotteryParams({
                    ticketPrice: lot.ticketPrice,
                    asset: lot.asset,
                    feeBp: lot.feeBp,
                    maxTickets: lot.maxTickets,
                    startTime: lot.startTime,
                    endTime: lot.endTime
                }),
                payoutRateBp: lot.payoutRateBp,
                cltAmountPerTicket: lot.cltAmountPerTicket,
                feederSuperLotteryId: lot.feederSuperLotteryId,
                feederAllocBp: lot.feederAllocBp
            });
    }

    /// @notice Runtime lottery state snapshot for off-chain reads.
    /// @param lotteryId Lottery ID.
    /// @return view_    Effective status, draw fields, and prize pool accounting.
    function getLotteryStateView(uint256 lotteryId) external view returns (LotteryStateView memory view_) {
        LotteryState storage s = _state[lotteryId];
        view_.status = _getLotteryStatus(lotteryId);
        view_.drawDeadline = s.drawDeadline;
        view_.drawGeneration = s.drawGeneration;
        view_.seed = s.seed;
        view_.creatorFees = s.creatorFees;
        view_.prizePool = s.prizePool;
        view_.claimedPrizePool = s.claimedPrizePool;
        view_.currentPrizePool = s.prizePool - s.claimedPrizePool;
    }

    /// @notice Total tickets sold for `lotteryId`.
    /// @param lotteryId Lottery ID.
    /// @return          Ticket count.
    function totalTicketsSold(uint256 lotteryId) external view returns (uint256) {
        return _sold(lotteryId);
    }

    /// @notice Returns the number of winner slots for `lotteryId` under its payout model.
    /// @dev Uses current tickets sold and prize pool; MULTIPLIER count grows with donations.
    function countWinners(uint256 lotteryId) external view returns (uint256) {
        return _winnerCount(lotteryId, _sold(lotteryId));
    }

    /// @notice Prize pool accounting snapshot.
    /// @dev `totalPrizePool` is the frozen pool at draw; claims increment `claimedPrizePool` only.
    /// @param lotteryId Lottery ID.
    /// @return claimedPrizePool   Sum paid to winners so far.
    /// @return unclaimedPrizePool `totalPrizePool - claimedPrizePool`.
    /// @return totalPrizePool     Full pool used for winner math.
    function getPrizePool(
        uint256 lotteryId
    ) external view returns (uint256 claimedPrizePool, uint256 unclaimedPrizePool, uint256 totalPrizePool) {
        LotteryState storage s = _state[lotteryId];
        totalPrizePool = s.prizePool;
        claimedPrizePool = s.claimedPrizePool;
        unclaimedPrizePool = totalPrizePool - claimedPrizePool;
    }

    /// @notice Raw claim-bitmap word covering winner slots `[wordIndex * 256, wordIndex * 256 + 255]`.
    /// @dev The one claim-bitmap primitive that cannot be synthesised from the other public
    ///      getters, so `LotteryWinnerReader` depends on it. Winner lists themselves are served
    ///      by that reader via `LotteryHub`, not from the manager.
    ///
    ///      Returns a whole word rather than a single flag so that paginating a winner list
    ///      costs one call per 256 slots instead of one per slot. Bit `n` of the result is the
    ///      claim flag for winner slot `wordIndex * 256 + n`. Unwritten words read as zero, so
    ///      an out-of-range `wordIndex` reports every slot as unclaimed.
    /// @param lotteryId Lottery to query.
    /// @param wordIndex 0-based bitmap word index (`winnerIndex >> 8`).
    function claimedWord(uint256 lotteryId, uint256 wordIndex) external view returns (uint256) {
        return _state[lotteryId].claimedWords[wordIndex];
    }

    /* ─────────────────────────── VRF callback ───────────────────────────── */

    /// @inheritdoc ILotteryRandomnessConsumer
    /// @notice Called by RndConsumer with the VRF seed; transitions to `DRAW_COMPLETED`.
    /// @dev Not `nonReentrant`: a valid fulfillment relayed from a callback that runs under the
    ///      manager lock (token transfer hooks in claims or donation withdrawal) must still land.
    ///      Safe only while `_fulfillRandomnessBase` and its full call chain make no external call;
    ///      adding one requires restoring a guard.
    function fulfillRandomness(
        uint256 lotteryId,
        uint256 seed
    ) external override onlyRole(RANDOMNESS_COORDINATOR_ROLE) {
        _fulfillRandomnessBase(lotteryId, seed);
    }

    /* ─────────────────────────── Internal — lifecycle ─────────────────────── */

    /// @dev Writes the packed `LotteryStored` + initial `LotteryState` and sets ticket index to `1`.
    ///      Stores `effectiveStart` (= max(params.startTime, block.timestamp)) as the lottery's
    ///      `startTime` so that storage is consistent with the duration validated in `_checkBase`.
    ///      Narrowing casts are safe: `_checkBase` (always executed before this) bounds
    ///      `ticketPrice` to uint128, `feeBp` to `BP_DENOMINATOR`, timestamps to uint40,
    ///      and `maxTickets` to uint24.
    function _initLottery(
        uint256 _lotteryId,
        LotteryKind _kind,
        PayoutModel _model,
        address _creator,
        LotteryParams calldata _params
    ) internal {
        // Write-once invariant: a lottery ID may be initialized exactly once.
        // `_state[id].status` is NONE (0) by default for any slot never written by this function.
        // The same slot is written below, so this read costs no additional cold SLOAD.
        if (_state[_lotteryId].status != LotteryStatus.NONE) revert LotteryAlreadyExists();

        uint64 nowTs = uint64(block.timestamp);
        uint64 effectiveStart = _params.startTime < nowTs ? nowTs : _params.startTime;

        LotteryStored storage lot = _lotteries[_lotteryId];
        lot.creator = _creator;
        lot.kind = _kind;
        lot.model = _model;
        lot.feeBp = uint16(_params.feeBp);
        lot.maxTickets = _params.maxTickets;
        lot.asset = _params.asset;
        lot.startTime = uint40(effectiveStart);
        lot.endTime = uint40(_params.endTime);
        lot.ticketPrice = uint128(_params.ticketPrice);

        LotteryState storage s = _state[_lotteryId];
        s.status = block.timestamp >= _params.startTime ? LotteryStatus.ACTIVE : LotteryStatus.PENDING;

        _lotteryIndex[_lotteryId] = 1;

        emit LotteryStatusUpdated(_lotteryId, s.status);
    }

    /// @dev Reverts unless quantity, timing, status, and capacity allow a purchase.
    /// @return sold       Tickets already sold (reused by the caller to avoid a second SLOAD).
    /// @return maxTickets Sale cap (reused by the caller to avoid a second SLOAD).
    function _validatePurchase(
        uint256 _lotteryId,
        uint256 _qty
    ) internal view returns (uint256 sold, uint256 maxTickets) {
        if (_qty == 0) revert InvalidQuantity();

        LotteryStatus status = _getLotteryStatus(_lotteryId);
        if (status == LotteryStatus.PENDING) revert LotteryNotStartedYet();
        if (status != LotteryStatus.ACTIVE && status != LotteryStatus.READY_TO_DRAW) revert LotteryNotActive();
        LotteryStored storage lot = _lotteries[_lotteryId];
        if (block.timestamp > lot.endTime) revert LotteryEnded();
        sold = _sold(_lotteryId);
        maxTickets = lot.maxTickets;
        uint256 remaining = maxTickets - sold;
        if (_qty > ticketLimit) revert ExceedsBatchLimit(ticketLimit);
        if (_qty > remaining) revert ExceedsMaxTickets(remaining);
    }

    /// @dev Validates core `LotteryParams` shared by all creator types.
    ///      Also enforces the packed-storage bounds required by `LotteryStored`
    ///      (uint128 price, uint40 timestamps, uint16 feeBp) so `_initLottery` casts are safe.
    function _checkBase(LotteryParams calldata _params, uint64 _maxDuration) internal view {
        if (_params.asset == address(0)) revert ZeroAddress();
        if (_params.ticketPrice < MIN_TICKET_PRICE) revert InvalidTicketPrice();
        if (_params.ticketPrice > type(uint128).max) revert InvalidTicketPrice();
        if (_params.feeBp > BP_DENOMINATOR) revert InvalidBp();
        if (_params.maxTickets == 0) revert InvalidMaxTickets();
        if (_params.maxTickets > type(uint24).max) revert InvalidMaxTickets();
        uint64 nowTs = uint64(block.timestamp);
        uint64 effectiveStart = _params.startTime < nowTs ? nowTs : _params.startTime;
        if (effectiveStart >= _params.endTime) revert InvalidTimeRange();
        if (_params.endTime > type(uint40).max) revert InvalidTimeRange();
        if (_maxDuration > 0 && _params.endTime - effectiveStart > _maxDuration) revert ExceedsMaxDuration();
    }

    /// @dev Validates multiplier BP against `minimumMultiplierBp` / `maximumMultiplierBp` when set.
    function _checkMultiplierBp(uint256 _bp) internal view {
        uint256 lo = minimumMultiplierBp;
        uint256 hi = maximumMultiplierBp;
        if (lo > 0 && _bp < lo) revert InvalidPayoutMultiplier();
        if (hi > 0 && _bp > hi) revert InvalidPayoutMultiplier();
    }

    /// @dev Validates win rate BP against configured bounds when non-zero.
    function _checkWinRateBp(uint256 _bp) internal view {
        uint256 lo = minimumWinRateBp;
        uint256 hi = maximumWinRateBp;
        if (lo > 0 && _bp < lo) revert InvalidWinRateBp();
        if (hi > 0 && _bp > hi) revert InvalidWinRateBp();
    }

    /// @dev Requires non-empty tier list within `maximumTiers` when configured.
    function _checkTiersLength(uint256 _tiersLength) internal view {
        if (_tiersLength == 0) revert TooManyTiers(_tiersLength);
        uint256 cap = maximumTiers;
        if (cap > 0 && _tiersLength > cap) revert TooManyTiers(_tiersLength);
    }

    /// @dev Sets READY_TO_DRAW when sold out; promotes PENDING → ACTIVE on first purchase after start.
    function _updateStatusAfterPurchase(
        uint256 _lotteryId,
        uint256 _soldBefore,
        uint256 _qty,
        uint256 _maxTickets
    ) internal {
        LotteryState storage s = _state[_lotteryId];
        if (_soldBefore + _qty == _maxTickets) {
            s.status = LotteryStatus.READY_TO_DRAW;
            emit LotteryStatusUpdated(_lotteryId, LotteryStatus.READY_TO_DRAW);
        } else if (s.status == LotteryStatus.PENDING) {
            s.status = LotteryStatus.ACTIVE;
            emit LotteryStatusUpdated(_lotteryId, LotteryStatus.ACTIVE);
        }
    }

    /// @dev ERC-20 token used for prize payouts; default is ticket payment asset.
    function _prizeAsset(uint256 _lotteryId) internal view virtual returns (address) {
        return _lotteries[_lotteryId].asset;
    }

    /// @dev Writes the packed `payoutRateBp`; bounds-checks the uint32 narrowing.
    function _setPayoutRateBp(uint256 _lotteryId, uint256 _bp) internal {
        if (_bp > type(uint32).max) revert InvalidBp();
        _lotteries[_lotteryId].payoutRateBp = uint32(_bp);
    }

    /// @dev Writes the packed `cltAmountPerTicket`; bounds-checks the uint96 narrowing.
    function _setCltAmountPerTicket(uint256 _lotteryId, uint256 _amount) internal {
        if (_amount > type(uint96).max) revert InvalidCltTicketReward();
        _lotteries[_lotteryId].cltAmountPerTicket = uint96(_amount);
    }

    /// @dev ERC-20 token accepted for prize-pool donations; default matches `_prizeAsset`.
    function _donationAsset(uint256 _lotteryId) internal view virtual returns (address) {
        return _prizeAsset(_lotteryId);
    }

    /// @notice Returns the ERC-20 token that must be used to donate to `lotteryId`.
    function getDonationAsset(uint256 lotteryId) external view returns (address) {
        return _donationAsset(lotteryId);
    }

    /// @dev Mints tickets and updates status; caller must have completed payment accounting.
    function _executeTicketPurchase(uint256 _lotteryId, uint256 _qty, address _ticketRecipient) internal {
        (uint256 sold, uint256 maxTix) = _validatePurchase(_lotteryId, _qty);
        _mintTix(_lotteryId, _qty, _ticketRecipient);
        _updateStatusAfterPurchase(_lotteryId, sold, _qty, maxTix);
    }

    /* ─────────────────────────── Internal — draw ──────────────────────────── */

    /// @dev Starts draw: instant fulfill if one ticket sold; else VRF request + deadline.
    /// @dev Re-entry after a timed-out VRF request (status still `DRAW_REQUESTED`, no seed,
    ///      deadline passed) issues a fresh request and extends the deadline.
    /// @dev `payer` is credited in `RndConsumer` with excess ETH and the full refund on single-ticket draws.
    function _requestDrawBase(uint256 _lotteryId, address _payer) internal {
        LotteryState storage s = _state[_lotteryId];

        if (s.status == LotteryStatus.DRAW_REQUESTED) {
            // Retry path: a prior VRF request timed out without delivering a seed.
            if (s.seed != 0) revert SeedAlreadyAdded();
            if (block.timestamp <= s.drawDeadline) revert DrawDeadlineNotReached();

            s.drawDeadline = uint64(block.timestamp + VRF_TIMEOUT);
            // Increment generation so any pending callback for the old generation is stale.
            s.drawGeneration++;
            uint256 retryRequestId = rndCoordinator.requestRandomness{value: msg.value}(
                _lotteryId, s.drawGeneration, _payer
            );
            emit DrawRequested(_lotteryId, retryRequestId);
            return;
        }

        LotteryStatus live = _getLotteryStatus(_lotteryId);

        if (live != LotteryStatus.READY_TO_DRAW) revert NotReadyToDraw();

        uint256 sold = _sold(_lotteryId);
        if (sold == 0) revert NoTicketsSold();

        if (sold == 1) {
            // Single-ticket lotteries skip VRF: the sole ticket holder is the guaranteed winner.
            // Seed 1 is a deterministic sentinel; see LotteryPrizeLib.winningTicketIndexInternal
            // which returns index 0 immediately when sold == 1, making the seed irrelevant.
            s.status = LotteryStatus.DRAW_REQUESTED;
            emit LotteryStatusUpdated(_lotteryId, LotteryStatus.DRAW_REQUESTED);
            _fulfillRandomnessBase(_lotteryId, 1);
            if (msg.value > 0) rndCoordinator.creditRefund{value: msg.value}(_payer);
            return;
        }

        s.status = LotteryStatus.DRAW_REQUESTED;
        s.drawDeadline = uint64(block.timestamp + VRF_TIMEOUT);
        // Increment generation on every new VRF request so callbacks from superseded
        // requests, including those left on a rotated-away coordinator, are detected as stale.
        s.drawGeneration++;
        emit LotteryStatusUpdated(_lotteryId, LotteryStatus.DRAW_REQUESTED);

        uint256 requestId = rndCoordinator.requestRandomness{value: msg.value}(
            _lotteryId, s.drawGeneration, _payer
        );

        emit DrawRequested(_lotteryId, requestId);
    }

    /// @dev Persists seed and moves to `DRAW_COMPLETED`.
    ///      This function and its full call chain must make no external call
    ///      (no token transfer, rewarder, feeder, coordinator or Hub call, no hook). It is reachable
    ///      from the unguarded `fulfillRandomness` while another function holds the manager lock.
    function _fulfillRandomnessBase(uint256 lotteryId, uint256 seed) internal {
        LotteryState storage s = _state[lotteryId];
        if (s.status != LotteryStatus.DRAW_REQUESTED) revert DrawNotRequested();
        if (s.seed != 0) revert SeedAlreadyAdded();

        s.seed = seed;
        s.status = LotteryStatus.DRAW_COMPLETED;

        emit LotteryStatusUpdated(lotteryId, LotteryStatus.DRAW_COMPLETED);
        emit DrawCompleted(lotteryId, seed);
    }

    /* ─────────────────────────── Internal — claims ────────────────────────── */

    /// @dev Single-slot claim: validate, mark bitmap, transfer prize.
    function _claimPrizeBase(uint256 _lotteryId, uint24 _winnerIndex, address _claimer) internal {
        LotteryState storage s = _state[_lotteryId];
        if (s.status != LotteryStatus.DRAW_COMPLETED && s.status != LotteryStatus.FULLY_CLAIMED)
            revert DrawNotCompleted();

        uint24 winnerCount = _countWinners(_lotteryId);
        uint24 sold = uint24(_sold(_lotteryId));

        uint256 prize = _processWinnerSlot(s, _lotteryId, _winnerIndex, winnerCount, sold, _claimer);
        _finalizeClaim(_lotteryId, s, _claimer, prize);

        emit PrizeClaimed(_lotteryId, _winnerIndex, _claimer, prize);
    }

    /// @dev Hub may claim on behalf of `claimer`; otherwise `claimer` must be `msg.sender`.
    function _assertClaimer(address _claimer) internal view {
        if (!hasRole(HUB_ROLE, msg.sender)) {
            if (_claimer != msg.sender) revert InvalidClaimer();
        }
    }

    /// @dev Marks winner slot claimed, verifies ticket ownership, returns prize amount.
    function _processWinnerSlot(
        LotteryState storage _s,
        uint256 _lotteryId,
        uint24 _wi,
        uint24 _winnerSlotCount,
        uint24 _sold,
        address _claimer
    ) internal returns (uint256) {
        if (_wi >= _winnerSlotCount) revert InvalidWinnerIndex();

        uint256 _wordIndex = uint256(_wi) >> 8;
        uint256 _bitIndex = uint256(_wi) & 255;
        uint256 word = _s.claimedWords[_wordIndex];
        if ((word >> _bitIndex) & 1 != 0) revert PrizeAlreadyClaimed();
        _s.claimedWords[_wordIndex] = word | (1 << _bitIndex);

        uint24 ticketIdx = LotteryPrizeLib.winningTicketIndex(_s.seed, _sold, _wi + 1);
        address owner = ownerOf(_lotteryId, uint256(ticketIdx) + 1);
        if (owner != _claimer) revert NotWinner();

        return _calcPrize(_lotteryId, _wi, _sold);
    }

    /// @dev Updates claimed pool, may set FULLY_CLAIMED, transfers ERC-20 prize.
    function _finalizeClaim(uint256 _lotteryId, LotteryState storage _s, address _claimer, uint256 _amount) internal {
        _s.claimedPrizePool += _amount;
        if (_s.claimedPrizePool >= _s.prizePool) {
            _s.status = LotteryStatus.FULLY_CLAIMED;
            emit LotteryStatusUpdated(_lotteryId, LotteryStatus.FULLY_CLAIMED);
        }
        if (_amount > 0) {
            IERC20(_prizeAsset(_lotteryId)).safeTransfer(_claimer, _amount);
        }
    }

    /// @dev Resolves effective status: time gates, sold-out, and full claim exhaustion.
    function _getLotteryStatus(uint256 _lotteryId) internal view returns (LotteryStatus) {
        LotteryState storage s = _state[_lotteryId];
        LotteryStatus stored = s.status;

        if (stored == LotteryStatus.NONE) return LotteryStatus.NONE;

        LotteryStored storage lot = _lotteries[_lotteryId];

        if (stored == LotteryStatus.PENDING) {
            // Expiry check first: a PENDING lottery past endTime has zero tickets sold
            // (any purchase would have stored ACTIVE), so it is permanently void.
            if (block.timestamp > lot.endTime) return LotteryStatus.CANCELLED;
            if (block.timestamp >= lot.startTime) return LotteryStatus.ACTIVE;
            return LotteryStatus.PENDING;
        }

        if (stored == LotteryStatus.ACTIVE && block.timestamp > lot.endTime) {
            // Enforce the intended lifecycle invariant: a lottery that expired with zero
            // tickets sold is CANCELLED, not READY_TO_DRAW.  The _sold() read is cold
            // any subsequent _sold() call in the same transaction (e.g. requestDraw).
            return _sold(_lotteryId) == 0 ? LotteryStatus.CANCELLED : LotteryStatus.READY_TO_DRAW;
        }

        if (stored == LotteryStatus.DRAW_COMPLETED) {
            if (s.prizePool > 0 && s.claimedPrizePool >= s.prizePool) {
                return LotteryStatus.FULLY_CLAIMED;
            }
        }

        return stored;
    }
}

contracts/abstract/MultiplierPayoutModel.sol

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

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

/// @title MultiplierPayoutModel
/// @notice Pure math for MULTIPLIER payout lotteries (variable winner count from pool × multiplier).
/// @dev Stateless helper mixed into concrete creators. The multiplier (`payoutRateBp`) is stored
///      on the per-lottery `Lottery` record in `BaseLotteryManager._lotteries`.
///
///      Winner count: K = (prizePool × BP) / (ticketPrice × payoutRateBp), minimum 1 when pool > 0.
///      Prizes: equal split; winner index 0 absorbs integer rounding remainder.
abstract contract MultiplierPayoutModel {
    /// @dev Basis-points denominator (100.00%).
    uint256 private constant BP = 10_000;

    /// @notice Computes how many winning positions exist for a multiplier lottery.
    /// @param _prizePool     Net prize pool after fees (token smallest units).
    /// @param _payoutRateBp  Target payout multiplier in BP (e.g. 15_000 = 1.5× ticket price).
    /// @param _ticketPrice   Per-ticket price (must be > 0).
    /// @return count        Number of winners (≥ 1 when inputs allow a draw; `0` if pool is zero).
    function _calcMultiplierWinnerCount(
        uint256 _prizePool,
        uint256 _payoutRateBp,
        uint256 _ticketPrice
    ) internal pure returns (uint24 count) {
        if (_prizePool == 0 || _ticketPrice == 0 || _payoutRateBp == 0) return 0;
        uint256 denom = _ticketPrice * _payoutRateBp;
        // Saturation check: determine if floor(_prizePool * BP / denom) would exceed uint24.max
        // WITHOUT computing _prizePool * BP (which can overflow uint256 for large prizePool).
        //
        // Condition: floor(p * BP / d) >= 2^24  iff  p * BP >= (uint24.max + 1) * d
        //         => p >= ceil((uint24.max + 1) * d / BP)
        //
        // Safety: (uint24.max + 1) = 2^24 = 16_777_216; denom ≤ uint128.max * uint32.max ≈ 1.46e48
        //         product ≤ 16_777_216 * 1.46e48 ≈ 2.45e55  <<  uint256.max — always safe.
        uint256 satCap = uint256(type(uint24).max) + 1; // 16_777_216
        if (_prizePool >= (satCap * denom + BP - 1) / BP) return type(uint24).max;
        uint256 k = Math.mulDiv(_prizePool, BP, denom);
        count = k == 0 ? 1 : uint24(k);
    }

    /// @notice Computes prize amount and total winner count for one winner index.
    /// @param _prizePool     Net prize pool after fees.
    /// @param _payoutRateBp  Multiplier in BP.
    /// @param _ticketPrice   Per-ticket price.
    /// @param _winnerIndex   0-based winner ordinal.
    /// @return prizeForIndex Prize for `winnerIndex`.
    /// @return winnerCount   Total winning positions.
    function _calcMultiplierPrize(
        uint256 _prizePool,
        uint256 _payoutRateBp,
        uint256 _ticketPrice,
        uint24 _winnerIndex
    ) internal pure returns (uint256 prizeForIndex, uint256 winnerCount) {
        winnerCount = _calcMultiplierWinnerCount(_prizePool, _payoutRateBp, _ticketPrice);
        if (winnerCount == 0) return (0, 0);
        if (winnerCount == 1) return (_prizePool, 1);
        uint256 perWinner = _prizePool / winnerCount;
        prizeForIndex = (_winnerIndex == 0) ? perWinner + (_prizePool % winnerCount) : perWinner;
    }
}

contracts/abstract/ReferrerFeeLedger.sol

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

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

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

/// @title ReferrerFeeLedger
/// @notice Shared ERC-20 referrer fee accounting for all lottery manager types.
/// @dev Inherits `BaseLotteryManager` to access `HUB_ROLE` / `hasRole` for the
///      Hub-proxy claim path. Both `ProtocolLotteryManager` and `UserLotteryManager`
///      inherit this mixin; C3 linearization merges the shared `BaseLotteryManager`
///      base correctly.
///
///      State layout (one storage slot per (referrer, token) pair):
///        `refFees[referrer][token]` — accrued ERC-20 referrer fees; claimed via
///        `claimReferrerFees`. CLT bonuses are tracked separately in `CltRewarder`.
abstract contract ReferrerFeeLedger is BaseLotteryManager {
    using SafeERC20 for IERC20;

    /* ─────────────────────────────────────── State ──────────────────────────── */

    /// @notice Accrued referrer fees: `refFees[referrer][token] → amount`.
    mapping(address referrer => mapping(address token => uint256 amount)) public refFees;

    /* ─────────────────────────────────────── Events ─────────────────────────── */

    /// @notice Emitted when ERC-20 referrer fees are accrued on ticket purchase.
    event ReferrerFeeAdded(
        uint256 indexed lotteryId,
        address indexed referrer,
        address indexed token,
        uint256 amount,
        address buyer
    );

    /// @notice Emitted when referrer fees are claimed.
    event ReferrerFeeClaimed(address indexed referrer, address indexed token, uint256 amount);

    /* ─────────────────────────────────────── Errors ─────────────────────────── */

    /// @notice Thrown when `claimReferrerFees` finds no accrued balance.
    error NoRefFees();

    /// @notice Thrown when a non-Hub caller tries to claim fees for another referrer.
    error InvalidReferrer();

    /* ─────────────────────────────────────── View ────────────────────────────── */

    /// @notice Returns accrued referrer fees for `referrer` in `token`.
    function getReferrerFee(address referrer, address token) external view returns (uint256) {
        return refFees[referrer][token];
    }

    /* ─────────────────────────────────────── Claim ───────────────────────────── */

    /// @notice Pays out all accrued ERC-20 referrer fees to `referrer`.
    /// @dev Hub calls with `referrer == msg.sender` (original caller forwarded).
    ///      Direct callers must match `referrer`.
    function claimReferrerFees(address referrer, address token) external {
        if (!hasRole(HUB_ROLE, msg.sender)) {
            if (referrer != msg.sender) revert InvalidReferrer();
        }

        uint256 amount = refFees[referrer][token];
        if (amount == 0) revert NoRefFees();
        refFees[referrer][token] = 0;
        IERC20(token).safeTransfer(referrer, amount);
        emit ReferrerFeeClaimed(referrer, token, amount);
    }
}

contracts/abstract/TierPayoutModel.sol

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

import {LotteryPrizeLib} from "../libraries/LotteryPrizeLib.sol";

/// @title TierPayoutModel
/// @notice Tier-weight storage and prize math for TIER payout lotteries.
/// @dev Maintains `_lTiers[lotteryId]`, an ordered array of tier weights in basis points.
///      Active winner count = `min(tiers.length, ticketsSold)`. Prizes are proportional to
///      the active tier weights; index 0 absorbs rounding dust when multiple tiers apply.
abstract contract TierPayoutModel {
    /// @dev Tier weights must not exceed 100% in aggregate at creation time.
    uint256 private constant TIER_WEIGHTS_BP_DENOM = 10_000;

    /// @dev Per-lottery tier weight array (BP). Written at creation by the concrete creator.
    mapping(uint256 lotteryId => uint16[] tiers) internal _lTiers;

    /// @notice Thrown when tier weights sum to more than 100% (`10_000` BP).
    /// @param sum Aggregate tier weight in BP.
    error InvalidTierWeightsSum(uint256 sum);

    /// @notice Thrown when the first tier weight is zero, which would allow the
    ///         active-tier sum to be zero and permanently strand the prize pool.
    error ZeroLeadingTierWeight();

    /// @notice Returns the number of tier weights configured for `lotteryId`.
    /// @dev Empty for non-TIER lotteries or unknown IDs.
    function countTiers(uint256 lotteryId) external view returns (uint256) {
        return _lTiers[lotteryId].length;
    }

    /// @notice Returns all tier weights (basis points) for `lotteryId`.
    /// @dev Bounded by `MAX_TIER_LENGTH` (100) at creation. Empty array if not a TIER lottery.
    function getLotteryTiers(uint256 lotteryId) external view returns (uint16[] memory) {
        return _lTiers[lotteryId];
    }

    /// @notice Persists tier weights for a lottery at creation time.
    /// @dev Sum of all tier weights must be `<= 10_000` BP. Among active tiers at draw time,
    ///      prizes are proportional to each weight relative to the active subset.
    /// @param _lotteryId Target lottery.
    /// @param _tiers     Non-empty tier weight array in BP.
    function _storeTiers(uint256 _lotteryId, uint16[] memory _tiers) internal {
        if (_tiers[0] == 0) revert ZeroLeadingTierWeight();
        uint256 len = _tiers.length;
        uint256 sum;
        for (uint256 i; i < len; ) {
            sum += uint256(_tiers[i]);
            // prettier-ignore
            unchecked { ++i; }
        }
        if (sum != TIER_WEIGHTS_BP_DENOM) revert InvalidTierWeightsSum(sum);
        _lTiers[_lotteryId] = _tiers;
    }

    /// @notice Returns the prize for one winner index under tier-proportional distribution.
    /// @param _lotteryId      Lottery ID.
    /// @param _winnerIndex    0-based winner ordinal.
    /// @param _prizePool      Net prize pool at draw time.
    /// @param _actualWinners  Active winners: `min(tiers.length, ticketsSold)`.
    /// @return amount        Prize in token smallest units.
    function _calcTierPrize(
        uint256 _lotteryId,
        uint24 _winnerIndex,
        uint256 _prizePool,
        uint24 _actualWinners
    ) internal view returns (uint256 amount) {
        amount = LotteryPrizeLib.prizeForTierProportionalFromStorage(
            _prizePool,
            _lTiers[_lotteryId],
            _actualWinners,
            _winnerIndex
        );
    }

    /// @notice Returns the number of winning positions for a tier lottery.
    /// @param lotteryId   Lottery ID.
    /// @param ticketsSold Total tickets sold.
    /// @return count      `min(tiers.length, ticketsSold)`.
    function _tierWinnerCount(uint256 lotteryId, uint256 ticketsSold) internal view returns (uint24 count) {
        uint256 tierCount = _lTiers[lotteryId].length;
        count = uint24(tierCount < ticketsSold ? tierCount : ticketsSold);
    }
}

contracts/abstract/WinRatePayoutModel.sol

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

/// @title WinRatePayoutModel
/// @notice Pure math for WIN_RATE payout lotteries (fixed fraction of tickets win, equal split).
/// @dev Stateless helper mixed into concrete creators. `winRateBp` is stored on the
///      per-lottery `Lottery` record. Winner ticket indices use `LotteryPrizeLib` affine mapping.
abstract contract WinRatePayoutModel {
    /// @dev Basis-points denominator (100.00%).
    uint256 private constant BP_DENOMINATOR = 10_000;

    /// @notice Computes the number of winners from tickets sold and win rate.
    /// @param totalTickets Total tickets sold.
    /// @param winRateBp    Fraction of tickets that win (e.g. 1_000 = 10%).
    /// @return count        Winner count; at least 1 when `totalTickets > 0`.
    function _calcWinnerCount(
        uint256 totalTickets,
        uint256 winRateBp
    ) internal pure returns (uint256 count) {
        if (totalTickets == 0) return 0;
        count = (totalTickets * winRateBp) / BP_DENOMINATOR;
        if (count == 0) count = 1;
    }

    /// @notice Splits the prize pool equally across `winnerCount` winners.
    /// @param prizePool    Net prize pool.
    /// @param winnerCount  Number of winners (must be > 0).
    /// @return perWinner   Base share per winner.
    /// @return dust        Remainder assigned to winner index 0.
    function _calcWinRatePrizePerWinner(
        uint256 prizePool,
        uint256 winnerCount
    ) internal pure returns (uint256 perWinner, uint256 dust) {
        perWinner = prizePool / winnerCount;
        dust = prizePool - (perWinner * winnerCount);
    }
}

contracts/interfaces/IRandomnessCoordinatorLike.sol

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

import {IVRFV2PlusWrapper} from "@chainlink/contracts/src/v0.8/vrf/dev/interfaces/IVRFV2PlusWrapper.sol";

/// @title IRandomnessCoordinatorLike
/// @notice Chainlink VRF v2.5 coordinator API implemented by `RndConsumer`.
/// @dev Lottery **creator** contracts register as consumers and call `requestRandomness` during
///      `requestDraw` (including its post-timeout retry). Fulfillment is delivered to the requesting consumer via
///      `ILotteryRandomnessConsumer.fulfillRandomness`. Uses native-token (ETH) direct funding.
interface IRandomnessCoordinatorLike {
    /// @notice Emitted when a consumer contract is registered or removed.
    /// @param consumer Creator or other protocol contract address.
    /// @param allowed  `true` when registered; `false` when deregistered.
    event ConsumerSet(address indexed consumer, bool allowed);

    /// @dev Declared for ABI stability. Not emitted: refunds are credited to `pendingRefunds`
    ///      instead of being sent.
    /// @param to     Intended refund recipient.
    /// @param amount Wei that could not be returned.
    event EtherRefundFailed(address indexed to, uint256 amount);

    /// @notice ETH credited to `recipient`'s withdrawable refund balance.
    /// @param recipient Address that may withdraw the refund.
    /// @param amount    Wei credited.
    event RefundCredited(address indexed recipient, uint256 amount);

    /// @notice `recipient` withdrew its refund balance to `to`.
    /// @param recipient Address whose balance was withdrawn.
    /// @param to        ETH destination.
    /// @param amount    Wei sent.
    event RefundWithdrawn(address indexed recipient, address indexed to, uint256 amount);

    /// @notice Zero address passed where forbidden.
    error ZeroAddress();

    /// @notice `msg.value` is below the current VRF request price.
    error InvalidEtherAmount();

    /// @notice `requestRandomness` / `cancelRequest` caller is not in `registeredConsumers`.
    /// @param sender Calling address.
    error NotRegisteredConsumer(address sender);

    /// @notice `cancelRequest` caller is not the consumer that created the request.
    error NotRequestConsumer();

    /// @notice Unknown request, already fulfilled, or cancelled mapping entry.
    error InvalidRequest();

    /// @notice Submits one VRF word for `lotteryId` using native ETH payment.
    /// @dev **Caller:** registered consumer (lottery creator).
    ///      **Payment:** `msg.value >= calculateRequestFee(currentGasPriceWei)`; excess credited to
    ///      `pendingRefunds[refundTo]` (no ETH sent to `refundTo`).
    ///      **State:** Stores `requestId → { consumer, lotteryId, drawGeneration }`;
    ///      increments `_pendingRequestCount[msg.sender]`.
    ///      **Returns:** Chainlink `requestId`.
    /// @param lotteryId     Lottery associated with the request (stored as `uint64`).
    /// @param drawGeneration Current draw generation from `LotteryState.drawGeneration`.
    ///                       Stored in the pending entry and checked on callback to detect
    ///                       stale responses from superseded requests or a rotated coordinator.
    /// @param refundTo      Address credited with excess ETH (`address(0)` forfeits it).
    /// @return requestId Chainlink VRF request identifier.
    function requestRandomness(
        uint256 lotteryId,
        uint32 drawGeneration,
        address refundTo
    ) external payable returns (uint256 requestId);

    /// @notice Credits `msg.value` to `recipient`'s withdrawable refund balance.
    /// @dev **Caller:** registered consumer. Used for single-ticket draw refunds. Sends no ETH.
    /// @param recipient Non-zero refund owner.
    function creditRefund(address recipient) external payable;

    /// @notice Withdraws the caller's full refund balance to `to`.
    /// @dev **Caller:** anyone with a non-zero `pendingRefunds` balance.
    /// @param to Non-zero ETH destination.
    function withdrawRefund(address to) external;

    /// @notice Withdrawable refund balance of `recipient`.
    function pendingRefunds(address recipient) external view returns (uint256 amount);

    /// @notice Sum of all withdrawable refund balances (reserved ETH).
    function totalPendingRefunds() external view returns (uint256 amount);

    /// @notice Removes a pending request so a late VRF callback reverts with `InvalidRequest`.
    /// @dev **Caller:** the consumer that created `requestId`.
    ///      **Validations:** `NotRequestConsumer` if caller mismatch; `InvalidRequest` if missing.
    ///      **State:** Deletes pending mapping entry; decrements `_pendingRequestCount[msg.sender]`.
    /// @param requestId Request to cancel before fulfillment.
    function cancelRequest(uint256 requestId) external;

    /// @notice Returns the number of outstanding VRF requests for `manager` that have not
    ///         yet been fulfilled or cancelled.
    /// @dev Used by `BaseLotteryManager.setRndConsumer` and `finalizeConsumerRevocation` to
    ///      decide whether revocation of an old coordinator is safe. Per-manager so multiple
    ///      managers sharing one `RndConsumer` have independent counts.
    /// @param manager The manager (consumer) contract address to query.
    /// @return count  Number of unresolved VRF requests from `manager`.
    function pendingRequestCount(address manager) external view returns (uint16 count);

    /// @notice Returns the configured Chainlink VRF v2.5 wrapper.
    /// @dev **Caller:** anyone (view).
    function vrfWrapper() external view returns (IVRFV2PlusWrapper wrapper);

    /// @notice Whether `consumer` may call `requestRandomness`.
    /// @dev **Caller:** anyone (view).
    /// @param consumer Contract address to check.
    /// @return allowed Registration flag.
    function isRegisteredConsumer(address consumer) external view returns (bool allowed);

    /// @notice Gas limit forwarded to the VRF callback on consumers.
    /// @dev **Caller:** anyone (view).
    function callbackGasLimit() external view returns (uint32 gasLimit);

    /// @notice Block confirmations required before VRF fulfillment.
    /// @dev **Caller:** anyone (view).
    function requestConfirmations() external view returns (uint16 confirmations);

    /// @notice Looks up the lottery ID for a pending VRF request.
    /// @dev **Caller:** anyone (view). Returns `0` after fulfillment or if unknown.
    /// @param requestId Chainlink request ID.
    /// @return lotteryId Associated lottery, or `0`.
    function requestToLottery(uint256 requestId) external view returns (uint256 lotteryId);

    /// @notice Returns the consumer that submitted `requestId`.
    /// @dev **Caller:** anyone (view). Zero address if not pending.
    /// @param requestId Chainlink request ID.
    /// @return consumer Originating consumer contract.
    function requestConsumer(uint256 requestId) external view returns (address consumer);

    /// @notice Gas-price-aware estimate of the native fee for one VRF word.
    /// @dev **Caller:** anyone (view). Delegates to `estimateRequestPriceNative` on the
    ///      underlying Chainlink wrapper using the supplied gas price. Off-chain safe.
    ///      Apply a buffer to the result; actual fee is recalculated at execution time.
    /// @param gasPriceWei The caller's gas-price assumption for this estimate (in wei).
    /// @return fee Estimated Wei required as `msg.value` for `requestRandomness`.
    function calculateRequestFee(uint256 gasPriceWei) external view returns (uint256 fee);
}

/// @title ILotteryRandomnessConsumer
/// @notice Callback surface implemented by lottery creators receiving VRF results.
/// @dev `RndConsumer` calls `fulfillRandomness` after normalising the raw word to `[1, type(uint256).max]`
///      so `seed == 0` remains the “draw incomplete” sentinel. Implementations must restrict
///      callers to the coordinator (`RANDOMNESS_COORDINATOR_ROLE` / router address).
interface ILotteryRandomnessConsumer {
    /// @notice Applies the verified draw seed to `lotteryId`.
    /// @dev **Caller:** `RndConsumer` (coordinator) only.
    ///      **State:** Sets `LotteryState.seed`, transitions to `DRAW_COMPLETED`, emits draw events.
    ///      **Reverts:** If lottery ID unknown or draw not expected (implementation-specific).
    /// @param lotteryId Target lottery on the consumer contract.
    /// @param seed      Normalised VRF output (`> 0`).
    function fulfillRandomness(uint256 lotteryId, uint256 seed) external;

    /// @notice Returns the current draw generation for `lotteryId`.
    /// @dev Called by `RndConsumer.fulfillRandomWords` to verify that an incoming VRF callback
    ///      belongs to the most recent pending request. If the generation stored in the
    ///      `PendingRequest` differs from the value returned here, the callback is stale and
    ///      must be discarded without forwarding randomness to the manager.
    ///      `0` means no draw has ever been requested for this lottery.
    /// @param lotteryId Target lottery.
    /// @return generation Current `LotteryState.drawGeneration`.
    function drawGeneration(uint256 lotteryId) external view returns (uint32 generation);
}

contracts/libraries/LotteryCoreLib.sol

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

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

import {LotteryStored, LotteryState, PayoutModel} from "../structs/MetadataStruct.sol";
import {LotteryPrizeLib} from "./LotteryPrizeLib.sol";

/// @title LotteryCoreLib
/// @notice Canonical winner-count and prize-amount math for every payout model.
/// @dev Linked into all managers and into `LotteryWinnerReader`, so on-chain claim amounts and
///      displayed amounts are computed by the same code and cannot diverge.
///
///      Structure:
///        • **Pure core** ({multiplierWinnerCount}, {winnerCountPure}, {calcPrizePure}) holds the
///          single implementation. Callers that already have the inputs in memory use it directly.
///        • **Storage wrappers** ({winnerCount}, {calcPrize}) exist only so managers can pass their
///          own storage pointers. Mappings are passed to libraries as slot numbers and
///          `DELEGATECALL` preserves `address(this)`, so there is no storage-layout impact.
///
///      The saturation cap in {multiplierWinnerCount} keeps the winner count inside `uint24`
///      without multiplying a large prize pool by the basis-point denominator, and must not be relaxed.
library LotteryCoreLib {
    /// @dev Basis-points denominator (100.00%).
    uint256 private constant BP = 10_000;

    /* ═══════════════════════════════════════════════════════════════════════════
       PURE CORE — single source of truth
    ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Winning positions for a MULTIPLIER lottery.
    /// @dev The saturation branch determines whether `floor(prizePool * BP / denom)`
    ///      would exceed `uint24.max` *without* computing `prizePool * BP`, which can overflow
    ///      `uint256` for a large pool.
    ///
    ///      Condition: `floor(p * BP / d) >= 2^24` iff `p * BP >= (uint24.max + 1) * d`
    ///              => `p >= ceil((uint24.max + 1) * d / BP)`
    ///
    ///      Safety: `(uint24.max + 1) = 2^24 = 16_777_216`; `denom <= uint128.max * uint32.max`
    ///              `≈ 1.46e48`, so the product `≈ 2.45e55 << uint256.max` — always safe.
    /// @param prizePool    Net prize pool after fees (token smallest units).
    /// @param payoutRateBp Target payout multiplier in BP (e.g. 15_000 = 1.5x ticket price).
    /// @param ticketPrice  Per-ticket price.
    /// @return count       Number of winners; `0` when any input is zero.
    function multiplierWinnerCount(
        uint256 prizePool,
        uint256 payoutRateBp,
        uint256 ticketPrice
    ) public pure returns (uint24 count) {
        if (prizePool == 0 || ticketPrice == 0 || payoutRateBp == 0) return 0;
        uint256 denom = ticketPrice * payoutRateBp;
        uint256 satCap = uint256(type(uint24).max) + 1; // 16_777_216
        if (prizePool >= (satCap * denom + BP - 1) / BP) return type(uint24).max;
        uint256 k = Math.mulDiv(prizePool, BP, denom);
        count = k == 0 ? 1 : uint24(k);
    }

    /// @notice Winner slot count for any payout model at a given tickets-sold snapshot.
    /// @dev When exactly one ticket is sold, every model yields a single winner who may claim
    ///      the entire pool (including pre-draw donations) in one claim.
    ///      MULTIPLIER uses `min(K, sold)` to prevent duplicate winner slots when `K > sold`;
    ///      WIN_RATE is at least 1 when `sold > 0` and the rate is non-zero;
    ///      TIER uses `min(tierCount, sold)`.
    /// @param model        Payout model, as the `PayoutModel` ordinal.
    /// @param payoutRateBp Multiplier (MULTIPLIER) or win rate (WIN_RATE) in BP.
    /// @param ticketPrice  Per-ticket price.
    /// @param prizePool    Net prize pool.
    /// @param tierCount    Configured tier count (TIER only).
    /// @param sold         Tickets sold snapshot.
    function winnerCountPure(
        uint8 model,
        uint256 payoutRateBp,
        uint256 ticketPrice,
        uint256 prizePool,
        uint256 tierCount,
        uint256 sold
    ) public pure returns (uint24) {
        if (sold == 0) return 0;
        if (sold == 1) return 1;

        if (model == uint8(PayoutModel.MULTIPLIER)) {
            uint24 k = multiplierWinnerCount(prizePool, payoutRateBp, ticketPrice);
            uint24 sold_ = uint24(sold);
            return k < sold_ ? k : sold_;
        }
        if (model == uint8(PayoutModel.WIN_RATE)) {
            if (payoutRateBp == 0) return 0;
            return uint24(_winRateWinnerCount(sold, payoutRateBp));
        }
        return uint24(tierCount < sold ? tierCount : sold);
    }

    /// @notice Prize amount for a 0-based winner index after the draw.
    /// @dev Mirrors `BaseLotteryManager._calcPrize` plus `_calcMultiplierPrizeForLottery`.
    ///      Winner index `0` absorbs integer rounding dust in every model.
    /// @param model        Payout model, as the `PayoutModel` ordinal.
    /// @param payoutRateBp Multiplier (MULTIPLIER) or win rate (WIN_RATE) in BP.
    /// @param ticketPrice  Per-ticket price.
    /// @param prizePool    Frozen `LotteryState.prizePool`.
    /// @param tiers        Tier weights in BP (TIER only; ignored otherwise).
    /// @param winnerIndex  0-based winner ordinal.
    /// @param sold         Tickets sold snapshot.
    function calcPrizePure(
        uint8 model,
        uint256 payoutRateBp,
        uint256 ticketPrice,
        uint256 prizePool,
        uint16[] memory tiers,
        uint24 winnerIndex,
        uint256 sold
    ) public pure returns (uint256) {
        if (model == uint8(PayoutModel.MULTIPLIER)) {
            // Single-ticket rule takes precedence: the sole winner claims the whole pool.
            if (sold == 1) return prizePool;

            uint24 k = multiplierWinnerCount(prizePool, payoutRateBp, ticketPrice);
            uint24 effectiveWinners = k < uint24(sold) ? k : uint24(sold);
            if (effectiveWinners == 0) return 0;
            if (effectiveWinners == 1) return prizePool;

            uint256 perWinner = prizePool / effectiveWinners;
            return winnerIndex == 0 ? perWinner + (prizePool % effectiveWinners) : perWinner;
        }

        if (model == uint8(PayoutModel.WIN_RATE)) {
            uint256 wCount = _winRateWinnerCount(sold, payoutRateBp);
            uint256 perWinner = prizePool / wCount;
            uint256 dust = prizePool - (perWinner * wCount);
            return winnerIndex == 0 ? perWinner + dust : perWinner;
        }

        uint24 tierWinners = uint24(tiers.length < sold ? tiers.length : sold);
        return LotteryPrizeLib.prizeForTierProportional(prizePool, tiers, tierWinners, winnerIndex);
    }

    /* ═══════════════════════════════════════════════════════════════════════════
       STORAGE WRAPPERS — manager side only
    ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice {winnerCountPure} fed from manager storage.
    /// @dev `lTiers` is only touched for TIER, so other models pay no extra SLOAD.
    function winnerCount(
        mapping(uint256 => LotteryStored) storage lotteries,
        mapping(uint256 => LotteryState) storage states,
        mapping(uint256 => uint16[]) storage lTiers,
        uint256 lotteryId,
        uint256 sold
    ) public view returns (uint24) {
        LotteryStored storage lot = lotteries[lotteryId];
        PayoutModel model = lot.model;
        return
            winnerCountPure(
                uint8(model),
                lot.payoutRateBp,
                lot.ticketPrice,
                model == PayoutModel.MULTIPLIER ? states[lotteryId].prizePool : 0,
                model == PayoutModel.TIER ? lTiers[lotteryId].length : 0,
                sold
            );
    }

    /// @notice {calcPrizePure} fed from manager storage.
    /// @dev TIER routes to {LotteryPrizeLib.prizeForTierProportionalFromStorage} rather than
    ///      copying the weights into memory here, avoiding a redundant round trip on the claim
    ///      path. Both paths share the same canonical tier math.
    function calcPrize(
        mapping(uint256 => LotteryStored) storage lotteries,
        mapping(uint256 => LotteryState) storage states,
        mapping(uint256 => uint16[]) storage lTiers,
        uint256 lotteryId,
        uint24 winnerIndex,
        uint256 sold
    ) public view returns (uint256) {
        LotteryStored storage lot = lotteries[lotteryId];
        uint256 prizePool = states[lotteryId].prizePool;
        PayoutModel model = lot.model;

        if (model == PayoutModel.TIER) {
            uint256 tierCount = lTiers[lotteryId].length;
            uint24 tierWinners = uint24(tierCount < sold ? tierCount : sold);
            return
                LotteryPrizeLib.prizeForTierProportionalFromStorage(
                    prizePool,
                    lTiers[lotteryId],
                    tierWinners,
                    winnerIndex
                );
        }

        uint16[] memory noTiers;
        return calcPrizePure(uint8(model), lot.payoutRateBp, lot.ticketPrice, prizePool, noTiers, winnerIndex, sold);
    }

    /* ═══════════════════════════════════════════════════════════════════════════
       PRIVATE HELPERS
    ═══════════════════════════════════════════════════════════════════════════ */

    /// @dev At least one winner whenever any ticket was sold, so a low rate cannot strand the pool.
    function _winRateWinnerCount(uint256 totalTickets, uint256 winRateBp) private pure returns (uint256 count) {
        if (totalTickets == 0) return 0;
        count = (totalTickets * winRateBp) / BP;
        if (count == 0) count = 1;
    }
}

contracts/libraries/LotteryPrizeLib.sol

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

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

/// @title LotteryPrizeLib
/// @notice Deterministic winner-index selection and tier prize allocation (pure/view library).
/// @dev Used by creator contracts and mission validation. Responsibilities:
///
///      **Winner selection** — For each 1-based winner ordinal `y`, derive a unique 0-based
///      ticket index via an 8-round alternating Feistel permutation over Z_a × Z_b:
///        a = ceil(sqrt(sold)), b = ceil(sold/a), D = a×b ≥ sold.
///        Forward: 1-based ordinal → 0-based ticketIndex (cycle-walking until in [0, sold-1]).
///        Inverse: 1-based ticketId → 0-based ordinal (used by mission validation).
///      A single-ticket lottery always maps to index 0.
///
///      **Prize allocation** — Tier and share-array helpers split `totalPrize` proportionally;
///      winner index `0` absorbs integer rounding remainder where applicable.
///
///      Payout models (MULTIPLIER, WIN_RATE, TIER) combine this library with model-specific
///      winner-count logic in their respective abstract payout contracts.
library LotteryPrizeLib {
    // ─────────────────────────────────────────────────────────────────────────
    // Errors
    // ─────────────────────────────────────────────────────────────────────────

    /// @dev Thrown when a Feistel input is outside the valid domain.
    ///      Requirements: sold > 0, ordinal ∈ [1, sold], ticketId ∈ [1, sold].
    error InvalidFeistelInput();

    // ─────────────────────────────────────────────────────────────────────────
    // Prize calculation (storage-backed)
    // ─────────────────────────────────────────────────────────────────────────

    /// @notice Tier-proportional prize for one winner using active tiers only.
    /// @dev Canonical implementation. Normalizes weights over the first `_actualWinners` tiers
    ///      (`min(tiers.length, ticketsSold)` at the call site). Winner index `0` absorbs
    ///      rounding dust when `_actualWinners >= 2`.
    ///
    ///      Reverts with an array out-of-bounds panic when `_actualWinners > _tiers.length`,
    ///      matching the storage variant.
    /// @param _totalPrize    Net prize pool at draw time.
    /// @param _tiers         Tier weight array in BP (memory).
    /// @param _actualWinners Active tier/winner count.
    /// @param _winnerIndex   0-based winner ordinal.
    /// @return amount        Prize in token smallest units.
    function prizeForTierProportional(
        uint256 _totalPrize,
        uint16[] memory _tiers,
        uint24 _actualWinners,
        uint24 _winnerIndex
    ) public pure returns (uint256 amount) {
        uint256 n = uint256(_actualWinners);
        if (n == 0) return 0;

        uint256 requested = uint256(_winnerIndex);
        uint256 activeTierSum;
        uint256 winnerTier;

        bool needDustPass = requested == 0 && n >= 2;
        uint256[] memory cached;
        if (needDustPass) cached = new uint256[](n);

        unchecked {
            for (uint256 i; i < n; ++i) {
                uint256 share = uint256(_tiers[i]);
                activeTierSum += share;
                if (i == requested) winnerTier = share;
                if (needDustPass) cached[i] = share;
            }
        }
        if (activeTierSum == 0) return 0;

        amount = Math.mulDiv(_totalPrize, winnerTier, activeTierSum);

        if (needDustPass) {
            uint256 totalAllocated;
            for (uint256 i; i < n; ) {
                totalAllocated += Math.mulDiv(_totalPrize, cached[i], activeTierSum);
                // prettier-ignore
                unchecked { ++i; } // counter only — n ≤ type(uint24).max = 16_777_215
            }
            if (_totalPrize > totalAllocated) {
                amount += _totalPrize - totalAllocated;
            }
        }
    }

    /// @notice Storage-pointer entry point for {prizeForTierProportional}.
    /// @dev Signature retained for existing callers. Copies the first `_actualWinners` weights
    ///      into memory and delegates, so tier math has exactly one implementation.
    ///
    ///      The copy loop reads the same slots the canonical loop would have read, so the SLOAD
    ///      count is unchanged and an out-of-range `_actualWinners` still panics on the same
    ///      index. The added cost is memory expansion plus loop overhead, bounded by
    ///      `MAX_TIER_LENGTH` (100).
    /// @param _totalPrize    Net prize pool at draw time.
    /// @param _tiers         Tier weight array in BP (storage pointer).
    /// @param _actualWinners Active tier/winner count.
    /// @param _winnerIndex   0-based winner ordinal.
    /// @return amount        Prize in token smallest units.
    function prizeForTierProportionalFromStorage(
        uint256 _totalPrize,
        uint16[] storage _tiers,
        uint24 _actualWinners,
        uint24 _winnerIndex
    ) public view returns (uint256 amount) {
        uint256 n = uint256(_actualWinners);
        if (n == 0) return 0;

        uint16[] memory tiers = new uint16[](n);
        for (uint256 i; i < n; ) {
            tiers[i] = _tiers[i];
            // prettier-ignore
            unchecked { ++i; } // counter only — n ≤ type(uint24).max = 16_777_215
        }

        return prizeForTierProportional(_totalPrize, tiers, _actualWinners, _winnerIndex);
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Winner selection (pure)
    // ─────────────────────────────────────────────────────────────────────────

    /// @notice Core 8-round Feistel forward cycle walk: 1-based ordinal → 0-based ticket index.
    /// @dev    Domain: a = ceil(sqrt(sold)), b = ceil(sold/a), D = a×b.
    ///         Starts from `ordinal − 1` (in-domain by guard). Applies one 8-round Feistel
    ///         eval per iteration; repeats until output < sold. Termination is guaranteed
    ///         because the cycle containing the start value always reaches an in-domain element.
    ///         Guards: sold > 0 and ordinal ∈ [1, sold] — enforced at library level.
    /// @param _seed          Draw seed (`LotteryState.seed`).
    /// @param _sold          Tickets sold at draw time.
    /// @param _ticketOrdinal 1-based winner ordinal.
    /// @return idx           Winning ticket index in `[0, _sold - 1]`.
    function winningTicketIndexInternal(
        uint256 _seed,
        uint24 _sold,
        uint24 _ticketOrdinal
    ) internal pure returns (uint24 idx) {
        uint256 n = uint256(_sold);
        if (n == 0 || _ticketOrdinal < 1 || _ticketOrdinal > _sold) revert InvalidFeistelInput();
        if (n == 1) return 0;
        uint256 a = _isqrtCeil(n);
        uint256 b = (n + a - 1) / a; // ceil(n / a)
        uint256 x = uint256(_ticketOrdinal - 1);
        while (true) {
            x = _feistelForward(x, a, b, _seed);
            if (x < n) return uint24(x);
        }
    }

    /// @notice Internal wrapper for winner ticket index derivation.
    /// @dev    Signature `(uint256, uint24, uint24) → uint24` is unchanged from the affine
    ///         implementation. Delegates directly to `winningTicketIndexInternal`.
    /// @param _seed          Draw seed.
    /// @param _sold          Tickets sold.
    /// @param _ticketOrdinal 1-based winner ordinal.
    /// @return idx           0-based winning ticket index.
    function winningTicketIndex(uint256 _seed, uint24 _sold, uint24 _ticketOrdinal) internal pure returns (uint24 idx) {
        return winningTicketIndexInternal(_seed, _sold, _ticketOrdinal);
    }

    /// @notice Inverse Feistel cycle walk: 1-based ticketId → 0-based ordinal.
    /// @dev    `ordinalForTicket(seed, sold, ticketId) < wCount` iff ticketId is a winner.
    ///         Equivalence with the exhaustive forward scan is guaranteed by Feistel bijectivity:
    ///         if forward maps ordinal `wi+1` to `ticketId−1`, then inverse maps `ticketId−1`
    ///         back to `wi`. Result 0-based so caller compares directly to wCount.
    ///         Guards: sold > 0 and ticketId ∈ [1, sold] — enforced at library level.
    /// @param _seed     Draw seed.
    /// @param _sold     Tickets sold at draw time.
    /// @param _ticketId 1-based ticket ID.
    /// @return ordinal0 0-based ordinal. ordinal0 < wCount → winner; ≥ wCount → loser.
    function ordinalForTicketInternal(
        uint256 _seed,
        uint24 _sold,
        uint256 _ticketId
    ) internal pure returns (uint24 ordinal0) {
        uint256 n = uint256(_sold);
        if (n == 0 || _ticketId < 1 || _ticketId > n) revert InvalidFeistelInput();
        if (n == 1) return 0;
        uint256 a = _isqrtCeil(n);
        uint256 b = (n + a - 1) / a;
        uint256 x = _ticketId - 1;
        while (true) {
            x = _feistelInverse(x, a, b, _seed);
            if (x < n) return uint24(x);
        }
    }

    /// @notice Thin internal wrapper for `ordinalForTicketInternal`.
    ///         Exposed externally only via PrizeLibHarness (test-only; not in production ABI).
    function ordinalForTicket(uint256 _seed, uint24 _sold, uint256 _ticketId) internal pure returns (uint24) {
        return ordinalForTicketInternal(_seed, _sold, _ticketId);
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Private helpers — Feistel
    // ─────────────────────────────────────────────────────────────────────────

    /// @dev Ceiling integer square root: smallest s such that s*s >= n.
    ///      Uses bit-scan initial estimate + Newton's method, then rounds up.
    // prettier-ignore
    function _isqrtCeil(uint256 n) internal pure returns (uint256 s) {
        if (n == 0) return 0;
        // Bit-length based initial over-estimate
        uint256 x = n;
        s = 1;
        unchecked {
            if (x >= 0x100000000000000000000000000000000) { x >>= 128; s <<= 64; }
            if (x >= 0x10000000000000000) { x >>= 64;  s <<= 32; }
            if (x >= 0x100000000)         { x >>= 32;  s <<= 16; }
            if (x >= 0x10000)             { x >>= 16;  s <<= 8;  }
            if (x >= 0x100)               { x >>= 8;   s <<= 4;  }
            if (x >= 0x10)                { x >>= 4;   s <<= 2;  }
            if (x >= 0x4)                 {             s <<= 1;  }
            // Newton's method — 7 iterations are sufficient for 256-bit n
            s = (s + n / s) >> 1;
            s = (s + n / s) >> 1;
            s = (s + n / s) >> 1;
            s = (s + n / s) >> 1;
            s = (s + n / s) >> 1;
            s = (s + n / s) >> 1;
            s = (s + n / s) >> 1;
            // s is now floor(sqrt(n)); clamp to true floor
            if (s > n / s) s = n / s;
        }
        // Round up to ceiling if not a perfect square
        if (s * s < n) {
            unchecked { ++s; }
        }
    }

    /// @dev Single 8-round forward Feistel eval over Z_a × Z_b.
    ///      A 96-byte keccak buffer [seed | round | half] is allocated once per call and
    ///      reused across all 8 rounds, preventing quadratic memory growth in cycle-walk loops.
    ///
    ///      Even rounds (i=0,2,4,6): f = keccak256(seed, i, R) % a;  L = (L + f) % a
    ///      Odd  rounds (i=1,3,5,7): f = keccak256(seed, i, L) % b;  R = (R + f) % b
    // prettier-ignore
    function _feistelForward(uint256 x, uint256 a, uint256 b, uint256 seed) internal pure returns (uint256) {
        uint256 L = x / b;
        uint256 R = x % b;
        uint256 f;
        uint256 hp;
        // Allocate 96-byte buffer once; advance free pointer by 0x60 only once per call.
        assembly {
            hp := mload(0x40)
            mstore(0x40, add(hp, 0x60))
            mstore(hp, seed)
        }
        for (uint256 i; i < 8; ++i) {
            if (i % 2 == 0) {
                // Even round: update L from R
                assembly {
                    mstore(add(hp, 0x20), i)
                    mstore(add(hp, 0x40), R)
                    f := mod(keccak256(hp, 0x60), a)
                }
                unchecked { L = (L + f) % a; }
            } else {
                // Odd round: update R from L
                assembly {
                    mstore(add(hp, 0x20), i)
                    mstore(add(hp, 0x40), L)
                    f := mod(keccak256(hp, 0x60), b)
                }
                unchecked { R = (R + f) % b; }
            }
        }
        return L * b + R;
    }

    /// @dev Single 8-round inverse Feistel eval over Z_a × Z_b (rounds 7→0, subtract modularly).
    ///      Correctly reverses the forward by undoing each round in reverse order:
    ///      Even rounds (i=6,4,2,0): f = keccak256(seed, i, R) % a;  L = (L + a − f) % a
    ///      Odd  rounds (i=7,5,3,1): f = keccak256(seed, i, L) % b;  R = (R + b − f) % b
    // prettier-ignore
    function _feistelInverse(uint256 x, uint256 a, uint256 b, uint256 seed) internal pure returns (uint256) {
        uint256 L = x / b;
        uint256 R = x % b;
        uint256 f;
        uint256 hp;
        assembly {
            hp := mload(0x40)
            mstore(0x40, add(hp, 0x60))
            mstore(hp, seed)
        }
        // Iterate from round 7 down to 0
        for (uint256 i = 8; i > 0; ) {
            unchecked { --i; }
            if (i % 2 == 0) {
                // Even round: undo L update (hash uses R, which is already the pre-round value)
                assembly {
                    mstore(add(hp, 0x20), i)
                    mstore(add(hp, 0x40), R)
                    f := mod(keccak256(hp, 0x60), a)
                }
                unchecked { L = (L + a - f) % a; }
            } else {
                // Odd round: undo R update (hash uses L, which is unchanged in this inverse step)
                assembly {
                    mstore(add(hp, 0x20), i)
                    mstore(add(hp, 0x40), L)
                    f := mod(keccak256(hp, 0x60), b)
                }
                unchecked { R = (R + b - f) % b; }
            }
        }
        return L * b + R;
    }
}

contracts/structs/MetadataStruct.sol

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

/* ─────────────────────────────────────────────────────────────────────────────
   Shared protocol types for the lottery system.
   Used by LotteryHub, creator contracts (USER / REGULAR / SUPER), and off-chain
   indexers. Lottery IDs are assigned globally by the Hub; per-lottery state lives
   on the creator contract that owns that ID.
   ───────────────────────────────────────────────────────────────────────────── */

/// @notice High-level lottery category. Determines fee splits, feeder behaviour, and
///         which creator contract (`LotteryHub` creator-type key) handles the lottery.
enum LotteryKind {
    /// @dev Sentinel — lottery slot unused or ID not yet created.
    NONE,
    /// @dev End-user-created lottery (`USER_LOTTERY`). Creator fee accrues in `creatorFees`.
    USER,
    /// @dev Protocol-operated lottery (`REGULAR_LOTTERY`). May link to a SUPER feeder target;
    ///         may credit per-ticket CLT mission rewards.
    REGULAR,
    /// @dev Protocol super-lottery (`REGULAR_LOTTERY` creator). Ticket payment is typically CLT;
    ///         prize pool may be funded in an ERC-20 by REGULAR feeders (`params.asset` of the feeder).
    SUPER,
    /// @dev Two-ticket duel (`BATTLE_LOTTERY` creator). Protocol vs user variants via `extraData`.
    BATTLE
}

/// @notice Defines how winners and payouts are calculated after the draw.
enum PayoutModel {
    /// @dev Sentinel value. Not used for active lotteries.
    NONE,

    /// @dev Multiplier-based payout model.
    /// The base payout is calculated from the ticket price:
    /// `ticketPrice * payoutRateBp / 10_000`.
    ///
    /// The multiplier defines how much one winning ticket is expected to receive
    /// relative to the ticket price.
    ///
    /// If the prize pool allows more payout slots than the number of sold tickets,
    /// the winner count must be limited by `soldTickets`.
    /// In this case, the prize pool should be distributed between real sold tickets,
    /// not between artificial repeated winner slots.
    ///
    /// The same ticket should not be duplicated in the winners list unless
    /// repeat-winning is explicitly supported by the lottery rules.
    MULTIPLIER,

    /// @dev Tier-based payout model.
    /// The prize pool is split between winners according to tier weights
    /// provided at lottery creation via `extraData`.
    ///
    /// Each tier represents a share of the prize pool.
    /// This model is usually used for classic lotteries with ranked prizes,
    /// such as first place, second place, third place, and so on.
    TIER,

    /// @dev Win-rate-based payout model.
    /// The number of winners is calculated as a percentage of sold tickets:
    /// `winnerCount = soldTickets * payoutRateBp / 10_000`.
    ///
    /// This model is usually used when the lottery defines what percentage
    /// of sold tickets should become winning tickets, for example SUPER lotteries.
    WIN_RATE
}

/// @notice On-chain lifecycle phase for a lottery.
/// @dev Stored in `LotteryState.status`. `getLotteryStatus` on creators may return
///      **virtual** values (ACTIVE, READY_TO_DRAW) derived from timestamps and sales
///      without rewriting storage.
///
/// Stored transitions (typical path):
///   NONE → PENDING → ACTIVE → READY_TO_DRAW → DRAW_REQUESTED → DRAW_COMPLETED → FULLY_CLAIMED
///
/// Short-circuit: if fewer than two tickets sold at draw time, randomness may be skipped
/// and status moves directly to DRAW_COMPLETED.
///
/// Virtual overlays (not always stored):
///   • PENDING + `startTime <= now <= endTime` → reported as ACTIVE.
///   • PENDING + `now > endTime` (no tickets sold) → reported as CANCELLED.
///   • ACTIVE + `now > endTime` + sold > 0 (not sold out) → reported as READY_TO_DRAW.
///   • ACTIVE + `now > endTime` + sold == 0 → reported as CANCELLED.
///   • DRAW_COMPLETED + all prizes claimed → reported as FULLY_CLAIMED.
// prettier-ignore
enum LotteryStatus {
    NONE,           // 0 — lottery does not exist
    PENDING,        // 1 — created; sale window not open yet
    ACTIVE,         // 2 — sales open (stored or virtual)
    DRAW_REQUESTED, // 3 — VRF request submitted; awaiting callback
    DRAW_COMPLETED, // 4 — seed set; prizes claimable
    FULLY_CLAIMED,  // 5 — all winner slots paid
    READY_TO_DRAW,  // 6 — sold out (stored) or ACTIVE past endTime with sold > 0 (virtual)
    CANCELLED       // 7 — PENDING past endTime, or ACTIVE past endTime with sold == 0 (virtual)
}

/// @notice Immutable economic and scheduling inputs set at lottery creation.
/// @dev Written once into `Lottery.params`. Validated by the creator (`_checkBase` and
///      kind-specific rules) before state is committed.
struct LotteryParams {
    /// @dev Price per ticket in `asset` smallest units.
    uint256 ticketPrice;
    /// @dev ERC-20 accepted for ticket payment (e.g. USDC, USDT). SUPER may use CLT via
    ///      a separate quote path while `asset` still describes the prize denomination.
    address asset;
    /// @dev Creator fee in basis points (10_000 = 100%). Interpretation depends on `LotteryKind`.
    uint256 feeBp;
    /// @dev Maximum tickets that may be sold (`maxTickets` cap).
    uint24 maxTickets;
    /// @dev Unix timestamp when sales may begin.
    uint64 startTime;
    /// @dev Unix timestamp when the sale window ends (unless sold out earlier).
    uint64 endTime;
}

/// @notice Static configuration for one lottery ID on a creator contract.
/// @dev Stored in `_lotteries[lotteryId]`. Never mutated after `createLotteryFromHub`.
struct Lottery {
    /// @dev Address that may claim the creator fee after draw completion (USER) or the
    ///      protocol fee recipient configured for REGULAR/SUPER.
    address creator;
    /// @dev USER, REGULAR, SUPER, or BATTLE.
    LotteryKind kind;
    /// @dev MULTIPLIER, TIER, WIN_RATE, or WINNER_TAKES_ALL (BATTLE).
    PayoutModel model;
    /// @dev Ticket token, price, fee, capacity, and timing.
    LotteryParams params;
    /// @dev Model-specific parameter encoded at creation:
    ///      • WIN_RATE (SUPER): `payoutRateBp` = win-rate in basis points.
    ///      • MULTIPLIER (USER / REGULAR): `payoutRateBp` = minimum payout multiplier in bp.
    ///      • TIER: typically `0`; tier table stored separately on the creator.
    uint256 payoutRateBp;
    /// @dev CLT credited per ticket for mission rewards (REGULAR only; `0` otherwise).
    uint256 cltAmountPerTicket;
    /// @dev Target SUPER lottery ID when this REGULAR lottery feeds a super pool (`0` if none).
    uint256 feederSuperLotteryId;
    /// @dev Share of each ticket payment forwarded to the SUPER pool, in basis points (REGULAR feeders).
    uint256 feederAllocBp;
}

/// @notice Packed storage layout for lottery configuration — 4 slots instead of the 9 used
///         by the ABI-facing `Lottery` struct.
/// @dev Used only for `_lotteries[lotteryId]` storage on manager contracts; all external
///      views (`getLottery`, `getLotteryBatch`) unpack into `Lottery` / `LotteryParams`,
///      so the public ABI is unchanged.
///
///      Field bounds (validated at creation in `_checkBase` / write helpers):
///        • `feeBp`, `feederAllocBp` ≤ 10_000 → uint16.
///        • `payoutRateBp` ≤ type(uint32).max (multipliers up to ~429,496x).
///        • `startTime` / `endTime` as uint40 (valid past year 36_000).
///        • `ticketPrice` as uint128, `cltAmountPerTicket` as uint96.
///        • `feederSuperLotteryId` as uint64.
///
///      Slot layout:
///        slot 0: creator (160) | kind (8) | model (8) | feeBp (16) | feederAllocBp (16) | maxTickets (24)
///        slot 1: asset (160) | startTime (40) | endTime (40)
///        slot 2: ticketPrice (128) | cltAmountPerTicket (96) | payoutRateBp (32)
///        slot 3: feederSuperLotteryId (64)
struct LotteryStored {
    /// @dev Address that may claim the creator fee (USER) or protocol fee recipient.
    address creator;
    /// @dev USER, REGULAR, SUPER, or BATTLE.
    LotteryKind kind;
    /// @dev MULTIPLIER, TIER, or WIN_RATE.
    PayoutModel model;
    /// @dev Creator / protocol fee in basis points (≤ 10_000).
    uint16 feeBp;
    /// @dev REGULAR feeders: share of gross forwarded to the SUPER pool (≤ 10_000).
    uint16 feederAllocBp;
    /// @dev Maximum tickets that may be sold.
    uint24 maxTickets;
    /// @dev ERC-20 accepted for ticket payment.
    address asset;
    /// @dev Unix timestamp when sales may begin.
    uint40 startTime;
    /// @dev Unix timestamp when the sale window ends (unless sold out earlier).
    uint40 endTime;
    /// @dev Price per ticket in `asset` smallest units.
    uint128 ticketPrice;
    /// @dev CLT credited per ticket for mission rewards (REGULAR only; `0` otherwise).
    uint96 cltAmountPerTicket;
    /// @dev Model-specific rate: multiplier BP, win-rate BP, or `0` for TIER.
    uint32 payoutRateBp;
    /// @dev Target SUPER lottery ID when this REGULAR lottery feeds a super pool (`0` if none).
    uint64 feederSuperLotteryId;
}

/// @notice ABI-safe snapshot of runtime lottery state (no nested mappings).
/// @dev Used for external reads and indexing. Referrer balances are **not** stored in
///      `LotteryState`; `referrerFees` here is a convenience field when a view helper
///      aggregates `refFees` for display. Claim progress uses `claimedPrizePool` vs `prizePool`.
///      Per-winner claim bits live in `LotteryState.claimedWords` — query via winner views.
struct LotteryStateView {
    /// @dev Effective status; may match virtual `getLotteryStatus` output.
    LotteryStatus status;
    /// @dev Deadline for VRF fulfillment after `requestDraw`; once passed, `requestDraw` may retry.
    uint64 drawDeadline;
    /// @dev Current draw generation; incremented on every new VRF request. Exposed for monitoring.
    uint32 drawGeneration;
    /// @dev Normalised VRF seed; `0` until the draw completes.
    uint256 seed;
    /// @dev Optional aggregate of referrer fee liability for this lottery (not in base storage).
    uint256 referrerFees;
    /// @dev Accrued creator fee balance (USER lotteries); claimable post-draw.
    uint256 creatorFees;
    /// @dev Frozen distributable prize pool snapshot (excludes fee slices taken at purchase).
    uint256 prizePool;
    /// @dev Cumulative amount already paid to winners.
    uint256 claimedPrizePool;
    /// @dev Remaining winner liability: `prizePool - claimedPrizePool`.
    uint256 currentPrizePool;
}

/// @notice Per-lottery mutable state on the creator contract.
/// @dev Contains `claimedWords` mapping — must be read via storage, not copied to memory.
///      `prizePool` is frozen at draw time for winner math; claims increment `claimedPrizePool`
///      without shrinking `prizePool`.
///
/// Storage packing (slot 0): `status` (1 byte) + `drawDeadline` (8 bytes) + `drawGeneration` (4 bytes) = 13 bytes.
struct LotteryState {
    /// @dev Stored lifecycle phase (may differ from virtual status returned by views).
    LotteryStatus status;
    /// @dev VRF callback deadline; `0` until a draw is requested.
    uint64 drawDeadline;
    /// @dev Monotonic counter incremented on every new VRF request (first draw or retry).
    ///      Stored in each PendingRequest; RndConsumer compares on callback to detect stale
    ///      responses from superseded or rotated-away requests. `0` until first requestDraw.
    uint32 drawGeneration;
    /// @dev Draw seed; `0` means draw not completed.
    uint256 seed;
    /// @dev USER lottery creator fee pot; cleared on `claimCreatorFee`.
    uint256 creatorFees;
    /// @dev Net prize pool base for `_calcPrize` / `_countWinners`; increased on ticket sales and donations.
    uint256 prizePool;
    /// @dev Running total of prizes transferred to winners.
    uint256 claimedPrizePool;
    /// @dev Bitmap of claimed winner slots: `wordIndex = winnerIndex >> 8`, bit `winnerIndex & 255`.
    mapping(uint256 wordIndex => uint256 bits) claimedWords;
}

contracts/structs/TicketPurchaseQuote.sol

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

/// @title TicketPurchaseQuote
/// @notice Payment breakdown for a ticket purchase in the Hub-pull flow.
/// @dev Produced by `ILotteryManager.quoteTicketPurchase` and consumed unchanged by
///      `registerTicketPurchase` after the Hub executes transfers.
///
///      **Hub flow**
///        1. Hub calls `quoteTicketPurchase` (view).
///        2. Hub `safeTransferFrom` buyer → `treasuryDest` / creator / CLT bank per quote.
///        3. Hub calls `registerTicketPurchase` with the same struct (no transfers inside creator).
///
///      **Accounting invariants** (enforced by creator implementations)
///        • Creator leg pulled by the Hub == `prizeAmount + refShare + netFeeder + creatorFee`.
///        • Total ERC-20 debited from the buyer == `toTreasury` + creator leg.
///        • CLT leg is orthogonal: `cltToBank` + `cltToTreasury` when `cltPayment == true`.
///
///      Derivable aggregates (`totalCost`, `toCreator`) and manager-local routing data
///      (`superLotteryId`, `superProtocolFee`) are intentionally not part of the struct:
///      the Hub recomputes the creator leg from the component fields and managers resolve
///      feeder links from their own storage, keeping the ABI payload minimal.
struct TicketPurchaseQuote {
    /* ── ERC-20 ticket payment (USER / REGULAR; SUPER prize pool asset) ─────── */

    /// @dev Ticket payment token (`Lottery.params.asset` or hub-configured treasury token).
    address token;
    /// @dev Protocol / revenue share sent to treasury.
    uint256 toTreasury;
    /// @dev Recipient of `toTreasury` (treasury or protocol address).
    address treasuryDest;

    /* ── Fields applied in registerTicketPurchase (no second pricing pass) ─── */

    /// @dev Portion of the creator leg added to `_state[lotteryId].prizePool`.
    uint256 prizeAmount;
    /// @dev Referrer share accrued in `refFees[referrer][token]` (post-draw claim via Hub).
    uint256 refShare;
    /// @dev Feeder share credited to the linked SUPER prize pool (REGULAR → SUPER).
    uint256 netFeeder;
    /// @dev USER only: slice added to `_state[lotteryId].creatorFees`; `0` for REGULAR/SUPER.
    uint256 creatorFee;

    /* ── CLT ticket path (SUPER lotteries) ─────────────────────────────────── */

    /// @dev `true` when ticket price is paid in CLT (`LotteryKind.SUPER`).
    bool cltPayment;
    /// @dev CLT token address when `cltPayment`.
    address cltToken;
    /// @dev CLT reward pool recipient when `cltPayment`.
    address rewardPoolDest;
    /// @dev CLT amount routed to the bank (mission / protocol sink).
    uint256 cltToBank;
    /// @dev CLT amount routed to treasury when under the configured cap.
    uint256 cltToTreasury;

    /* ── CLT buyer per-ticket reward (REGULAR) ─────────────────────────────── */

    /// @dev Total CLT credited to the buyer for this purchase (`cltAmountPerTicket × qty`).
    ///      NOT the flat referrer welcome bonus (type-1), which is a fixed per-new-referral
    ///      amount set on `CltRewarder` and independent of this value.
    uint256 cltLotteryReward;

    /// @dev `true` when the lottery is a USER lottery.
    bool isUserLottery;
}
Compiler settingsShow
{
  "viaIR": true,
  "libraries": {
    "contracts/UserLotteryManager.sol": {
      "LotteryCoreLib": "0x82db0ad5631209e15149cbe06511c09c599a0557"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.