# LottoPolla 5/49 (lotto game)

Current approved Lotto rules: 5/49 without bonus number/reimbursement, 100 sats per bet. The simulated HTTP cycle is tested; production admin configuration/results still depend on an authorised signing identity (see [LOTTO-MULTIPLE.md](LOTTO-MULTIPLE.md)). This does not mean real purchases or automatic payouts are enabled.

## What it is

A second type of game, chosen **per draw** in the panel (Events → edit an event → «Game type»), next to the classic one (numbers with endings):

- The player picks **N numbers from 1 to M** (5 of 49 by default). Each combination has a fixed price.
- Several people can play the same combination: **there are no taken numbers** nor locking reservations.
- There are **fixed categories by matches** (5, 4 and 3 by default), each with a % of the prize fund **published in advance** in `config.json`.
- Only for explicit legacy configurations: **bonus number** (a 7th number used for the «5 + C» category) and **reimbursement** (a 0–9 digit per combination, the Spanish *reintegro*).
- The game name is configurable (by default «LottoPolla 5/49»).

## Configuration (`lotto`)

Each event can define its own `lotto` rules; otherwise it inherits the main draw's. Each draw (the main one or one announced in `public.draws`) says which game it is with `game` and can carry a carry-over with `carryIn`:

```json
"game": "lotto",
"price": 100,
"carryIn": 0,
"lotto": {
  "name": "LottoPolla 5/49",
  "pick": 5, "max": 49,
  "bonus": false,
  "reimbursement": false,
  "houseFee": 3,
  "carry": true,
  "tiers": [
    { "id": "5",   "hits": 5, "pct": 50 },
    { "id": "4",   "hits": 4, "pct": 30 },
    { "id": "3",   "hits": 3, "pct": 20 }
  ]
}
```

- `pick` from 1 to 10; `max` up to 99. `houseFee` between 0 and **5 %** (3 % by default).
- The `pct` values are % of the **prize fund** (all the sales) and must add up to **100**. Otherwise the panel does not let you publish.
- With reimbursement a category `{ "id": "R", "reimbursement": true, "pct": … }` is required.
- An announced draw without `game` plays the same as the main one. The carry-over (`carryIn`) is **not** inherited: it belongs to each draw.
- Only lotto draws with the same N of M and the same reimbursement can be bought together (one invoice for several draws).

### Probabilities with 5 of 49 without bonus number

There are C(49,5) = 1,906,884 single combinations. The probability of h matches is C(5,h) × C(44,5-h) / C(49,5).

| Category | % of the net fund after 3 % management | Possible winning combinations |
|---|---|---|
| 5 matches | 50 % | 1 |
| 4 matches | 30 % | 220 |
| 3 matches | 20 % | 9,460 |

Picking six numbers generates C(6,5)=6 sub-bets for 600 sats on a single ticket. Each sub-bet takes part separately and all its prizes are aggregated. Categories without winners carry over when `carry=true`. Legacy events with explicit 6/49 rules keep those rules; they are not migrated over sales.

## LOTTO21 4/21 (template `lotto21`, minutes of 23/11/2026)

| | |
|---|---|
| Game | 4 of 21 → 5985 combinations, 210 sats per bet |
| Split of the fund | 50 / 35 / 15 for 4 / 3 / 2 matches (2 matches ≈ refund of the bet) |
| `seed` | 10 000 sats contributed by the owner to **each of the first 21 official draws** (from LOTTO21 #1, 03/12/2026; until 02/12/2026 the plan said 21 000 × 10), top category only. Shown on the web, in the results (`ownerSeed`) and in Treasury as his contribution. If nobody hits the top category it rolls over with the jackpot; the next draw gets its own 10 000 on top. From the 22nd draw on, 0. |
| `jackpot` | `true` (LOTTO21 created from 02/12/2026, with `carry: false`): **4 matches is a jackpot**. See «Jackpot» below. |
| `maxSalesPct` | 49 → at most **2932 bets per draw** (`salesCapOf`). The server refuses quotes beyond it (sold + pending invoices), and `buildState` refunds any bet paid beyond it (whoever paid first stays), so anyone with the purchase list can check it. It is a cap on the draw, never per person. |
| Carry-over | no ceiling |

All these fields are optional: rules without them keep exactly the same normalized form as before.

### Jackpot (02/12/2026)

Problem found on 02/12/2026: with `carry: false`, a top category without winners was shared among the lower ones
(step 6 below). That is not how LOTTO21 is meant to work. From that date the LOTTO21 template carries
`carry: false, jackpot: true`:

- **4 matches is only for 4-match winners.** Its amount = 50 % of the sales of the draw + the carry-over received +
  the owner's contribution (`seed`). If nobody hits it, **all of it** rolls over to the 4-match category of the next
  draw. It never gives to, nor receives from, the other categories.
- **3 or 2 without winners**: its share is split among the other lower category with winners, in proportion to its %.
  If neither has winners, it rolls over to the next draw's jackpot.
- Rounding remainders roll over too.

**Earlier draws are not touched.** Their stored rules have no `jackpot` key, they normalize exactly as before and
their results, signed and paid, stay as they were (the server keeps checking them against those rules). Draws already
created and on sale keep their rules too (rules are frozen once an event has invoices): the jackpot rule applies to
the LOTTO21 created from the panel from that date (or to a draw without sales whose rules are edited).

### Jackpot chain: `carryFrom` (02/12/2026)

The carry-over used to be moved by hand (button «Move the carry-over…» + publish the config). That does not work for a
weekly series: the next LOTTO21 is usually on sale before the previous one is held, and `carryIn` is frozen once a draw
has invoices. Now a lotto draw can say **which draw it receives the carry-over from**: `"carryFrom": "LOTTO21-03"`.

- «New event» fills it in for each new LOTTO21: the latest earlier LOTTO21 of the same kind (real or test) whose
  carry-over no other draw receives yet. It is frozen with the rules once the draw sells. The panel can set it by hand on
  a draw without sales («Receives the jackpot of»). With `carryFrom`, `carryIn` must stay empty.
- The carry-over is **not typed**: it is the `carryNext` of the signed result of that draw. The server resolves it
  (`core.withCarry`) when it computes, checks and pays results, and publishes it in `GET /api/draws`
  (`lotto.carryIn`, `lotto.carryFrom`, `lotto.carryPending`). Pages without the server read `results/<carryFrom>.json`.
- The server **does not compute** a draw's result while the draw it receives from has no result (`carryPending`), so a
  jackpot is never lost or guessed. A manual result refuses too.
- A draw without sales still signs its «no-sales» result, and for lotto it now carries `carryReceived`, `ownerSeed` (if
  paid) and `carryNext` = carry-over + contribution, so the chain goes on.
- The pre-draw commitment records `carryFrom`; the result records `carryFrom` and `carryReceived`.
- Validation: the origin must be an earlier Lotto draw (listed, or with a result kept on the server), and no two draws
  can receive the same carry-over.

### Informative breakdowns

Lotto results add (only informative; the split is the same function):

- `jackpot`: `{ sales, carryIn, seed, total }` — where the top category comes from.
- `carryNextParts`: `{ jackpot, categories, rounding }` — what rolls over and why (`carryNext` is their sum).

The home page shows the pot as «sales + rolled over from earlier draws + operator», and the jackpot today as
«{total} = {sales} + {carry-over} + {operator}».
**Paying the `seed`.** A draw with `seed` does not sell (`409`, `seedPending`) until the owner pays it:
- In the panel, saving the events to the VPS asks for the invoice of the selected draw (`POST /api/admin/events/<id>/seed`, signed with NIP-98) and shows it as a QR. The box «💰 Owner's contribution» stays on screen until it is paid.
- The server marks it paid only when its wallet confirms it (`GET /api/seed/<id>` is public), signs it as a kind 1 event (`k=seed`, `d=seed:<id>`), publishes it and adds it to the pre-draw commitment (`seed`).
- It is never stored as a purchase. A paid contribution is never charged twice; if the rules change its amount afterwards, the server refuses until they are put back.

Pending (separate PRs): bets hidden until the close (only aggregate totals during sales) and the colour-only heatmap from 50 bets.

## Winning combination from blocks (verifiable algorithm, separate from the manual mode)

The simulator's manual mode does not prove randomness and must not pass for the Christmas block result. A future production manual route must be limited to explicit, authenticated TEST events separate from the official draw.

1. The **first Bitcoin block with a time equal to or later than `drawAt`** is taken (as in the numbers game). It does not move to the next block: nobody needs to have played the combination.
2. `h1 = SHA-256("POLLA-lotto-v1|" + draw_id + "|" + block_hash)`, with the block hash in lowercase hexadecimal, as mempool.space shows it. The text is UTF-8 encoded.
3. `h(k+1) = SHA-256(h(k))`, over the **32 bytes** of the previous hash (not over its hexadecimal text).
4. From each hash the **first 4 bytes** are read as an unsigned big-endian integer: `x` between 0 and 2³² − 1.
5. To get a number from 1 to M without modulo bias (rejection sampling): if `x ≥ 2³² − (2³² mod M)` the hash is discarded; otherwise the number is `1 + (x mod M)`. If that number has already come out, it is also discarded.
6. The first N accepted numbers are the combination; the next one, the **bonus number** (if enabled); and then the **reimbursement digit** (if enabled), with the same rule and M = 10, as `x mod 10` (0–9).

Including the draw id makes two draws decided by the same block give different combinations. The public website shows every step (hash, x, accepted or discarded number and why).

### Recompute it yourself (Python 3, no dependencies)

```python
import hashlib
def lotto(block_hash, draw_id, pick=5, maxn=49, bonus=False, reimb=False):
    h = hashlib.sha256(f"POLLA-lotto-v1|{draw_id}|{block_hash.lower()}".encode()).digest()
    nums, c, r = [], None, None
    while len(nums) < pick or (bonus and c is None) or (reimb and r is None):
        x = int.from_bytes(h[:4], "big")
        if len(nums) == pick and (not bonus or c is not None):          # reimbursement digit
            if x < 2**32 - 2**32 % 10: r = x % 10
        elif x < 2**32 - 2**32 % maxn:
            v = 1 + x % maxn
            if v not in nums and v != c:
                if len(nums) < pick: nums.append(v)
                else: c = v
        h = hashlib.sha256(h).digest()
    return sorted(nums), c, r

print(lotto("00000000000000000001ae4ba0e035415ad48348417571ad13b5965353d7eba3", "LOTTO5-01"))
# A recomputation example, not an official result nor a manual test result.
```

The tests (`tests/lotto.test.mjs`) compare the website's implementation with a second independent one (`node:crypto`) over hundreds of random blocks.

## Splitting the pot

Everything in whole sats, always rounding down:

1. **Pot** = valid combinations × draw price (without tips or payments to refund).
2. **Fund** = pot. Costs (`houseFee`) are deducted from each prize when it is collected ([COSTS.md](COSTS.md)); `house` is 0.
3. Amount of each category = ⌊fund × pct / 100⌋. The **carry-over received** (`carryIn`) is added entirely to the top category.
4. Each combination wins in the **highest category it meets** (5 > 4 > 3 in the approved rules; legacy categories only if explicitly listed). With reimbursement, if it matches the digit it also wins the reimbursement category.
5. Each category is split **equally** among its winning combinations: ⌊amount / winners⌋ each. If two purchases play the same combination and it wins, they are two winners.
6. **Category without winners**: with `carry: true` its amount goes to the **carry-over of the next draw**; with `carry: false` it is shared among the categories that do have winners in proportion to their %. If there is no winner at all, everything goes to the next draw. With `jackpot: true` the top category is left out of this step: without winners it always rolls over whole, and the other categories are shared only among themselves (if none has winners, they roll over).
7. **Rounding remainders** also go to the next draw.

Balance (checked by the code and the tests): `paid + carry_next = fund + carry_received + owner_contribution`, and `fund = pot`. Never more than that is paid.

With `carryFrom` (see «Jackpot chain») the next draw receives `carryNext` by itself. Draws without it keep the old way: after computing the result, the panel has the «Move the carry-over to the next Lotto draw» button, which puts it in the `carryIn` of the next lotto draw by date; then the `config.json` must be published. The value always stays in `results/<id>.json` (`carryNext`), so anyone can check the next draw brings what it should.

## Purchase, ledger and claim

- **Invoice**: the same v2 description as the rest (`@2|ID:price+…|comb1,comb2,…|hash|contacts|tip`), with each combination in canonical form: sorted, no repeats and zero-padded (`03-11-17-25-38`, `M01-02-03-04-05-06` for a multiple; `…R7` only with legacy reimbursement). A mistyped combination does not count. At most 20 selections, 126 sub-bets per selection and 630 sub-bets per purchase as technical limits.
- **Validity**: the usual rules (full amount, within the reservation, before the close, declared price not lower than the configured one). There are no double payments because nothing is taken.
- **CSV ledger**: one line per combination and draw (column `number` = the combination) and a `game` column. `purchase_id`, `position` and `lines_in_purchase` link the lines of a purchase, as in #13.
- **One secret code per purchase** (#13): it claims any winning combination of the purchase, one or several, in any of its draws.
- **Results** (`results/<id>.json`, v1 with `"game": "lotto"`): combination, bonus number, reimbursement, rules used, house, fund, carry-overs, categories (amount, winners, per winner) and `prizes[]` with **one aggregated entry per winning selection and purchase**, including all its winning sub-bets (`n`, `prize`, `sats`, `purchase`, `h`).
- **Ticket**: the same design as #11, with the combination as balls, the game name and the reimbursement digit if any.
