prizerail 1.0.0 → 1.1.1

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
@@ -142,6 +142,21 @@ A slug is looked up on www.prizerail.com. For a draw from a sandbox campaign, ad
142
142
 
143
143
  It exits 0 when every check passes, 1 when one fails, and 2 when the proof can't be read.
144
144
 
145
+ ## Check an integration
146
+
147
+ With your key in `PRIZERAIL_API_KEY`, `check` reads a campaign and says whether the integration is set up right: the key and its environment, that the campaign is active with a drawing taking entries, and that the entrant ids and entries it has look right. Ids that read as an email, a username or a plain user id fail, since every locked list is published, hashed.
148
+
149
+ ```sh
150
+ npx prizerail check your-campaign
151
+ npx prizerail check your-campaign --draw # sandbox only: draw now, then verify the result
152
+ ```
153
+
154
+ A `pr_sandbox_` key checks the sandbox and a `pr_prod_` key production. It exits 0 when nothing failed. From code, `checkCampaign(campaign, { draw })` returns the same checks.
155
+
156
+ ## Skills for coding agents
157
+
158
+ `plugins/prizerail` is a Claude Code plugin with three skills: integrate Prizerail into an app, check an integration with `prizerail check`, and look up or verify draws. Install it with `/plugin marketplace add coordinationlabs/prizerail-js-sdk` then `/plugin install prizerail@prizerail`. The same skills are served as files at [docs.prizerail.com/ai/assistants](https://docs.prizerail.com/ai/assistants) for other agents.
159
+
145
160
  ## Options
146
161
 
147
162
  ```ts
@@ -0,0 +1,48 @@
1
+ import type { CampaignClient } from "./client.js";
2
+ import type { Campaign, Drawing, SentEntrant } from "./types.js";
3
+ import type { Check } from "./verify.js";
4
+ export type { Check };
5
+ /**
6
+ * What `prizerail check` reports: one line per check, in the order a
7
+ * partner's integration is set up. `ok: null` is a note the checks can't
8
+ * settle, such as every entrant having one entry.
9
+ */
10
+ export type CheckResult = {
11
+ /** True when no check failed. */
12
+ ok: boolean;
13
+ checks: Check[];
14
+ campaign?: Campaign;
15
+ /** The draw run with `--draw`, once settled. */
16
+ drawing?: Drawing;
17
+ };
18
+ export type CheckOptions = {
19
+ /** Sandbox only: draw the open drawing now and verify it. */
20
+ draw?: boolean;
21
+ /** Entrants to read from the open drawing before judging their ids. */
22
+ sample?: number;
23
+ /** For tests: the clock. */
24
+ now?: () => number;
25
+ /** For tests: how long to wait between polls of a draw still running. */
26
+ pollMs?: number;
27
+ };
28
+ /** "in 2h 5m", "in 40s", or "passed". */
29
+ export declare function untilText(at: string, now: number): string;
30
+ export type IdShape = "opaque" | "email" | "username" | "number" | "uuid" | "short";
31
+ export declare function idShape(id: string): IdShape;
32
+ /**
33
+ * True when the ids' numbers run like a counter: 1041, 1042, 1043, or
34
+ * customer00000001, customer00000002.
35
+ */
36
+ export declare function looksSequential(ids: string[]): boolean;
37
+ /** The id checks over a sample of the open drawing's entrants. */
38
+ export declare function checkEntrantIds(entrants: SentEntrant[]): Check[];
39
+ /** The entries checks over the same sample. */
40
+ export declare function checkEntries(entrants: SentEntrant[]): Check[];
41
+ /** Why the campaign couldn't be read, as a failed check, or null to rethrow. */
42
+ export declare function keyFailure(error: unknown, apiKey: string | undefined, siteUrl: string): Check | null;
43
+ /**
44
+ * Checks a partner's integration end to end with their key: the key, the
45
+ * campaign, its open drawing, the entrant ids and entries it has, and with
46
+ * `draw`, in the sandbox, a whole draw and its proof.
47
+ */
48
+ export declare function checkCampaign(campaign: CampaignClient, options?: CheckOptions): Promise<CheckResult>;
package/dist/check.js ADDED
@@ -0,0 +1,379 @@
1
+ import { PrizerailError } from "./errors.js";
2
+ /** The most entrants read for the id and entries checks. */
3
+ const SAMPLE = 5_000;
4
+ /** How long `--draw` waits for a drawing whose random value is on its way. */
5
+ const DRAW_WAIT_MS = 3 * 60_000;
6
+ const pass = (label, detail) => ({
7
+ ok: true,
8
+ label,
9
+ detail,
10
+ });
11
+ const fail = (label, detail) => ({
12
+ ok: false,
13
+ label,
14
+ detail,
15
+ });
16
+ const note = (label, detail) => ({
17
+ ok: null,
18
+ label,
19
+ detail,
20
+ });
21
+ const n = (v) => v.toLocaleString("en-US");
22
+ /** "in 2h 5m", "in 40s", or "passed". */
23
+ export function untilText(at, now) {
24
+ const ms = Date.parse(at) - now;
25
+ if (!Number.isFinite(ms))
26
+ return "at an unknown time";
27
+ if (ms <= 0)
28
+ return "passed";
29
+ const s = Math.round(ms / 1000);
30
+ if (s < 90)
31
+ return `in ${s}s`;
32
+ const m = Math.round(s / 60);
33
+ if (m < 90)
34
+ return `in ${m}m`;
35
+ const h = Math.floor(m / 60);
36
+ return `in ${h}h ${m - h * 60}m`;
37
+ }
38
+ /**
39
+ * What an entrant id looks like. Ids are published, hashed, with every
40
+ * draw, so one that reads as an email, a username or a small number can be
41
+ * tied back to a person, or guessed, by anyone who tries.
42
+ */
43
+ /**
44
+ * A word as a person types one: lowercase, Capitalized or ALLCAPS. A run
45
+ * of letters with capitals inside it (jQHuVfTIcYGWFJ) is random, so the
46
+ * handle rules below are case-sensitive and never match it.
47
+ */
48
+ const WORD = "(?:[a-z]+|[A-Z][a-z]*|[A-Z]+)";
49
+ const HANDLE_WITH_YEAR = new RegExp(`^${WORD}(?:[_.-]${WORD})+[_.-]?\\d{1,4}$`);
50
+ const LABELLED_COUNTER = new RegExp(`^${WORD}[_.-]?\\d{3,}$`);
51
+ const HANDLE = new RegExp(`^${WORD}(?:[_.-]${WORD})*(?:[_.-]?\\d{1,4})?$`);
52
+ export function idShape(id) {
53
+ if (id.includes("@"))
54
+ return "email";
55
+ // A space or a letter beyond ASCII is a person's name, never a generated id.
56
+ if (/\s/.test(id) || /[^\x20-\x7e]/.test(id))
57
+ return "username";
58
+ // A handle with a year: Ada_Lovelace_1988. Words with a separator, and
59
+ // digits only on the end.
60
+ if (HANDLE_WITH_YEAR.test(id))
61
+ return "username";
62
+ if (/^\d+$/.test(id))
63
+ return "number";
64
+ // A word and then only digits is a labelled counter: customer00000001,
65
+ // user_1042. The label hides nothing, and the number is guessable.
66
+ if (LABELLED_COUNTER.test(id) && !/^[0-9a-f]+$/i.test(id))
67
+ return "number";
68
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id))
69
+ return "uuid";
70
+ // Hex of 16 or more characters is a hash, or a 64-bit or wider random id.
71
+ if (/^(0x)?[0-9a-f]{16,}$/i.test(id))
72
+ return "opaque";
73
+ // A camelCase handle: two words with one capital between them, and at
74
+ // most a short run of digits on the end.
75
+ if (/^[a-z]{2,}[A-Z][a-z]{2,}\d{0,4}$/.test(id))
76
+ return "username";
77
+ // Mixed case this long is a generated id (nanoid, a Firebase UID, a
78
+ // prefixed random id like cus_Nx6v2dG9mLk8Qa), never a handle someone typed.
79
+ if (id.length >= 16 &&
80
+ /[a-z]/.test(id) &&
81
+ /[A-Z]/.test(id) &&
82
+ (/\d/.test(id) || !/[_.-]/.test(id)))
83
+ return "opaque";
84
+ // Base64 or similar of 21 characters or more, a nanoid's length, with
85
+ // both letters and digits.
86
+ if (/^[A-Za-z0-9_\-+/=]{21,}$/.test(id) && /\d/.test(id) && /[a-z]/i.test(id))
87
+ return "opaque";
88
+ if (id.length < 16) {
89
+ // Hex this short is a truncated hash: too short, not a name.
90
+ if (/^[0-9a-f]+$/i.test(id))
91
+ return "short";
92
+ return HANDLE.test(id) ? "username" : "short";
93
+ }
94
+ // A handle reads as words: letters with separators, and at most a short
95
+ // run of digits on the end, as in ada_lovelace_1988. One long word with
96
+ // no separators (a cuid2) or digits inside it (usr_k3j9d8s7f6g5h4j3) is a
97
+ // generated id.
98
+ const oneLongWord = /^[a-z]{20,}$/i.test(id);
99
+ return HANDLE.test(id) && !oneLongWord ? "username" : "opaque";
100
+ }
101
+ /**
102
+ * True when the ids' numbers run like a counter: 1041, 1042, 1043, or
103
+ * customer00000001, customer00000002.
104
+ */
105
+ export function looksSequential(ids) {
106
+ const nums = ids
107
+ .map(id => id.match(/(\d{1,15})$/)?.[1])
108
+ .filter((n) => n !== undefined)
109
+ .map(Number)
110
+ .sort((a, b) => a - b);
111
+ if (nums.length < 3)
112
+ return false;
113
+ let close = 0;
114
+ for (let i = 1; i < nums.length; i++) {
115
+ if (nums[i] - nums[i - 1] <= 10)
116
+ close++;
117
+ }
118
+ return close >= (nums.length - 1) * 0.8;
119
+ }
120
+ /** The id checks over a sample of the open drawing's entrants. */
121
+ export function checkEntrantIds(entrants) {
122
+ if (entrants.length === 0)
123
+ return [];
124
+ const shapes = new Map();
125
+ for (const e of entrants) {
126
+ const shape = idShape(e.entrantId);
127
+ shapes.set(shape, [...(shapes.get(shape) ?? []), e.entrantId]);
128
+ }
129
+ const example = (shape) => {
130
+ const ids = shapes.get(shape) ?? [];
131
+ return `${n(ids.length)} of ${n(entrants.length)}, like "${ids[0]}"`;
132
+ };
133
+ const checks = [];
134
+ if (shapes.has("email")) {
135
+ checks.push(fail("Entrant ids are not emails", `${example("email")}. Ids are published, hashed, with every draw. Send an HMAC of your user id instead.`));
136
+ }
137
+ const usernames = shapes.get("username") ?? [];
138
+ if (usernames.length > 0) {
139
+ // The handle shape is a heuristic: a random id now and then reads as
140
+ // one (usr_hoajwtbmnhlvlcfv). An integration that sends usernames
141
+ // sends nearly all of them that way, so a few in a large sample is a
142
+ // note, not a failure.
143
+ const stragglers = usernames.length < 20 && usernames.length < entrants.length * 0.02;
144
+ checks.push((stragglers ? note : fail)(stragglers
145
+ ? "A few entrant ids read like usernames"
146
+ : "Entrant ids are not usernames", `${example("username")}. A name can be tied back to a person. ${stragglers ? "Fine if these are random ids that happen to look like words. If they're names, send" : "Send"} an HMAC of your user id instead.`));
147
+ }
148
+ const numbers = shapes.get("number") ?? [];
149
+ if (numbers.length > 0) {
150
+ checks.push(fail("Entrant ids are not your user ids", `${example("number")}${looksSequential(numbers) ? ", running in sequence" : ""}. A plain or sequential id can be guessed. Send an HMAC of it with a secret key instead.`));
151
+ }
152
+ if (shapes.has("short")) {
153
+ checks.push(fail("Entrant ids are long enough to be unguessable", `${example("short")}. Use an HMAC-SHA256 of your user id (64 hex characters) or a random id you store.`));
154
+ }
155
+ if (shapes.has("uuid")) {
156
+ checks.push(note("Entrant ids are UUIDs", `${example("uuid")}. Fine if it's a random id made for Prizerail and stored. Not fine if it's your users table's id, which other systems know.`));
157
+ }
158
+ if (checks.length === 0) {
159
+ checks.push(pass("Entrant ids look opaque", `${n(entrants.length)} read, like "${entrants[0].entrantId}"`));
160
+ }
161
+ return checks;
162
+ }
163
+ /** The entries checks over the same sample. */
164
+ export function checkEntries(entrants) {
165
+ if (entrants.length === 0)
166
+ return [];
167
+ const counts = entrants.map(e => e.entries);
168
+ const bad = counts.filter(c => !Number.isInteger(c) || c < 1);
169
+ if (bad.length > 0) {
170
+ return [
171
+ fail("Entries are whole numbers from 1", `${n(bad.length)} entrants have ${bad[0]}`),
172
+ ];
173
+ }
174
+ const max = Math.max(...counts);
175
+ const total = counts.reduce((a, b) => a + b, 0);
176
+ if (entrants.length >= 2 && max === 1) {
177
+ return [
178
+ note("Every entrant has 1 entry", "Right if you don't use entries. If you meant to send totals, send `entries` every time: an entrant sent without it is set back to 1."),
179
+ ];
180
+ }
181
+ const sorted = [...counts].sort((a, b) => a - b);
182
+ const median = sorted[Math.floor(sorted.length / 2)];
183
+ const checks = [
184
+ pass("Entries look deliberate", `${n(total)} entries over ${n(entrants.length)} entrants, median ${n(median)}, highest ${n(max)}`),
185
+ ];
186
+ if (entrants.length >= 10 && max > median * 100) {
187
+ const top = entrants.find(e => e.entries === max);
188
+ checks.push(note("One entrant has far more entries than the rest", `"${top?.entrantId}" has ${n(max)} against a median of ${n(median)}. Check it isn't a running total added on every send.`));
189
+ }
190
+ return checks;
191
+ }
192
+ /** Why the campaign couldn't be read, as a failed check, or null to rethrow. */
193
+ export function keyFailure(error, apiKey, siteUrl) {
194
+ if (!(error instanceof PrizerailError))
195
+ return null;
196
+ if (error.status === 401) {
197
+ const sandboxKey = apiKey?.trim().startsWith("pr_sandbox_");
198
+ const sandboxSite = siteUrl === "https://sandbox.prizerail.com";
199
+ const prizerailSite = sandboxSite || siteUrl === "https://www.prizerail.com";
200
+ const mismatch = !prizerailSite
201
+ ? "Unknown or revoked key for this site."
202
+ : sandboxKey && !sandboxSite
203
+ ? "This is a pr_sandbox_ key, and the site isn't the sandbox. Sandbox keys only work at https://sandbox.prizerail.com."
204
+ : !sandboxKey && sandboxSite
205
+ ? "This isn't a pr_sandbox_ key, and the site is the sandbox. Production keys only work at https://www.prizerail.com."
206
+ : "Unknown or revoked key. An owner makes keys in the partner portal under Team → API keys.";
207
+ return fail(`The key works at ${siteUrl}`, mismatch);
208
+ }
209
+ if (error.status === 404) {
210
+ return fail("The campaign is under this key's account", `${error.detail ?? "Not found."} Check the slug, the last part of the campaign's page link, and that the key belongs to the same account and environment.`);
211
+ }
212
+ if (error.code === "no_api_key") {
213
+ return fail("The key is set", "Set PRIZERAIL_API_KEY to your pr_… key.");
214
+ }
215
+ return null;
216
+ }
217
+ async function readSample(campaign, drawingId, sample) {
218
+ const out = [];
219
+ for await (const entrant of campaign.entries.all({ drawing: drawingId })) {
220
+ out.push(entrant);
221
+ if (out.length >= sample)
222
+ break;
223
+ }
224
+ return out;
225
+ }
226
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
227
+ /**
228
+ * Checks a partner's integration end to end with their key: the key, the
229
+ * campaign, its open drawing, the entrant ids and entries it has, and with
230
+ * `draw`, in the sandbox, a whole draw and its proof.
231
+ */
232
+ export async function checkCampaign(campaign, options = {}) {
233
+ const now = options.now ?? Date.now;
234
+ const checks = [];
235
+ const done = (extra = {}) => ({
236
+ ok: !checks.some(c => c.ok === false),
237
+ checks,
238
+ ...extra,
239
+ });
240
+ const { siteUrl, http } = campaign.prizerail;
241
+ let info;
242
+ try {
243
+ info = await campaign.get();
244
+ }
245
+ catch (error) {
246
+ const failed = keyFailure(error, http.options.apiKey, siteUrl);
247
+ if (!failed)
248
+ throw error;
249
+ checks.push(failed);
250
+ return done();
251
+ }
252
+ checks.push(pass(`The key works at ${siteUrl}`));
253
+ try {
254
+ return await checkRest(campaign, info, checks, options, now, done);
255
+ }
256
+ catch (error) {
257
+ // A bug is a crash, not a failed check: the CLI exits 2 with it.
258
+ if (!(error instanceof PrizerailError))
259
+ throw error;
260
+ // An API or network failure part-way keeps the checks that passed.
261
+ checks.push(fail("The check finished", error instanceof Error ? error.message : String(error)));
262
+ return done({ campaign: info });
263
+ }
264
+ }
265
+ async function checkRest(campaign, info, checks, options, now, done) {
266
+ checks.push(info.status === "active"
267
+ ? pass(`Campaign "${info.name}" is active`)
268
+ : fail(`Campaign "${info.name}" is active`, info.status === "draft"
269
+ ? "It's a draft, so it doesn't draw and takes no entries. An owner sets it active in the partner portal."
270
+ : info.status === "paused"
271
+ ? "It's paused, so no drawing is taking entries."
272
+ : "It has ended and takes no more entries."));
273
+ const open = info.nextDrawing;
274
+ if (!open) {
275
+ checks.push(fail("A drawing is taking entries", "None is open. Entries sent now get 409 no_open_drawing. A paused campaign has none, and a new one's first drawing appears about two days before it draws."));
276
+ return done({ campaign: info });
277
+ }
278
+ checks.push(pass("A drawing is taking entries", `${open.id}, cutoff ${untilText(open.cutoffAt, now())} (${open.cutoffAt}), draws ${open.drawAt}`));
279
+ const sample = options.sample ?? SAMPLE;
280
+ const page = await campaign.entries.list({ drawing: open.id, limit: 1 });
281
+ if (page.entrantCount === 0) {
282
+ checks.push(note("The open drawing has no entries yet", "Run your sender, then check again. Entries go to the drawing whose cutoff is next, and totals don't carry over from the last one."));
283
+ }
284
+ else {
285
+ const entrants = await readSample(campaign, open.id, sample);
286
+ checks.push(pass("The open drawing has entries", `${n(page.entrantCount)} entrants, ${n(page.totalEntries)} entries`));
287
+ checks.push(...checkEntrantIds(entrants));
288
+ checks.push(...checkEntries(entrants));
289
+ }
290
+ if (!options.draw)
291
+ return done({ campaign: info });
292
+ if (page.entrantCount === 0) {
293
+ checks.push(fail("A draw runs now", "Nothing to draw from: send some entries first."));
294
+ return done({ campaign: info });
295
+ }
296
+ let drawing;
297
+ try {
298
+ drawing = await campaign.drawings.run(open.id);
299
+ }
300
+ catch (error) {
301
+ if (error instanceof PrizerailError && error.code === "sandbox_only") {
302
+ checks.push(fail("A draw runs now", "Draw now works only in the sandbox (a pr_sandbox_ key at https://sandbox.prizerail.com). Production draws run on schedule."));
303
+ return done({ campaign: info });
304
+ }
305
+ const unanswered = error instanceof PrizerailError &&
306
+ (error.status === 0 ||
307
+ error.status >= 500 ||
308
+ error.code === "invalid_response");
309
+ if (!unanswered) {
310
+ if (error instanceof PrizerailError) {
311
+ checks.push(fail("A draw runs now", error.message));
312
+ return done({ campaign: info });
313
+ }
314
+ throw error;
315
+ }
316
+ // No usable answer, but the route may well have run: the drawing's
317
+ // status says. Draw now moves the cutoff before anything else, so a
318
+ // drawing still open didn't run.
319
+ drawing = await campaign.drawings.get(open.id);
320
+ if (drawing.status === "open") {
321
+ checks.push(fail("A draw runs now", `The draw request got no answer (${error.message}) and drawing ${open.id} is still open, so it didn't run. Run the check again.`));
322
+ return done({ campaign: info, drawing });
323
+ }
324
+ }
325
+ const running = (d) => d.status === "locked" || d.status === "entropy_requested";
326
+ const deadline = now() + DRAW_WAIT_MS;
327
+ let timedOut = false;
328
+ while (running(drawing) && drawing.needsAttention === null) {
329
+ if (now() >= deadline) {
330
+ timedOut = true;
331
+ break;
332
+ }
333
+ await sleep(options.pollMs ?? 5_000);
334
+ drawing = await campaign.drawings.get(drawing.id);
335
+ }
336
+ const final = drawing.status === "settled" || drawing.status === "paid";
337
+ if (drawing.status === "skipped") {
338
+ checks.push(fail("A draw runs now", `Drawing ${drawing.id} closed without a draw: it had no entries at the cutoff.`));
339
+ return done({ campaign: info, drawing });
340
+ }
341
+ if (!final && drawing.needsAttention !== null) {
342
+ checks.push(fail("A draw runs now", `Drawing ${drawing.id} needs attention: ${drawing.needsAttention}`));
343
+ return done({ campaign: info, drawing });
344
+ }
345
+ if (!final) {
346
+ checks.push(fail("A draw runs now", timedOut
347
+ ? `Drawing ${drawing.id} is still ${drawing.status} after ${DRAW_WAIT_MS / 60_000} minutes. Read it again with GET /drawings/${drawing.id}.`
348
+ : `Drawing ${drawing.id} is ${drawing.status}, so it isn't drawing. Read it with GET /drawings/${drawing.id}.`));
349
+ return done({ campaign: info, drawing });
350
+ }
351
+ checks.push(pass("A draw runs now", `Drawing ${drawing.id} is ${drawing.status} with ${n(drawing.winners.length)} winner${drawing.winners.length === 1 ? "" : "s"}`));
352
+ if (drawing.needsAttention !== null) {
353
+ // Settled, so the winners are final and the proof stands. The flag is
354
+ // about what comes after, such as a sandbox campaign with no payout
355
+ // wallet, which is the normal sandbox state.
356
+ checks.push(note("The drawing is flagged for staff", drawing.needsAttention));
357
+ }
358
+ let result;
359
+ try {
360
+ result = await campaign.drawings.verify(drawing.id);
361
+ }
362
+ catch (error) {
363
+ // The entrant list is read page by page with no retries, so a blip
364
+ // here is reported with the draw kept, not thrown over it. A bug is
365
+ // still a crash: fetch's own TypeError is the one read failure that
366
+ // shares the class.
367
+ if (error instanceof TypeError && !/fetch/i.test(error.message))
368
+ throw error;
369
+ checks.push(fail("Its proof verifies", `${error instanceof Error ? error.message : String(error)}. The draw ran: read ${campaign.drawings.proofUrl(drawing.id)}, or run \`npx prizerail verify ${campaign.slug} ${drawing.id}\` again.`));
370
+ return done({ campaign: info, drawing });
371
+ }
372
+ const failed = result.checks.filter(c => c.ok === false);
373
+ checks.push(failed.length === 0
374
+ ? pass("Its proof verifies", `${campaign.drawings.proofUrl(drawing.id)}. Run \`npx prizerail verify ${campaign.slug} ${drawing.id}\` for every check.`)
375
+ : fail("Its proof verifies", failed
376
+ .map(c => `${c.label}${c.detail ? `: ${c.detail}` : ""}`)
377
+ .join("\n ")));
378
+ return done({ campaign: info, drawing });
379
+ }
package/dist/cli.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { existsSync } from "node:fs";
3
+ import { checkCampaign } from "./check.js";
3
4
  import { Prizerail, VERSION } from "./client.js";
4
5
  import { verifyDraw } from "./verify.js";
5
6
  const USAGE = `prizerail ${VERSION}
@@ -7,17 +8,20 @@ const USAGE = `prizerail ${VERSION}
7
8
  Usage:
8
9
  prizerail verify <proof.json link or file> [entrants link or file]
9
10
  prizerail verify <campaign slug> <drawing id> [--site https://www.prizerail.com]
11
+ prizerail check <campaign slug> [--draw] [--site https://www.prizerail.com]
10
12
 
11
- Checks a draw from its public proof: the locked entrant list, the random
12
- value, and every winner and prize. Exits 0 when every check passes, 1 when
13
- one fails, and 2 when the proof can't be read.
13
+ verify checks a draw from its public proof: the locked entrant list, the
14
+ random value, and every winner and prize. Exits 0 when every check passes, 1
15
+ when one fails, and 2 when the proof can't be read.
14
16
 
15
- A slug is looked up on www.prizerail.com. For a sandbox campaign, pass
16
- --site https://sandbox.prizerail.com, or set PRIZERAIL_API_KEY to a pr_sandbox_ key.`;
17
- function print(result) {
18
- const { proof, checks } = result;
19
- // A malformed proof may lack these, and its failed checks still print.
20
- console.log(`\n${proof?.campaign?.name ?? "Unknown campaign"}, draw of ${proof?.drawing?.drawAt ?? "unknown date"} (${proof?.drawing?.id ?? "unknown drawing"})\n`);
17
+ check reads a campaign with PRIZERAIL_API_KEY and checks the integration:
18
+ the key and its environment, the campaign and its open drawing, and the
19
+ entrant ids and entries it has. With --draw, in the sandbox, it draws the
20
+ open drawing now and verifies the result.
21
+
22
+ A slug is looked up on the site the key belongs to: www.prizerail.com, or
23
+ sandbox.prizerail.com for a pr_sandbox_ key. --site points anywhere else.`;
24
+ function printChecks(checks, passed) {
21
25
  for (const { ok, label, detail } of checks) {
22
26
  const mark = ok === true ? "✓" : ok === false ? "✗" : "i";
23
27
  console.log(`${mark} ${label}${detail ? `\n ${detail}` : ""}`);
@@ -25,18 +29,45 @@ function print(result) {
25
29
  const failed = checks.filter(c => c.ok === false).length;
26
30
  console.log(failed
27
31
  ? `\n${failed} check${failed === 1 ? "" : "s"} failed.`
28
- : "\nEvery result follows from the inputs.");
32
+ : `\n${passed}`);
29
33
  return failed ? 1 : 0;
30
34
  }
35
+ function print(result) {
36
+ const { proof, checks } = result;
37
+ // A malformed proof may lack these, and its failed checks still print.
38
+ console.log(`\n${proof?.campaign?.name ?? "Unknown campaign"}, draw of ${proof?.drawing?.drawAt ?? "unknown date"} (${proof?.drawing?.id ?? "unknown drawing"})\n`);
39
+ return printChecks(checks, "Every result follows from the inputs.");
40
+ }
31
41
  async function main(argv) {
32
42
  const args = [...argv];
33
43
  const siteAt = args.indexOf("--site");
34
44
  const site = siteAt === -1 ? undefined : args.splice(siteAt, 2)[1];
45
+ if (siteAt !== -1 && !site) {
46
+ console.log(USAGE);
47
+ return 2;
48
+ }
49
+ const drawAt = args.indexOf("--draw");
50
+ const draw = drawAt !== -1;
51
+ if (draw)
52
+ args.splice(drawAt, 1);
35
53
  const [command, a, b] = args;
36
54
  if (command === "--version" || command === "-v") {
37
55
  console.log(VERSION);
38
56
  return 0;
39
57
  }
58
+ if (command === "check" && a) {
59
+ const apiKey = process.env.PRIZERAIL_API_KEY;
60
+ if (!apiKey) {
61
+ console.error("Set PRIZERAIL_API_KEY to your pr_… key.");
62
+ return 2;
63
+ }
64
+ const campaign = new Prizerail({ siteUrl: site, apiKey }).campaign(a);
65
+ console.log(`\nChecking ${a} at ${campaign.prizerail.siteUrl}\n`);
66
+ const result = await checkCampaign(campaign, { draw });
67
+ return printChecks(result.checks, draw
68
+ ? "The integration works end to end."
69
+ : "The integration looks right. Add --draw in the sandbox to run a whole draw.");
70
+ }
40
71
  if (command !== "verify" || !a) {
41
72
  console.log(USAGE);
42
73
  return command === undefined || command === "--help" || command === "-h"
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, EntriesPage, Guarantee, SendEntriesResponse, SentEntrant } from "./types.js";
3
3
  import { type DrawProof, type VerifyResult } from "./verify.js";
4
- export declare const VERSION = "1.0.0";
4
+ export declare const VERSION = "1.1.1";
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.0.0";
4
+ export const VERSION = "1.1.1";
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/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { type CheckOptions, type CheckResult, checkCampaign, checkEntrantIds, checkEntries, idShape, } from "./check.js";
1
2
  export { CampaignClient, DrawingsClient, ENTRIES_PER_REQUEST, EntriesClient, type IncrementResult, Prizerail, type PrizerailOptions, type SendOptions, type SendResult, VERSION, } from "./client.js";
2
3
  export { hashEntrant } from "./entrant.js";
3
4
  export { PrizerailCutoffError, PrizerailDrawingChangedError, PrizerailError, type SendProgress, } from "./errors.js";
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ export { checkCampaign, checkEntrantIds, checkEntries, idShape, } from "./check.js";
1
2
  export { CampaignClient, DrawingsClient, ENTRIES_PER_REQUEST, EntriesClient, Prizerail, VERSION, } from "./client.js";
2
3
  export { hashEntrant } from "./entrant.js";
3
4
  export { PrizerailCutoffError, PrizerailDrawingChangedError, PrizerailError, } from "./errors.js";
package/dist/types.d.ts CHANGED
@@ -118,7 +118,11 @@ export type DrawingsPage = {
118
118
  /** An entrant id, with one entry, or an id with their entries and how they show if they win. */
119
119
  export type Entrant = string | {
120
120
  entrantId: string;
121
- /** Their number of entries, a whole number from 1. Leave it out and it's 1. */
121
+ /**
122
+ * Their number of entries, a whole number from 1. Leave it out and it's
123
+ * 1. Entries are chances: 5 entries is five times as likely to be picked
124
+ * as 1.
125
+ */
122
126
  entries?: number;
123
127
  /** Up to 40 characters. */
124
128
  displayName?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prizerail",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "description": "The Prizerail SDK: send entries, read draws and verify them.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://docs.prizerail.com",
@@ -25,6 +25,7 @@
25
25
  },
26
26
  "files": [
27
27
  "dist",
28
+ "plugins",
28
29
  "README.md",
29
30
  "LICENSE"
30
31
  ],
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "prizerail",
3
+ "version": "1.1.1",
4
+ "description": "Integrate Prizerail prize draws into an app, check an integration end to end, and look up or verify draws.",
5
+ "author": {
6
+ "name": "Prizerail",
7
+ "email": "team@coordinationlabs.com",
8
+ "url": "https://www.prizerail.com"
9
+ },
10
+ "homepage": "https://docs.prizerail.com/ai/assistants",
11
+ "repository": "https://github.com/coordinationlabs/prizerail-js-sdk",
12
+ "license": "MIT",
13
+ "keywords": ["prizerail", "sweepstakes", "prize draw", "verifiable"]
14
+ }
@@ -0,0 +1,16 @@
1
+ # Prizerail plugin for Claude Code
2
+
3
+ Three skills for building on [Prizerail](https://www.prizerail.com):
4
+
5
+ - **prizerail-integrate**: add Prizerail to an app so its users enter the partner's prize draws.
6
+ - **prizerail-check**: check an integration end to end with `npx prizerail check`.
7
+ - **prizerail-draw**: look up a campaign's draws and verify one from its public proof.
8
+
9
+ Install it in Claude Code:
10
+
11
+ ```
12
+ /plugin marketplace add coordinationlabs/prizerail-js-sdk
13
+ /plugin install prizerail@prizerail
14
+ ```
15
+
16
+ The same skills are served as plain files for any agent that reads them: [prizerail-integrate](https://www.prizerail.com/skills/prizerail-integrate/SKILL.md), [prizerail-check](https://www.prizerail.com/skills/prizerail-check/SKILL.md) and [prizerail-draw](https://www.prizerail.com/verify/SKILL.md). The copies here ship in the `prizerail` package too, and prizerail.com's tests fail if its served files differ from them.
@@ -0,0 +1,47 @@
1
+ ---
2
+ name: prizerail-check
3
+ description: "Check a Prizerail integration end to end with the developer's API key by running `npx prizerail check <campaign>`: that the key works and matches its environment, that the campaign is active with a drawing taking entries, that the entrant ids sent look opaque, that entry counts look right, and in the sandbox that a whole draw runs and verifies. Use when someone asks whether their Prizerail integration works, why entries aren't showing up, to test or smoke-test a campaign, or to run a draw in the sandbox."
4
+ ---
5
+
6
+ # Check a Prizerail integration
7
+
8
+ Run the command instead of reasoning through the checks. It reads the campaign with the developer's key, inspects what Prizerail has, and prints one line per check.
9
+
10
+ ```sh
11
+ npx prizerail check <campaign slug>
12
+ npx prizerail check <campaign slug> --draw # sandbox only: also run a draw and verify it
13
+ ```
14
+
15
+ It needs `PRIZERAIL_API_KEY` in the environment. The key picks the site: a `pr_sandbox_` key checks `https://sandbox.prizerail.com`, a `pr_prod_` key `https://www.prizerail.com`. Pass `--site <url>` only for a server somewhere else. Node 20 or later.
16
+
17
+ ## What it checks
18
+
19
+ | Check | Passes when | When it doesn't |
20
+ |---|---|---|
21
+ | **Key** | The key is accepted by the site it belongs to | A `401` means an unknown or revoked key, or a sandbox key sent to production (or the reverse). Keys are made by an owner in the partner portal under **Team → API keys**, and each works only on its own site. |
22
+ | **Campaign** | `status` is `active` | A `draft` doesn't draw. A `paused` campaign has no drawing taking entries. An `ended` one refuses entries with `409 campaign_ended`. The owner changes status in the portal. |
23
+ | **Open drawing** | A drawing is taking entries, with its cutoff shown | None open while paused, or between a cutoff and the next drawing being made. Entries sent now would get `409 no_open_drawing`. |
24
+ | **Entrant ids** | The first 5,000 ids in the open drawing look opaque | It fails on ids that look like an email, a username (a word with separators or in camelCase, even with a year on the end), a name with spaces, any all-digit id, or any id shorter than 16 characters. A few username-shaped ids in a large sample are a note, not a failure, since a random id now and then reads like a word. It notes any UUID: fine if it was made for Prizerail and stored, not if it's the app's own users table id. Entrant ids are published, hashed, with every draw, so they must be an HMAC of the user id with a secret key, or a random id the app stores. See [Entrant ids](https://docs.prizerail.com/getting-started/concepts#make-entrant-ids-with-an-hmac). |
25
+ | **Entries** | Entries are whole numbers from 1 to 4,294,967,295, and the spread looks deliberate | It notes when every entrant has exactly 1 entry, which is fine if entries aren't used, and a problem if the app meant to send totals and left `entries` out, since an entrant sent without it is set back to 1. It also notes a total that is far above the others. |
26
+ | **Draw** (`--draw`, sandbox only) | The open drawing is drawn now, settles, and its proof passes the verify script | Outside the sandbox the API answers `403 sandbox_only`. With no entries the command stops with "Nothing to draw from" before asking (the API's own answer to a bare run is `409 no_entries`). If the API answers 202 with the draw still `entropy_requested`, the command polls it for up to 3 minutes and says so if it hasn't settled. A `✗` saying the drawing "needs attention" before it settles is on Prizerail's side, usually the random value pending past 30 minutes, and nothing in the integration causes it: wait, and tell us if it stays. A settled draw can carry an `i` "flagged for staff" note, such as "Campaign has no payout address" in a sandbox campaign with no wallet: the draw and its proof still pass, it just stays `settled` rather than `paid`. |
27
+
28
+ It prints `✓` for a passing check, `✗` for a failing one, and `i` for a note, and exits 0 only if nothing failed. Report each `✗` and `i` line as printed, with the fix from the table above.
29
+
30
+ ## Reading the output with the developer
31
+
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
+ - **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
+ - **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
+ - **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
+ - **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
+ ## Without the command
39
+
40
+ If `npx` can't run, the same checks by hand, all with `Authorization: Bearer $PRIZERAIL_API_KEY` against the site the key belongs to:
41
+
42
+ 1. `GET /api/v1/campaigns/{slug}` for `status` and `nextDrawing` (its `cutoffAt` is when entries close).
43
+ 2. `GET /api/v1/campaigns/{slug}/entries?limit=1000` for the open drawing's `entrantCount`, `totalEntries` and entrants. Take `drawing.id` from the first page and pass it as `drawing={id}` with `after` on every later page until `next` is `null`, so a cutoff mid-way can't mix two drawings.
44
+ 3. In the sandbox, `POST /api/v1/campaigns/{slug}/drawings/{id}/run`, then `GET /api/v1/campaigns/{slug}/drawings/{id}` until `status` is `settled` or `paid`.
45
+ 4. `npx prizerail verify <slug> <drawing id>`, or download `https://www.prizerail.com/verify/verify-draw.mjs` and run it on the drawing's `proof.json`.
46
+
47
+ Never compute the draw's hashes yourself: keccak256 can't be done reliably by reasoning. The verify script does it.
@@ -0,0 +1,107 @@
1
+ ---
2
+ name: prizerail-draw
3
+ description: "Check the status of a Prizerail campaign's draws (whether a draw is open, locked, drawn or paid, who won what), independently verify a draw using only public endpoints, and answer how Prizerail works from its docs. Use when someone asks about a Prizerail draw, its winners or prizes, whether it has been drawn or paid, or wants to verify or audit one, and when they ask how Prizerail works: entries and winning, sending entries and cutoffs, who can enter, how winners claim and are ID-checked, or free entry."
4
+ ---
5
+
6
+ # Prizerail draws: status and verification
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.
9
+
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
+
12
+ ## Concepts
13
+
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.
16
+ - **Cutoff:** the partner can send entries until `cutoffAt`. Each campaign sets how long before `drawAt` that is, from minutes to days.
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
19
+ - **Prize:** the same math the Prizerail contract runs onchain. For the winner in slot `i`:
20
+ - `campaignId` is the proof's `campaign.id` as ASCII, right-padded to 32 bytes, and `drawingId` is `drawing.number`
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
22
+ - `roll = randomValue mod denominator`, from 0 to `denominator - 1`
23
+ - the prize is the first tier in the proof's list whose `threshold` is above `roll`. Tiers run top prize first, each `weight` rolls wide
24
+ - the top prize is won at most once per draw. If two or more winners roll it, the one with the lowest `randomValue` (as a 256-bit number) keeps it, and every other one gets the second tier. Only the top tier works this way
25
+ - **Guarantee draws:** a draw with `kind: "guarantee"` is a guarantee period's own draw: one winner, picked from everyone who entered the period, each person once. Its proof's `campaign.id` ends in `-g`, its own drawing-number sequence, and both prize tiers pay the guarantee amount. Verify it like any draw.
26
+ - **Random value source:** real campaigns draw with Pyth Entropy through the Prizerail contract on Base mainnet, which isn't live yet, so no real campaign has drawn. Test draws on Base Sepolia use Pyth through the same contract, with `entropy.provider` set to `pyth`, and their proof's `entropy.chain` names the contract and transactions to check onchain. Older test draws have source `mock`, test randomness made by Prizerail. A `mock` draw can't be checked independently, so its order "locked before the random value" rests on Prizerail's own timestamps. Say so when you report on one.
27
+
28
+ ## Questions about how Prizerail works
29
+
30
+ For questions beyond one draw, such as whether a person can win twice, how partners send entries, when draws close, how winners claim and are ID-checked, who can enter, or how free entry works, answer from the docs rather than from memory: the [Partner FAQ](https://docs.prizerail.com/getting-started/faq) and [Winners and eligibility](https://docs.prizerail.com/campaigns/winners), or all of the docs at [llms-full.txt](https://docs.prizerail.com/llms-full.txt). Say when something there is marked as coming soon.
31
+
32
+ ## Stages
33
+
34
+ | `stage` | Meaning | What's public |
35
+ |---|---|---|
36
+ | `open` | Taking entries until `cutoffAt` | Times only |
37
+ | `locked` | Entrant list locked | `winnersCommitment` (the list's fingerprint), `entrants` (count, total weight, link to the hashed list), `lockedAt` |
38
+ | `drawing` | Random value requested | The same |
39
+ | `drawn` | Prizes decided | `proof` link with every input and result |
40
+ | `paid` | Prizes sent to the partner to pay winners | The same, plus `paidAt` |
41
+
42
+ A draw still `open` well after its `cutoffAt`, or stuck in `locked` or `drawing` for more than about 30 minutes after `drawAt`, is behind. Say so.
43
+
44
+ ## Endpoints
45
+
46
+ Base `https://www.prizerail.com`. Public, with CORS `*`.
47
+
48
+ | Endpoint | Returns |
49
+ |---|---|
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. |
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
+ | `GET /verify/verify-draw.mjs` | The verify script (Node.js 18+, no dependencies) |
54
+
55
+ Amounts are US cents: `amountCents: 1000` is $10. Times are ISO 8601 in UTC. Show them in the user's time zone if you know it, otherwise in UTC.
56
+
57
+ An unknown campaign returns `404 {"error": "No such campaign."}`, and a draw that isn't drawn yet returns `404` for its proof.
58
+
59
+ ## Workflow: status of a campaign's draws
60
+
61
+ 1. **Find the slug.** It is the last part of the campaign page's link. If the user gives a name instead, ask for the link.
62
+ 2. **Fetch** `GET /campaigns/{slug}/draws.json`.
63
+ 3. **Pick the draw.**
64
+ - "next" or "today's": the earliest `open` draw.
65
+ - "latest": the newest `drawn` or `paid` draw.
66
+ - A date: the draw whose `drawAt` falls on that date in the campaign's `timezone`.
67
+ 4. **Report** in this shape.
68
+
69
+ ```
70
+ {campaign.name}: draw of {drawAt}. Stage: {stage}
71
+ Entrants: {entrants.count} entrants, fingerprint {winnersCommitment}, locked {lockedAt}
72
+ Prizes: {for each result: winner, roll, prize} (from the proof, once drawn)
73
+ Proof: {proof link}
74
+ ```
75
+
76
+ ## Verify a draw
77
+
78
+ Run this whenever asked to verify, audit or double-check a draw:
79
+
80
+ ```sh
81
+ curl -sO https://www.prizerail.com/verify/verify-draw.mjs
82
+ node verify-draw.mjs https://www.prizerail.com/campaigns/{slug}/draws/{id}/proof.json
83
+ ```
84
+
85
+ The script is short and readable. Read it first if the user wants to know what it does. It:
86
+
87
+ - tests its own keccak256 against published values
88
+ - checks that the prize table's weights add up to its denominator
89
+ - fetches the hashed entrant list and recomputes its fingerprint
90
+ - redraws every winner from the list, and checks each winner's id hashes to the entry their pick landed on
91
+ - recomputes every winner's random value, roll and prize, and compares them with the proof
92
+
93
+ It prints `✓` for a check that passes, `✗` for one that fails, and `i` for information the math can't settle (such as the random value's source). It exits 0 only if nothing failed. Report each `✗` and `i` line to the user as printed.
94
+
95
+ If the user can't run code, the campaign page has a "Verify in your browser" button on each draw that runs the same script. Mention that it runs on Prizerail's own site, so downloading and running the script is the independent check.
96
+
97
+ To cross-check with a library instead, viem's `keccak256(encodeAbiParameters(...))` with the types above gives the same values.
98
+
99
+ ## Gotchas
100
+
101
+ - **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.
102
+ - **Rolls run from 0 to `denominator - 1`.**
103
+ - **Tier order:** tiers in the proof are top prize first, and the top prize owns the lowest rolls.
104
+ - **One top prize per draw:** a winner whose roll lands in the top tier can still get the second prize, if another winner rolled the top tier with a lower random value. That's the rule working, not a mismatch.
105
+ - **A slot's prize doesn't depend on who fills it.** Each slot's roll uses only the random value, the campaign, the draw's number and the slot.
106
+ - **Fairness scope:** the proof shows the winners and prizes follow from the list and the random value. Whether the right people are on the list is the partner's own record of who entered. Anyone on it can check they're in from their own id.
107
+ - **Entrant IDs are public, hashed.** Every locked list is published hashed, and winners' IDs are in each proof. If you're helping a partner choose IDs, recommend an HMAC of their user ID with a secret key, kept fixed for the campaign, or a random ID they store. Never suggest a plain hash: a hash of a sequential or public user ID can be reversed by hashing guesses. Never use emails or usernames.
@@ -0,0 +1,178 @@
1
+ ---
2
+ name: prizerail-integrate
3
+ description: Add Prizerail to an app so its users enter the partner's prize draws. Reads the repo to find the stack and where users earn entries, picks set or increment mode, writes the sender (the prizerail SDK in TypeScript and JavaScript, plain HTTP elsewhere) with HMAC entrant ids, an eligibility filter, env wiring for sandbox and production keys, and tests. Use when someone asks to integrate Prizerail, send entries to a campaign, add a sweepstakes or prize draw with Prizerail, or wire up the prizerail package.
4
+ ---
5
+
6
+ # Integrate Prizerail
7
+
8
+ Prizerail runs prize draws for partner apps. The partner's backend sends each eligible user as an **entrant** with their number of **entries** (chances: 5 entries is five times as likely to be picked as 1), and at each **cutoff** Prizerail locks the list, draws the winners from it with a public random value, and sends the prizes to the partner's wallet to pay out. The partner never picks winners and never handles the randomness. This skill builds the sending side.
9
+
10
+ Read the docs when a detail isn't here: [Send entries](https://docs.prizerail.com/api/send-entries), [Concepts](https://docs.prizerail.com/getting-started/concepts), [Winners and eligibility](https://docs.prizerail.com/campaigns/winners), or everything at [llms-full.txt](https://docs.prizerail.com/llms-full.txt). Whole runnable projects are in [prizerail-examples](https://github.com/coordinationlabs/prizerail-examples): a Next.js app that adds entries as users earn them, a Node worker that sends the day's entries, and the same send in Python.
11
+
12
+ ## 1. Read the repo first
13
+
14
+ Before writing anything, find out:
15
+
16
+ - **The stack.** TypeScript or JavaScript (Node 20 or later) uses the `prizerail` package. Anything else uses plain HTTP against the API, following the Python pattern below.
17
+ - **Where users earn entries.** Look for the actions the partner rewards: orders, referrals, deposits, daily check-ins, completed tasks. Find the code path that runs when each one happens, and the table or model that records it.
18
+ - **The user id and where users live.** The entrant id is derived from the partner's stable internal user id. Eligibility needs each user's country, US state and age, or a flag the app already keeps.
19
+ - **Secrets and env.** How the app reads secrets, and where `PRIZERAIL_API_KEY`, `PRIZERAIL_CAMPAIGN` and `ENTRANT_ID_KEY` go.
20
+ - **Scheduled jobs.** A cron, queue or worker the daily send can live in, if set mode fits.
21
+
22
+ Then ask the developer anything the repo doesn't settle, in one message: how entries are earned, whether a user's entries change through the day, and which campaign slug and environment to wire.
23
+
24
+ ## 2. Pick the mode
25
+
26
+ | Mode | Use it when | How it works |
27
+ |---|---|---|
28
+ | **set** (default) | The app knows each user's running total, and sends everyone once before each cutoff, for example in a daily job | `POST /entries` with each entrant's total. Sending an entrant again before the cutoff **sets** their entries to what was sent. |
29
+ | **increment** | Entries are earned by events as they happen, and the app would rather add them than keep a total | `POST /entries` with `"mode": "increment"`, one event per entrant with an `eventId`. Prizerail adds the event's entries to what the entrant has, and ignores an `eventId` it has seen before. |
30
+
31
+ Rules that hold in both modes, and must be in the code and its comments:
32
+
33
+ - **Entries land in the drawing whose cutoff is next** when they arrive. After a cutoff, they go to the following drawing. Totals never carry over between draws.
34
+ - **The same person must have the same entrant id for the whole campaign.** The guarantee draw counts each person once by their id across a period. Never rotate the key mid-campaign, and never make an id per draw, per session or per device.
35
+ - **Only eligible users are sent.** Who can enter is below.
36
+ - **Nothing personal is sent.** No emails, usernames, names or raw user ids as entrant ids. `displayName` and `avatarUrl` are optional and public if that entrant wins, so send them only if the partner wants them shown.
37
+
38
+ ### Set mode gotchas
39
+
40
+ - A retry before the cutoff is safe: it sets the same total again. A retry **after** the cutoff goes to the next draw, and the request whose answer was lost may already be stored, so a late retry can enter people in two draws.
41
+ - The SDK handles this: `entries.send` pins every batch to one drawing and throws `PrizerailCutoffError` rather than send or retry within its cutoff margin (the request timeout, 30 seconds). Plain HTTP code must do the same: read the open drawing and its `cutoffAt` first, send no batch and start no retry within 30 seconds of it, and stop if a response names a different drawing.
42
+ - Send `entries` every time if it's ever used. An entrant sent without it is set back to 1.
43
+ - Up to 1,000 entrants per request, and a drawing takes up to 100,000 entrants.
44
+
45
+ ### Increment mode gotchas
46
+
47
+ - **The `eventId` is the id of the thing that happened**: an order id, a referral id, a transaction hash. With none to hand, make a UUID when the event happens and store it with the event. **Never make it per attempt.** A timestamp, or a random id per retry, adds the entries again on every retry.
48
+ - A repeated `eventId` is ignored, even across a cutoff. That makes every retry safe at any time, which is why increment mode needs no cutoff margin.
49
+ - The same `eventId` with a different entrant or number of entries is a `409 event_conflict`, and nothing in that request is stored.
50
+ - Each event goes to the drawing taking entries when it arrives, so events either side of a cutoff split between two draws. That is correct.
51
+
52
+ ## 3. Entrant ids
53
+
54
+ Every locked list is published, hashed, so anyone can check a draw. An entrant id must not be guessable or linkable back to a person. Use an HMAC-SHA256 of the partner's user id with a secret key:
55
+
56
+ ```ts
57
+ // TypeScript and JavaScript: the SDK's helper, which also runs on edge runtimes.
58
+ import { hashEntrant } from "prizerail"
59
+ const entrantId = await hashEntrant(user.id, process.env.ENTRANT_ID_KEY!)
60
+ ```
61
+
62
+ ```python
63
+ # Python, with the standard library.
64
+ import hashlib, hmac, os
65
+ key = os.environ["ENTRANT_ID_KEY"].encode()
66
+ entrant_id = hmac.new(key, str(user.id).encode(), hashlib.sha256).hexdigest()
67
+ ```
68
+
69
+ - Make the key once (`openssl rand -hex 32`) and keep it in the server's secrets manager. Never put it in a client app or a web page.
70
+ - **Keep the same key for the life of the campaign.** A new key gives every user a new id, which breaks the guarantee draw's "each person once".
71
+ - Never use a plain hash: a plain SHA-256 of a sequential or public user id can be reversed by hashing guesses. And never use emails or usernames, hashed or not.
72
+
73
+ ## 4. Keys and environments
74
+
75
+ - `PRIZERAIL_API_KEY`: an owner makes it in the partner portal under **Team → API keys**. It's shown once. One key covers every campaign of the account.
76
+ - `PRIZERAIL_CAMPAIGN`: the campaign's slug, the last part of its public page `https://www.prizerail.com/campaigns/{slug}`.
77
+ - **Sandbox and production are separate sites with separate keys.** `pr_sandbox_` keys work only at `https://sandbox.prizerail.com`, `pr_prod_` keys only at `https://www.prizerail.com`. A sandbox key sent to production gets a `401`. Wire a `pr_sandbox_` key in development and a `pr_prod_` key in production.
78
+ - The SDK picks the site from the key, so the code is the same in both environments. Plain HTTP code must pick the base URL from the key's prefix: `pr_sandbox_` → `https://sandbox.prizerail.com/api/v1`, otherwise `https://www.prizerail.com/api/v1`.
79
+ - Sandbox draws run on a test network and pay nothing. The developer makes a sandbox account at [sandbox.prizerail.com/signup](https://sandbox.prizerail.com/signup).
80
+
81
+ ## 5. Eligibility filter
82
+
83
+ Add one function, `isEligible(user)`, that every send goes through, and keep its rules in one place. The standard Prizerail rules:
84
+
85
+ - **US:** legal residents 18 or older, or 19 in Alabama and Nebraska and 21 in Mississippi. Residents of **Florida, New York and Rhode Island** can't enter.
86
+ - **Outside the US:** the same age standard. Residents of countries under US sanctions, as listed by [OFAC](https://ofac.treasury.gov/sanctions-programs-and-country-information), can't enter.
87
+
88
+ A campaign's official rules can narrow these. Read them from the partner, and point the developer at [Who can enter](https://docs.prizerail.com/campaigns/winners#who-can-enter). If the app doesn't know a user's age or location, say so rather than guess, and send nobody whose eligibility is unknown.
89
+
90
+ ## 6. Write the sender
91
+
92
+ ### TypeScript and JavaScript: the `prizerail` package
93
+
94
+ `npm install prizerail`. Batching, retries, the cutoff rule and the site choice are built in.
95
+
96
+ Set mode, from a job that runs before each cutoff:
97
+
98
+ ```ts
99
+ import {
100
+ Prizerail,
101
+ PrizerailCutoffError,
102
+ PrizerailDrawingChangedError,
103
+ hashEntrant,
104
+ type Entrant,
105
+ } from "prizerail"
106
+
107
+ const campaign = new Prizerail({ apiKey: process.env.PRIZERAIL_API_KEY }).campaign(
108
+ process.env.PRIZERAIL_CAMPAIGN!
109
+ )
110
+
111
+ export async function sendTodaysEntries() {
112
+ const users = await eligibleUsersWithEntries() // your query, filtered by isEligible
113
+ const entrants: Entrant[] = await Promise.all(
114
+ users.map(async u => ({
115
+ entrantId: await hashEntrant(u.id, process.env.ENTRANT_ID_KEY!),
116
+ entries: u.entries, // their total for this draw, a whole number from 1
117
+ }))
118
+ )
119
+ try {
120
+ const res = await campaign.entries.send(entrants)
121
+ return { drawingId: res.drawing.id, sent: res.sent, entrantCount: res.entrantCount }
122
+ } catch (error) {
123
+ if (
124
+ error instanceof PrizerailCutoffError ||
125
+ error instanceof PrizerailDrawingChangedError
126
+ ) {
127
+ // Both carry progress: error.progress.sent entrants were confirmed in
128
+ // error.progress.drawing. Check the rest with entries.list().
129
+ throw new Error(`${error.progress.sent} sent to ${error.progress.drawing.id}: ${error.detail}`)
130
+ }
131
+ throw error
132
+ }
133
+ }
134
+ ```
135
+
136
+ Increment mode, from the code path where the event happens:
137
+
138
+ ```ts
139
+ // eventId is stored with the event, so a retry or a redelivered queue message sends the same one.
140
+ export async function addEntries(userId: string, entries: number, eventId: string) {
141
+ const entrantId = await hashEntrant(userId, process.env.ENTRANT_ID_KEY!)
142
+ return campaign.entries.increment([{ entrantId, entries, eventId }])
143
+ }
144
+ ```
145
+
146
+ ### Any other language: plain HTTP
147
+
148
+ Follow the TypeScript `fetch` and Python `requests` tabs on [Send entries](https://docs.prizerail.com/api/send-entries#code), which are complete and tested in CI. The shape:
149
+
150
+ - `POST {base}/campaigns/{slug}/entries` with `Authorization: Bearer {key}` and a JSON body `{"entrants": [...]}`, or `{"mode": "increment", "entrants": [...]}`.
151
+ - A 30-second timeout on every request. Retry a `429`, a `5xx`, a timeout or a network error with a growing, jittered wait, honoring `Retry-After`. Don't retry a `4xx` other than `429`.
152
+ - Set mode: read `GET {base}/campaigns/{slug}/entries?limit=1` first for the open drawing's `id` and `cutoffAt`, send in batches of 1,000, send no batch and start no retry within 30 seconds of the cutoff, and stop if a response's `drawing.id` differs from the one read first.
153
+ - Increment mode: one event per entrant with `eventId`, retried at any time.
154
+
155
+ ## 7. Tests
156
+
157
+ Write them in the project's own test framework. Each one guards a rule above:
158
+
159
+ 1. **Same user, same entrant id.** Hashing the same user id twice gives the same entrant id, and two different users give different ids.
160
+ 2. **The id isn't personal.** The entrant id is 64 hex characters and contains neither the user id, nor their email, nor their username.
161
+ 3. **Nothing personal is sent.** Capture the request body (mock `fetch` or the SDK's `fetch` option) and assert no email, username or raw user id appears in it.
162
+ 4. **Retries carry the same `eventId`** (increment mode): calling the sender twice for one event sends the same `eventId` both times.
163
+ 5. **Nothing is sent near the cutoff** (set mode): with the open drawing's `cutoffAt` 10 seconds away, the sender stops without posting a batch. With the SDK, that's `PrizerailCutoffError`.
164
+ 6. **Ineligible users are filtered out:** a user from Florida, or under 18, never reaches the sender.
165
+
166
+ ## 8. Try it in the sandbox
167
+
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
+
170
+ ## Checklist before handing back
171
+
172
+ - [ ] Mode chosen and explained in a comment at the sender
173
+ - [ ] Entrant ids are HMAC-SHA256 with `ENTRANT_ID_KEY`, never a plain hash or anything personal
174
+ - [ ] `PRIZERAIL_API_KEY` and `PRIZERAIL_CAMPAIGN` wired, sandbox key in development, production key in production
175
+ - [ ] Eligibility filter in front of every send
176
+ - [ ] Set mode: cutoff margin and drawing pinning. Increment mode: `eventId` fixed when the event happens
177
+ - [ ] `entries` sent every time it's used, a whole number from 1 to 4,294,967,295
178
+ - [ ] Tests from section 7