# Buying, verifying and claiming without a browser (for agents)

The contract is [`/openapi.json`](../openapi.json); this is the walkthrough. Nothing here needs the
website (the SPA) or any key of the lottery. **Production is Bitcoin mainnet when `testMode` is false**: an invoice is
real money. Never pay blindly, never retry a payment by guessing, and never log, paste or send a claim code
(`POLLA-…` / `LOTTO-…`), an `nsec` or an NWC connection string.

The lottery key (the auditor) signs the sales, the list of participants, the block anchor and the result. That is part
of the design. Prizes are paid **by hand** after review (`payouts: false` on purpose): a claim never pays by itself.

## 1. Read the state

```http
GET https://polla21.org/api/health
GET https://polla21.org/api/draws
```

- `health.testMode === false` → mainnet. `health.payouts === false` → prizes are paid by hand.
- In `/api/draws`, buy only a draw with **`onSale: true`**. `onSale` is the server's own answer, with the same checks as
  `POST /api/invoice` (enabled, not paused, sales window open, LOTTO21 contribution paid…). Do not buy because an id is
  in `enabledDraws` or because the dates «look» open: «announced» is not «on sale».
- From the same entry take `price` (sats per number or per combination), `tickets` / `lotto`, `maxPerBuy`,
  `invoiceExpiry` (typically 300 s) and `closeAt`.

## 2. Make the purchase's secret code (yours alone)

The buyer keeps an 18-byte random **secret**; only hashes leave the buyer:

| Value | How |
|---|---|
| `sk` (claim key) | `sha256("POLLA-claim-sk-v1|" ‖ secret)` |
| `pubkey` | secp256k1 x-only public key of `sk` (as in Nostr) |
| `claim` (claim hash) | `hex(sha256("POLLA-claim-hash-v1|" ‖ pubkey bytes))` |
| printed code | `POLLA-` (or `LOTTO-` for LOTTO21) + base32 Crockford of `secret ‖ sha256("POLLA-claim-check-v1|" ‖ secret)[0..2]`, in groups of 4 |

The reference implementation is `purchases.js` (`newClaimCode`, `claimKeys`, `claimHashFromPubkey`). Store the secret
(or the printed code) somewhere safe: without it the prize cannot be claimed. It is never sent anywhere.

## 3. Create the invoice

```http
POST https://polla21.org/api/invoice
Content-Type: application/json

{ "draws": ["<id>"], "nums": ["007"], "claim": "<claim hash, 64 hex>", "requestId": "<claim hash>", "tip": 0 }
```

- `nums`: zero-padded to the board's digits (`"007"` on a 1000-number board). One invoice may cover several draws
  (`draws`) of the same game and shape; every one must be `onSale`.
- `contact` (optional) must be encrypted to the lottery's `contactKey` (`e1.…`, see `common.js` `encryptForAdmin`). If
  you cannot encrypt it, leave it out.
- `hn` (optional): one claim hash per `"draw:number"` (bearer tickets). Leave it out if you do not need them.
- **The server computes the amount** (`numbers × sum of prices + tip`). Compute it yourself and **reject the invoice if
  `tx.amount` differs**, if it is not a BOLT11 for that amount, or if `tx.expires_at` is too close.
- **Idempotency**: `requestId` (the website uses the claim hash). Repeating the **same** body with the same `requestId`
  returns the same invoice instead of creating another; a different body with that id is `409`. Without `requestId`, a
  retried `POST` creates a second invoice: do not retry blindly.
- Errors are `{"error": "…"}` in the `Accept-Language` language: `400` (invalid list, numbers, or `Sales for that draw are
  closed`), `409` (numbers taken, LOTTO21 cap, contribution unpaid), `415` (no `Content-Type: application/json`),
  `429` (wait `Retry-After`), `503` (draw not on sale, or sales paused).

The answer is `{ "tx": { "key", "amount", "expires_at", "invoice": "lnbc…", "payment_hash", … } }`.

## 4. Pay and wait

Pay `tx.invoice` (BOLT11; `lnbc…` on mainnet) before `tx.expires_at`. Then poll:

```http
GET https://polla21.org/api/invoice/<tx.key>
```

until `tx.settled_at > 0` (paid) or `expires_at` passes (not paid: the numbers go back on sale). A few seconds between
polls is enough (`429` means slow down). An invoice paid after it expired or after the close is not a sale: it goes to
refunds.

## 5. Verify (never from the HTML)

```http
GET https://polla21.org/api/proof/<id>          # bundle: catalog entry + signed result + commitment + anchor
GET https://polla21.org/api/results/<id>/proof  # signed result + OpenTimestamps stamp
GET https://polla21.org/api/commitment/<id>     # signed list of participants (before the draw time)
GET https://polla21.org/api/anchor/<id>         # signed block anchor (anchor-v1)
```

Check that each event is signed by the lottery key (`/api/health` → `signer`) and follow
[VERIFY-DRAW.md](VERIFY-DRAW.md), or run the independent verifier, which checks all of it without trusting the server:

```sh
node scripts/verify-draw.mjs --server https://polla21.org/api --draw <id>
```

A `404` of these routes means «not published yet» (for example a draw held without a signed list), not a routing error.

## 6. Claim a prize (it is not a payment)

```http
POST https://polla21.org/api/claim
Content-Type: application/json

{ "event": { …signed Nostr event… }, "binding": { …only with a BOLT11 destination… } }
```

- `event`: kind `30078`, tag `["t","polla-claim-api"]`, **signed with the claim key `sk`** (the code itself never
  travels), `created_at` within 10 minutes of the server's clock, content
  `{"v":1,"h":"<claim hash>","k":"<purchase key>","picks":[{"d":"<draw>","n":"<number>"}],"pay":"<BOLT11 | Lightning address | LNURL>","c":"","at":<unix>}`.
  The reference builder is `purchases.js` `buildServerClaim`.
- With a BOLT11 destination the invoice must be for the exact prize amount and come with the signed `binding` to its
  payment hash (`purchases.js` `buildPaymentBinding`).
- The server checks that the prize is in the **pre-draw commitment** before anything is paid, stores the claim **for
  review** and the organiser pays it by hand. `GET /api/claim/<id>` shows its state. A claim under review is **not** a
  paid prize. `payouts` stays false: this API never enables automatic payouts.
- Never put the code in URLs, logs, issues or examples. An empty body returns `400 malformed claim`.

## Trying it without money

Run the server in test mode (`node server/test-mode.mjs`, see [TEST-MODE.md](TEST-MODE.md)): fake invoices
(`lnmock1pollatest…`) and a simulated payment. On production, only requests that must fail are safe to try (a closed
draw → `400 Sales for that draw are closed`, `{}` → `400 Invalid draw list`, no JSON content type → `415`).
