prizerail 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -109,10 +109,10 @@ To answer a user who asks whether their entries counted, look them up in one dra
109
109
 
110
110
  ```ts
111
111
  const found = await campaign.drawings.entrant(drawingId, entrantId)
112
- // { entered, entries, position, receivedAt, drawn, winner }
112
+ // { entered, entries, position, receivedAt, drawn, winner, winners, totalCents }
113
113
  ```
114
114
 
115
- `entered` is false, not an error, for someone who isn't in the drawing. `winner` stays null for everyone until `drawn` is true. See [Look up an entrant](https://docs.prizerail.com/api/drawings#look-up-an-entrant).
115
+ `entered` is false, not an error, for someone who isn't in the drawing. `winner` stays null for everyone until `drawn` is true. In a campaign with repeat winners one entrant can win several slots, so credit users from `winners` or `totalCents`, not `winner` alone. See [Look up an entrant](https://docs.prizerail.com/api/drawings#look-up-an-entrant).
116
116
 
117
117
  ## Draw now, in the sandbox
118
118
 
package/dist/client.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Http } from "./http.js";
2
2
  import type { Campaign, Drawing, DrawingRef, DrawingStatus, DrawingsPage, Entrant, EntrantEvent, EntrantLookup, EntriesPage, Guarantee, SendEntriesResponse, SentEntrant } from "./types.js";
3
3
  import { type DrawProof, type VerifyResult } from "./verify.js";
4
- export declare const VERSION = "1.2.0";
4
+ export declare const VERSION = "1.3.0";
5
5
  /** The API takes up to this many entries per request. */
6
6
  export declare const ENTRIES_PER_REQUEST = 1000;
7
7
  export type PrizerailOptions = {
package/dist/client.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { PrizerailCutoffError, PrizerailDrawingChangedError, PrizerailError, } from "./errors.js";
2
2
  import { Http } from "./http.js";
3
3
  import { verifyDraw } from "./verify.js";
4
- export const VERSION = "1.2.0";
4
+ export const VERSION = "1.3.0";
5
5
  const badPage = (detail) => new PrizerailError(0, "invalid_response", `Paging stopped: ${detail}.`);
6
6
  /** The API takes up to this many entries per request. */
7
7
  export const ENTRIES_PER_REQUEST = 1000;
package/dist/types.d.ts CHANGED
@@ -41,6 +41,12 @@ export type Campaign = {
41
41
  endsAt: string | null;
42
42
  };
43
43
  winnersPerDraw: number;
44
+ /**
45
+ * True when one entrant can win several slots in a draw. New drawings take
46
+ * a change, so `nextDrawing.repeatWinners` can differ for up to one draw
47
+ * period. Absent from servers before repeat winners shipped.
48
+ */
49
+ repeatWinners?: boolean;
44
50
  prizeTable: PrizeTable | null;
45
51
  guarantee: {
46
52
  amountCents: number;
@@ -55,6 +61,7 @@ export type Campaign = {
55
61
  drawAt: string;
56
62
  cutoffAt: string;
57
63
  winnersPerDraw: number;
64
+ repeatWinners?: boolean;
58
65
  averagePrizeCents: number | null;
59
66
  } | null;
60
67
  };
@@ -95,6 +102,8 @@ export type Drawing = {
95
102
  cutoffAt: string;
96
103
  status: DrawingStatus;
97
104
  winnersExpected: number;
105
+ /** Whether one entrant can win several slots in this drawing. */
106
+ repeatWinners?: boolean;
98
107
  prizeTable: PrizeTable | null;
99
108
  needsAttention: string | null;
100
109
  winners: Winner[];
@@ -143,12 +152,22 @@ export type EntrantLookup = {
143
152
  * `winner` is null for everyone, so null alone doesn't mean they lost.
144
153
  */
145
154
  drawn: boolean;
146
- /** Their win, or null. `position` is their slot in the drawing's winners. */
147
- winner: {
148
- position: number;
149
- amountCents: number;
150
- heldForManualPayout: boolean;
151
- } | null;
155
+ /**
156
+ * Their win, or null. `position` is their slot in the drawing's winners.
157
+ * With repeat winners it's their first slot, so credit users from
158
+ * `winners` or `totalCents`.
159
+ */
160
+ winner: EntrantSlot | null;
161
+ /** Every slot they won, in slot order. Empty until drawn. */
162
+ winners?: EntrantSlot[];
163
+ /** What they won in all, or null if they didn't win. */
164
+ totalCents?: number | null;
165
+ };
166
+ /** One winning slot in `drawings.entrant()`. */
167
+ export type EntrantSlot = {
168
+ position: number;
169
+ amountCents: number;
170
+ heldForManualPayout: boolean;
152
171
  };
153
172
  export type DrawingsPage = {
154
173
  drawings: Drawing[];
@@ -29,7 +29,8 @@
29
29
  * at or above 2^256 mod the weight of the entrants not picked yet. The
30
30
  * pick is that value mod the same weight, and the winner is the entrant
31
31
  * whose range holds it, counting the ones still in, in index order. They
32
- * sit out later slots.
32
+ * sit out later slots, unless the proof's entrantList.repeatWinners is
33
+ * true: then nobody sits out, and one entrant can fill several slots.
33
34
  * 4. Each winner's ID hashes to the entry the pick landed on.
34
35
  * 5. Each winner's random value is the first
35
36
  * keccak256(abi.encode(bytes32 entropy, bytes32 campaignId,
@@ -310,7 +311,8 @@ export function selectWinners(
310
311
  campaignId,
311
312
  drawingNumber,
312
313
  list,
313
- winnerCount
314
+ winnerCount,
315
+ repeat = false
314
316
  ) {
315
317
  const weights = list.map(([, weight]) => weight);
316
318
  const sums = new Array(weights.length + 1).fill(0);
@@ -335,7 +337,8 @@ export function selectWinners(
335
337
  const entropyBytes = hexBytes(entropy);
336
338
  const id = campaignIdBytes32(campaignId);
337
339
  const picks = [];
338
- for (let slot = 0; slot < Math.min(winnerCount, list.length); slot++) {
340
+ const slots = repeat ? winnerCount : Math.min(winnerCount, list.length);
341
+ for (let slot = 0; slot < slots; slot++) {
339
342
  const threshold = (1n << 256n) % BigInt(remaining);
340
343
  let r;
341
344
  for (let k = 0n; ; k++) {
@@ -354,6 +357,7 @@ export function selectWinners(
354
357
  const pick = Number(BigInt(r) % BigInt(remaining));
355
358
  const entrantIndex = find(pick);
356
359
  picks.push({ entrantIndex, selectionValue: r, pick });
360
+ if (repeat) continue;
357
361
  add(entrantIndex, -weights[entrantIndex]);
358
362
  remaining -= weights[entrantIndex];
359
363
  }
@@ -545,6 +549,9 @@ export function verifyProof(proof, entrants) {
545
549
  /** The entrant list's checks: its root, then every pick. */
546
550
  function checkEntrants(proof, entrants, check, results) {
547
551
  const { root, count, totalWeight, winnersRequested } = proof.entrantList;
552
+ // Proofs from before the setting have no field, and those draws took
553
+ // each winner out.
554
+ const repeat = proof.entrantList.repeatWinners === true;
548
555
  if (
549
556
  typeof root !== "string" ||
550
557
  !HASH.test(root) ||
@@ -562,10 +569,16 @@ function checkEntrants(proof, entrants, check, results) {
562
569
  );
563
570
  return;
564
571
  }
565
- const expected = Math.min(winnersRequested, count);
572
+ // Without repeat winners each entrant fills at most one slot, so the draw
573
+ // has as many winners as asked for, or as entrants if fewer. With them,
574
+ // every slot asked for is filled. Draws the first contracts ran never
575
+ // repeat, so their proofs say false or leave the field out.
576
+ const expected = repeat
577
+ ? winnersRequested
578
+ : Math.min(winnersRequested, count);
566
579
  check(
567
580
  proof.results.length === expected,
568
- `${expected} winner${expected === 1 ? "" : "s"}: ${winnersRequested} asked for, from ${count.toLocaleString("en-US")} entrants`
581
+ `${expected} winner${expected === 1 ? "" : "s"}: ${winnersRequested} asked for, from ${count.toLocaleString("en-US")} entrants${repeat ? ", repeat winners allowed" : ""}`
569
582
  );
570
583
  if (!entrants) {
571
584
  // The root and the picks are what make an entrants draw checkable, so
@@ -633,7 +646,8 @@ function checkEntrants(proof, entrants, check, results) {
633
646
  proof.campaign.id,
634
647
  proof.drawing.number,
635
648
  list,
636
- winnersRequested
649
+ expected,
650
+ repeat
637
651
  );
638
652
  for (const [slot, pick] of picks.entries()) {
639
653
  const result = results.get(slot);
package/dist/verify.d.ts CHANGED
@@ -23,6 +23,8 @@ export type DrawProof = {
23
23
  count: number;
24
24
  totalWeight: number;
25
25
  winnersRequested: number;
26
+ /** One entrant can fill several slots. Absent, or false, they can't. */
27
+ repeatWinners?: boolean;
26
28
  lockedAt: string | null;
27
29
  };
28
30
  [field: string]: unknown;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prizerail",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "The Prizerail SDK: send entries, read draws and verify them.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://docs.prizerail.com",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prizerail",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Integrate Prizerail prize draws into an app, check an integration end to end, and look up or verify draws.",
5
5
  "author": {
6
6
  "name": "Prizerail",
@@ -32,6 +32,7 @@ It prints `✓` for a passing check, `✗` for a failing one, and `i` for a note
32
32
  - **No entries in the open drawing** with a passing key and campaign: the sender hasn't run yet, or it's pointed at another campaign or the other environment. Check `PRIZERAIL_CAMPAIGN` and the key's prefix against the site.
33
33
  - **Entries in the last drawing but not this one:** entries land in the drawing whose cutoff is next when they arrive, and totals don't carry over. A daily job must run before each cutoff.
34
34
  - **Every entrant at 1 entry** when the app rewards actions: set mode sends each entrant's total, so `entries` has to be sent every time. Or the app meant increment mode.
35
+ - **One user's entries missing:** look that id up with `campaign.drawings.entrant(drawingId, entrantId)`, or `GET /api/v1/campaigns/{slug}/drawings/{id}/entrant?entrantId=…` with a `+` sent as `%2B`. `entered: false` is a `200`, not an error: the entries went to another drawing, or never arrived.
35
36
  - **Fewer entrants than expected:** the eligibility filter, or an `eventId` reused across different events (`409 event_conflict`, nothing in that request stored). Look at the sender's logs for `409`s.
36
37
  - **A sandbox draw with winners:** the integration works end to end. `npx prizerail verify <slug> <drawing id>` checks any draw again from its public proof.
37
38
 
@@ -5,17 +5,17 @@ description: "Check the status of a Prizerail campaign's draws (whether a draw i
5
5
 
6
6
  # Prizerail draws: status and verification
7
7
 
8
- Prizerail runs prize draws for partner apps. Through each period the partner sends Prizerail its entrants. At the cutoff Prizerail locks the entrant list, a random value draws the winners from it and decides each winner's prize from the campaign's prize table, and the prizes are sent to the partner to pay out. Everything below uses public endpoints: no keys, no accounts.
8
+ Prizerail runs prize draws for partner apps. Through each period the partner sends Prizerail its entrants. At the cutoff Prizerail locks the entrant list, a random value draws the winners from it and decides each winner's prize from the campaign's prize table, and the prizes are sent to the partner to pay out. Everything below uses public endpoints, with no keys or accounts, except the one lookup marked as needing the partner's API key.
9
9
 
10
10
  **Never compute the hashes yourself.** keccak256 can't be done reliably by reasoning, and Python's `hashlib.sha3_256` is a different hash (different padding) that gives different answers. Run the verify script below and report what it prints.
11
11
 
12
12
  ## Concepts
13
13
 
14
14
  - **Campaign:** a partner's draw, found by its slug in `https://www.prizerail.com/campaigns/{slug}`. Draws run on a schedule (hourly, daily, weekly or monthly) in the campaign's time zone.
15
- - **Entrants:** the partner sends them, each an id with a number of `entries` (1 unless it sends more), which the proof calls its `weight`. Nobody picks who wins: the random value draws the winners from the locked list, each entrant in proportion to their weight, and nobody wins twice in one draw. A draw proves the winners and prizes are fair for the list it was given.
15
+ - **Entrants:** the partner sends them, each an id with a number of `entries` (1 unless it sends more), which the proof calls its `weight`. Nobody picks who wins: the random value draws the winners from the locked list, each entrant in proportion to their weight, and nobody wins twice in one draw unless the proof's `entrantList.repeatWinners` is true. A draw has `winnersRequested` winners. Without `repeatWinners` that's capped at `count`, so every entrant wins when there are fewer. With it, every slot is filled even from a short list. A draw proves the winners and prizes are fair for the list it was given.
16
16
  - **Cutoff:** the partner can send entries until `cutoffAt`. Each campaign sets how long before `drawAt` that is, from minutes to days.
17
17
  - **Entrant list fingerprint:** the root of an OpenZeppelin `StandardMerkleTree` over `(uint256 index, bytes32 keccak256(bytes(entrantId)), uint64 weight)`. The tree sorts its leaves, so the root commits to the set of entries and the index is the only order: indices must run exactly 0 to `count - 1`. It is recorded and published, with the hashed list, when the list locks, before the random value exists.
18
- - **Winners:** for slot `j`, `r` is the first `keccak256(abi.encode(bytes32 entropy, bytes32 campaignId, uint64 drawingId, bytes32 "prizerail.entrant", uint256 j, uint256 k))` for `k = 0, 1, …` that is at least `2^256 mod remaining`, where `remaining` is the weight of the entrants not drawn yet. `pick = r mod remaining`, and the winner is the entrant whose run of weight holds `pick`, counting the ones still in, in index order
18
+ - **Winners:** for slot `j`, `r` is the first `keccak256(abi.encode(bytes32 entropy, bytes32 campaignId, uint64 drawingId, bytes32 "prizerail.entrant", uint256 j, uint256 k))` for `k = 0, 1, …` that is at least `2^256 mod remaining`, where `remaining` is the weight of the entrants not drawn yet (with `repeatWinners`, nobody is taken out, so it's the whole list's weight every slot). `pick = r mod remaining`, and the winner is the entrant whose run of weight holds `pick`, counting the ones still in, in index order
19
19
  - **Prize:** the same math the Prizerail contract runs onchain. For the winner in slot `i`:
20
20
  - `campaignId` is the proof's `campaign.id` as ASCII, right-padded to 32 bytes, and `drawingId` is `drawing.number`
21
21
  - `randomValue` is the first `keccak256(abi.encode(bytes32 entropy, bytes32 campaignId, uint64 drawingId, uint256 i, uint256 k))` for `k = 0, 1, …` that is at least `2^256 mod denominator`. In practice `k` is always 0
@@ -48,7 +48,7 @@ Base `https://www.prizerail.com`. Public, with CORS `*`.
48
48
  | Endpoint | Returns |
49
49
  |---|---|
50
50
  | `GET /campaigns/{slug}/draws.json` | `campaign` (name, status, cadence, timezone, winnersPerDraw, payout chain and token), `draws[]` newest first (`id`, `number`, `drawAt`, `cutoffAt`, `stage`, `winners`, `winnersCommitment`, `entrants`, `lockedAt`, `settledAt`, `paidAt`, `proof`), and `nextBefore`. Page back with `?before={nextBefore}`. `?limit=` up to 100, default 30 |
51
- | `GET /campaigns/{slug}/draws/{id}/proof.json` | A drawn draw's proof: `entrantList` (`root`, `count`, `totalWeight`, `winnersRequested`, `lockedAt`, `url` of the list), `entropy` (`provider`, `requestId`, `value`, `revealedAt`), `prizeTable` (`denominator`, `tiers[]` of `amountCents` and `weight`), `results[]` (`position`, `winner`, `displayName`, `entrantPosition`, `selectionValue`, `pick`, `randomValue`, `roll`, `amountCents`). `displayName` is the partner's public name for the winner, shown only and never hashed. |
51
+ | `GET /campaigns/{slug}/draws/{id}/proof.json` | A drawn draw's proof: `entrantList` (`root`, `count`, `totalWeight`, `winnersRequested`, `repeatWinners`, `lockedAt`, `url` of the list), `entropy` (`provider`, `requestId`, `value`, `revealedAt`), `prizeTable` (`denominator`, `tiers[]` of `amountCents` and `weight`), `results[]` (`position`, `winner`, `displayName`, `entrantPosition`, `selectionValue`, `pick`, `randomValue`, `roll`, `amountCents`). `displayName` is the partner's public name for the winner, shown only and never hashed. |
52
52
  | `GET /campaigns/{slug}/draws/{id}/entrants.json?page=1` | A locked draw's entrant list, hashed: `entrants[]` of `[index, keccak256(bytes(entrantId)), weight]` sorted by index, 20,000 a page, with `root`, `count`, `totalWeight`, `page`, `pages` and `next` |
53
53
  | `GET /verify/verify-draw.mjs` | The verify script (Node.js 18+, no dependencies) |
54
54
 
@@ -96,6 +96,11 @@ If the user can't run code, the campaign page has a "Verify in your browser" but
96
96
 
97
97
  To cross-check with a library instead, viem's `keccak256(encodeAbiParameters(...))` with the types above gives the same values.
98
98
 
99
+ ## Check someone was in a draw
100
+
101
+ - **With no key:** once a draw is drawn, `verifyDraw(proofUrl)` and then `wasEntered(entrantId, result.entrants)` from the `prizerail` package find their row in the published list. Only read the answer when `result.ok` is true and `result.entrants` is there: `verifyDraw` still returns the rows when a check fails, and `wasEntered` only searches them. Otherwise say their entry couldn't be verified, not that they weren't in it. That is the independent check, and it gives their `entries` and index only.
102
+ - **With the partner's API key:** `new Prizerail({ apiKey }).campaign(slug).drawings.entrant(drawingId, entrantId)`, which picks the site from the key, or `GET /api/v1/campaigns/{slug}/drawings/{id}/entrant?entrantId=…` with a `+` sent as `%2B`, on the key's own site (`https://sandbox.prizerail.com` for a `pr_sandbox_` key), says what Prizerail received for any drawing, open ones too, and what they won. It is Prizerail's own record, not an independent check. `entered: false` is an answer, not an error. `winner` is `null` for everyone until `drawn` is true, so check `drawn` before reading a `null` winner as a loss, and a `skipped` drawing was never drawn. In a guarantee draw everyone has 1 entry.
103
+
99
104
  ## Gotchas
100
105
 
101
106
  - **The index is the order, not the row.** A shuffled `entrants.json` gives the same root and winners. A duplicate, missing or out-of-range index makes the list invalid, and the verify script reports it.
@@ -167,6 +167,21 @@ Write them in the project's own test framework. Each one guards a rule above:
167
167
 
168
168
  With a `pr_sandbox_` key and a sandbox campaign, send a few entrants and then run `npx prizerail check <slug> --draw` (the `prizerail-check` skill). It checks the key, the campaign and what was sent, then **draws now**: the drawing locks, settles and pays within seconds, and its proof is verified, so the whole integration is seen to pass. Draw now consumes the drawing's entries and opens a fresh, empty one, so send entries again before any second draw. To draw by hand instead, use `campaign.drawings.run(drawingId)` in the SDK, `POST /campaigns/{slug}/drawings/{id}/run`, or the **Draw now** button on the drawing in the sandbox portal, then `campaign.drawings.latest()` shows the winners and `npx prizerail verify <slug> <drawing id>` checks the proof.
169
169
 
170
+ ## 9. When a user asks whether their entries counted
171
+
172
+ Look them up in that drawing rather than paging `entries.all()`, from the server like every call with the key. The drawing taking entries now is `(await campaign.entries.openDrawing()).id`, or `drawing.id` from a `send()` result. Earlier ones come from `campaign.drawings.list()`, newest first, and open ones from `campaign.drawings.list({ status: "open" })`, soonest cutoff first, so the next one is the open drawing after it.
173
+
174
+ ```ts
175
+ const entrantId = await hashEntrant(user.id, process.env.ENTRANT_ID_KEY!)
176
+ const found = await campaign.drawings.entrant(drawingId, entrantId)
177
+ // { drawing, entrantId, entered, entries, position, receivedAt, drawn, winner }
178
+ ```
179
+
180
+ - `entered: false` is an answer, not an error: entries sent after the cutoff went to the next drawing, and ones that failed to send aren't anywhere. Check the next drawing and the sender's logs.
181
+ - `winner` is `null` for everyone until `drawn` is true, so check `drawn` before reading a `null` winner as a loss. A `skipped` drawing (`drawing.status`) was never drawn, so there's no winner to wait for.
182
+ - `position` is `null` until the drawing locks. In a guarantee draw (`drawing.kind` is `"guarantee"`) everyone has 1 entry, `position` is set from the start, and `receivedAt` is when the guarantee draw was made.
183
+ - Plain HTTP: `GET {base}/campaigns/{slug}/drawings/{id}/entrant?entrantId=…`, URL-encoded, so a `+` goes as `%2B`. A bare `+` reads as a space, and the lookup finds no one.
184
+
170
185
  ## Checklist before handing back
171
186
 
172
187
  - [ ] Mode chosen and explained in a comment at the sender