prizerail 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +129 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +60 -0
- package/dist/client.d.ts +127 -0
- package/dist/client.js +258 -0
- package/dist/entrant.d.ts +7 -0
- package/dist/entrant.js +14 -0
- package/dist/errors.d.ts +36 -0
- package/dist/errors.js +42 -0
- package/dist/http.d.ts +35 -0
- package/dist/http.js +138 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/types.d.ts +169 -0
- package/dist/types.js +2 -0
- package/dist/verify-draw.d.mts +15 -0
- package/dist/verify-draw.mjs +786 -0
- package/dist/verify.d.ts +64 -0
- package/dist/verify.js +69 -0
- package/package.json +37 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Coordination Labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,130 @@
|
|
|
1
|
-
#
|
|
1
|
+
# prizerail
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Prizerail SDK for JavaScript and TypeScript. Send entries, read results and prizes, and verify any draw from its public proof.
|
|
4
|
+
|
|
5
|
+
- Typed client for the [partner API](https://docs.prizerail.com/api/authentication), with paging and safe retries.
|
|
6
|
+
- `verifyDraw`, the same checks as the public verify script, plus `wasEntered` to find someone in a locked list.
|
|
7
|
+
- `npx prizerail verify` from the command line.
|
|
8
|
+
- No dependencies. Node 20 or later, Deno, Bun, and edge runtimes with `fetch` and WebCrypto.
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npm install prizerail
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
The API is early (v0.x), so names can change between minor versions. Each change is in the [changelog](https://docs.prizerail.com/changelog).
|
|
15
|
+
|
|
16
|
+
## Send entries
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { Prizerail, hashEntrant } from "prizerail"
|
|
20
|
+
|
|
21
|
+
const prizerail = new Prizerail({ apiKey: process.env.PRIZERAIL_API_KEY })
|
|
22
|
+
const campaign = prizerail.campaign("your-campaign")
|
|
23
|
+
|
|
24
|
+
const entries = await Promise.all(
|
|
25
|
+
users.map(async user => ({
|
|
26
|
+
entrantId: await hashEntrant(user.id, process.env.ENTRANT_ID_KEY!),
|
|
27
|
+
weight: user.tickets,
|
|
28
|
+
}))
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
const result = await campaign.entries.send(entries)
|
|
32
|
+
// { drawing: { id, drawAt, cutoffAt }, sent, added, updated, unchanged, count, totalWeight, batches }
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`count` and `totalWeight` are the drawing's own totals, so reconcile with those. `added`, `updated` and `unchanged` add up what each batch reported, and a batch that was stored before its response was lost comes back as `unchanged` on the retry.
|
|
36
|
+
|
|
37
|
+
`send` takes any number of entries and sends them in requests of 1,000. It retries a `429`, a `5xx`, a timeout or a network error with a jittered, growing wait, and honors `Retry-After`.
|
|
38
|
+
|
|
39
|
+
Sending an entrant again before the cutoff only sets their weight, so a retry is safe until then. After the cutoff a retry would go to the next drawing, so every send is pinned to one drawing:
|
|
40
|
+
|
|
41
|
+
- Before the first batch it reads which drawing is taking entries, or uses the `drawing` you pass.
|
|
42
|
+
- It sends no batch and starts no retry within the request timeout (30 seconds) of that drawing's cutoff. It throws `PrizerailCutoffError` instead.
|
|
43
|
+
- If a batch still lands in another drawing, it throws `PrizerailDrawingChangedError`.
|
|
44
|
+
|
|
45
|
+
Both errors carry `progress`, which says how many entries the drawing confirmed. Check what it has with `entries.list({ drawing })` before you send the rest.
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
import { PrizerailCutoffError } from "prizerail"
|
|
49
|
+
|
|
50
|
+
try {
|
|
51
|
+
await campaign.entries.send(entries)
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if (!(error instanceof PrizerailCutoffError)) throw error
|
|
54
|
+
console.log(`${error.progress.sent} sent to ${error.progress.drawing.id}`)
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Entrant ids
|
|
59
|
+
|
|
60
|
+
Every locked list is published, hashed. Use an id that can't be guessed or linked back to a person. `hashEntrant(userId, key)` gives the HMAC-SHA256 of the user id as hex, the same as Node's `createHmac("sha256", key).update(id).digest("hex")`. Keep the key secret, and fixed for the life of the campaign. See [Entrant ids](https://docs.prizerail.com/getting-started/concepts#make-entrant-ids-with-an-hmac).
|
|
61
|
+
|
|
62
|
+
### Check what Prizerail has
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
let count = 0
|
|
66
|
+
for await (const entry of campaign.entries.all()) count++
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`entries.all()` pages through the drawing taking entries now, pinned to it after the first page. Pass `{ drawing: id }` for another drawing.
|
|
70
|
+
|
|
71
|
+
## Results and prizes
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
const info = await campaign.get()
|
|
75
|
+
// schedule, prizeTable.tiers with odds, guarantee, nextDrawing, termsUrl
|
|
76
|
+
|
|
77
|
+
const latest = await campaign.drawings.latest()
|
|
78
|
+
// the newest settled or paid drawing, with winners and payouts
|
|
79
|
+
|
|
80
|
+
for await (const drawing of campaign.drawings.all({ status: "paid" })) {
|
|
81
|
+
console.log(drawing.number, drawing.winners)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const guarantees = await campaign.guarantees.list()
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Errors
|
|
88
|
+
|
|
89
|
+
Every API error is a `PrizerailError` with the HTTP `status`, the API's `code` (like `not_found` or `no_open_drawing`) and a `detail`. A request that never got a response has status 0 and code `network_error`. See [Errors](https://docs.prizerail.com/api/errors).
|
|
90
|
+
|
|
91
|
+
## Verify a draw
|
|
92
|
+
|
|
93
|
+
Anyone can check a draw from its public proof, with no API key.
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
import { verifyDraw, wasEntered } from "prizerail"
|
|
97
|
+
|
|
98
|
+
const result = await verifyDraw(
|
|
99
|
+
"https://www.prizerail.com/campaigns/your-campaign/draws/DRAWING_ID/proof.json"
|
|
100
|
+
)
|
|
101
|
+
result.ok // true when every check passes
|
|
102
|
+
result.checks // [{ ok, label, detail }]
|
|
103
|
+
|
|
104
|
+
wasEntered(entrantId, result.entrants!) // { index, weight } or null
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
With a client, `campaign.drawings.verify(id)` does the same. The checks are the public [verify script](https://docs.prizerail.com/verification/verify-a-draw), shipped unchanged: the entrant list's Merkle root, the random value, and each winner and prize.
|
|
108
|
+
|
|
109
|
+
From the command line:
|
|
110
|
+
|
|
111
|
+
```sh
|
|
112
|
+
npx prizerail verify https://www.prizerail.com/campaigns/your-campaign/draws/DRAWING_ID/proof.json
|
|
113
|
+
npx prizerail verify your-campaign DRAWING_ID
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
It exits 0 when every check passes, 1 when one fails, and 2 when the proof can't be read.
|
|
117
|
+
|
|
118
|
+
## Options
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
new Prizerail({
|
|
122
|
+
apiKey: "pr_…",
|
|
123
|
+
siteUrl: "https://www.prizerail.com", // the default
|
|
124
|
+
timeoutMs: 30_000, // per attempt
|
|
125
|
+
maxRetries: 4,
|
|
126
|
+
fetch, // your own fetch, if you need one
|
|
127
|
+
})
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Keep the API key on your server. It can send entries for every campaign under your account.
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { Prizerail, VERSION } from "./client.js";
|
|
4
|
+
import { verifyDraw } from "./verify.js";
|
|
5
|
+
const USAGE = `prizerail ${VERSION}
|
|
6
|
+
|
|
7
|
+
Usage:
|
|
8
|
+
prizerail verify <proof.json link or file> [entrants link or file]
|
|
9
|
+
prizerail verify <campaign slug> <drawing id> [--site https://www.prizerail.com]
|
|
10
|
+
|
|
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.`;
|
|
14
|
+
function print(result) {
|
|
15
|
+
const { proof, checks } = result;
|
|
16
|
+
// A malformed proof may lack these, and its failed checks still print.
|
|
17
|
+
console.log(`\n${proof?.campaign?.name ?? "Unknown campaign"}, draw of ${proof?.drawing?.drawAt ?? "unknown date"} (${proof?.drawing?.id ?? "unknown drawing"})\n`);
|
|
18
|
+
for (const { ok, label, detail } of checks) {
|
|
19
|
+
const mark = ok === true ? "✓" : ok === false ? "✗" : "i";
|
|
20
|
+
console.log(`${mark} ${label}${detail ? `\n ${detail}` : ""}`);
|
|
21
|
+
}
|
|
22
|
+
const failed = checks.filter(c => c.ok === false).length;
|
|
23
|
+
console.log(failed
|
|
24
|
+
? `\n${failed} check${failed === 1 ? "" : "s"} failed.`
|
|
25
|
+
: "\nEvery result follows from the inputs.");
|
|
26
|
+
return failed ? 1 : 0;
|
|
27
|
+
}
|
|
28
|
+
async function main(argv) {
|
|
29
|
+
const args = [...argv];
|
|
30
|
+
const siteAt = args.indexOf("--site");
|
|
31
|
+
const site = siteAt === -1 ? undefined : args.splice(siteAt, 2)[1];
|
|
32
|
+
const [command, a, b] = args;
|
|
33
|
+
if (command === "--version" || command === "-v") {
|
|
34
|
+
console.log(VERSION);
|
|
35
|
+
return 0;
|
|
36
|
+
}
|
|
37
|
+
if (command !== "verify" || !a) {
|
|
38
|
+
console.log(USAGE);
|
|
39
|
+
return command === undefined || command === "--help" || command === "-h"
|
|
40
|
+
? 0
|
|
41
|
+
: 2;
|
|
42
|
+
}
|
|
43
|
+
// A link or any file on disk is a proof. Anything else is a campaign slug.
|
|
44
|
+
const looksLikeProof = /^https?:\/\//.test(a) || existsSync(a);
|
|
45
|
+
if (looksLikeProof)
|
|
46
|
+
return print(await verifyDraw(a, { entrants: b }));
|
|
47
|
+
if (!b) {
|
|
48
|
+
console.log(USAGE);
|
|
49
|
+
return 2;
|
|
50
|
+
}
|
|
51
|
+
const campaign = new Prizerail({ siteUrl: site }).campaign(a);
|
|
52
|
+
return print(await campaign.drawings.verify(b));
|
|
53
|
+
}
|
|
54
|
+
// exitCode rather than exit(), so a long report piped to a file isn't cut off.
|
|
55
|
+
main(process.argv.slice(2)).then(code => {
|
|
56
|
+
process.exitCode = code;
|
|
57
|
+
}, error => {
|
|
58
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
59
|
+
process.exitCode = 2;
|
|
60
|
+
});
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { Http } from "./http.js";
|
|
2
|
+
import type { Campaign, Drawing, DrawingRef, DrawingStatus, DrawingsPage, EntriesPage, Entry, Guarantee, SendEntriesResponse, SentEntry } from "./types.js";
|
|
3
|
+
import { type DrawProof, type VerifyResult } from "./verify.js";
|
|
4
|
+
export declare const VERSION = "0.1.0";
|
|
5
|
+
/** The API takes up to this many entries per request. */
|
|
6
|
+
export declare const ENTRIES_PER_REQUEST = 1000;
|
|
7
|
+
export type PrizerailOptions = {
|
|
8
|
+
/** Your `pr_…` key. Only the public helpers work without one. */
|
|
9
|
+
apiKey?: string;
|
|
10
|
+
/** Defaults to https://www.prizerail.com. */
|
|
11
|
+
siteUrl?: string;
|
|
12
|
+
/** Per attempt. Defaults to 30 seconds. */
|
|
13
|
+
timeoutMs?: number;
|
|
14
|
+
/** Retries for 429s, 5xx and network errors. Defaults to 4. */
|
|
15
|
+
maxRetries?: number;
|
|
16
|
+
/** Defaults to the global fetch. */
|
|
17
|
+
fetch?: typeof fetch;
|
|
18
|
+
};
|
|
19
|
+
export type SendOptions = {
|
|
20
|
+
/**
|
|
21
|
+
* The drawing to send to, as `entries.list()` or a previous send returned
|
|
22
|
+
* it. By default, the one taking entries now.
|
|
23
|
+
*/
|
|
24
|
+
drawing?: DrawingRef;
|
|
25
|
+
/**
|
|
26
|
+
* No batch is sent, and no retry started, this close to the cutoff, so
|
|
27
|
+
* no request arrives after it. Defaults to the request timeout.
|
|
28
|
+
*/
|
|
29
|
+
cutoffMarginMs?: number;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* `count` and `totalWeight` are the drawing's totals after the last batch.
|
|
33
|
+
* `added`, `updated` and `unchanged` sum what each batch reported, so a
|
|
34
|
+
* batch stored before its response was lost, then retried, counts as
|
|
35
|
+
* unchanged. Reconcile with `count`, not with `added`.
|
|
36
|
+
*/
|
|
37
|
+
export type SendResult = SendEntriesResponse & {
|
|
38
|
+
/** Entries in the batches the drawing confirmed. */
|
|
39
|
+
sent: number;
|
|
40
|
+
batches: number;
|
|
41
|
+
};
|
|
42
|
+
export declare class Prizerail {
|
|
43
|
+
readonly siteUrl: string;
|
|
44
|
+
/** @internal */
|
|
45
|
+
readonly http: Http;
|
|
46
|
+
constructor(options?: PrizerailOptions);
|
|
47
|
+
/** A campaign under your account, by slug. */
|
|
48
|
+
campaign(slug: string): CampaignClient;
|
|
49
|
+
}
|
|
50
|
+
export declare class CampaignClient {
|
|
51
|
+
readonly prizerail: Prizerail;
|
|
52
|
+
readonly slug: string;
|
|
53
|
+
readonly entries: EntriesClient;
|
|
54
|
+
readonly drawings: DrawingsClient;
|
|
55
|
+
readonly guarantees: {
|
|
56
|
+
list(): Promise<Guarantee[]>;
|
|
57
|
+
};
|
|
58
|
+
constructor(prizerail: Prizerail, slug: string);
|
|
59
|
+
/** @internal */
|
|
60
|
+
get http(): Http;
|
|
61
|
+
/** @internal */
|
|
62
|
+
path(rest?: string): string;
|
|
63
|
+
/** Schedule, prize table with odds, guarantee, next drawing, terms. */
|
|
64
|
+
get(): Promise<Campaign>;
|
|
65
|
+
}
|
|
66
|
+
export declare class EntriesClient {
|
|
67
|
+
private readonly campaign;
|
|
68
|
+
constructor(campaign: CampaignClient);
|
|
69
|
+
/**
|
|
70
|
+
* Sends entries to one drawing, in requests of 1,000, retrying 429s, 5xx
|
|
71
|
+
* and network errors. Sending an entrant again before the cutoff only sets
|
|
72
|
+
* their weight, so a retry is safe, but a retry after the cutoff would go
|
|
73
|
+
* to the next drawing. So the send is pinned to one drawing: it stops with
|
|
74
|
+
* a PrizerailCutoffError rather than send or retry near its cutoff, and
|
|
75
|
+
* with a PrizerailDrawingChangedError if a batch lands anywhere else.
|
|
76
|
+
*/
|
|
77
|
+
send(entries: Entry[], options?: SendOptions): Promise<SendResult>;
|
|
78
|
+
/** The drawing taking entries now. */
|
|
79
|
+
openDrawing(): Promise<DrawingRef>;
|
|
80
|
+
/** One page of a drawing's entries, in arrival order. */
|
|
81
|
+
list(query?: {
|
|
82
|
+
drawing?: string;
|
|
83
|
+
limit?: number;
|
|
84
|
+
after?: string;
|
|
85
|
+
}): Promise<EntriesPage>;
|
|
86
|
+
/**
|
|
87
|
+
* Every entry in a drawing, page by page. Without `drawing`, the one
|
|
88
|
+
* taking entries now, pinned by id after the first page so a cutoff
|
|
89
|
+
* mid-read can't mix in the next drawing.
|
|
90
|
+
*/
|
|
91
|
+
all(query?: {
|
|
92
|
+
drawing?: string;
|
|
93
|
+
pageSize?: number;
|
|
94
|
+
}): AsyncGenerator<SentEntry>;
|
|
95
|
+
}
|
|
96
|
+
export declare class DrawingsClient {
|
|
97
|
+
private readonly campaign;
|
|
98
|
+
constructor(campaign: CampaignClient);
|
|
99
|
+
/**
|
|
100
|
+
* One page. Open drawings come soonest first and page with `after`; the
|
|
101
|
+
* rest come newest first and page with `before`.
|
|
102
|
+
*/
|
|
103
|
+
list(query?: {
|
|
104
|
+
status?: DrawingStatus;
|
|
105
|
+
limit?: number;
|
|
106
|
+
before?: string;
|
|
107
|
+
after?: string;
|
|
108
|
+
}): Promise<DrawingsPage>;
|
|
109
|
+
/** Every drawing, following the cursors. */
|
|
110
|
+
all(query?: {
|
|
111
|
+
status?: DrawingStatus;
|
|
112
|
+
pageSize?: number;
|
|
113
|
+
}): AsyncGenerator<Drawing>;
|
|
114
|
+
get(id: string): Promise<Drawing>;
|
|
115
|
+
/**
|
|
116
|
+
* The newest drawing with final winners, `settled` or `paid`, or null.
|
|
117
|
+
* A large prize paid by hand can keep a newer draw at `settled`, so this
|
|
118
|
+
* reads both and takes the later.
|
|
119
|
+
*/
|
|
120
|
+
latest(): Promise<Drawing | null>;
|
|
121
|
+
/** The public proof link for a drawing. */
|
|
122
|
+
proofUrl(id: string): string;
|
|
123
|
+
/** The drawing's public proof. Needs no API key. */
|
|
124
|
+
proof(id: string): Promise<DrawProof>;
|
|
125
|
+
/** Fetches the proof and entrant list and checks the draw. */
|
|
126
|
+
verify(id: string): Promise<VerifyResult>;
|
|
127
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { PrizerailCutoffError, PrizerailDrawingChangedError, PrizerailError, } from "./errors.js";
|
|
2
|
+
import { Http } from "./http.js";
|
|
3
|
+
import { verifyDraw } from "./verify.js";
|
|
4
|
+
export const VERSION = "0.1.0";
|
|
5
|
+
const badPage = (detail) => new PrizerailError(0, "invalid_response", `Paging stopped: ${detail}.`);
|
|
6
|
+
/** The API takes up to this many entries per request. */
|
|
7
|
+
export const ENTRIES_PER_REQUEST = 1000;
|
|
8
|
+
export class Prizerail {
|
|
9
|
+
siteUrl;
|
|
10
|
+
/** @internal */
|
|
11
|
+
http;
|
|
12
|
+
constructor(options = {}) {
|
|
13
|
+
this.siteUrl = (options.siteUrl ?? "https://www.prizerail.com").replace(/\/+$/, "");
|
|
14
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
15
|
+
if (!fetchImpl)
|
|
16
|
+
throw new Error("No fetch here. Pass options.fetch.");
|
|
17
|
+
const timeoutMs = options.timeoutMs ?? 30_000;
|
|
18
|
+
const maxRetries = options.maxRetries ?? 4;
|
|
19
|
+
// AbortSignal.timeout takes whole ms up to the platform's timer limit.
|
|
20
|
+
if (!Number.isInteger(timeoutMs) ||
|
|
21
|
+
timeoutMs < 1 ||
|
|
22
|
+
timeoutMs > 2 ** 31 - 1) {
|
|
23
|
+
throw new TypeError("timeoutMs must be a whole number of ms, from 1 to 2147483647.");
|
|
24
|
+
}
|
|
25
|
+
if (!Number.isInteger(maxRetries) || maxRetries < 0) {
|
|
26
|
+
throw new TypeError("maxRetries must be a whole number from 0.");
|
|
27
|
+
}
|
|
28
|
+
this.http = new Http({
|
|
29
|
+
apiKey: options.apiKey,
|
|
30
|
+
baseUrl: `${this.siteUrl}/api/v1`,
|
|
31
|
+
fetch: fetchImpl.bind(globalThis),
|
|
32
|
+
timeoutMs,
|
|
33
|
+
maxRetries,
|
|
34
|
+
userAgent: `prizerail-js/${VERSION}`,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
/** A campaign under your account, by slug. */
|
|
38
|
+
campaign(slug) {
|
|
39
|
+
if (!slug)
|
|
40
|
+
throw new Error("campaign() needs a slug.");
|
|
41
|
+
return new CampaignClient(this, slug);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export class CampaignClient {
|
|
45
|
+
prizerail;
|
|
46
|
+
slug;
|
|
47
|
+
entries;
|
|
48
|
+
drawings;
|
|
49
|
+
guarantees;
|
|
50
|
+
constructor(prizerail, slug) {
|
|
51
|
+
this.prizerail = prizerail;
|
|
52
|
+
this.slug = slug;
|
|
53
|
+
this.entries = new EntriesClient(this);
|
|
54
|
+
this.drawings = new DrawingsClient(this);
|
|
55
|
+
this.guarantees = {
|
|
56
|
+
list: async () => (await this.http.request("GET", this.path("/guarantees"))).guarantees,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** @internal */
|
|
60
|
+
get http() {
|
|
61
|
+
return this.prizerail.http;
|
|
62
|
+
}
|
|
63
|
+
/** @internal */
|
|
64
|
+
path(rest = "") {
|
|
65
|
+
return `campaigns/${encodeURIComponent(this.slug)}${rest}`;
|
|
66
|
+
}
|
|
67
|
+
/** Schedule, prize table with odds, guarantee, next drawing, terms. */
|
|
68
|
+
async get() {
|
|
69
|
+
return (await this.http.request("GET", this.path()))
|
|
70
|
+
.campaign;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export class EntriesClient {
|
|
74
|
+
campaign;
|
|
75
|
+
constructor(campaign) {
|
|
76
|
+
this.campaign = campaign;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Sends entries to one drawing, in requests of 1,000, retrying 429s, 5xx
|
|
80
|
+
* and network errors. Sending an entrant again before the cutoff only sets
|
|
81
|
+
* their weight, so a retry is safe, but a retry after the cutoff would go
|
|
82
|
+
* to the next drawing. So the send is pinned to one drawing: it stops with
|
|
83
|
+
* a PrizerailCutoffError rather than send or retry near its cutoff, and
|
|
84
|
+
* with a PrizerailDrawingChangedError if a batch lands anywhere else.
|
|
85
|
+
*/
|
|
86
|
+
async send(entries, options = {}) {
|
|
87
|
+
if (entries.length === 0)
|
|
88
|
+
throw new Error("send() needs entries.");
|
|
89
|
+
const margin = options.cutoffMarginMs ?? this.campaign.http.options.timeoutMs;
|
|
90
|
+
// A bad margin or cutoff would turn the cutoff guard off, so refuse them.
|
|
91
|
+
if (!Number.isFinite(margin) || margin < 0) {
|
|
92
|
+
throw new TypeError("cutoffMarginMs must be a number of ms from 0.");
|
|
93
|
+
}
|
|
94
|
+
const target = options.drawing ?? (await this.openDrawing());
|
|
95
|
+
const cutoff = Date.parse(target.cutoffAt);
|
|
96
|
+
if (!target.id || !Number.isFinite(cutoff)) {
|
|
97
|
+
throw new TypeError("drawing must have the id and cutoffAt that entries.list() or a send returned.");
|
|
98
|
+
}
|
|
99
|
+
const progress = {
|
|
100
|
+
drawing: target,
|
|
101
|
+
sent: 0,
|
|
102
|
+
added: 0,
|
|
103
|
+
updated: 0,
|
|
104
|
+
unchanged: 0,
|
|
105
|
+
};
|
|
106
|
+
const stop = (detail, cause) => new PrizerailCutoffError(detail, { ...progress }, cause);
|
|
107
|
+
let last;
|
|
108
|
+
let batches = 0;
|
|
109
|
+
for (let i = 0; i < entries.length; i += ENTRIES_PER_REQUEST) {
|
|
110
|
+
if (Date.now() + margin >= cutoff) {
|
|
111
|
+
throw stop(`Drawing ${target.id}'s cutoff is at ${target.cutoffAt}, so the rest wasn't sent.`);
|
|
112
|
+
}
|
|
113
|
+
const batch = entries.slice(i, i + ENTRIES_PER_REQUEST);
|
|
114
|
+
const res = await this.campaign.http.request("POST", this.campaign.path("/entries"), {
|
|
115
|
+
body: { entries: batch },
|
|
116
|
+
deadline: cutoff - margin,
|
|
117
|
+
onDeadline: cause => stop(`A batch failed and a retry would reach drawing ${target.id}'s cutoff. Check what it has before sending again.`, cause),
|
|
118
|
+
});
|
|
119
|
+
if (res.drawing.id !== target.id) {
|
|
120
|
+
throw new PrizerailDrawingChangedError({ ...progress }, res.drawing);
|
|
121
|
+
}
|
|
122
|
+
progress.sent += batch.length;
|
|
123
|
+
progress.added += res.added;
|
|
124
|
+
progress.updated += res.updated;
|
|
125
|
+
progress.unchanged += res.unchanged;
|
|
126
|
+
last = res;
|
|
127
|
+
batches++;
|
|
128
|
+
}
|
|
129
|
+
const final = last;
|
|
130
|
+
return {
|
|
131
|
+
drawing: final.drawing,
|
|
132
|
+
added: progress.added,
|
|
133
|
+
updated: progress.updated,
|
|
134
|
+
unchanged: progress.unchanged,
|
|
135
|
+
count: final.count,
|
|
136
|
+
totalWeight: final.totalWeight,
|
|
137
|
+
sent: progress.sent,
|
|
138
|
+
batches,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/** The drawing taking entries now. */
|
|
142
|
+
async openDrawing() {
|
|
143
|
+
const { drawing } = await this.list({ limit: 1 });
|
|
144
|
+
return {
|
|
145
|
+
id: drawing.id,
|
|
146
|
+
drawAt: drawing.drawAt,
|
|
147
|
+
cutoffAt: drawing.cutoffAt,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
/** One page of a drawing's entries, in arrival order. */
|
|
151
|
+
list(query = {}) {
|
|
152
|
+
return this.campaign.http.request("GET", this.campaign.path("/entries"), { query });
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Every entry in a drawing, page by page. Without `drawing`, the one
|
|
156
|
+
* taking entries now, pinned by id after the first page so a cutoff
|
|
157
|
+
* mid-read can't mix in the next drawing.
|
|
158
|
+
*/
|
|
159
|
+
async *all(query = {}) {
|
|
160
|
+
let drawing = query.drawing;
|
|
161
|
+
let after;
|
|
162
|
+
for (;;) {
|
|
163
|
+
const page = await this.list({
|
|
164
|
+
drawing,
|
|
165
|
+
limit: query.pageSize ?? ENTRIES_PER_REQUEST,
|
|
166
|
+
after,
|
|
167
|
+
});
|
|
168
|
+
drawing ??= page.drawing.id;
|
|
169
|
+
if (page.drawing.id !== drawing) {
|
|
170
|
+
throw badPage(`a page came from drawing ${page.drawing.id}, not ${drawing}`);
|
|
171
|
+
}
|
|
172
|
+
yield* page.entries;
|
|
173
|
+
if (page.next === null)
|
|
174
|
+
return;
|
|
175
|
+
// Each cursor must move forward, or a bad page would loop forever.
|
|
176
|
+
// Cursors are whole numbers sent as strings, so compare them as numbers.
|
|
177
|
+
if (!/^\d+$/.test(page.next) ||
|
|
178
|
+
BigInt(page.next) <= BigInt(after ?? -1)) {
|
|
179
|
+
throw badPage(`next ${page.next} doesn't move past ${after}`);
|
|
180
|
+
}
|
|
181
|
+
after = page.next;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
export class DrawingsClient {
|
|
186
|
+
campaign;
|
|
187
|
+
constructor(campaign) {
|
|
188
|
+
this.campaign = campaign;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* One page. Open drawings come soonest first and page with `after`; the
|
|
192
|
+
* rest come newest first and page with `before`.
|
|
193
|
+
*/
|
|
194
|
+
list(query = {}) {
|
|
195
|
+
return this.campaign.http.request("GET", this.campaign.path("/drawings"), { query });
|
|
196
|
+
}
|
|
197
|
+
/** Every drawing, following the cursors. */
|
|
198
|
+
async *all(query = {}) {
|
|
199
|
+
let cursor = {};
|
|
200
|
+
for (;;) {
|
|
201
|
+
const page = await this.list({
|
|
202
|
+
status: query.status,
|
|
203
|
+
limit: query.pageSize ?? 100,
|
|
204
|
+
...cursor,
|
|
205
|
+
});
|
|
206
|
+
yield* page.drawings;
|
|
207
|
+
// Each cursor must move on, or a bad page would loop forever.
|
|
208
|
+
if (page.nextAfter) {
|
|
209
|
+
if (cursor.after && !(page.nextAfter > cursor.after)) {
|
|
210
|
+
throw badPage(`nextAfter ${page.nextAfter} doesn't move past ${cursor.after}`);
|
|
211
|
+
}
|
|
212
|
+
cursor = { after: page.nextAfter };
|
|
213
|
+
}
|
|
214
|
+
else if (page.nextBefore) {
|
|
215
|
+
if (cursor.before && !(page.nextBefore < cursor.before)) {
|
|
216
|
+
throw badPage(`nextBefore ${page.nextBefore} doesn't move past ${cursor.before}`);
|
|
217
|
+
}
|
|
218
|
+
cursor = { before: page.nextBefore };
|
|
219
|
+
}
|
|
220
|
+
else
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
async get(id) {
|
|
225
|
+
return (await this.campaign.http.request("GET", this.campaign.path(`/drawings/${encodeURIComponent(id)}`))).drawing;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* The newest drawing with final winners, `settled` or `paid`, or null.
|
|
229
|
+
* A large prize paid by hand can keep a newer draw at `settled`, so this
|
|
230
|
+
* reads both and takes the later.
|
|
231
|
+
*/
|
|
232
|
+
async latest() {
|
|
233
|
+
// In this order, so a draw that turns paid between the two reads still
|
|
234
|
+
// shows in one of them.
|
|
235
|
+
const settled = await this.list({ status: "settled", limit: 1 });
|
|
236
|
+
const paid = await this.list({ status: "paid", limit: 1 });
|
|
237
|
+
// Paid first, so a drawing that moved from settled to paid between the
|
|
238
|
+
// two reads ties to its paid copy (the sort is stable).
|
|
239
|
+
const found = [...paid.drawings, ...settled.drawings];
|
|
240
|
+
found.sort((a, b) => Date.parse(b.drawAt) - Date.parse(a.drawAt));
|
|
241
|
+
return found[0] ?? null;
|
|
242
|
+
}
|
|
243
|
+
/** The public proof link for a drawing. */
|
|
244
|
+
proofUrl(id) {
|
|
245
|
+
const site = this.campaign.prizerail.siteUrl;
|
|
246
|
+
return `${site}/campaigns/${encodeURIComponent(this.campaign.slug)}/draws/${encodeURIComponent(id)}/proof.json`;
|
|
247
|
+
}
|
|
248
|
+
/** The drawing's public proof. Needs no API key. */
|
|
249
|
+
proof(id) {
|
|
250
|
+
return this.campaign.http.getPublic(this.proofUrl(id));
|
|
251
|
+
}
|
|
252
|
+
/** Fetches the proof and entrant list and checks the draw. */
|
|
253
|
+
async verify(id) {
|
|
254
|
+
const proof = await this.proof(id);
|
|
255
|
+
const { fetch, timeoutMs } = this.campaign.http.options;
|
|
256
|
+
return verifyDraw(proof, { proofUrl: this.proofUrl(id), fetch, timeoutMs });
|
|
257
|
+
}
|
|
258
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An entrant id for a user: HMAC-SHA256 of their id with your secret key,
|
|
3
|
+
* as hex. The same user and key always give the same id, and without the
|
|
4
|
+
* key nobody can work back to the user. Keep the key fixed for the life of
|
|
5
|
+
* the campaign. Matches Node's createHmac("sha256", key).update(id).digest("hex").
|
|
6
|
+
*/
|
|
7
|
+
export declare function hashEntrant(userId: string | number, key: string): Promise<string>;
|
package/dist/entrant.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An entrant id for a user: HMAC-SHA256 of their id with your secret key,
|
|
3
|
+
* as hex. The same user and key always give the same id, and without the
|
|
4
|
+
* key nobody can work back to the user. Keep the key fixed for the life of
|
|
5
|
+
* the campaign. Matches Node's createHmac("sha256", key).update(id).digest("hex").
|
|
6
|
+
*/
|
|
7
|
+
export async function hashEntrant(userId, key) {
|
|
8
|
+
if (!key)
|
|
9
|
+
throw new Error("hashEntrant needs your secret key.");
|
|
10
|
+
const enc = new TextEncoder();
|
|
11
|
+
const cryptoKey = await globalThis.crypto.subtle.importKey("raw", enc.encode(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
12
|
+
const mac = await globalThis.crypto.subtle.sign("HMAC", cryptoKey, enc.encode(String(userId)));
|
|
13
|
+
return Array.from(new Uint8Array(mac), b => b.toString(16).padStart(2, "0")).join("");
|
|
14
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { DrawingRef } from "./types.js";
|
|
2
|
+
/** An error response from the API, or a request that never got one. */
|
|
3
|
+
export declare class PrizerailError extends Error {
|
|
4
|
+
/** The HTTP status. 0 when the request failed before a response. */
|
|
5
|
+
readonly status: number;
|
|
6
|
+
/** The API's error code, like `not_found` or `no_open_drawing`. */
|
|
7
|
+
readonly code: string;
|
|
8
|
+
readonly detail?: string;
|
|
9
|
+
constructor(status: number, code: string, detail?: string);
|
|
10
|
+
}
|
|
11
|
+
/** What a send had stored before it stopped. */
|
|
12
|
+
export type SendProgress = {
|
|
13
|
+
drawing: DrawingRef;
|
|
14
|
+
/** Entries in the batches Prizerail confirmed. */
|
|
15
|
+
sent: number;
|
|
16
|
+
added: number;
|
|
17
|
+
updated: number;
|
|
18
|
+
unchanged: number;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* A send stopped so that no entry lands in the drawing after the one it
|
|
22
|
+
* targeted. Entries past `progress.sent` were not confirmed: check with
|
|
23
|
+
* `entries.list({ drawing })` before sending them to the next drawing.
|
|
24
|
+
*/
|
|
25
|
+
export declare class PrizerailCutoffError extends PrizerailError {
|
|
26
|
+
readonly progress: SendProgress;
|
|
27
|
+
readonly cause?: unknown;
|
|
28
|
+
constructor(detail: string, progress: SendProgress, cause?: unknown);
|
|
29
|
+
}
|
|
30
|
+
/** A batch went to a different drawing from the rest of the send. */
|
|
31
|
+
export declare class PrizerailDrawingChangedError extends PrizerailError {
|
|
32
|
+
readonly progress: SendProgress;
|
|
33
|
+
/** Where the last batch went. */
|
|
34
|
+
readonly landedIn: DrawingRef;
|
|
35
|
+
constructor(progress: SendProgress, landedIn: DrawingRef);
|
|
36
|
+
}
|