Skip to content
Verified contractExactMIT

LotteryHub

Address0x4958cb13fa5881b2c67bde408708e72411bb3bbb
Balance

0 ETH

 

Transactions

27

 

Compiler

solc 0.8.34

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,282,768
Creation transaction
0x4937a2d158…22f8310e7c

contracts/LotteryHub.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 {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 {Nonces} from "@openzeppelin/contracts/utils/Nonces.sol";

import {LotteryKind, LotteryParams, PayoutModel, Lottery, LotteryStateView, LotteryStatus} from "./structs/MetadataStruct.sol";
import {TicketPurchaseQuote} from "./structs/TicketPurchaseQuote.sol";
import {ILotteryManager} from "./interfaces/ILotteryManager.sol";
import {IReferralRegistry} from "./interfaces/IReferralRegistry.sol";
import {ICltRewarder} from "./interfaces/ICltRewarder.sol";

/// @notice Winner slot summary returned by {getWinnerInfo} and {getWinnersInfo}.
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;
}

/// @dev Minimal read interface for a previous Hub deployment used when `lotteryId < initialLotteryId`.
///      Exposes `getManager` (the transitive resolver) rather than the raw `lotteryIdToManager` mapping
///      so that resolution recurses through the full legacy-hub chain across N generations.
///      All deployed `LotteryHub` contracts already implement this function; no old-hub redeployment needed.
interface ILotteryHubLegacy {
    function getManager(uint256 lotteryId) external view returns (address);
}

/// @dev Extended manager views used by Hub batch read helpers.
interface ILotteryManagerDetail {
    function getLottery(uint256 lotteryId) external view returns (Lottery memory);

    function getLotteryStateView(uint256 lotteryId) external view returns (LotteryStateView memory);

    function totalTicketsSold(uint256 lotteryId) external view returns (uint256);

    function getLotteryTiers(uint256 lotteryId) external view returns (uint16[] memory);
}

/// @dev Off-manager winner-list reader. Winner views were moved off the managers to keep
///      `ProtocolLotteryManager` under the EIP-170 bytecode limit; see `w`.
///      Declared locally (rather than imported) so this file keeps its own `WinnerInfo`.
interface ILotteryWinnerReader {
    function getWinnersInfo(
        address manager,
        uint256 lotteryId,
        uint256 from,
        uint256 limit
    ) external view returns (WinnerInfo[] memory);
}

/// @notice Full lottery snapshot returned by {getLotteryBatch}.
struct LotteryFullInfo {
    uint256 lotteryId;
    address manager;
    Lottery lottery;
    LotteryStateView state;
    uint256 ticketsSold;
    uint16[] tiers;
}

/// @title LotteryHub
/// @notice Single entry point: lottery lifecycle routing, Hub-pull payments, and referrals.

/// @dev Architecture:
///        • Global `lotteryCount` assigns IDs; `lotteryIdToManager` is write-once per ID.
///        • `managerRegistry` maps type keys → manager; only affects new creations.
///        • All user-facing actions resolve a manager then delegate to `ILotteryManager`.
///
///      Hub-pull ticket flow (`buyTickets`):
///        1. `refRegistry.linkReferrer(buyer, referrer)` → effective referrer.
///        2. `creator.quoteTicketPurchase(lotteryId, qty, effectiveReferrer)` (view).
///        3. Hub `safeTransferFrom` buyer → `treasuryDest` / creator / `rewardPoolDest` per quote.
///        4. `creator.registerTicketPurchase(...)` — mints tickets, no transfers inside.
///        5. If REGULAR lottery (not USER, not SUPER/`cltPayment`) and first such purchase by this
///           buyer (`_welcomeBonusCredited[buyer] == false`), `rewarder.addCltReferrerBonus(referrer)`
///           (flat welcome bonus).
///
///      Buyers approve only this Hub for ERC-20 pulls (payment token and CLT paths).
///
///      Access control:
///        • `DEFAULT_ADMIN_ROLE` — admin rotation (24h delay).
///        • `WORKER_ROLE` — registry wiring, manager registration, legacy hub pointer.
///
///      Legacy routing: IDs below `initialLotteryId` may resolve via `legacyHub` when set.
contract LotteryHub is AccessControl, ReentrancyGuard, Nonces {
    using SafeERC20 for IERC20;

    /* ─────────────────────────────────────── Roles ──────────────────────────── */

    /// @notice Role for protocol configuration and creator registry management.
    bytes32 public constant WORKER_ROLE = keccak256("WORKER_ROLE");

    /* ─────────────────────────────────────── Manager type keys ────────────────── */

    /// @notice `managerType` key for `UserLotteryManager` (USER kind only).
    bytes32 public constant USER_LOTTERY = keccak256("USER_LOTTERY");

    /// @notice `managerType` key for `ProtocolLotteryManager` (REGULAR and SUPER kinds).
    bytes32 public constant REGULAR_LOTTERY = keccak256("REGULAR_LOTTERY");

    /* ─────────────────────────────────────── Enums ──────────────────────────── */

    /// @notice Whether a registered manager may receive new lotteries via `createLottery`.
    /// @dev Existing lotteries keep routing via `lotteryIdToManager` regardless of status.
    enum ManagerStatus {
        NONE,
        ACTIVE,
        CREATION_PAUSED,
        DEPRECATED
    }

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

    /// @notice Optional previous Hub for `lotteryId < initialLotteryId` lookups.
    ILotteryHubLegacy public legacyHub;

    /// @notice Referral registry; Hub holds `REFERRAL_LINKER_ROLE` and links on each buy.
    IReferralRegistry public refRegistry;

    /// @notice Referrer welcome CLT; Hub calls `addCltRewards` on first referral + CLT quote.
    ICltRewarder public rewarder;

    /// @dev Off-manager winner-list reader backing {getWinnersInfo} and {getWinnerInfo}.
    ///      Both getters degrade to empty/zero results while unset, so the Hub stays usable
    ///      between deployment and {setWinnerReader}.
    ILotteryWinnerReader public winnerReader;

    /// @notice Global lottery ID counter; next ID is `lotteryCount + 1` after increment.
    uint256 public lotteryCount;

    /// @notice First lottery ID owned by this Hub; lower IDs may use `legacyHub`.
    uint256 public immutable initialLotteryId;

    /// @notice Permanent manager routing table (set once at creation, never updated).
    mapping(uint256 lotteryId => address manager) public lotteryIdToManager;

    /// @notice Mutable map from manager type key to current manager implementation.
    mapping(bytes32 managerType => address manager) public managerRegistry;

    /// @notice Creation gate per manager address (see {ManagerStatus}).
    mapping(address manager => ManagerStatus) public managerStatus;

    /// @dev Tracks whether a buyer has already triggered the referrer welcome bonus on a protocol lottery.
    mapping(address buyer => bool) private _welcomeBonusCredited;

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

    /// @notice Emitted when `refRegistry` is set or replaced.
    event RefRegistrySet(address indexed newRefRegistry);

    /// @notice Emitted when `rewarder` is set or replaced.
    event RewarderSet(address indexed newRewarder);

    /// @notice Emitted after a lottery is created and routed in this Hub.
    /// @param lotteryId   Assigned global ID.
    /// @param manager     Manager contract that initialized storage.
    /// @param managerType Type key used in `createLottery`.
    /// @param nonce       Hub creation nonce (event ordering aid).
    /// @param kind        Lottery kind stored on the manager.
    /// @param sender      `msg.sender` of `createLottery` (lottery owner / operator).
    event LotteryRegistered(
        uint256 indexed lotteryId,
        address indexed manager,
        bytes32 indexed managerType,
        uint256 nonce,
        LotteryKind kind,
        address sender
    );

    /// @notice Emitted when a manager address is bound to a type key.
    event ManagerRegistered(bytes32 indexed managerType, address indexed manager);

    /// @notice Emitted when a manager's {ManagerStatus} changes.
    event ManagerStatusChanged(address indexed manager, ManagerStatus indexed status);

    /// @notice Emitted when `legacyHub` is set or cleared.
    event LegacyHubSet(address indexed legacyHub);
    event WinnerReaderSet(address indexed winnerReader);

    /// @notice Emitted after a successful `buyTickets` (indexer / analytics hook).
    /// @param lotteryId  Lottery purchased.
    /// @param buyer      `msg.sender` of `buyTickets` (payer).
    /// @param qty        Ticket count.
    /// @param referrer   Effective referrer from registry (zero if none).
    event TicketsBought(uint256 indexed lotteryId, address indexed buyer, uint256 qty, address referrer);

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

    /// @notice Thrown when a configured address must be non-zero.
    error ZeroAddress();

    /// @notice Thrown when `managerRegistry[managerType]` is unset.
    /// @param managerType Unknown type key passed to `createLottery`.
    error UnknownManagerType(bytes32 managerType);

    /// @notice Thrown when no creator resolves for `lotteryId` on this Hub or legacy Hub.
    /// @param lotteryId Unrouted or non-existent ID.
    error UnknownLotteryId(uint256 lotteryId);

    /// @notice Thrown when the target manager is not {ManagerStatus.ACTIVE} for new lotteries.
    /// @param manager Manager that rejected creation.
    error ManagerPaused(address manager);

    /// @notice Thrown when `setManagerStatus` is called with {ManagerStatus.NONE}.
    error InvalidStatus();

    /// @notice Thrown when `claimReferrerFees` is called with an empty managers array.
    error EmptyManagersArray();

    /// @notice Thrown when the actual tokens received by the manager after a transfer are less
    ///         than the nominal amount requested.  Indicates a fee-on-transfer or otherwise
    ///         non-standard token that the protocol does not support.
    error TransferAmountMismatch();

    /// @notice Thrown when a donation is not allowed for the given lottery.
    error ProhibitedDonation();

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

    /// @notice Deploys the Hub and seeds the lottery ID space.
    /// @param initialDefaultAdmin `DEFAULT_ADMIN_ROLE` holder.
    /// @param initialLotteryId_   First ID this Hub assigns (use `legacyCount + 1` when migrating).
    constructor(address initialDefaultAdmin, uint256 initialLotteryId_) {
        if (initialDefaultAdmin == address(0)) revert ZeroAddress();
        _grantRole(DEFAULT_ADMIN_ROLE, initialDefaultAdmin);
        _grantRole(WORKER_ROLE, msg.sender);

        initialLotteryId = initialLotteryId_;
        lotteryCount = initialLotteryId_ - 1;
    }

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

    /// @notice Sets the referral registry used during `buyTickets`.
    /// @param refRegistry_ Non-zero `ReferralRegistry` address.
    function setRefRegistry(address refRegistry_) external onlyRole(WORKER_ROLE) {
        if (refRegistry_ == address(0)) revert ZeroAddress();
        refRegistry = IReferralRegistry(refRegistry_);
        emit RefRegistrySet(refRegistry_);
    }

    /// @notice Sets the CLT rewarder invoked on first-time referrer links with CLT missions.
    /// @param rewarder_ Non-zero `CltRewarder` address.
    function setRewarder(address rewarder_) external onlyRole(WORKER_ROLE) {
        if (rewarder_ == address(0)) revert ZeroAddress();
        rewarder = ICltRewarder(rewarder_);
        emit RewarderSet(rewarder_);
    }

    /// @notice Sets the reader that serves {getWinnersInfo} and {getWinnerInfo}.
    /// @param winnerReader_ Non-zero `LotteryWinnerReader` address.
    function setWinnerReader(address winnerReader_) external onlyRole(WORKER_ROLE) {
        if (winnerReader_ == address(0)) revert ZeroAddress();
        winnerReader = ILotteryWinnerReader(winnerReader_);
        emit WinnerReaderSet(winnerReader_);
    }

    /// @notice Points sub-threshold lottery IDs at a previous Hub deployment.
    /// @dev Pass `address(0)` when legacy lotteries are fully settled.
    /// @param legacyHub_ Previous Hub implementing {ILotteryHubLegacy}, or zero.
    function setLegacyHub(address legacyHub_) external onlyRole(WORKER_ROLE) {
        legacyHub = ILotteryHubLegacy(legacyHub_);
        emit LegacyHubSet(legacyHub_);
    }

    /* ─────────────────────────── Manager registry (WORKER_ROLE) ─────────────── */

    /// @notice Registers or updates the manager for `managerType` (future creations only).
    /// @dev First registration sets {ManagerStatus.ACTIVE}. Does not alter `lotteryIdToManager`.
    /// @param managerType Key such as {USER_LOTTERY} or {REGULAR_LOTTERY}.
    /// @param manager     `ILotteryManager` implementation; must be non-zero.
    function registerManager(bytes32 managerType, address manager) external onlyRole(WORKER_ROLE) {
        if (manager == address(0)) revert ZeroAddress();
        managerRegistry[managerType] = manager;
        if (managerStatus[manager] == ManagerStatus.NONE) {
            managerStatus[manager] = ManagerStatus.ACTIVE;
            emit ManagerStatusChanged(manager, ManagerStatus.ACTIVE);
        }
        emit ManagerRegistered(managerType, manager);
    }

    /// @notice Pauses or resumes new lottery creation on a manager without affecting existing IDs.
    /// @param manager Manager contract address.
    /// @param status  must not be {NONE} (reserved for unregistered state).
    function setManagerStatus(address manager, ManagerStatus status) external onlyRole(WORKER_ROLE) {
        if (manager == address(0)) revert ZeroAddress();
        if (status == ManagerStatus.NONE) revert InvalidStatus();
        managerStatus[manager] = status;
        emit ManagerStatusChanged(manager, status);
    }

    /* ─────────────────────────── Lottery creation ─────────────────────────────── */

    /// @notice Creates a lottery: assigns ID, delegates to manager, then records routing.
    /// @dev Atomic: counter increment reverts if `createLotteryFromHub` reverts.
    ///      `extraData` encoding is manager-specific (see `UserLotteryManager` / `ProtocolLotteryManager`).
    /// @param managerType  Registry key selecting the manager module.
    /// @param kind         USER, REGULAR, or SUPER (validated on manager).
    /// @param payoutModel  MULTIPLIER, TIER, or WIN_RATE.
    /// @param params       Shared {LotteryParams} struct.
    /// @param extraData    ABI-encoded manager extension fields.
    /// @return lotteryId   New global lottery identifier.
    function createLottery(
        bytes32 managerType,
        LotteryKind kind,
        PayoutModel payoutModel,
        LotteryParams calldata params,
        bytes calldata extraData
    ) external nonReentrant returns (uint256 lotteryId) {
        address manager = managerRegistry[managerType];
        if (manager == address(0)) revert UnknownManagerType(managerType);
        if (managerStatus[manager] != ManagerStatus.ACTIVE) revert ManagerPaused(manager);

        lotteryId = ++lotteryCount;

        uint256 nonce = _useNonce(msg.sender);

        // Emitted after the manager call so reverted creations never pay for this log.
        emit LotteryRegistered(lotteryId, manager, managerType, nonce, kind, msg.sender);

        ILotteryManager(manager).createLotteryFromHub(lotteryId, msg.sender, kind, payoutModel, params, extraData);

        lotteryIdToManager[lotteryId] = manager;
    }

    /* ─────────────────────────── Hub-pull ticket purchase ───────────────────── */

    /// @notice Purchases tickets using the Hub-pull payment model.
    /// @dev Buyer must approve this Hub for `quote.token` (and CLT when `quote.cltPayment`).
    /// @param lotteryId        Target lottery.
    /// @param qty              Number of tickets.
    /// @param referrer         Proposed referrer (registry may override with stored binding).
    /// @param ticketRecipient  Ticket owner (may differ from payer `msg.sender`).
    function buyTickets(
        uint256 lotteryId,
        uint256 qty,
        address referrer,
        address ticketRecipient
    ) external nonReentrant {
        address manager = _resolveManager(lotteryId);
        if (manager == address(0)) revert UnknownLotteryId(lotteryId);

        address sender = _msgSender();
        (address effectiveReferrer, ) = refRegistry.linkReferrer(sender, referrer);

        TicketPurchaseQuote memory q = ILotteryManager(manager).quoteTicketPurchase(lotteryId, qty, effectiveReferrer);

        // Creator leg recomputed from quote components (struct carries no aggregate fields).
        uint256 toCreator = q.prizeAmount + q.refShare + q.netFeeder + q.creatorFee;
        ILotteryManager(manager).openHubSettlement();
        _pullExact(IERC20(q.token), sender, q.treasuryDest, q.toTreasury, manager, toCreator);
        if (q.cltPayment) {
            _pullExact(IERC20(q.cltToken), sender, q.treasuryDest, q.cltToTreasury, q.rewardPoolDest, q.cltToBank);
        }

        emit TicketsBought(lotteryId, sender, qty, effectiveReferrer);

        ILotteryManager(manager).registerTicketPurchase(lotteryId, qty, ticketRecipient, sender, effectiveReferrer, q);

        if (!_welcomeBonusCredited[sender]) {
            if (!q.isUserLottery && !q.cltPayment && effectiveReferrer != address(0)) {
                ICltRewarder _rewarder = rewarder;
                // Rewarder performs atomic global dedup and returns true when the hub should close its local gate.
                // Returns false only when referrerWelcomeBonus == 0 (bonus disabled) — gate stays open so eligibility
                // is preserved and the bonus fires once the bonus amount is re-enabled.
                bool closeGate = _rewarder.addCltReferreWelcomeBonus(effectiveReferrer, lotteryId, sender);
                if (closeGate) {
                    _welcomeBonusCredited[sender] = true;
                }
            }
        }
    }

    /* ─────────────────────────── Referrer fees ──────────────────────────────── */

    function claimReferrerFees(address[] memory managers, address token) external nonReentrant {
        if (token == address(0)) revert ZeroAddress();
        uint256 len = managers.length;
        if (len == 0) revert EmptyManagersArray();

        for (uint256 i = 0; i < len; ++i) {
            ILotteryManager(managers[i]).claimReferrerFees(msg.sender, token);
        }
    }

    /* ─────────────────────────── Draw and prize claims ──────────────────────── */

    /// @notice Requests a VRF draw via the resolved manager. Calling again after the draw deadline
    ///         expired without fulfillment re-issues the VRF request.
    /// @dev Passes `msg.sender` as `payer` so excess ETH and single-ticket instant refunds are
    ///      credited to the caller in `RndConsumer` (`withdrawRefund`) — the Hub never holds them.
    /// @param lotteryId Lottery to draw.
    function requestDraw(uint256 lotteryId) external payable nonReentrant {
        address manager = _resolveManager(lotteryId);
        if (manager == address(0)) revert UnknownLotteryId(lotteryId);
        ILotteryManager(manager).requestDraw{value: msg.value}(lotteryId, msg.sender);
    }

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

    /// @notice Boosts the prize pool of `lotteryId` by `amount` of its prize / donation asset.
    /// @dev Hub-pull model: caller approves this Hub for the donation asset (ticket asset for
    ///      USER/REGULAR; feeder prize ERC-20 for SUPER).
    ///
    ///      The flow is split so the asset address is known before the transfer (needed to
    ///      approve and snapshot balances) while accounting is only written after the transfer
    ///      succeeds.  A before/after `balanceOf` snapshot guards against fee-on-transfer tokens:
    ///      if the manager receives less than `amount` the transaction reverts — such tokens
    ///      are not supported by the protocol.
    ///        1. `getDonationAsset` — validates the lottery accepts donations,
    ///           returns the asset address (no accounting written).
    ///        2. `openHubSettlement` — locks the manager against nested Hub credits (any Hub).
    ///        3. Hub pulls tokens donor → manager; snapshot asserts no fee was deducted.
    ///        4. `recordDonationFor` — writes `amount` into `prizePool` and closes the settlement.
    /// @param lotteryId Target lottery.
    /// @param amount    Token amount to donate.
    function donate(uint256 lotteryId, uint256 amount) external nonReentrant {
        address manager = _resolveManager(lotteryId);
        if (manager == address(0)) revert UnknownLotteryId(lotteryId);

        (address asset, bool allowed) = ILotteryManager(manager).getDonationAsset(lotteryId, amount);
        if (!allowed) revert ProhibitedDonation();

        ILotteryManager(manager).openHubSettlement();
        _pullExact(IERC20(asset), msg.sender, manager, amount, address(0), 0);

        ILotteryManager(manager).recordDonationFor(lotteryId, msg.sender, amount);
    }

    /// @notice Withdraws the caller's pre-draw donation; asset transferred directly to caller.
    /// @param lotteryId Lottery from which to withdraw.
    function withdrawDonation(uint256 lotteryId) external nonReentrant {
        address manager = _resolveManager(lotteryId);
        if (manager == address(0)) revert UnknownLotteryId(lotteryId);
        ILotteryManager(manager).withdrawDonationFor(lotteryId, msg.sender);
    }

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

    /// @notice Claims one winner slot; `msg.sender` must own the winning ticket.
    /// @dev No Hub-level reentrancy guard: pure proxy; the manager's `claimPrize` is guarded.
    /// @param lotteryId    Lottery to claim from.
    /// @param winnerIndex  Zero-based winner index from the draw (uint24 — ABI enforces upper bound).
    function claimPrize(uint256 lotteryId, uint24 winnerIndex) external {
        address manager = _resolveManager(lotteryId);
        if (manager == address(0)) revert UnknownLotteryId(lotteryId);
        ILotteryManager(manager).claimPrize(lotteryId, winnerIndex, msg.sender);
    }

    /// @notice Claims multiple winner slots in one transaction.
    /// @dev No Hub-level reentrancy guard: pure proxy; the manager's `claimPrizeBatch` is guarded.
    /// @param lotteryId      Lottery to claim from.
    /// @param winnerIndices  Winner indices to claim.
    function claimPrizeBatch(uint256 lotteryId, uint24[] calldata winnerIndices) external {
        address manager = _resolveManager(lotteryId);
        if (manager == address(0)) revert UnknownLotteryId(lotteryId);
        ILotteryManager(manager).claimPrizeBatch(lotteryId, winnerIndices, msg.sender);
    }

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

    /// @notice Batch read of full lottery config, runtime state, ticket count, and tiers.
    /// @dev Unmapped IDs leave the corresponding entry zeroed. Prize pool figures live in
    ///      `results[i].state` (`prizePool`, `claimedPrizePool`, `currentPrizePool`).
    ///      `tiers` is non-empty only for `PayoutModel.TIER` lotteries.
    /// @param lotteryIds Lottery IDs to query.
    /// @return results   Per-ID snapshot, aligned with `lotteryIds`.
    function getLotteryBatch(uint256[] calldata lotteryIds) external view returns (LotteryFullInfo[] memory results) {
        uint256 len = lotteryIds.length;
        results = new LotteryFullInfo[](len);

        for (uint256 i = 0; i < len; ) {
            uint256 lotteryId = lotteryIds[i];
            address manager = _resolveManager(lotteryId);

            if (manager != address(0)) {
                ILotteryManagerDetail detail = ILotteryManagerDetail(manager);
                Lottery memory lottery = detail.getLottery(lotteryId);

                results[i] = LotteryFullInfo({
                    lotteryId: lotteryId,
                    manager: manager,
                    lottery: lottery,
                    state: detail.getLotteryStateView(lotteryId),
                    ticketsSold: detail.totalTicketsSold(lotteryId),
                    tiers: lottery.model == PayoutModel.TIER ? detail.getLotteryTiers(lotteryId) : new uint16[](0)
                });
            }
            // prettier-ignore
            unchecked { ++i; }
        }
    }

    /// @notice Returns the number of winner slots for `lotteryId` on the resolved manager.
    /// @param lotteryId Lottery to query.
    function countWinners(uint256 lotteryId) external view returns (uint256) {
        address manager = _resolveManager(lotteryId);
        if (manager == address(0)) revert UnknownLotteryId(lotteryId);
        return ILotteryManager(manager).countWinners(lotteryId);
    }

    /// @notice Paginated winner list; returns an empty array when `startIndex` is out of range.
    /// @dev Slot indices align with `claimPrize(lotteryId, winnerIndex)`.
    ///      Served by {winnerReader}; returns an empty array for an unknown `lotteryId` or while
    ///      the reader is unset.
    /// @param lotteryId  Lottery to query.
    /// @param startIndex 0-based index of the first winner slot to return.
    /// @param count      Maximum number of slots to include.
    function getWinnersInfo(
        uint256 lotteryId,
        uint256 startIndex,
        uint256 count
    ) external view returns (WinnerInfo[] memory) {
        address manager = _resolveManager(lotteryId);
        ILotteryWinnerReader reader = winnerReader;
        if (manager == address(0) || address(reader) == address(0)) return new WinnerInfo[](0);
        return reader.getWinnersInfo(manager, lotteryId, startIndex, count);
    }

    /// @notice Returns full information for a single winner slot.
    /// @dev Returns a zero-value struct when `winnerIndex` is out of range, the draw has not
    ///      completed yet, or `lotteryId` is unknown.  Safe to call at any lifecycle stage.
    ///
    ///      Implemented as a single-element {getWinnersInfo} request: the reader already clamps
    ///      `winnerIndex` to the winner count and returns an empty array when out of range, so
    ///      the previous explicit `countWinners` bounds staticcall is no longer needed.
    /// @param lotteryId   Lottery to query.
    /// @param winnerIndex 0-based winner slot in [0, countWinners - 1].
    function getWinnerInfo(uint256 lotteryId, uint256 winnerIndex) external view returns (WinnerInfo memory) {
        address manager = _resolveManager(lotteryId);
        ILotteryWinnerReader reader = winnerReader;
        if (manager == address(0) || address(reader) == address(0)) return WinnerInfo(0, 0, address(0), false);

        WinnerInfo[] memory infos = reader.getWinnersInfo(manager, lotteryId, winnerIndex, 1);
        if (infos.length == 0) return WinnerInfo(0, 0, address(0), false);
        return infos[0];
    }

    /// @notice Returns prize pool breakdown from the resolved creator.
    /// @return claimedPrizePool   Already paid out.
    /// @return unclaimedPrizePool Remaining claimable.
    /// @return totalPrizePool     Sum of claimed and unclaimed.
    function getPrizePool(
        uint256 lotteryId
    ) external view returns (uint256 claimedPrizePool, uint256 unclaimedPrizePool, uint256 totalPrizePool) {
        address manager = _resolveManager(lotteryId);
        if (manager == address(0)) return (0, 0, 0);
        return ILotteryManager(manager).getPrizePool(lotteryId);
    }

    /// @notice Returns accrued referrer fees for `referrer` in `token` on `manager`.
    function getReferrerFee(address manager, address referrer, address token) external view returns (uint256) {
        if (manager == address(0)) return 0;
        try ILotteryManager(manager).getReferrerFee(referrer, token) returns (uint256 fee) {
            return fee;
        } catch {
            return 0;
        }
    }

    /// @notice Returns the effective lifecycle status of `lotteryId`.
    /// @dev Routes through `_resolveManager`; returns `LotteryStatus.NONE` when no manager is registered.
    function getLotteryStatus(uint256 lotteryId) external view returns (LotteryStatus) {
        address manager = _resolveManager(lotteryId);
        if (manager == address(0)) return LotteryStatus.NONE;
        return ILotteryManager(manager).getLotteryStatus(lotteryId);
    }

    /// @notice Returns the manager responsible for `lotteryId` (local table or legacy Hub).
    function getManager(uint256 lotteryId) external view returns (address) {
        return _resolveManager(lotteryId);
    }

    /// @notice Batch-resolves manager address per lottery ID (local table + optional legacy Hub).
    function getManagerBatch(uint256[] calldata lotteryIds) external view returns (address[] memory managers) {
        uint256 len = lotteryIds.length;
        managers = new address[](len);
        for (uint256 i = 0; i < len; ) {
            managers[i] = _resolveManager(lotteryIds[i]);
            // prettier-ignore
            unchecked { ++i; }
        }
        return managers;
    }

    /// @notice Returns whether `buyer` has ever had the referrer welcome bonus credited globally.
    /// @dev Delegates to `CltRewarder.isWelcomeBonusCredited` — returns global truth, not the local Hub cache.
    ///      The hub-local `_welcomeBonusCredited` mapping is a gas-saving cache and may be stale for users
    ///      credited on a prior Hub who have not yet made their first purchase on the current Hub.
    function getWelcomeBonusCredited(address buyer) external view returns (bool) {
        return rewarder.isWelcomeBonusCredited(buyer);
    }

    function _pullExact(IERC20 t, address from, address toA, uint256 amtA, address toB, uint256 amtB) private {
        // Degenerate shapes first: there is nothing to batch, so avoid the overlap analysis below.
        if (amtA == 0) {
            if (amtB != 0) _pullLeg(t, from, toB, amtB);
            return;
        }
        if (amtB == 0) {
            _pullLeg(t, from, toA, amtA);
            return;
        }

        // A self-directed leg moves no balance, so it gets no recipient bracket and is excluded
        // from the expected debit; the aggregate payer assertion then proves it was a no-op.
        bool selfA = toA == from;
        bool selfB = toB == from;
        // Both legs sharing a destination (`treasuryDest == manager`, or
        // `treasuryDest == rewardPoolDest`) is measured with one bracket against the summed amount.
        bool merged = !selfA && !selfB && toA == toB;

        uint256 expectedDebit = (selfA ? 0 : amtA) + (selfB ? 0 : amtB);

        uint256 fromBefore = t.balanceOf(from);
        uint256 aBefore = selfA ? 0 : t.balanceOf(toA);
        uint256 bBefore = (selfB || merged) ? 0 : t.balanceOf(toB);

        t.safeTransferFrom(from, toA, amtA);
        t.safeTransferFrom(from, toB, amtB);

        if (!selfA && t.balanceOf(toA) != aBefore + (merged ? amtA + amtB : amtA)) {
            revert TransferAmountMismatch();
        }
        if (!selfB && !merged && t.balanceOf(toB) != bBefore + amtB) revert TransferAmountMismatch();
        if (t.balanceOf(from) + expectedDebit != fromBefore) revert TransferAmountMismatch();
    }

    /// @dev Single-leg form of {_pullExact}: 4 balance reads, which is the floor for asserting both
    ///      sides of one transfer. `amount` must be non-zero.
    ///
    ///      Comparisons are written as `after != before + amount` rather than
    ///      `after - before != amount` so that an unexpected balance *decrease* on either side
    ///      surfaces as TransferAmountMismatch instead of an arithmetic panic.
    function _pullLeg(IERC20 t, address from, address to, uint256 amount) private {
        if (from == to) {
            t.safeTransferFrom(from, to, amount);
            return;
        }

        uint256 fromBefore = t.balanceOf(from);
        uint256 toBefore = t.balanceOf(to);

        t.safeTransferFrom(from, to, amount);

        if (t.balanceOf(to) != toBefore + amount) revert TransferAmountMismatch();
        if (t.balanceOf(from) + amount != fromBefore) revert TransferAmountMismatch();
    }

    /// @dev Resolves manager: local `lotteryIdToManager`, then `legacyHub` for old IDs.
    function _resolveManager(uint256 _lotteryId) private view returns (address manager) {
        manager = lotteryIdToManager[_lotteryId];
        if (manager == address(0) && _lotteryId < initialLotteryId) {
            ILotteryHubLegacy legacy = legacyHub;
            if (address(legacy) != address(0)) {
                manager = legacy.getManager(_lotteryId);
            }
        }
    }
}

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

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

/**
 * @dev Provides tracking nonces for addresses. Nonces will only increment.
 */
abstract contract Nonces {
    /**
     * @dev The nonce used for an `account` is not the expected current nonce.
     */
    error InvalidAccountNonce(address account, uint256 currentNonce);

    mapping(address account => uint256) private _nonces;

    /**
     * @dev Returns the next unused nonce for an address.
     */
    function nonces(address owner) public view virtual returns (uint256) {
        return _nonces[owner];
    }

    /**
     * @dev Consumes a nonce.
     *
     * Returns the current value and increments nonce.
     */
    function _useNonce(address owner) internal virtual returns (uint256) {
        // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
        // decremented or reset. This guarantees that the nonce never overflows.
        unchecked {
            // It is important to do x++ and not ++x here.
            return _nonces[owner]++;
        }
    }

    /**
     * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
     */
    function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
        uint256 current = _useNonce(owner);
        if (nonce != current) {
            revert InvalidAccountNonce(owner, current);
        }
    }
}

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

contracts/interfaces/ICltRewarder.sol

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

/// @title ICltRewarder
/// @notice CLT reward ledger wired from `LotteryHub` and creator contracts.
/// @dev Three independent flows:
///      1. **Referrer welcome bonus** — `addCltReferreWelcomeBonus` / `claimReferrerBonus`
///         (flat bonus when an invited user is linked for the first time).
///      2. **Per-lottery referrer CLT** — accrued via `addCltPurchaseRewards`, claimed with
///         `claimCltLotteryReferrerReward` / `claimCltLotteryReferrerRewardBatch`.
///      3. **Per-lottery buyer CLT** — accrued via `addCltPurchaseRewards`, claimed with
///         `claimCltPerTicketReward` / `claimCltPerTicketRewardBatch`.
///      Hub calls `addCltReferreWelcomeBonus` when `buyTickets` establishes a new referral (`isNew`).
interface ICltRewarder {
    /// @notice Credits the configured referrer welcome bonus to `referrer` for `user`'s first qualifying purchase.
    /// @dev **Caller:** `REWARD_OPERATOR_ROLE` (Hub).
    ///      **Return semantics (evaluated in order):**
    ///        - Global `_welcomeBonusCredited[user]` already `true` → no credit, returns `true` (Hub closes local gate).
    ///        - `referrerWelcomeBonus == 0` → no credit, returns `false` (Hub leaves local gate open; eligibility preserved).
    ///        - First real credit → marks global flag (CEI), increments `_pendingCltWelcomeBonus[referrer]`, returns `true`.
    ///      **Selector:** unchanged (`void → bool` does not affect the 4-byte selector).
    ///      **State:** Sets `_welcomeBonusCredited[user]` and increments `_pendingCltWelcomeBonus[referrer]` on first credit.
    ///      **Events:** `CltReferrerWelcomeBonusAdded` on first credit only.
    /// @param referrer Referrer receiving the welcome bonus.
    /// @param lotteryId Lottery in which the qualifying purchase occurred.
    /// @param user      Buyer whose eligibility is checked and marked.
    /// @return closeGate `true` when the Hub should close its local `_welcomeBonusCredited` cache for `user`;
    ///         `false` when the bonus is disabled and the Hub must leave the gate open.
    function addCltReferreWelcomeBonus(address referrer, uint256 lotteryId, address user) external returns (bool);

    /// @notice Returns whether `user` has ever had the referrer welcome bonus credited globally.
    /// @dev Persists across Hub migrations — stored in `CltRewarder`, not in Hub.
    ///      Not called in the `buyTickets` hot path; provided for off-chain queries and Hub getter delegation.
    function isWelcomeBonusCredited(address user) external view returns (bool);

    /// @notice Returns unclaimed referrer welcome bonus for `referrer`.
    function getCltWelcomeBonusAmount(address referrer) external view returns (uint256);

    /// @notice Claims all unclaimed referrer welcome bonus for `msg.sender`.
    /// @dev **Caller:** referrer with a balance.
    ///      **Validations:** Reverts `NoCltReward` when balance zero.
    ///      **State:** Clears pending balance; pulls CLT via `ICltRewardPool`.
    ///      **Events:** `ReferrerBonusClaimed`.
    function claimReferrerBonus() external;

    /// @notice Returns sum of pending per-lottery referrer CLT for `user` across `lotteryIds`.
    /// @param lotteryIds Lottery IDs to query.
    /// @param user       Account to query.
    /// @return totalAmount Sum of pending CLT across the given lotteries.
    function getCltLotteryReferrerRewardAmount(
        uint256[] calldata lotteryIds,
        address user
    ) external view returns (uint256 totalAmount);

    /// @notice Claims per-lottery referrer CLT accrued for `msg.sender` in one lottery.
    /// @param lotteryId Lottery whose pending balance is claimed.
    function claimCltLotteryReferrerReward(uint256 lotteryId) external;

    /// @notice Claims pending referrer CLT for `msg.sender` across multiple lotteries in one bank withdrawal.
    /// @param lotteryIds Lotteries to claim; zero-balance IDs are skipped.
    function claimCltLotteryReferrerRewardBatch(uint256[] calldata lotteryIds) external;

    /// @notice Credits buyer per-ticket CLT and referrer lottery CLT in a single call.
    /// @dev Gas optimisation for the REGULAR buy path: one external call instead of two.
    ///      The two accruals remain in **separate ledgers** (`_pendingCltPerTicketReward` for
    ///      `buyer`, `_pendingCltLotteryReferrerReward` for `referrer`); zero amounts and a
    ///      zero `referrer` skip the corresponding leg without reverting.
    /// @param lotteryId      Target lottery.
    /// @param buyer          Per-ticket reward beneficiary.
    /// @param buyerAmount    CLT credited to `buyer` (0 = skip).
    /// @param referrer       Referrer reward beneficiary (zero = skip).
    /// @param referrerAmount CLT credited to `referrer` (0 = skip).
    function addCltPurchaseRewards(
        uint256 lotteryId,
        address buyer,
        uint256 buyerAmount,
        address referrer,
        uint256 referrerAmount
    ) external;

    /// @notice Returns sum of pending per-ticket buyer CLT for `user` across `lotteryIds`.
    /// @param lotteryIds Lottery IDs to query.
    /// @param user       Account to query.
    /// @return totalAmount Sum of pending CLT across the given lotteries.
    function getCltPerTicketRewardAmount(
        uint256[] calldata lotteryIds,
        address user
    ) external view returns (uint256 totalAmount);

    /// @notice Claims per-ticket buyer CLT accrued for `msg.sender` in one lottery.
    /// @dev **Validations:** Reverts `LotteryNotDrawn` when `lotteryId` status is not
    ///      `DRAW_COMPLETED` or `FULLY_CLAIMED`. Reverts `LotteryHubNotSet` when the
    ///      hub has not been configured. Reverts `NoCltReward` when balance is zero.
    /// @param lotteryId Lottery whose ticket rewards are claimed.
    function claimCltPerTicketReward(uint256 lotteryId) external;

    /// @notice Claims pending per-ticket buyer CLT for `msg.sender` across multiple lotteries in one bank withdrawal.
    /// @dev **Validations:** Reverts `LotteryHubNotSet` when the hub has not been configured.
    ///      Input IDs whose status is not `DRAW_COMPLETED` or `FULLY_CLAIMED` are omitted from processing.
    ///      Reverts `NoCltReward` when aggregate claimable amount is zero.
    ///      **Events:** `CltPerTicketRewardClaimedBatch` lists only draw-completed IDs from the input.
    /// @param lotteryIds Lotteries to attempt; non-completed IDs are skipped without revert.
    function claimCltPerTicketRewardBatch(uint256[] calldata lotteryIds) external;
}

contracts/interfaces/ILotteryManager.sol

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

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

/// @title ILotteryManager
/// @notice API implemented by every lottery manager (`UserLotteryManager`,
///         `ProtocolLotteryManager`, and related modules) and routed through `LotteryHub`.
/// @dev **ID assignment** — The Hub increments `lotteryCount`, assigns `lotteryId`, then calls
///      `createLotteryFromHub`. Creators must never mint their own global IDs.
///
///      **Hub-pull ticket sales** — Buyers approve only the Hub. The Hub quotes, pulls ERC-20/CLT,
///      then registers the purchase on the owning creator with zero transfers in step 3.
///
///      **Access** — State-changing entry points (except draw/claim when called directly) expect
///      `msg.sender == hub` via `HUB_ROLE` / `onlyHub` on implementations.
interface ILotteryManager {
    /* ─────────────────────────── Lifecycle ──────────────────────────── */

    /// @notice Initialises lottery `lotteryId` on this creator.
    /// @dev **Caller:** `LotteryHub.createLottery` only (atomic with ID assignment).
    ///      **Validations:** Kind/model/params/extraData checks are implementation-specific;
    ///      reverts roll back the Hub counter increment.
    ///      **State:** Writes `Lottery`, initial `LotteryState`, ticket index; may emit
    ///      `LotteryStatusUpdated`, `LotteryCreated` (per creator).
    /// @param lotteryId       Hub-assigned global ID.
    /// @param originalCaller  `msg.sender` of the Hub create call (fee beneficiary for USER).
    /// @param kind            `USER`, `REGULAR`, or `SUPER`.
    /// @param payoutModel     `MULTIPLIER`, `TIER`, or `WIN_RATE`.
    /// @param params          Base economics and schedule (`LotteryParams`).
    /// @param extraData       ABI-encoded model data (multiplier bp, tier array, win-rate bp, …).
    function createLotteryFromHub(
        uint256 lotteryId,
        address originalCaller,
        LotteryKind kind,
        PayoutModel payoutModel,
        LotteryParams calldata params,
        bytes calldata extraData
    ) external;

    /* ─────────────────────────── Ticket purchase (Hub-pull) ───────────── */

    /// @notice Computes the full payment breakdown for buying `qty` tickets.
    /// @dev **Caller:** anyone (view). Hub calls before transfers.
    ///      **Validations:** Reverts if lottery inactive, sold out, bad `qty`, or timing invalid
    ///      (`InvalidQuantity`, `LotteryNotActive`, `ExceedsMaxTickets`, …).
    ///      **State:** none.
    /// @param lotteryId Target lottery.
    /// @param qty       Ticket count (`> 0`).
    /// @param referrer  Effective referrer from `ReferralRegistry` (`address(0)` allowed).
    /// @return quote    Struct used for Hub transfers and `registerTicketPurchase`.
    function quoteTicketPurchase(
        uint256 lotteryId,
        uint256 qty,
        address referrer
    ) external view returns (TicketPurchaseQuote memory quote);

    /// @notice Mints tickets and updates accounting after Hub transfers.
    /// @dev **Caller:** Hub only (`HUB_ROLE`).
    ///      **Validations:** Same purchase rules as quote; quote fields must match what Hub paid.
    ///      **State:** Increments sold count, updates `prizePool` / `creatorFees` / `refFees` /
    ///      feeder SUPER pool, may transition status to ACTIVE or READY_TO_DRAW; mints tickets.
    ///      **Events:** Ticket mint / status events per creator (Hub emits `TicketsBought`).
    /// @param lotteryId        Target lottery.
    /// @param qty              Ticket count.
    /// @param ticketRecipient  Owner of minted ticket IDs.
    /// @param originalCaller   Hub buyer (`msg.sender` on `buyTickets`).
    /// @param referrer         Resolved referrer.
    /// @param quote            Prior `quoteTicketPurchase` result.
    function registerTicketPurchase(
        uint256 lotteryId,
        uint256 qty,
        address ticketRecipient,
        address originalCaller,
        address referrer,
        TicketPurchaseQuote calldata quote
    ) external;

    /* ─────────────────────────── Draw & prizes ────────────────────────── */

    /// @notice Requests randomness for `lotteryId` when the lottery is ready to draw.
    /// @dev **Caller:** Hub (sets `payer = msg.sender`) or direct call (must have `payer == msg.sender`).
    ///      **Payment:** `msg.value` must cover the VRF fee. Excess ETH and single-ticket instant
    ///      refunds are credited to `payer` in `RndConsumer` (`pendingRefunds`, pulled via
    ///      `withdrawRefund`) — never sent during the draw and never bounced through the Hub.
    ///      **State:** Sets `DRAW_REQUESTED`, `drawDeadline`; may short-circuit to
    ///      `DRAW_COMPLETED` when `< 2` tickets sold.
    ///      **Retry:** if a prior request timed out without a seed, calling again after the
    ///      `drawDeadline` re-issues the VRF request (reverts before the deadline or once fulfilled).
    /// @param lotteryId Lottery to draw.
    /// @param payer     Originating user; credited with any ETH refund in `RndConsumer`.
    function requestDraw(uint256 lotteryId, address payer) external payable;

    /// @notice Validates that a donation is allowed and returns the donation asset, without
    ///         writing any accounting. The Hub calls this before the token transfer so that the
    ///         actual received amount (after any fee-on-transfer deduction) can be measured
    ///         with a before/after `balanceOf` snapshot and then recorded via `recordDonationFor`.
    /// @dev **Caller:** Hub only (`HUB_ROLE`). Reverts with `ZeroAmount` when `amount == 0`.
    ///      Returns `allowed == false` when the lottery no longer accepts donations; the Hub
    ///      reverts with `ProhibitedDonation` in that case.
    /// @param lotteryId Lottery to boost.
    /// @param amount    Intended donation amount (used only for the zero-check; not stored).
    /// @return asset    ERC-20 the Hub must pull from the donor.
    function getDonationAsset(uint256 lotteryId, uint256 amount) external view returns (address asset, bool allowed);

    /// @notice Records the accounting for a Hub-routed donation after the token transfer.
    /// @dev **Caller:** Hub only (`HUB_ROLE`). `actualReceived` is the balance delta measured by
    ///      the Hub around the `safeTransferFrom`, reflecting actual tokens received (which may be
    ///      less than the original `amount` for fee-on-transfer tokens). Emits `Donated`.
    /// @param lotteryId     Lottery to boost.
    /// @param donor         Donor address tracked for potential pre-draw withdrawal.
    /// @param actualReceived Tokens actually received by this contract (Hub-measured delta).
    function recordDonationFor(uint256 lotteryId, address donor, uint256 actualReceived) external;

    /// @notice Opens the manager-wide Hub settlement before a Hub transfers tokens to it.
    /// @dev **Caller:** Hub only (`HUB_ROLE`). Reverts while another Hub settlement is in flight on
    ///      this manager. `recordDonationFor` / `registerTicketPurchase` close it and revert when
    ///      it is not open.
    function openHubSettlement() external;

    /// @notice Withdraws a pre-draw donation on behalf of `donor`; transfers asset to `donor`.
    /// @dev **Caller:** Hub only (`HUB_ROLE`). Reverts with `NoDonation` when balance is zero.
    ///      Emits `DonationWithdrawn`.
    /// @param lotteryId Lottery from which to withdraw.
    /// @param donor     Address whose donation is cleared and refunded.
    function withdrawDonationFor(uint256 lotteryId, address donor) external;

    /// @notice Pays the prize for winner slot `winnerIndex` to `claimer`.
    /// @dev **Caller:** Hub sets `claimer` to the end user; direct calls must pass the real winner.
    ///      **Validations:** `DRAW_COMPLETED` or `FULLY_CLAIMED`; `claimer` owns winning ticket;
    ///      slot not already claimed (`AlreadyClaimed`, `NotWinner`, `DrawNotCompleted`).
    ///      **State:** Sets claim bit, increases `claimedPrizePool`, may set `FULLY_CLAIMED`.
    ///      **Events:** `PrizeClaimed` (creator / Hub).
    /// @param lotteryId    Lottery ID.
    /// @param winnerIndex  0-based winner rank from VRF mapping.
    /// @param claimer      Recipient of the ERC-20 prize transfer.
    function claimPrize(uint256 lotteryId, uint24 winnerIndex, address claimer) external;

    /// @notice Batch variant of `claimPrize` for multiple winner indices.
    /// @dev **Caller / validations:** Same as `claimPrize` per index; empty array reverts.
    ///      **Events:** `PrizeClaimedBatch` on implementations that support it.
    /// @param lotteryId       Lottery ID.
    /// @param winnerIndices   0-based winner slots.
    /// @param claimer         Prize recipient; must own each winning ticket.
    /// @return totalAmount    Sum of prizes transferred in this batch.
    function claimPrizeBatch(
        uint256 lotteryId,
        uint24[] calldata winnerIndices,
        address claimer
    ) external returns (uint256 totalAmount);

    /* ─────────────────────────── Referrer fees ────────────────────────── */

    /// @notice Returns accrued referrer fees for `referrer` in `token` on this creator.
    /// @dev **Caller:** anyone (view). Hub `getReferrerFee(lotteryId, …)` resolves the creator first.
    /// @param referrer Referrer address.
    /// @param token    Fee denomination (ticket asset).
    /// @return Accrued balance not yet claimed.
    function getReferrerFee(address referrer, address token) external view returns (uint256);

    /// @notice Transfers accrued referrer fees to `referrer`.
    /// @dev **Caller:** Hub only; Hub passes `msg.sender` as `referrer`.
    ///      **Validations:** `amount > 0` or reverts `NoRefFees`.
    ///      **State:** Clears `refFees[referrer][token]`.
    ///      **Events:** `ReferrerFeeClaimed`.
    /// @param referrer Recipient (must match Hub caller when routed via Hub).
    /// @param token    ERC-20 to transfer.
    function claimReferrerFees(address referrer, address token) external;

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

    /// @notice Effective lifecycle status including virtual overlays.
    /// @dev **Caller:** anyone (view).
    /// @param lotteryId Lottery ID on this creator.
    /// @return Status per `LotteryStatus` (may differ from raw `LotteryState.status`).
    function getLotteryStatus(uint256 lotteryId) external view returns (LotteryStatus);

    /// @notice Owner of ticket `ticketId` (1-based IDs).
    /// @dev **Caller:** anyone (view). Used by Hub prize checks and `CltMissions`.
    /// @param lotteryId Lottery ID.
    /// @param ticketId  Ticket index.
    /// @return Owner address or revert `TicketDoesNotExist`.
    function ticketOwner(uint256 lotteryId, uint256 ticketId) external view returns (address);

    /// @notice Prize pool balances for winner payouts.
    /// @dev **Caller:** anyone (view).
    /// @param lotteryId Lottery ID.
    /// @return claimedPrizePool   Paid out so far.
    /// @return unclaimedPrizePool `prizePool - claimedPrizePool`.
    /// @return totalPrizePool     Frozen `prizePool` snapshot.
    function getPrizePool(
        uint256 lotteryId
    )
        external
        view
        returns (uint256 claimedPrizePool, uint256 unclaimedPrizePool, uint256 totalPrizePool);

    /// @notice Returns the number of claimable winner slots for `lotteryId`.
    /// @dev Uses current tickets sold and prize pool; MULTIPLIER count grows with donations.
    /// @param lotteryId Lottery ID on this creator.
    /// @return Winner slot count under the lottery payout model.
    function countWinners(uint256 lotteryId) external view returns (uint256);
}

contracts/interfaces/IReferralRegistry.sol

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

/// @title IReferralRegistry
/// @notice Permanent one-time referrer binding for lottery participants.
/// @dev Only addresses with `REFERRAL_LINKER_ROLE` (the deployed `LotteryHub`) may call
///      `linkReferrer`. The Hub invokes it at the start of `buyTickets` so every buyer is
///      registered before ticket proceeds are split.
interface IReferralRegistry {
    /// @notice Records `referrer` for `user` on first interaction; idempotent thereafter.
    /// @dev **Caller:** `REFERRAL_LINKER_ROLE` (Hub).
    ///      **Validations:** `user` must be non-zero (implementation); zero `referrer` or
    ///      `referrer == user` is stored as self-referral and exposed as `address(0)`.
    ///      **State:** Writes `_referrerOf[user]` once.
    ///      **Events:** `ReferrerLinked` on first link only.
    /// @param user     Buyer being registered.
    /// @param referrer Proposed referrer (`address(0)` → self-referral).
    /// @return effectiveReferrer  Stored referrer, or `address(0)` for self-referral.
    /// @return isNew                `true` when a new non-self referrer link was created.
    function linkReferrer(address user, address referrer) external returns (address, bool isNew);

    /// @notice Returns whether `user` has ever been linked (including self-referral).
    /// @dev **Caller:** anyone (view).
    /// @param user Address to query.
    /// @return `true` if `linkReferrer` has been called for `user`.
    function isRegistered(address user) external view returns (bool);

    /// @notice Returns the effective referrer for `user`.
    /// @dev **Caller:** anyone (view).
    ///      Returns `address(0)` when unregistered or self-referred.
    /// @param user Address to query.
    /// @return Referrer address or zero.
    function getReferrer(address user) external view returns (address);

    /// @notice Returns registration flag and effective referrer in one call.
    /// @dev **Caller:** anyone (view).
    ///      Self-referral returns `(true, address(0))`.
    /// @param user Address to query.
    /// @return isUserRegistered `true` after any `linkReferrer` call.
    /// @return referrer         Effective referrer; zero for none/self.
    function getReferrerInfo(address user) external view returns (bool isUserRegistered, address referrer);
}

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,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.