◆ Decentralized Lottery Protocol

Technical Whitepaper

A cross-chain, provably fair lottery protocol built on Polygon
with Chainlink VRF V2.5 (subscription mode) and LayerZero V2

Version 4.0 December 2026

Table of Contents

  1. Executive Overview
  2. System Architecture
  3. Smart Contracts
  4. Lottery Mechanics
  5. User Flow — Playing the Lottery
  6. Verifiable Randomness
  7. Cross-Chain Infrastructure
  8. NFT Ticket System
  9. 0x Token Swap Integration
  10. Frontend Application
  11. Data Indexing — Goldsky Subgraph
  12. Security Model
  13. Governance, Access Control & Multisig
  14. Technology Stack
Section 01

Executive Overview

Lottura is a decentralized, cross-chain lottery protocol that brings provably fair draws to blockchain users across multiple networks. The protocol leverages Polygon as its settlement layer, Chainlink VRF V2.5 (subscription-funded) for verifiable randomness, LayerZero V2 for cross-chain messaging, and USDT (via the USDT0 OFT standard) for stable-value ticket purchases and prize payouts.

🎲

50-6 Lottery Format

Players pick 6 unique numbers from 1–50. Match 4, 5, or all 6 to win tiered prizes.

🔗

Cross-Chain

Buy tickets directly on Polygon, Ethereum, Arbitrum, or Optimism, or fund a purchase from Base or BNB Chain via Relay. LayerZero V2 handles cross-chain messaging.

🔒

Provably Fair

Chainlink VRF V2.5 (subscription mode) ensures every draw is cryptographically verifiable.

💰

USDT Payments

All transactions in USDT for price stability. Winners claim their USDT prize from their ticket once the draw completes.

🎨

NFT Tickets

Each ticket is an ERC-721 NFT (ONFT721) that can be transferred across chains.

🛠

Upgradeable

UUPS proxy pattern allows protocol evolution without disrupting user assets.

📅

Saturday 14:00 UTC Draws

Weekly draws are anchored on-chain via the DrawSchedule library. Commission auto-routes to three Pool contracts (Reserve Fund 7%, Management & Marketing 15%, Charity 15%) at each draw close.

Version 4.0 lists the production deployment (November 2026) on all four chains, adds Optimism and the Relay funding route from Base and BNB Chain, describes the multi-signature governance now in force, and corrects the descriptions of prize rollover, commission recipients, reserve allocation and the Pool contracts. Prizes are not sent to winners when a draw completes: the holder of a winning ticket claims the prize, as described in Section 4.6.

Section 02

System Architecture

Lottura follows a hub-and-spoke architecture where the core lottery logic resides exclusively on Polygon, while satellite hubs deployed on each supported chain serve as entry points for ticket purchases and prize claims.

┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ ┌───────────────────────────────┐ │ Ethereum │ │ Arbitrum │ │ Optimism │ │ Polygon (Core) │ │ │ │ │ │ │ │ │ │ ┌──────────────┐ │ │ ┌──────────────┐ │ │ ┌──────────────┐ │ │ ┌───────────────────┐ │ │ │ LotturaHub │ │ │ │ LotturaHub │ │ │ │ LotturaHub │ │ │ │ LotturaHub │ │ │ ├──────────────┤ │ │ ├──────────────┤ │ │ ├──────────────┤ │ │ ├───────────────────┤ │ │ │ TicketNFT │ │ │ │ TicketNFT │ │ │ │ TicketNFT │ │ │ │ TicketNFT │ │ │ ├──────────────┤ │ │ ├──────────────┤ │ │ ├──────────────┤ │ │ ├───────────────────┤ │ │ │ USDT0 (OFT) │ │ │ │ USDT0 (OFT) │ │ │ │ USDT0 (OFT) │ │ │ │ USDT0 (OFT) │ │ │ └──────────────┘ │ │ └──────────────┘ │ │ └──────────────┘ │ │ ├───────────────────┤ │ └────────┬─────────┘ └────────┬─────────┘ └────────┬─────────┘ │ │ LotturaCore │◄── VRF │ │ │ │ │ ├───────────────────┤ │ └─── LayerZero V2 ────┴─────────────────────┴──────────────▶│ │ 3 Pool contracts │ │ │ └───────────────────┘ │ └───────────────────────────────┘ Base ─┐ ├── Relay: bridges funds to USDT in the player's own Polygon wallet ──▶ checkout on Polygon BNB ──┘

Component Overview

ComponentNetworkPurpose
LotturaCorePolygon onlyCore lottery engine — draws, randomness, prize calculation, winner processing, automatic commission routing
LotturaHubPolygon, Ethereum, Arbitrum, OptimismUser-facing entry point — ticket purchases, USDT approvals, prize claims
LotturaTicketNFTPolygon, Ethereum, Arbitrum, OptimismERC-721 ONFT721 — mints ticket NFTs, supports cross-chain transfers
ReserveFundPoolPolygon onlyReceives 7% of ticket-sale commission at draw close. UUPS-upgradeable; withdraw(token, amount) is onlyOwner, and upgrades are blocked during the blackout window.
ManagementMarketingPoolPolygon onlyReceives 15% of ticket-sale commission at draw close. UUPS-upgradeable; same governance shape as the other pools.
CharityPoolPolygon onlyReceives 15% of ticket-sale commission at draw close. UUPS-upgradeable; donations flow out via owner-controlled withdrawals.
LotturaCoreLibPolygon onlyExternally-linked Solidity library for compose decoding and cross-chain prize delivery. Deployed separately and linked into LotturaCore to fit the EIP-170 24KB bytecode limit.
USDT0 (OFT)Polygon, Ethereum, Arbitrum, OptimismOmnichain Fungible Token wrapping USDT for cross-chain transfers
Chainlink VRF V2.5PolygonVerifiable Random Function (subscription mode) for provably fair number generation
LayerZero V2Polygon, Ethereum, Arbitrum, OptimismCross-chain messaging protocol for ticket purchases and claims
RelayBase, BNB ChainThird-party bridge the app uses to move a player's funds to USDT in their own Polygon wallet before checkout. No Lottura contracts are deployed on these chains (Section 7.5).
Goldsky SubgraphPolygon, Ethereum, Arbitrum, OptimismIndexes on-chain events for frontend queries
Section 03

Smart Contracts

3.1 — LotturaCore.sol

The central lottery engine deployed exclusively on Polygon. Manages the full draw lifecycle, ticket registration, VRF integration, winner processing, and prize distribution.

Inheritance Chain

UUPSUpgradeable → AccessControlUpgradeable → PausableUpgradeable → OAppUpgradeable → OAppOptionsType3Upgradeable → IOAppComposer

Key State Variables

VariableTypeDescription
currentDrawIduint256Current active draw identifier
paymentTokenIERC20USDT token contract reference
paymentTokenOFTaddressUSDT OFT (LayerZero) for cross-chain prize delivery. Now public in V2.
accumulatedCommissionuint256Total commission collected this draw — automatically distributed to the three Pool contracts at _completeDraw (no manual withdraw).
vrfV2PlusCoordinatorIVRFCoordinatorV2PlusChainlink VRF V2.5 coordinator (subscription mode). Replaces the direct-funding wrapper.
genesisAnchoruint256Saturday-anchored on-chain draw schedule reference. Set in initialize via DrawSchedule.computeNextDrawTime.
_reserveFundRecipientaddressAddress that receives the Reserve Fund share (7%) of commission. Set at initialize; ADMIN_ROLE can change it with setCommissionRecipients outside the blackout window (emits CommissionRecipientsUpdated).
_managementMarketingRecipientaddressAddress that receives the Management & Marketing share (15%) of commission. Set at initialize; changeable by ADMIN_ROLE with setCommissionRecipients.
_charityRecipientaddressAddress that receives the Charity share (15%) of commission. Set at initialize; changeable by ADMIN_ROLE with setCommissionRecipients.
_vrfKeyHashbytes32Chainlink VRF gas-lane identifier.
_vrfSubscriptionIduint256Chainlink VRF 2.5 subscription id (256-bit value).
_vrfCallbackGasLimituint32VRF callback gas limit (default 400,000 in V2).
_drawsmappingDraw ID → Draw struct
_ticketsmappingToken ID → Ticket struct
_winnersByTiermappingDraw ID → Tier → Token IDs

Draw Struct

struct Draw {
    uint256 id;
    uint40  startTime;
    uint40  endTime;
    uint48  winningNumbers;       // packed 6 numbers
    uint256 prizePool;
    uint32  ticketsSold;
    uint256[3] rolloverAmount;    // per-tier rollover [tier4, tier5, tier6]
    DrawStatus status;            // PENDING=0 → OPEN=1 → DRAWING=2 → PROCESSING_WINNERS=3 → COMPLETED=4
    uint256 vrfRequestId;
    uint256 combinedCommittedRandomness;
    uint256[3] winningTicketsCounts;
    uint256[3] prizesPerWinner;
    uint256 vrfSeed;
}

Note: V2 added a leading PENDING=0 variant, so every numeric value shifted by one (OPEN moved from 0 to 1, etc.). Any indexer or client code that assumes status == 0 means OPEN must be updated.

Ticket Struct

struct Ticket {
    uint256 id;
    uint256 drawId;
    uint48  numbers;              // packed 6 numbers (1–50)
    uint40  purchaseTime;
    TicketStatus status;          // PENDING → ACTIVE → PAID (WON/LOST folded into PAID in V2)
    uint8   matchedCount;
    uint256 prizeAmount;
    uint256 sourceChain;
}

Note: V2 collapsed the TicketStatus enum to three variants (PENDING=0, ACTIVE=1, PAID=2). The legacy WON and LOST variants no longer exist — winner status is derived from the on-chain ticket-to-draw match calculation.

Core Functions

FunctionAccessDescription
purchaseTicket()onlyHubRegister a ticket for current draw
claimTicket()onlyHubProcess a prize claim for a winning ticket and pay the prize to the claimer address supplied by the Hub (Section 4.6)
executeDraw()OPERATOR_ROLETrigger VRF request to execute a draw. In V2, this is called automatically by a Vercel cron every 1 minute on mainnet — the on-chain function still exists, but the admin UI no longer surfaces a manual button.
retryVRFRequest(uint32)OPERATOR_ROLERestart a stuck VRF request. Requires draw status DRAWING; issues a fresh _requestRandomWords with the caller-supplied callback gas limit, overwrites draw.vrfRequestId, and re-emits DrawExecutionStarted.
setWinningTicketsCounts()OPERATOR_ROLESet winner counts per tier after processing. Also driven by the cron in V2.
setVRFConfig(address,bytes32,uint256,uint32,uint16)ADMIN_ROLESingle setter for coordinator / key hash / subscription id / callback gas limit / request confirmations. Replaces the pre-V2 setVRFV2PlusWrapper and setVRFRequestConfirmations. Emits VRFConfigUpdated.
setCommissionRecipients(address,address,address)ADMIN_ROLEChange the three addresses that receive the Reserve Fund, Management & Marketing and Charity shares of commission. Not callable during the blackout window (BlackoutWindowActive); all addresses must be non-zero. Emits CommissionRecipientsUpdated. The percentages themselves are constants and cannot be changed.
allocateReserve(uint256)ADMIN_ROLEAdd funds to the current draw's prize pool. Pulls the amount from the caller (typically funds withdrawn from the ReserveFundPool), requires the current draw to be OPEN, splits it 60% / 25% / 15% across the three tiers, and emits ReserveAllocated. Top-ups are discretionary; the contracts do not guarantee a minimum prize.
pause()ADMIN_ROLEPause LotturaCore. Must be called inside the Saturday 11:00–15:00 UTC blackout window AND the current draw must be OPEN with zero ticketsSold (errors: NotInBlackoutWindow, DrawHasTicketsSold).
unpause()ADMIN_ROLEUnpause LotturaCore (no time-window restriction).
rawFulfillRandomWords()VRF Coordinator (OnlyVRFCoordinator)Chainlink VRF callback with random seed
lzCompose()LZ EndpointHandle cross-chain messages from remote Hubs

3.2 — LotturaHub.sol

User-facing contract deployed on every supported chain. Handles USDT approval, ticket purchase flow, and prize claiming. On Polygon, it calls LotturaCore directly. On other chains, it sends cross-chain messages via LayerZero.

Inheritance Chain

UUPSUpgradeable → OAppUpgradeable → PausableUpgradeable → OAppOptionsType3Upgradeable

Key State Variables

VariableTypeDescription
TICKET_PRICEuint256 constantHardcoded 2_000_000 (2 USDT, 6 decimals). Exposed as the pure getter TICKET_PRICE() in V2.
ticketNFTaddressLotturaTicketNFT contract
isOnPolygonChainboolWhether this Hub is on the core chain
maxClaimsPerTicketuint8Limit on cross-chain claim messages per ticket (default 3). Applied only on non-Polygon Hubs; the owner can reset a ticket's count with resetClaimCount.

Ticket price and commission are no longer configurable in V2. Commission lives on LotturaCore as immutable constants: COMMISSION = 3700 bps total, split as COMMISSION_RESERVE_FUND = 700 / COMMISSION_MANAGEMENT_MARKETING = 1500, with the remainder (1,500 bps, 15% of the ticket price) going to charity. The pre-V2 updateTicketPrice / updateCommission setters and TicketPriceUpdated / CommissionUpdated events have been removed.

Core Functions

FunctionAccessDescription
purchaseTickets()whenNotPaused whenNotBlackedOutBuy one or more tickets for a draw. Reverts with TicketSalesBlackedOut between 11:00–15:00 UTC on Saturdays (3 hours before through 1 hour after the on-chain draw anchor).
claimTicket()whenNotPausedClaim the prize for a winning ticket. The caller must hold the ticket NFT and receives the prize. Not blocked by the blackout window.
pause()onlyOwner + blackout window onlyHub pause is restricted to the Saturday 11:00–15:00 UTC blackout.
unpause()onlyOwnerHub unpause is unrestricted.

3.3 — LotturaTicketNFT.sol

An ONFT721Enumerable (LayerZero's Omnichain NFT standard) ERC-721 token representing lottery tickets. Each NFT stores a TicketReceipt containing the selected numbers, draw ID, and timestamp.

Inheritance Chain

ONFT721Enumerable (non-upgradeable)

TicketReceipt Struct

struct TicketReceipt {
    uint8[6] numbers;    // 6 selected numbers (1–50)
    uint256  drawId;     // Draw this ticket belongs to
    uint40   timestamp;  // Purchase timestamp
}

3.4 — Libraries

NumberConversionLib

Packs/unpacks 6 numbers into uint48, implements Fisher-Yates shuffle for random number generation, and count-matches logic.

Common.sol / DrawSchedule

Shared structs (TicketReceipt, ExtendedSendParam) plus the on-chain DrawSchedule library that hardcodes the Saturday 14:00 UTC weekly anchor and blackout window.

ONFT721MsgCodecExtended

LayerZero message encoding/decoding for ticket receipts in cross-chain NFT transfers.

3.5 — Pool Contracts (LotturaPool)

V2 introduces three audited UUPS-upgradeable Pool contracts deployed on Polygon. Each one is an empty concrete subclass of an abstract LotturaPool base contract. They receive their fixed slice of each draw's commission automatically — there is no manual withdrawCommission step in V2.

ReserveFundPool

Receives 7% of ticket-sale commission at draw close (COMMISSION_RESERVE_FUND = 700 bps).

ManagementMarketingPool

Receives 15% of ticket-sale commission at draw close (COMMISSION_MANAGEMENT_MARKETING = 1500 bps).

CharityPool

Receives 15% of the ticket price at draw close: the remainder of the commission after the Reserve Fund and Management & Marketing shares, which also absorbs rounding dust.

Shared LotturaPool Surface

State: genesisAnchor. Functions: withdraw(IERC20 token, uint256 amount) (onlyOwner; transfers any ERC-20 the pool holds to the owner, at any time), owner(). Events: FundsWithdrawn(token, recipient, amount). Upgrade: _authorizeUpgrade is onlyOwner and reverts with UpgradeBlockedDuringBlackout during the Saturday 11:00–15:00 UTC window. The pools are not pausable and reject native-token transfers. A 48-slot storage gap is reserved. Each pool is owned by a Safe multi-signature wallet (Section 13.3).

Commission auto-routes from LotturaCore._distributeCommission(drawId) inside _completeDraw — the 7/15/15 split is transferred to the three Pool contracts in a single atomic transaction at draw completion, emitting CommissionDistributed.

3.6 — LotturaCoreLib (External Library)

To fit LotturaCore inside the EIP-170 24KB bytecode limit, compose decoding and cross-chain prize delivery were extracted into a separately-deployed external library LotturaCoreLib.

3.7 — Deployed Addresses (Production)

The production deployment went live in November 2026; the first draw was held on 14 November 2026. All contracts are verified on their block explorers. LotturaCoreLib is linked into LotturaCore at deploy time.

Polygon (core chain, chain ID 137)

Contract / ResourceAddress
LotturaCore (proxy)0x5580c02B8122EbD694807a9b24e393E059E4de18
LotturaCoreLib0xebc0873c14676f7778206abc4fd0e1c64e47d0fc
LotturaHub (proxy)0x4b5D3d65DF9D5a1E828a485bb4453CFd45d149fa
LotturaTicketNFT0xf73e752fb37f1a5702c91d2e6a6aab30a30176be
ReserveFundPool (proxy)0x9ACe3e6a3200F0e27DE8016B68E309E5C7c46d50
ManagementMarketingPool (proxy)0xB0c327236224bcedc3cd77F5b4fD74cfE4BC2604
CharityPool (proxy)0xcBe2d505cE96E32909946CE378a00315c7282a00
USDT (Polygon)0xc2132D05D31c914a87C6611C10748AEb04B58e8F
USDT-OFT (LayerZero)0x6BA10300f0DC58B7a1e4c0e41f5daBb7D7829e13
Chainlink VRF Coordinator0xec0Ed46f36576541C75739E915ADbCb3DE24bD77
VRF key hash (gas lane)0x192234a5cda4cc07c0b66dfbcfbb785341cc790edc50032e842667dbb506cada
VRF subscription ID102451892430248543960373622798668107713513023009719705247420380408137425533236 (256-bit value)

Hub chains

NetworkLotturaHub (proxy)LotturaTicketNFT
Ethereum (1)0xB0c327236224bcedc3cd77F5b4fD74cfE4BC26040xbb9499864bec033d625530d1ef32f531b9707604
Arbitrum (42161)0x4b5D3d65DF9D5a1E828a485bb4453CFd45d149fa0xf73e752fb37f1a5702c91d2e6a6aab30a30176be
Optimism (10)0x4b5D3d65DF9D5a1E828a485bb4453CFd45d149fa0xf73e752fb37f1a5702c91d2e6a6aab30a30176be

Some addresses repeat across chains because the contracts were deployed from the same deployer account at the same nonce. Each address refers to a separate contract on its own chain.

Section 04

Lottery Mechanics

4.1 — Game Format

50-6 Lottery

Players select 6 unique numbers from a pool of 1 to 50. The order of selection does not matter — matching is based on which numbers are chosen, regardless of position. Each ticket costs a fixed amount in USDT. The odds of matching all 6 numbers are approximately 1 in 15,890,700.

4.2 — Prize Tiers

TierMatches RequiredPrize Pool ShareDescription
Tier 14 of 615%Consolation prize — accessible to many players
Tier 25 of 625%Mid-tier — substantial reward for near-winners
Tier 36 of 660%Jackpot — the full match grand prize

4.3 — Draw Lifecycle

1

PENDING

Internal default state before the initial draw creation. Not user-facing.

2

OPEN

The draw is live; ticket sales are open. End time is computed deterministically as DrawSchedule.getDrawEndTime(genesisAnchor, drawId), which always lands on Saturday 14:00 UTC. Players purchase tickets via LotturaHub. Each purchase contributes to the prize pool (ticket price minus commission). Each buyer also submits a hashed randomness commitment that's XOR'd into the draw's combinedCommittedRandomness.

3

DRAWING

A Vercel cron calls executeDraw(drawId) automatically once endTime has passed. LotturaCore submits a Chainlink VRF subscription request and the draw status flips to DRAWING.

4

PROCESSING_WINNERS

The Chainlink VRF coordinator delivers the random seed via rawFulfillRandomWords (restricted by OnlyVRFCoordinator). The seed is XOR'd with combinedCommittedRandomness and fed into NumberConversionLib.generateRandomNumbers() (Fisher-Yates shuffle) to produce 6 winning numbers. The cron then iterates tickets and counts matches.

5

COMPLETED

_completeDraw runs, atomically transferring 7% / 15% / 15% of accumulated commission to ReserveFundPool, ManagementMarketingPool, and CharityPool (emitting CommissionDistributed). Prize amounts per winner per tier are calculated, and winners can then claim them with claimTicket() (Section 4.6). A new draw is automatically created — unless the contract is paused.

UX-only "Finalizing" State

Between the countdown reaching zero and the cron + VRF settlement landing, the frontend shows a UI-level Finalizing state for up to ~5 minutes. This is purely a frontend affordance derived from isSettlementOverdue(), not a new on-chain status.

4.4 — Rollover Mechanism

Prize money that is not won rolls over into the next draw. When a draw completes, LotturaCore takes the draw's total pool (ticket contributions plus anything carried in), subtracts the prizes owed to that draw's winners, and carries the remainder into the next draw, split 60% / 25% / 15% across the three tiers (stored in rolloverAmount, indices 0, 1, 2 for tiers 4, 5 and 6, and emitted as RolloverAdded).

Each draw's prizes are then calculated from its whole pool, so carried-over money is shared across all three tiers rather than kept in the tier it came from. An unwon jackpot keeps 60% of its value in the next jackpot; the other 40% goes to the 5-match and 4-match tiers. Because every draw puts 60% of its pool into the jackpot tier, the jackpot still grows from week to week while nobody wins it. Reserve top-ups made with allocateReserve are split across the tiers the same way.

4.5 — Blackout Window

V2 enforces a hardcoded, on-chain Saturday 11:00–15:00 UTC blackout window — 3 hours before to 1 hour after the 14:00 UTC draw anchor. The constants live in DrawSchedule (BLACKOUT_BEFORE = 3 hours, BLACKOUT_AFTER = 1 hour, DRAW_HOUR = 14 hours, SATURDAY = 5) and are not configurable.

During the blackout:

Before V2 the blackout was a frontend-only convenience banner; in V2 it is enforced by the contracts themselves.

4.6 — Prize Claims

Prizes are not sent to winners when a draw completes. Each winning ticket is claimed through LotturaHub.claimTicket(tokenId), and LotturaCore pays the prize at that point.

The ticket NFT is a standard ERC-721 with no transfer restrictions at any stage of the draw. A winning ticket can therefore change hands before it is claimed, and the prize goes to whoever holds it when the claim is made.

Section 05

User Flow — Playing the Lottery

The end-to-end experience for a player, from connecting a wallet to claiming a prize. The frontend guides users through every step with visual feedback and transaction status updates.

5.1 — Connecting & Authentication

1

Connect Wallet

The player clicks the auth button. Privy presents a modal offering MetaMask, Coinbase Wallet, Rainbow, OKX, WalletConnect, or email/SMS login. Wallet-based login is shown first.

2

Network Guard

The NetworkGuard component checks the connected chain. Players can stay on any chain with a Lottura Hub (Polygon, Ethereum, Arbitrum or Optimism) and buy tickets there directly. On Base or BNB Chain the app offers Relay funding instead (Section 7.5). On any other chain it asks the wallet to switch to Polygon Mainnet. Dev/staging builds use Polygon Amoy.

3

Role Resolution

The UserRoleSync component queries LotturaCore.hasRole() on-chain for the connected address. Regular players are assigned the USER role. Admin/Operator/Upgrader roles unlock the admin dashboard. The role is persisted in Redux.

5.2 — Purchasing Tickets

4

Navigate to /play

The Play page displays the current draw countdown, prize pool, and the number picker grid (1–50). The player selects 6 unique numbers. Selected numbers are highlighted with the Lottura purple accent.

5

Add Tickets to Cart

After selecting 6 numbers, the player adds the ticket to their cart via OTicketSelectedRow. Multiple tickets can be added for the same draw. The OPlayCheckout component shows the total cost in USDT.

6

USDT Approval (Transaction 1)

When the player clicks "Buy Tickets", the usePurchaseTickets hook first checks the USDT allowance. If insufficient, it sends an approve() transaction to the USDT0 contract, authorizing LotturaHub to spend the required amount.

7

Purchase (Transaction 2)

After approval, the hook calls LotturaHub.purchaseTickets() with the numbers list, draw ID, and hashed randomness commitments. On Polygon, the Hub calls LotturaCore directly and mints an NFT ticket. On other chains, it sends a LayerZero cross-chain message.

8

NFT Ticket Minted

A LotturaTicketNFT is minted to the player's wallet with a TicketReceipt storing their 6 numbers, draw ID, and purchase timestamp. The ticket appears immediately in /user/tickets.

5.3 — Checking Results

9

Draw Completes

When the on-chain Saturday 14:00 UTC anchor lands, the Vercel cron auto-calls executeDraw. Chainlink VRF (subscription mode) delivers the random seed, winning numbers are generated, and the cron processes winners with setWinningTicketsCounts. The draw moves to COMPLETED status.

10

View Results at /winners

The Winners page queries the Goldsky subgraph for completed draws. Each draw shows the winning numbers, prize pool, and number of winners per tier. Players can click into /winners/[drawId] for full details.

5.4 — Claiming Prizes

11

Check Winning Status

At /user/tickets, the frontend reads each ticket and its draw from LotturaCore and, once the draw is COMPLETED, compares the ticket's numbers with the winning numbers. Tickets with 4 or more matches display a "Claim Prize" button. LotturaCore repeats the match calculation when it processes the claim, so the frontend's result does not decide payment.

12

Claim Prize (Transaction)

The player clicks "Claim Prize" and the useClaimTicket hook calls LotturaHub.claimTicket(tokenId) from the connected wallet, which must hold the ticket NFT. On Polygon, the Hub forwards the claim to LotturaCore, which transfers USDT to that wallet. On other chains, the Hub sends a LayerZero claim message and LotturaCore returns the prize to the same wallet on that chain via OFT. The ticket status changes to PAID, so each ticket pays out once. Non-Polygon Hubs also limit each ticket to 3 claim messages (Section 4.6).

5.5 — User Dashboard

PageWhat the User Sees
/user/ticketsAll purchased tickets, draw associations, match counts, claim status, and claim buttons for winners
/user/walletConnected wallet address, USDT balance, MATIC balance, and network info
/user/profileUser profile with wallet display and session info
/user/transaction-historyComplete transaction history: purchases, claims, approvals with block explorer links
Section 06

Verifiable Randomness

Lottura implements a dual-layer randomness model combining Chainlink VRF with participant-committed randomness, inspired by PancakeSwap's lottery design.

6.1 — Randomness Sources

① Chainlink VRF V2.5 (Subscription Mode)

Delivers a cryptographically provable random seed via on-chain proof verification. Funded off-chain via vrf.chain.link (the subscription ID is a 256-bit value). Polygon mainnet subscription ID 102451892430248543960373622798668107713513023009719705247420380408137425533236; coordinator 0xec0Ed46f36576541C75739E915ADbCb3DE24bD77; key hash (gas lane) 0x192234a5cda4cc07c0b66dfbcfbb785341cc790edc50032e842667dbb506cada. Default callback gas limit is 400,000 (raised from 100,000); request confirmations and callback gas limit are configurable via setVRFConfig.

② Participant Commitment

Each ticket purchase includes a hashed randomness value. All commitments are XOR'd together into combinedCommittedRandomness, ensuring no single party controls the seed.

6.2 — Number Generation

Final Seed = VRF Seed ⊕ combinedCommittedRandomness

→ NumberConversionLib.generateRandomNumbers(finalSeed)
→ Fisher-Yates shuffle on [1..50]
→ Take first 6 numbers
→ Pack into uint48 via numbersToUint48()

The Fisher-Yates shuffle ensures uniform distribution. The combined seed approach prevents both the VRF oracle and individual participants from predicting or manipulating the outcome.

Section 07

Cross-Chain Infrastructure

Lottura enables players on Polygon, Ethereum, Arbitrum and Optimism to buy tickets directly in the same lottery pools, and players on Base and BNB Chain to take part by bridging funds to Polygon through Relay. LayerZero V2 serves as the cross-chain messaging backbone for the four Hub chains.

7.1 — Supported Networks

NetworkChain IDLZ Endpoint IDContracts
Polygon Core13730109LotturaCore + LotturaHub + TicketNFT
Ethereum130101LotturaHub + TicketNFT
Arbitrum4216130110LotturaHub + TicketNFT
Optimism1030111LotturaHub + TicketNFT
Base8453—None — funding via Relay (Section 7.5)
BNB Chain56—None — funding via Relay (Section 7.5)

7.2 — Cross-Chain Purchase Flow

1

User on Ethereum

Calls LotturaHub.purchaseTickets() on Ethereum. Hub mints the TicketNFT locally and collects USDT0.

2

LayerZero Message

Hub sends USDT0 via OFT cross-chain transfer with a compose message (MSG_TYPE_PURCHASE = 1) containing ticket data.

3

LotturaCore on Polygon

lzCompose() receives the message, decodes ticket data, and registers the ticket in the current draw.

7.3 — Cross-Chain Claim Flow

When a winner on a non-Polygon chain claims their prize, the Hub checks that the caller holds the ticket NFT on that chain and sends a MSG_TYPE_CLAIM (2) message via LayerZero carrying the token ID and the caller's address. LotturaCore processes the claim and sends USDT0 to that address on the originating chain via OFT transfer.

7.4 — Message Types

TypeValueDirectionPayload
PurchaseMSG_TYPE_PURCHASE = 1Hub → CoreToken ID, buyer, numbers, draw ID, hashed randomness, price, commission
ClaimMSG_TYPE_CLAIM = 2Hub → Core → HubToken ID, claimer address

7.5 — Funding from Base and BNB Chain (Relay)

Base and BNB Chain have no Lottura contracts. Players there fund a Polygon purchase through Relay, a third-party cross-chain bridge:

1

Quote on the source chain

The app requests a Relay quote to convert the player's chosen asset on Base or BNB Chain into USDT on Polygon, plus a small POL top-up for checkout gas if the wallet needs it. The app checks that the quote's recipient is the player's own wallet.

2

Delivery to the player's Polygon wallet

The player signs the Relay transaction on the source chain. Relay delivers USDT to the same wallet address on Polygon, and the app confirms the delivery.

3

Standard checkout on Polygon

The wallet switches to Polygon and the normal approve → purchaseTickets() flow runs. The ticket NFT is minted on Polygon and is claimed there.

Section 08

NFT Ticket System

Every lottery ticket is represented as an ERC-721 NFT using LayerZero's ONFT721Enumerable standard. This provides transferability, provenance, and cross-chain portability.

8.1 — Token Features

8.2 — Token ID Strategy

Each chain has a local token counter. Token IDs are chain-local, preventing collisions. Cross-chain transfers preserve the original token's receipt data via ONFT721MsgCodecExtended.

Section 09

0x Token Swap Integration

Lottura integrates the 0x Swap API (v2) as an optional convenience layer. When a player doesn't have enough USDT to purchase tickets, the checkout flow automatically offers to swap their native tokens (POL/MATIC) into USDT — all within the same modal, with no need to leave the app.

Optional & Non-Blocking

The 0x swap is entirely optional. Players who already hold sufficient USDT proceed directly to the standard approve → purchase flow. The swap UI only appears when the player's USDT balance is below the required amount and they have enough native tokens to cover the difference.

9.1 — Architecture

Server-Side Proxy

The 0x API key (ZEROX_API_KEY) is server-only. Two Next.js API routes act as proxies to keep the key secure:

Route0x EndpointPurpose
/api/swap/price/swap/{type}/priceIndicative price estimate (no commitment)
/api/swap/quote/swap/{type}/quoteFirm executable quote with transaction data

The {type} is allowance-holder for native token sells or permit2 for ERC-20 sells.

9.2 — Swap Flow

1

Balance Check

The OCheckoutModal detects the player's USDT balance is below the required amount. canSwapToCover() checks if their native token balance can cover the deficit.

2

Get Estimate

getSwapEstimate() calls the /api/swap/price route to show the player approximately how much POL they'll need. Displayed alongside their native balance.

3

Get Quote & Execute

Player clicks the swap button. getSwapQuote() fetches a firm quote, then executeSwap() sends the transaction via the Privy wallet provider. For native sells, a two-step probe is used: first a small sell to determine the exchange rate, then the actual swap with a ~30% buffer.

4

Balance Refresh & Purchase

After the swap succeeds, the frontend polls the USDT balance for up to ~10 seconds. Once the new balance is confirmed, the standard approve → purchase flow resumes automatically.

9.3 — Supported Tokens & Networks

Sell TokenBuy TokenNetworkNotes
POL (native)USDT (0xc2132...8e8F)Polygon MainnetPrimary swap path

Mainnet Only

0x swaps are only available on Polygon Mainnet. On testnet (Amoy), a warning is shown and swaps are disabled.

Permit2

ERC-20 sells use the Permit2 contract (0x0000...0BA3) for gasless approvals. Native sells use the Allowance Holder pattern.

9.4 — Key Components

FilePurpose
src/lib/hooks/use-token-swap.tsCore swap logic: estimate, quote, execute, state management
src/app/api/swap/price/route.tsServer proxy to 0x price API (keeps API key secure)
src/app/api/swap/quote/route.tsServer proxy to 0x quote API
src/components/o-checkout-modal/Checkout UI with integrated swap section
Section 10

Frontend Application

The Lottura frontend is a Next.js 16 application with the App Router, built with React 19, TypeScript, and Tailwind CSS. It provides the complete user interface for playing the lottery, viewing draws, managing tickets, and administering the protocol.

10.1 — Key Pages

RoutePurpose
/Home — next draw countdown, unclaimed prizes, past draws, FAQ
/playTicket purchase — number picker (1–50), ticket list, checkout with USDT approval
/winnersCompleted draws list with winner details
/winners/[drawId]Detailed draw results and winning tickets
/user/ticketsUser's purchased tickets and claim status
/user/walletWallet balance, USDT holdings
/admin/overviewAdmin dashboard — draw management, protocol stats
/admin/editAdmin telemetry & governance — read-only display of immutable Tier-A constants (ticket price, commission, prize distribution all hard-coded in V2), role grants/revokes, VRF config rotation, recovery actions. Pool management lives at /admin/pools.

10.2 — Wallet Integration

Authentication and wallet management is handled by Privy, supporting:

10.3 — State Management

Redux Toolkit

Client state: user role, UI flags. Persisted via redux-persist to localStorage.

TanStack React Query

Server state: caching, background refetching for contract reads and GraphQL queries.

Wagmi Hooks

On-chain reads/writes: contract interactions via typed hooks with Viem as the transport layer.

10.4 — Contract Integration Hooks

The frontend uses a comprehensive hook library for contract interactions:

HookContractPurpose
usePurchaseTicketsLotturaHubFull purchase flow: approve USDT → purchase tickets
useClaimTicketLotturaHubClaim winnings for a ticket
useCurrentDrawLotturaCoreFetch current draw state
useWinnersByTierLotturaCoreGet winners for each prize tier
useTicketNFTBalanceLotturaTicketNFTUser's ticket count
useLotturaCoreAdminLotturaCoreAdmin: manage draws, config, emergencies
Section 11

Data Indexing — Goldsky Subgraph

Lottura uses a Goldsky-hosted subgraph (built on The Graph protocol) to index on-chain events from all six contracts on Polygon — the Core, Hub, and TicketNFT contracts plus the three Pool contracts — and from the Hubs on Ethereum, Arbitrum and Optimism. This provides fast, queryable historical data for the frontend via GraphQL, removing the need for expensive on-chain read calls for historical data.

11.1 — Why a Subgraph?

Performance

Querying indexed data via GraphQL is orders of magnitude faster than scanning blockchain events directly. Essential for paginated views like draw history and ticket lists.

Cost Efficiency

Avoids repeated RPC calls. The subgraph indexes events once and serves unlimited queries. Frontend caching via TanStack Query further reduces load.

Rich Queries

Supports filtering, sorting, pagination, and relationship traversal (e.g. all tickets for a draw) that would be impractical with direct contract reads.

11.2 — Indexed Data Sources

ContractAddressStart BlockEvents Indexed
LotturaCore (Polygon)0x5580c02B8122EbD694807a9b24e393E059E4de1897,099,828DrawCreated, DrawExecutionStarted, DrawProcessingWinners, DrawCompleted, TicketPurchased, PrizePaid, RandomnessCommitted, RolloverAdded, ReserveAllocated, CommissionDistributed, RoleGranted, RoleRevoked, plus a purchaseTicket(...) callHandler that backfills Ticket.purchaseAmount (V2 event payload dropped that field).
LotturaHub (Polygon)0x4b5D3d65DF9D5a1E828a485bb4453CFd45d149fa97,099,828TokenPurchased, TokenClaimed
LotturaTicketNFT (Polygon)0xf73e752fb37f1a5702c91d2e6a6aab30a30176be97,099,828Transfer (ERC-721)
ReserveFundPool (Polygon)0x9ACe3e6a3200F0e27DE8016B68E309E5C7c46d5097,099,828FundsWithdrawn, OwnershipTransferred
ManagementMarketingPool (Polygon)0xB0c327236224bcedc3cd77F5b4fD74cfE4BC260497,099,828FundsWithdrawn, OwnershipTransferred
CharityPool (Polygon)0xcBe2d505cE96E32909946CE378a00315c7282a0097,099,828FundsWithdrawn, OwnershipTransferred
LotturaHub (Ethereum)0xB0c327236224bcedc3cd77F5b4fD74cfE4BC260426,387,956TokenPurchased
LotturaHub (Arbitrum)0x4b5D3d65DF9D5a1E828a485bb4453CFd45d149fa523,127,656TokenPurchased
LotturaHub (Optimism)0x4b5D3d65DF9D5a1E828a485bb4453CFd45d149fa159,378,211TokenPurchased

The pre-V2 PrizeDistributionUpdated event has been removed (prize distribution is now compile-time constants on LotturaCore).

11.3 — Schema Entities

EntityFieldsDescription
DrawdrawId, startTime, endTime, winningNumbers, prizePool, ticketsSold, rolloverAmounts, status, vrfRequestId, winningTicketsCounts, prizesPerWinner, tickets (derived)Full draw lifecycle data with related tickets
TicketticketId, owner, draw, numbers, purchaseTime, status, matchedCount, prizeAmount, purchaseAmountIndividual ticket with draw association. purchaseAmount is backfilled via a purchaseTicket callHandler since the V2 event payload dropped that field.
PrizePaidticketId, winner, amount, matchCount, timestampImmutable record of each prize payment
DrawCompleteddrawId, winningNumbers, totalPrizePool, timestampImmutable snapshot when a draw completes
RandomnessCommitteddrawId, committer, tokenId, timestampEach participant's randomness contribution
AdminActionactionType, contractName, actor, target, role, value, details, timestampAdmin/operator action log (role grants/revokes, VRF config rotations, pause/unpause, ownership transfers, etc.).
CommissionDistributiondrawId, reserveFundAmount, managementMarketingAmount, charityAmount, timestampPer-pool commission amounts at draw close (replaces the removed CommissionWithdrawn event).
Poolid, kind (RESERVE_FUND / MANAGEMENT_MARKETING / CHARITY), address, totalReceived, totalWithdrawn, updatedAtOne row per Pool contract; totalReceived incremented by CommissionDistributed deposits (recordPoolDeposit), totalWithdrawn incremented by each pool's FundsWithdrawn handler (recordWithdrawal).
PoolDepositpool, drawId, amount, timestampAutomatic deposits from _distributeCommission at draw close.
PoolWithdrawalpool, to, amount, timestampManual onlyOwner withdrawals via LotturaPool.withdraw (to derives from the contract's FundsWithdrawn.recipient param).
PrizeDistributiontier4, tier5, tier6, updatedAtSingleton snapshot of the immutable prize-distribution constants for historical queries (fixed id key, not per-draw).
NFTTransferfrom, to, tokenId, timestampTicket NFT transfer history
ReceiptreceiptId, user, ticketId, drawId, statusCross-chain purchase receipts
LotteryStatstotalDraws, totalTicketsSold, totalPrizesPaid, totalWinnersAggregate protocol statistics

11.4 — Event Handler Mapping

Each contract's events are processed by dedicated mapping functions that create and update the entities above:

LotturaCore Handlers (goldsky-subgraph/src/mappings/lottura-core.ts)

handleDrawCreated → creates Draw (OPEN), increments LotteryStats.totalDraws
handleTicketPurchased → creates Ticket, updates Draw.ticketsSold
handleDrawExecutionStarted → sets Draw status to DRAWING
handleDrawProcessingWinners → sets Draw status to PROCESSING_WINNERS, stores winningNumbers
handleDrawCompleted → sets Draw to COMPLETED, creates DrawCompleted snapshot
handlePrizePaid → creates PrizePaid, marks Ticket status as CLAIMED and Receipt status as WINNER (the subgraph TicketStatus enum is ACTIVE / CLAIMED / EXPIRED; the contract's terminal PAID state maps to CLAIMED in the subgraph)
handleRandomnessCommitted → creates RandomnessCommitted record
handleRolloverAdded → appends to Draw.rolloverAmounts
handleCommissionDistributed → creates CommissionDistribution entity with per-pool amounts (7% / 15% / 15% split)
handleReserveAllocated → reserve fund allocation event
handleRoleGranted / handleRoleRevoked → AdminAction entries for role changes
purchaseTicket callHandler → backfills Ticket.purchaseAmount since V2 dropped that field from the event payload

LotturaPool Handlers (goldsky-subgraph/src/mappings/lottura-pool.ts)

handleReserveFundPoolWithdrawn / handleManagementMarketingPoolWithdrawn / handleCharityPoolWithdrawn → each creates a PoolWithdrawal entity and increments Pool.totalWithdrawn (Pool tracks totalReceived / totalWithdrawn, not a running balance)
handle*PoolOwnershipTransferred → write an AdminAction (OWNERSHIP_TRANSFERRED)

LotturaHub Handlers (goldsky-subgraph/src/mappings/lottura-hub.ts)

handleTokenPurchased → cross-chain ticket-purchase receipt
handleTokenClaimed → marks the cross-chain claim
handlePaymentTokenUpdated / handleTicketNFTUpdated / handleLotturaCoreUpdated → write an AdminAction (config updates; these do not mutate a Pool entity)
handleHubPaused / handleHubUnpaused / handleHubOwnershipTransferred → AdminAction entries for pause and ownership changes

11.5 — GraphQL Queries & Frontend Hooks

QueryFrontend HookUsed In
GET_COMPLETED_DRAWSuseCompletedDrawsGraphQL/winners — paginated list with 1M/6M/1Y filters
GET_DRAW_BY_IDuseDrawGraphQL/winners/[drawId] — draw detail page
GET_DRAWS_BY_TIME_RANGEuseDrawsByTimeRangeGraphQLTime-filtered draw views
GET_COMPLETED_DRAWS_COUNTuseCompletedDrawsGraphQLPagination total count
GET_DRAW_TICKETSuseDrawTicketsGraphQL/winners/[drawId] — participants list
GET_WINNING_TICKETSuseWinningTicketsGraphQLWinners display (matchedCount ≥ 4)
GET_USER_TICKETS(available)User ticket history by address
Section 12

Security Model

12.1 — Smart Contract Security

Access Control

Role-based (ADMIN, OPERATOR, UPGRADER) via OpenZeppelin AccessControl. Functions are gated by role requirements.

Safe Token Handling

All ERC-20 operations use OpenZeppelin's SafeERC20 (forceApprove, safeTransfer, safeTransferFrom).

Pausable

LotturaCore and LotturaHub are Pausable. Both can only be paused during the Saturday 11:00–15:00 UTC blackout window, and Core also requires the open draw to have zero tickets sold. While paused, purchases and claims through the Hub revert, and cross-chain messages to Core wait at the LayerZero endpoint until unpause; draw results, tickets and prize funds are unaffected. The Pool contracts are not pausable.

Upgradeable (UUPS)

LotturaCore, LotturaHub, and each LotturaPool use UUPS proxies. Upgrades require UPGRADER_ROLE (Core) or onlyOwner (Hub / Pools), all held by Safe multi-signature wallets (Section 13.3). Core and Hub upgrades require the contract to be paused, and pausing can only start during the blackout window (for Core, only while the open draw has no tickets sold). Pool upgrades are blocked during the blackout window.

Automatic Commission Distribution

At each draw close, _distributeCommission performs a 3-way atomic transfer of 7% / 15% / 15% of accumulated commission to the Reserve Fund / Management & Marketing / Charity Pool contracts. No manual withdrawCommission step exists in V2. Emits CommissionDistributed.

VRF Protection

VRF callback is restricted to the configured Chainlink VRF Coordinator (OnlyVRFCoordinator error). Subscription mode means LotturaCore no longer holds native MATIC for VRF — funding happens off-chain at vrf.chain.link.

12.2 — Cross-Chain Security

12.3 — Frontend Security

Section 13

Governance, Access Control & Multisig

13.1 — Role Hierarchy

RoleBytes32 HashPermissions
DEFAULT_ADMIN 0x0000...0000 Can grant and revoke all other roles. The "root" role in OpenZeppelin AccessControl
ADMIN 0xa498...1775 Configuration (read-only telemetry in V2; ticket price / commission / draw interval / prize distribution are all immutable), token & OFT registration, hub/OApp registration, pause/unpause LotturaCore (blackout-gated), setVRFConfig to rotate the Chainlink VRF subscription, payment token / OFT updates, setCommissionRecipients (outside the blackout window), and allocateReserve to add funds to the open draw's prize pool.
OPERATOR 0x9766...b929 Owns the cron wallet that auto-calls executeDraw, setWinningTicketsCounts, and winner processing every minute. Manual operator intervention is limited to retryVRFRequest(uint32 callbackGasLimit) for stuck-VRF recovery (always operates on the current draw — no draw id passed) and topping up the off-chain Chainlink VRF subscription at vrf.chain.link.
UPGRADER 0x189a...d2e3 Authorize UUPS proxy upgrades on LotturaCore

13.2 — Role Assignment at Deployment

When LotturaCore is initialized, all four roles (DEFAULT_ADMIN_ROLE, ADMIN_ROLE, OPERATOR_ROLE, UPGRADER_ROLE) are granted to the deployer address (msg.sender). LotturaHub and LotturaTicketNFT use OpenZeppelin Ownable, where the deployer becomes the initial owner.

13.3 — Gnosis Safe Multi-Signature Governance

All admin control of the production deployment is held by Safe{Wallet} (Gnosis Safe v1.5.0) multi-signature wallets, each requiring 3 of 5 signers. No single private key can upgrade, pause or reconfigure the protocol, or move pool funds. Ownership and roles can be checked on the block explorers with owner() and hasRole().

SafeAddressThresholdControls
Protocol Safe0xbbdec976f2367fcb87d4c65c29157ddef3d8941a3 of 5Owner of LotturaCore, with DEFAULT_ADMIN_ROLE, ADMIN_ROLE, OPERATOR_ROLE and UPGRADER_ROLE; owner of the LotturaHub and LotturaTicketNFT contracts on Polygon, Ethereum, Arbitrum and Optimism (the same address on each chain); owner of the ReserveFundPool.
Management & Marketing Safe0x3ce1e16236ab838e6a8125cd859290647941871c3 of 5Owner of the ManagementMarketingPool.
Charity Safe0xd540810fe335aee84804aa3d4d26935a5d66457f3 of 5Owner of the CharityPool.

Day-to-day draw execution uses a separate automation wallet holding only OPERATOR_ROLE (Section 13.5). The Protocol Safe can revoke that role at any time.

13.4 — Ownership Transfer Process

Ownership was transferred to the Safes with dedicated scripts in lottura-contracts, run with NEW_OWNER_ADDRESS set to the Safe address:

1

Create a Gnosis Safe

Go to app.safe.global, connect on Polygon, and create a new Safe with the chosen signers and threshold (3-of-5 in production).

2

Transfer LotturaTicketNFT Ownership

Script 08_transferLotturaTicketNFTOwnership.ts calls transferOwnership(safeAddress) on the NFT contract. The Safe becomes the sole owner and can call setMinter().

3

Transfer LotturaHub Ownership

Script 09_transferLotturaHubOwnership.ts calls transferOwnership(safeAddress). The Safe becomes the Hub owner and can pause/unpause, update config, and execute emergency functions.

4

Transfer LotturaCore Ownership & Roles

Script 10_transferLotturaCoreOwnership.ts performs a comprehensive handover:

  • transferOwnership(safeAddress)
  • grantRole(ADMIN_ROLE, safeAddress)
  • grantRole(OPERATOR_ROLE, safeAddress)
  • grantRole(UPGRADER_ROLE, safeAddress)
  • renounceRole(ADMIN_ROLE, deployer)
  • renounceRole(OPERATOR_ROLE, deployer)
  • renounceRole(UPGRADER_ROLE, deployer)

In V2, the cron job (Vercel cron every 1 minute on mainnet) requires OPERATOR_ROLE on its OPERATOR_PRIVATE_KEY wallet to call executeDraw / setWinningTicketsCounts. Grant OPERATOR_ROLE to both the cron wallet (kept hot) and the Safe (cold). The Safe retains the power to revoke the cron wallet's OPERATOR_ROLE in an emergency.

5

Grant DEFAULT_ADMIN_ROLE to Safe

For full governance, also grant DEFAULT_ADMIN_ROLE to the Safe and have the deployer renounce it. This gives the Safe the ability to grant/revoke all roles in the future. This step can also be done from the frontend's Roles tab at /admin/edit.

13.5 — Operating with the Safe

After ownership transfer, all admin actions require multi-sig approval:

ActionHow to Execute
Manual Execute Draw / Set Winner CountsBackup path only — cron handles these in V2. If cron is down, use Safe's Transaction Builder with the LotturaCore address and ABI.
Rotate VRF SubscriptionPropose setVRFConfig(coordinator, keyHash, subscriptionId, callbackGasLimit, requestConfirmations) on LotturaCore via Transaction Builder.
Pause / Unpause LotturaCorePropose pause() / unpause() via Transaction Builder. Core pause is blackout-gated and requires zero ticketsSold.
Withdraw from a PoolPropose LotturaPool.withdraw(token, amount) from the Safe that owns the pool (Section 13.3).
Contract UpgradePropose upgradeToAndCall() on LotturaCore / LotturaHub / Pool proxies. Requires UPGRADER_ROLE on Core; Core and Hub require pause first (only possible during the blackout window); Pool upgrades are blocked during the blackout window.
Grant/Revoke RolesPropose grantRole() or revokeRole() on LotturaCore

Operational Tip: Dedicated Operator Key

For day-to-day draw execution (which happens on a regular cadence), consider granting OPERATOR_ROLE to a dedicated hot wallet or the cron server's OPERATOR_PRIVATE_KEY in addition to the Safe. This allows automated draw execution while keeping admin functions behind the multi-sig. The Safe retains the ability to revoke this role at any time.

Section 14

Technology Stack

Smart Contracts

TechnologyVersionPurpose
Solidity0.8.22Smart contract language
Hardhat2.26.0Development framework & task runner
OpenZeppelin Contracts5.1.0 / 5.4.0Standard implementations & upgradeable patterns
Chainlink Contracts1.5.0VRF V2.5 (subscription mode) integration
LotturaCoreLib (external library)internalSolidity library deployed separately and linked into LotturaCore at deploy time to fit the EIP-170 bytecode limit
LayerZero V2LatestOApp, OFT, ONFT721 for cross-chain
Ethers.js6.xDeployment scripts & testing

Frontend

TechnologyVersionPurpose
Next.js16.0.7React framework (App Router)
React19.2.0UI library
TypeScript5.8.2Type safety
Tailwind CSS4.1.16Utility-first styling
Wagmi2.19.4React hooks for Ethereum
Viem2.39.0TypeScript Ethereum library
Privy3.6.1Wallet authentication
Redux Toolkit2.10.1Client state management
TanStack Query5.90.6Server state & caching
shadcn/ui + RadixVariousAccessible UI components

Infrastructure

ServicePurpose
Polygon Mainnet (production)Core settlement chain. Amoy is used as a development network only — V2 frontend cron hardcodes useMainnet=true and the subgraph (2.0.4) is mainnet-only.
Chainlink VRF V2.5 (subscription mode)Verifiable randomness oracle
LayerZero V2Cross-chain messaging
Goldsky (The Graph)Subgraph indexing & GraphQL
RelayCross-chain funding from Base and BNB Chain to Polygon
VercelFrontend hosting & blob storage
PrivyWallet auth & account abstraction