claimpaign 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.
Files changed (4) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +88 -0
  3. package/dist/bin.js +952 -0
  4. package/package.json +42 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Lichtstaub
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # claimpaign
2
+
3
+ Command line tool for Claimpaign sandbox campaigns and CIP-99 claims. It is made for events like hackathons, workshops and school classes where many people need preprod ada or test tokens quickly: the organizer creates a campaign from the terminal and hands out codes or QR cards, participants claim without owning a wallet yet, and the organization's own test tokens can be distributed the same way. It also claims CIP-99 codes from other faucets on the Cardano preprod testnet.
4
+
5
+ ## Install
6
+
7
+ ```
8
+ npx claimpaign --help
9
+ ```
10
+
11
+ Or install it globally:
12
+
13
+ ```
14
+ npm install -g claimpaign
15
+ ```
16
+
17
+ ## Login
18
+
19
+ Run `claimpaign login` and paste your sandbox API key when prompted. Get a key from Settings, Sandbox API on claimpaign.com, it looks like `cps_` followed by 40 characters. Setting `CLAIMPAIGN_TOKEN` skips `claimpaign login` entirely, every command reads it before anything else. `claimpaign login` itself always prompts for a key even when the variable is set, its whole purpose is storing a key in the config file.
20
+
21
+ ## Hackathon flow
22
+
23
+ 1. Deposit test tokens into the org wallet, or top up sandbox credits in the web interface. `claimpaign deposit` shows the wallet address and the top up link.
24
+ 2. `claimpaign campaign create --name "..." --claims 50 --ada 2` creates a campaign and exports its codes. Run one `campaign create` at a time, two parallel creations would produce two funded campaigns.
25
+ 3. `claimpaign campaign codes <id> --qr-dir ./qr --pdf codes.pdf` prints QR codes and a cut sheet PDF.
26
+ 4. Hand out the codes, on paper or as QR images.
27
+ 5. `claimpaign campaign status <id>` shows how many codes are claimed.
28
+ 6. `claimpaign campaign end <id>` ends the campaign and refunds unclaimed credits.
29
+
30
+ ## For participants
31
+
32
+ ```
33
+ claimpaign claim <uri-or-code> <addr_test...>
34
+ ```
35
+
36
+ Works with a scanned CIP-99 claim URI, or a bare code together with `--faucet <url>`. Also works against other CIP-99 faucets, not just Claimpaign campaigns.
37
+
38
+ Sandbox (Cardano preprod) only, never mainnet.
39
+
40
+ ## Exit codes
41
+
42
+ - `0` success
43
+ - `1` the command ran but failed, an API error, a rejected claim, a network problem
44
+ - `2` usage error, bad arguments or a missing required environment variable
45
+ - `130` the login prompt was cancelled (Ctrl-C)
46
+
47
+ ## JSON output
48
+
49
+ Every command accepts a top level `--json` flag, which prints the shape below instead of the human readable text. Fields marked `?` are only present when the value applies.
50
+
51
+ - `login` no stdout output, only the exit code and the stored config change
52
+ - `logout` no stdout output, only the exit code and the stored config change
53
+ - `balance` `{ credits: <raw org credits body>, wallet: <raw org wallet body> }`
54
+ - `deposit` `{ address, network }`
55
+ - `campaign create` `{ campaign: { id, status, codePrefix, totalCodes }, pricing?, codesFile?, exportError? }`
56
+ - `campaign list` `{ campaigns: [...] }`
57
+ - `campaign status` the raw campaign GET body, `{ campaign, codes, queue, pagination }`
58
+ - `campaign codes` without `--csv`/`--qr-dir`/`--pdf`, `{ campaign: { id, name, codePrefix }, codes: [{ code, status, claim_uri, fallback_url }] }`
59
+ - `campaign codes` with `--csv`/`--qr-dir`/`--pdf`, `{ csv?, qrDir?, pdf?, count }`
60
+ - `campaign end` the raw endpoint body, `{ ok, status, refunded? }`
61
+ - `campaign pause` / `campaign resume` the raw endpoint body, `{ ok, status }`
62
+ - `claim` the raw faucet response body, `{ code, status, message?, lovelaces?, tokens?, queue_position? }`, printed even when the claim is not accepted, before the command exits with an error
63
+
64
+ ## Configuration
65
+
66
+ The CLI stores its login in `~/.config/claimpaign/config.json` (mode 0600).
67
+
68
+ - `CLAIMPAIGN_API` API base URL, overrides the stored one and the default `https://claimpaign.com`
69
+ - `CLAIMPAIGN_TOKEN` sandbox API key, overrides the stored one and skips the login prompt
70
+ - `CLAIMPAIGN_CONFIG_DIR` directory for `config.json`, default `~/.config/claimpaign`
71
+
72
+ ## Development
73
+
74
+ From a checkout: `npm install && npm run build`, then `node dist/bin.js --help`, or `npm link` once to get the `claimpaign` command. `npx claimpaign` only works with the published package.
75
+
76
+ ```
77
+ npm test
78
+ ```
79
+
80
+ `scripts/e2e.sh` runs an end to end test against a real API, not part of `npm test`. It needs `CLAIMPAIGN_API`, `CLAIMPAIGN_TOKEN` and `E2E_ADDRESSES` (a file with one `addr_test` address per line) as environment variables. The default run is a smoke test, `--full` adds a 60 claim acceptance run, `--foreign` adds a claim against an external CIP-99 faucet and needs `E2E_FOREIGN_URI` (a CIP-99 claim uri, for example the tUSDM preprod faucet).
81
+
82
+ ## Documentation
83
+
84
+ https://claimpaign.com/docs
85
+
86
+ ## License
87
+
88
+ Apache 2.0
package/dist/bin.js ADDED
@@ -0,0 +1,952 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { Command, CommanderError } from "commander";
5
+ import { createRequire } from "module";
6
+
7
+ // src/output.ts
8
+ var UsageError = class extends Error {
9
+ };
10
+ var CancelledError = class extends Error {
11
+ };
12
+ function print(value, opts) {
13
+ if (opts.json) {
14
+ process.stdout.write(JSON.stringify(value, null, 2) + "\n");
15
+ return;
16
+ }
17
+ if (typeof value === "string") process.stdout.write(value + "\n");
18
+ else process.stdout.write(JSON.stringify(value, null, 2) + "\n");
19
+ }
20
+ function formatAda(value) {
21
+ return value.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
22
+ }
23
+ function table(rows) {
24
+ if (rows.length === 0) return "(none)";
25
+ const keys = Object.keys(rows[0]);
26
+ const widths = keys.map((k) => Math.max(k.length, ...rows.map((r) => String(r[k] ?? "").length)));
27
+ const line = (cells) => cells.map((c, i) => c.padEnd(widths[i])).join(" ");
28
+ return [line(keys), line(widths.map((w) => "-".repeat(w))), ...rows.map((r) => line(keys.map((k) => String(r[k] ?? ""))))].join("\n");
29
+ }
30
+
31
+ // src/config.ts
32
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "fs";
33
+ import { homedir } from "os";
34
+ import { join } from "path";
35
+ var DEFAULT_API = "https://claimpaign.com";
36
+ function configDir() {
37
+ return process.env.CLAIMPAIGN_CONFIG_DIR || join(homedir(), ".config", "claimpaign");
38
+ }
39
+ function configPath() {
40
+ return join(configDir(), "config.json");
41
+ }
42
+ function readConfig() {
43
+ try {
44
+ const parsed = JSON.parse(readFileSync(configPath(), "utf8"));
45
+ return typeof parsed === "object" && parsed ? parsed : {};
46
+ } catch {
47
+ return {};
48
+ }
49
+ }
50
+ function writeConfig(patch, remove = []) {
51
+ const next = { ...readConfig(), ...patch };
52
+ for (const key of remove) delete next[key];
53
+ if (!existsSync(configDir())) mkdirSync(configDir(), { recursive: true, mode: 448 });
54
+ chmodSync(configDir(), 448);
55
+ writeFileSync(configPath(), JSON.stringify(next, null, 2) + "\n", { mode: 384 });
56
+ chmodSync(configPath(), 384);
57
+ }
58
+ function resolveToken() {
59
+ return process.env.CLAIMPAIGN_TOKEN || readConfig().token;
60
+ }
61
+ function resolveApi(flag) {
62
+ const raw = flag || process.env.CLAIMPAIGN_API || readConfig().api || DEFAULT_API;
63
+ return raw.replace(/\/+$/, "");
64
+ }
65
+
66
+ // src/api.ts
67
+ var ApiError = class extends Error {
68
+ status;
69
+ body;
70
+ constructor(status, message, body) {
71
+ super(message);
72
+ this.name = "ApiError";
73
+ this.status = status;
74
+ this.body = body;
75
+ }
76
+ };
77
+ var DEFAULT_RETRY_DELAYS_MS = [2e3, 4e3, 8e3];
78
+ var DEFAULT_TIMEOUT_MS = 3e4;
79
+ var RETRYABLE_METHODS = /* @__PURE__ */ new Set(["GET", "PATCH"]);
80
+ function sleep(ms) {
81
+ return new Promise((resolve) => setTimeout(resolve, ms));
82
+ }
83
+ function messageFromBody(body, status) {
84
+ if (body && typeof body === "object") {
85
+ const record = body;
86
+ if (typeof record.error === "string") return record.error;
87
+ if (typeof record.message === "string") return record.message;
88
+ if (typeof record.status === "string") return record.status;
89
+ }
90
+ return `HTTP ${status}`;
91
+ }
92
+ async function apiRequest(options) {
93
+ const { api, token, method, path, body, headers, allow = [], retryDelaysMs = DEFAULT_RETRY_DELAYS_MS, timeoutMs = DEFAULT_TIMEOUT_MS } = options;
94
+ const url = `${api}${path}`;
95
+ const requestHeaders = { ...headers };
96
+ if (token) requestHeaders.authorization = `Bearer ${token}`;
97
+ if (body !== void 0) requestHeaders["content-type"] = "application/json";
98
+ const canRetry = RETRYABLE_METHODS.has(method.toUpperCase());
99
+ let attempt = 0;
100
+ for (; ; ) {
101
+ let status;
102
+ let parsedBody;
103
+ try {
104
+ const response = await fetch(url, {
105
+ method,
106
+ headers: requestHeaders,
107
+ body: body !== void 0 ? JSON.stringify(body) : void 0,
108
+ signal: AbortSignal.timeout(timeoutMs)
109
+ });
110
+ status = response.status;
111
+ const text = await response.text();
112
+ try {
113
+ parsedBody = text ? JSON.parse(text) : void 0;
114
+ } catch {
115
+ parsedBody = text;
116
+ }
117
+ } catch (err) {
118
+ const name = err?.name;
119
+ if (name === "TimeoutError" || name === "AbortError") {
120
+ throw new ApiError(0, `Timed out after ${timeoutMs / 1e3}s waiting for ${api}`);
121
+ }
122
+ throw new ApiError(0, `Could not reach ${api}`);
123
+ }
124
+ if (status === 429 && canRetry && attempt < retryDelaysMs.length) {
125
+ await sleep(retryDelaysMs[attempt]);
126
+ attempt += 1;
127
+ continue;
128
+ }
129
+ if (status >= 400 && !allow.includes(status)) {
130
+ throw new ApiError(status, messageFromBody(parsedBody, status), parsedBody);
131
+ }
132
+ return { status, body: parsedBody };
133
+ }
134
+ }
135
+ function requireToken() {
136
+ const token = resolveToken();
137
+ if (!token) throw new UsageError("Not logged in. Run: claimpaign login");
138
+ return token;
139
+ }
140
+
141
+ // src/commands/login.ts
142
+ function promptSecret(question, input = process.stdin) {
143
+ process.stderr.write(question);
144
+ const isTty = !!input.isTTY && typeof input.setRawMode === "function";
145
+ if (isTty) input.setRawMode(true);
146
+ input.resume();
147
+ let buffer = "";
148
+ return new Promise((resolve, reject) => {
149
+ const finish = (value, err) => {
150
+ input.off("data", onData);
151
+ input.off("end", onEnd);
152
+ input.off("error", onError);
153
+ if (isTty) input.setRawMode(false);
154
+ input.pause();
155
+ input.unref?.();
156
+ if (isTty) process.stderr.write("\n");
157
+ if (err) reject(err);
158
+ else resolve((value ?? buffer).trim());
159
+ };
160
+ const onData = (chunk) => {
161
+ for (const ch of chunk.toString("utf8")) {
162
+ if (ch === "\r" || ch === "\n") return finish(buffer);
163
+ if (ch === "") {
164
+ finish(null, new CancelledError("Cancelled"));
165
+ return;
166
+ }
167
+ if (ch === "\x7F" || ch === "\b") buffer = buffer.slice(0, -1);
168
+ else buffer += ch;
169
+ }
170
+ };
171
+ const onEnd = () => finish(buffer);
172
+ const onError = (err) => finish(null, err);
173
+ input.on("data", onData);
174
+ input.on("end", onEnd);
175
+ input.on("error", onError);
176
+ });
177
+ }
178
+ async function login(opts) {
179
+ const api = resolveApi(opts.api);
180
+ const token = opts.token ?? await promptSecret("Paste your sandbox API key (from Settings, Sandbox API): ");
181
+ if (!/^cps_[a-z2-9]{40}$/.test(token)) throw new UsageError("That does not look like a Claimpaign sandbox key (cps_ followed by 40 characters)");
182
+ try {
183
+ await apiRequest({ api, token, method: "GET", path: "/api/org/credits" });
184
+ } catch (err) {
185
+ if (err instanceof ApiError && err.status === 401) throw new Error("This key was not accepted. Create one under Settings, Sandbox API.");
186
+ throw err;
187
+ }
188
+ writeConfig({ token, api });
189
+ if (!opts.json) process.stdout.write(`Logged in. Key stored in ${configPathHint()} (sandbox only).
190
+ `);
191
+ }
192
+ async function logout() {
193
+ writeConfig({}, ["token"]);
194
+ }
195
+ function configPathHint() {
196
+ return process.env.CLAIMPAIGN_CONFIG_DIR ? `${process.env.CLAIMPAIGN_CONFIG_DIR}/config.json` : "~/.config/claimpaign/config.json";
197
+ }
198
+
199
+ // src/commands/balance.ts
200
+ async function balance(opts) {
201
+ const token = requireToken();
202
+ const api = resolveApi(opts.api);
203
+ const [credits, wallet] = await Promise.all([
204
+ apiRequest({ api, token, method: "GET", path: "/api/org/credits" }),
205
+ apiRequest({ api, token, method: "GET", path: "/api/org/wallet" })
206
+ ]);
207
+ if (opts.json) {
208
+ print({ credits: credits.body, wallet: wallet.body }, { json: true });
209
+ return;
210
+ }
211
+ const creditsBody = credits.body;
212
+ const walletBody = wallet.body;
213
+ const ownTokens = walletBody.tokens.filter((t) => !t.platform);
214
+ const platformTokens = walletBody.tokens.filter((t) => t.platform);
215
+ const rows = [...ownTokens, ...platformTokens].map((t) => ({
216
+ // Asset names with a CIP-68 label or binary bytes must not break the table
217
+ Token: t.assetNameUtf8.replace(/[\x00-\x1f\x7f\ufffd]/g, "") + (t.platform ? " (platform)" : ""),
218
+ Available: t.available,
219
+ Reserved: t.reserved,
220
+ Settling: t.inFlight
221
+ }));
222
+ const lines = [
223
+ `Sandbox credits: ${formatAda(creditsBody.balance.ada)} tADA (locked in campaigns: ${formatAda(creditsBody.summary.lockedInCampaigns.ada)}, active campaigns: ${creditsBody.summary.activeCampaignCount})`,
224
+ `Org wallet: ${walletBody.address} (${formatAda(walletBody.ada.ada)} tADA)`,
225
+ "",
226
+ table(rows)
227
+ ];
228
+ print(lines.join("\n"), { json: false });
229
+ }
230
+
231
+ // src/commands/deposit.ts
232
+ async function deposit(opts) {
233
+ const token = requireToken();
234
+ const api = resolveApi(opts.api);
235
+ const { body: wallet } = await apiRequest({ api, token, method: "GET", path: "/api/org/wallet" });
236
+ if (opts.json) {
237
+ print({ address: wallet.address, network: wallet.network }, { json: true });
238
+ return;
239
+ }
240
+ const lines = [
241
+ `Org wallet: ${wallet.address}`,
242
+ "",
243
+ "Send test tokens to this address. They stay the property of the organization and get distributed from there.",
244
+ "Any tADA sent along with them is used for payouts, it does not become sandbox credits.",
245
+ `Top up tADA credits in the web interface at ${api}/admin/create/.`,
246
+ "Preprod ada for the wallet itself comes from the Cardano testnet faucet: https://docs.cardano.org/cardano-testnets/tools/faucet"
247
+ ];
248
+ print(lines.join("\n"), { json: false });
249
+ }
250
+
251
+ // src/commands/campaign.ts
252
+ import { existsSync as existsSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync2, writeFileSync as writeFileSync3, chmodSync as chmodSync2, rmSync } from "fs";
253
+ import { join as join3 } from "path";
254
+ import { randomInt, randomUUID, createHash } from "crypto";
255
+
256
+ // src/codes.ts
257
+ var CODE_LENGTH = 10;
258
+ var CROCKFORD_CODE = /^[0-9A-HJKMNP-TV-Z]{10}$/;
259
+ var LEGACY_HEX_CODE = /^[a-f0-9]{6,9}$/;
260
+ function normalizeShortCode(input) {
261
+ const trimmed = input.trim();
262
+ if (trimmed.length === CODE_LENGTH) {
263
+ const folded = trimmed.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1");
264
+ return CROCKFORD_CODE.test(folded) ? folded : null;
265
+ }
266
+ const lower = trimmed.toLowerCase();
267
+ return LEGACY_HEX_CODE.test(lower) ? lower : null;
268
+ }
269
+ function splitFullCode(full) {
270
+ const sep = full.lastIndexOf("_");
271
+ if (sep < 0) return null;
272
+ const prefix = full.slice(0, sep);
273
+ const shortCode = full.slice(sep + 1);
274
+ if (!prefix || !shortCode) return null;
275
+ return { prefix, shortCode };
276
+ }
277
+ function buildClaimUri(api, prefix, shortCode) {
278
+ const faucetUrl = `${api}/api/claim/${prefix}`;
279
+ return `web+cardano://claim/v1?faucet_url=${encodeURIComponent(faucetUrl)}&code=${encodeURIComponent(shortCode)}`;
280
+ }
281
+ function buildFallbackUri(api, fullCode) {
282
+ return `${api}/api/qr/${fullCode}`;
283
+ }
284
+ var CLAIM_URI_PREFIXES = ["web+cardano://claim/v1", "web+cardano:claim/v1"];
285
+ function parseClaimUri(uri) {
286
+ const qIndex = uri.indexOf("?");
287
+ if (qIndex < 0) return null;
288
+ const head = uri.slice(0, qIndex);
289
+ if (!CLAIM_URI_PREFIXES.includes(head)) return null;
290
+ const params = new URLSearchParams(uri.slice(qIndex + 1));
291
+ const faucetUrl = params.get("faucet_url");
292
+ const code = params.get("code");
293
+ if (!faucetUrl || !code) return null;
294
+ return { faucetUrl, code };
295
+ }
296
+
297
+ // src/export.ts
298
+ import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
299
+ import { dirname, join as join2 } from "path";
300
+ import QRCode from "qrcode";
301
+ import { PDFDocument, StandardFonts } from "pdf-lib";
302
+ var PAGE_WIDTH = 595;
303
+ var PAGE_HEIGHT = 842;
304
+ var COLS = 3;
305
+ var ROWS = 4;
306
+ var PER_PAGE = COLS * ROWS;
307
+ var MARGIN = 36;
308
+ var QR_SIZE = 120;
309
+ function toWinAnsi(text) {
310
+ return Array.from(text).map((ch) => {
311
+ const code = ch.codePointAt(0) ?? 0;
312
+ return code >= 32 && code <= 126 || code >= 160 && code <= 255 ? ch : "?";
313
+ }).join("");
314
+ }
315
+ function csvField(value) {
316
+ if (/[",\n]/.test(value)) return '"' + value.replace(/"/g, '""') + '"';
317
+ return value;
318
+ }
319
+ function ensureDirFor(path) {
320
+ const dir = dirname(path);
321
+ if (dir) mkdirSync2(dir, { recursive: true });
322
+ }
323
+ function writeCsv(path, rows, columns) {
324
+ ensureDirFor(path);
325
+ const keys = columns ?? (rows.length > 0 ? Object.keys(rows[0]) : []);
326
+ if (keys.length === 0) {
327
+ writeFileSync2(path, "");
328
+ return;
329
+ }
330
+ const lines = [keys.map(csvField).join(",")];
331
+ for (const row of rows) lines.push(keys.map((k) => csvField(row[k] ?? "")).join(","));
332
+ writeFileSync2(path, lines.join("\n") + "\n");
333
+ }
334
+ async function writeQrImages(dir, items) {
335
+ mkdirSync2(dir, { recursive: true });
336
+ for (const item of items) {
337
+ await QRCode.toFile(join2(dir, `${item.code}.png`), item.uri, { width: 512, margin: 2 });
338
+ }
339
+ }
340
+ function drawCard(page, qrImage, code, title, monoFont, titleFont, cellX, cellTop, cellWidth) {
341
+ const qrX = cellX + (cellWidth - QR_SIZE) / 2;
342
+ const qrY = cellTop - QR_SIZE - 12;
343
+ page.drawImage(qrImage, { x: qrX, y: qrY, width: QR_SIZE, height: QR_SIZE });
344
+ const safeCode = toWinAnsi(code);
345
+ const codeSize = 10;
346
+ const codeWidth = monoFont.widthOfTextAtSize(safeCode, codeSize);
347
+ page.drawText(safeCode, { x: cellX + (cellWidth - codeWidth) / 2, y: qrY - 14, size: codeSize, font: monoFont });
348
+ const safeTitle = toWinAnsi(title);
349
+ const titleSize = 7;
350
+ const titleWidth = titleFont.widthOfTextAtSize(safeTitle, titleSize);
351
+ page.drawText(safeTitle, { x: cellX + (cellWidth - titleWidth) / 2, y: qrY - 26, size: titleSize, font: titleFont });
352
+ }
353
+ async function writePdf(path, items, title) {
354
+ ensureDirFor(path);
355
+ const doc = await PDFDocument.create();
356
+ const monoFont = await doc.embedFont(StandardFonts.Courier);
357
+ const titleFont = await doc.embedFont(StandardFonts.Helvetica);
358
+ const cellWidth = (PAGE_WIDTH - 2 * MARGIN) / COLS;
359
+ const cellHeight = (PAGE_HEIGHT - 2 * MARGIN) / ROWS;
360
+ let page;
361
+ let onPage = 0;
362
+ for (const item of items) {
363
+ if (!page || onPage === PER_PAGE) {
364
+ page = doc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
365
+ onPage = 0;
366
+ }
367
+ const col = onPage % COLS;
368
+ const row = Math.floor(onPage / COLS);
369
+ const cellX = MARGIN + col * cellWidth;
370
+ const cellTop = PAGE_HEIGHT - MARGIN - row * cellHeight;
371
+ const qrBuffer = await QRCode.toBuffer(item.uri, { width: 256, margin: 1 });
372
+ const qrImage = await doc.embedPng(qrBuffer);
373
+ drawCard(page, qrImage, item.code, title, monoFont, titleFont, cellX, cellTop, cellWidth);
374
+ onPage += 1;
375
+ }
376
+ const bytes = await doc.save();
377
+ writeFileSync2(path, bytes);
378
+ }
379
+
380
+ // src/commands/campaign-codes.ts
381
+ var MAX_PAGES = 1e3;
382
+ var CSV_COLUMNS = ["code", "status", "claim_uri", "fallback_url"];
383
+ async function loadAllCodes(params) {
384
+ const { api, token, campaignId } = params;
385
+ const first = params.firstPage ?? (await apiRequest({
386
+ api,
387
+ token,
388
+ method: "GET",
389
+ path: `/api/admin/campaign/${campaignId}?page=1&limit=200`
390
+ })).body;
391
+ const dedup = /* @__PURE__ */ new Map();
392
+ for (const c of first.codes) dedup.set(c.code, c);
393
+ const totalPages = Number.isFinite(first.pagination.pages) ? Math.min(first.pagination.pages, MAX_PAGES) : 1;
394
+ for (let p = 2; p <= totalPages; p++) {
395
+ const res = await apiRequest({
396
+ api,
397
+ token,
398
+ method: "GET",
399
+ path: `/api/admin/campaign/${campaignId}?page=${p}&limit=200`
400
+ });
401
+ for (const c of res.body.codes) dedup.set(c.code, c);
402
+ }
403
+ return { campaign: first.campaign, codes: [...dedup.values()] };
404
+ }
405
+ function buildExportItems(rows, fallback) {
406
+ return rows.map((r) => ({ code: r.code, uri: fallback ? r.fallback_url : r.claim_uri }));
407
+ }
408
+ async function campaignCodes(id, opts) {
409
+ const token = requireToken();
410
+ const api = resolveApi(opts.api);
411
+ const { campaign, codes } = await loadAllCodes({ api, token, campaignId: id });
412
+ const isShared = campaign.code_mode === "shared";
413
+ const filtered = opts.all || isShared ? codes : codes.filter((c) => c.status === "unclaimed");
414
+ const items = filtered.map((c) => {
415
+ const split = splitFullCode(c.code);
416
+ const shortCode = split?.shortCode ?? c.code;
417
+ const codePrefix = split?.prefix ?? campaign.code_prefix;
418
+ return {
419
+ code: c.code,
420
+ status: c.status,
421
+ claim_uri: buildClaimUri(api, codePrefix, shortCode),
422
+ fallback_url: buildFallbackUri(api, c.code)
423
+ };
424
+ });
425
+ const hasOutputs = Boolean(opts.csv || opts.qrDir || opts.pdf);
426
+ if (!hasOutputs) {
427
+ if (opts.json) {
428
+ print({ campaign: { id: campaign.id, name: campaign.name, codePrefix: campaign.code_prefix }, codes: items }, { json: true });
429
+ } else {
430
+ print(table(items.map((it) => ({ code: it.code, status: it.status, claim_uri: it.claim_uri }))), { json: false });
431
+ }
432
+ return;
433
+ }
434
+ const exportItems = buildExportItems(items, Boolean(opts.fallback));
435
+ const result = { count: items.length };
436
+ if (opts.csv) {
437
+ writeCsv(opts.csv, items.map((it) => ({ code: it.code, status: it.status, claim_uri: it.claim_uri, fallback_url: it.fallback_url })), CSV_COLUMNS);
438
+ result.csv = opts.csv;
439
+ }
440
+ if (opts.qrDir) {
441
+ await writeQrImages(opts.qrDir, exportItems);
442
+ result.qrDir = opts.qrDir;
443
+ }
444
+ if (opts.pdf) {
445
+ await writePdf(opts.pdf, exportItems, campaign.name);
446
+ result.pdf = opts.pdf;
447
+ }
448
+ if (opts.json) {
449
+ print(result, { json: true });
450
+ return;
451
+ }
452
+ const lines = [];
453
+ if (result.csv) lines.push(`Wrote ${items.length} codes to ${result.csv}`);
454
+ if (result.qrDir) lines.push(`Wrote ${items.length} QR images to ${result.qrDir}`);
455
+ if (result.pdf) lines.push(`Wrote ${items.length} codes to ${result.pdf}`);
456
+ print(lines.join("\n"), { json: false });
457
+ }
458
+
459
+ // src/commands/campaign.ts
460
+ var PREFIX_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
461
+ var TOKEN_ARG = /^([a-fA-F0-9]{56})\.([a-fA-F0-9]*):([0-9]+)$/;
462
+ var DEFAULT_POLL_MS = 1e4;
463
+ var DEFAULT_POLL_TIMEOUT_MS = 9e5;
464
+ var DEFAULT_END_WAIT_MS = 2e4;
465
+ var DEFAULT_END_WAIT_TIMEOUT_MS = 9e5;
466
+ function hashToken(token) {
467
+ return createHash("sha256").update(token).digest("hex").slice(0, 12);
468
+ }
469
+ function pendingPath() {
470
+ return join3(configDir(), "pending-create.json");
471
+ }
472
+ function readPendingEntry() {
473
+ try {
474
+ const parsed = JSON.parse(readFileSync2(pendingPath(), "utf8"));
475
+ if (parsed && typeof parsed === "object" && typeof parsed.key === "string" && typeof parsed.api === "string" && typeof parsed.tokenHash === "string" && parsed.body && typeof parsed.body === "object" && parsed.body.network === "preprod") {
476
+ return parsed;
477
+ }
478
+ return void 0;
479
+ } catch {
480
+ return void 0;
481
+ }
482
+ }
483
+ function writePendingEntry(entry) {
484
+ if (!existsSync2(configDir())) mkdirSync3(configDir(), { recursive: true, mode: 448 });
485
+ chmodSync2(configDir(), 448);
486
+ writeFileSync3(pendingPath(), JSON.stringify(entry, null, 2) + "\n", { mode: 384 });
487
+ chmodSync2(pendingPath(), 384);
488
+ }
489
+ function deletePendingEntry() {
490
+ try {
491
+ rmSync(pendingPath());
492
+ } catch {
493
+ }
494
+ }
495
+ function derivePrefix(name) {
496
+ const cleaned = name.replace(/[^a-zA-Z0-9]/g, "").toUpperCase().slice(0, 8);
497
+ const base = cleaned || "CP";
498
+ let suffix = "";
499
+ for (let i = 0; i < 2; i++) suffix += PREFIX_CHARS[randomInt(PREFIX_CHARS.length)];
500
+ return base + suffix;
501
+ }
502
+ function parseTokenArg(raw) {
503
+ const match = TOKEN_ARG.exec(raw);
504
+ if (!match) {
505
+ throw new UsageError(`Invalid --token value "${raw}", expected <policyId 56 hex>.<assetNameHex>:<quantity digits>`);
506
+ }
507
+ const [, policyId, assetNameHex, quantity] = match;
508
+ return { unit: `${policyId}.${assetNameHex}`.toLowerCase(), quantity };
509
+ }
510
+ function buildRequestBody(opts, name, claims, prefix) {
511
+ const body = {
512
+ name,
513
+ codePrefix: prefix,
514
+ codeCount: claims,
515
+ network: "preprod"
516
+ };
517
+ if (opts.ada !== void 0) body.adaPerClaim = Math.round(opts.ada * 1e6);
518
+ if (opts.token && opts.token.length > 0) body.tokenBundle = opts.token.map(parseTokenArg);
519
+ if (opts.shared) body.codeMode = "shared";
520
+ if (opts.expires) body.expiresAt = opts.expires;
521
+ if (opts.description) body.description = opts.description;
522
+ return body;
523
+ }
524
+ function isDefinitiveRejection(status, body) {
525
+ if (status === 400 || status === 401 || status === 403 || status === 404 || status === 422) return true;
526
+ if (status === 409) {
527
+ const record = body;
528
+ if (record?.campaign?.status === "creation_failed") return true;
529
+ if (typeof record?.error === "string" && record.error.includes("creation_failed")) return true;
530
+ }
531
+ return false;
532
+ }
533
+ function formatLovelace(lovelace) {
534
+ return (lovelace / 1e6).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
535
+ }
536
+ function pendingMismatchMessage(pending, api, tokenHash) {
537
+ const reasons = [];
538
+ if (pending.api !== api) reasons.push(`the pending attempt targets ${pending.api}, this run targets ${api}`);
539
+ if (pending.tokenHash !== tokenHash) reasons.push("the pending attempt used a different API key");
540
+ return `A pending campaign creation exists, but ${reasons.join(" and ")}. Run with --fresh to start a new one.`;
541
+ }
542
+ async function pollUntilActive(params) {
543
+ const { api, token, campaignId, pollMs, deadline } = params;
544
+ for (; ; ) {
545
+ const res = await apiRequest({
546
+ api,
547
+ token,
548
+ method: "GET",
549
+ path: `/api/admin/campaign/${campaignId}?page=1&limit=200`
550
+ });
551
+ const page1 = res.body;
552
+ if (page1.campaign.status === "active") return page1;
553
+ if (page1.campaign.status === "creation_failed") {
554
+ deletePendingEntry();
555
+ throw new Error(`Campaign ${campaignId} failed during creation. Check the dashboard or start a new campaign with --fresh.`);
556
+ }
557
+ if (Date.now() >= deadline) {
558
+ throw new Error(
559
+ `Campaign ${campaignId} is still settling. It stays pending, run "claimpaign campaign create" again to resume it, or use --fresh to start a new campaign instead.`
560
+ );
561
+ }
562
+ await sleep(pollMs);
563
+ }
564
+ }
565
+ async function exportCodes(params) {
566
+ const { api, token, campaignId, page1, outDir } = params;
567
+ const { campaign, codes } = await loadAllCodes({ api, token, campaignId, firstPage: page1 });
568
+ const prefix = campaign.code_prefix;
569
+ const rows = codes.map((c) => {
570
+ const split = splitFullCode(c.code);
571
+ const shortCode = split?.shortCode ?? c.code;
572
+ const codePrefix = split?.prefix ?? prefix;
573
+ return { code: c.code, status: "unclaimed", claim_uri: buildClaimUri(api, codePrefix, shortCode), fallback_url: buildFallbackUri(api, c.code) };
574
+ });
575
+ mkdirSync3(outDir, { recursive: true });
576
+ const csvPath = join3(outDir, `${prefix}-codes.csv`);
577
+ writeCsv(csvPath, rows, CSV_COLUMNS);
578
+ return csvPath;
579
+ }
580
+ async function campaignCreate(opts) {
581
+ const token = requireToken();
582
+ const api = resolveApi(opts.api);
583
+ const tokenHash = hashToken(token);
584
+ const pollMs = opts.pollMs ?? DEFAULT_POLL_MS;
585
+ const pollTimeoutMs = opts.pollTimeoutMs ?? DEFAULT_POLL_TIMEOUT_MS;
586
+ let pending = readPendingEntry();
587
+ if (opts.fresh && pending) {
588
+ deletePendingEntry();
589
+ pending = void 0;
590
+ }
591
+ let key;
592
+ let body;
593
+ if (pending) {
594
+ if (pending.api !== api || pending.tokenHash !== tokenHash) {
595
+ throw new UsageError(pendingMismatchMessage(pending, api, tokenHash));
596
+ }
597
+ key = pending.key;
598
+ body = pending.body;
599
+ const ageHours = Math.floor((Date.now() - new Date(pending.createdAt).getTime()) / 36e5);
600
+ process.stderr.write(`Resuming the previous creation from ${pending.createdAt} (key ${pending.key.slice(0, 8)}...)
601
+ `);
602
+ if (ageHours >= 24) process.stderr.write(`This attempt is ${ageHours} hours old.
603
+ `);
604
+ } else {
605
+ const { name, claims } = opts;
606
+ if (!name || claims === void 0) throw new UsageError("--name and --claims are required to create a new campaign");
607
+ if (!Number.isInteger(claims) || claims <= 0) throw new UsageError("--claims must be a positive integer");
608
+ if (opts.ada !== void 0 && (!Number.isFinite(opts.ada) || opts.ada < 0)) throw new UsageError("--ada must be a non negative number");
609
+ const prefix = opts.prefix || derivePrefix(name);
610
+ body = buildRequestBody(opts, name, claims, prefix);
611
+ key = randomUUID();
612
+ writePendingEntry({ key, api, tokenHash, body, createdAt: (/* @__PURE__ */ new Date()).toISOString() });
613
+ }
614
+ let createBody;
615
+ try {
616
+ const res = await apiRequest({
617
+ api,
618
+ token,
619
+ method: "POST",
620
+ path: "/api/admin/campaign/create",
621
+ body,
622
+ headers: { "Idempotency-Key": key }
623
+ });
624
+ createBody = res.body;
625
+ } catch (err) {
626
+ if (err instanceof ApiError && isDefinitiveRejection(err.status, err.body)) deletePendingEntry();
627
+ throw err;
628
+ }
629
+ const campaignId = createBody.campaign.id;
630
+ const pricing = createBody.pricing;
631
+ if (createBody.campaign.status === "creating") process.stderr.write("Funding is settling.\n");
632
+ const page1 = await pollUntilActive({ api, token, campaignId, pollMs, deadline: Date.now() + pollTimeoutMs });
633
+ deletePendingEntry();
634
+ let codesFile;
635
+ let exportError;
636
+ try {
637
+ codesFile = await exportCodes({ api, token, campaignId, page1, outDir: opts.out || process.cwd() });
638
+ } catch (err) {
639
+ exportError = `Could not export codes for campaign ${campaignId}: ${err.message}. Run: claimpaign campaign codes ${campaignId}`;
640
+ }
641
+ const result = {
642
+ campaign: {
643
+ id: campaignId,
644
+ status: page1.campaign.status,
645
+ codePrefix: page1.campaign.code_prefix,
646
+ totalCodes: page1.campaign.total_codes
647
+ },
648
+ ...pricing ? { pricing } : {},
649
+ ...codesFile ? { codesFile } : {},
650
+ ...exportError ? { exportError } : {}
651
+ };
652
+ if (opts.json) {
653
+ print(result, { json: true });
654
+ } else {
655
+ const lines = [`Campaign ${result.campaign.id} is active.`, `Prefix: ${result.campaign.codePrefix}`];
656
+ if (page1.campaign.code_mode === "shared") lines.push(`Claim capacity: ${result.campaign.totalCodes} (one shared code)`);
657
+ else lines.push(`Codes: ${result.campaign.totalCodes}`);
658
+ lines.push(`Cost: ${pricing ? `${formatLovelace(pricing.totalCost)} tADA` : "see claimpaign campaign status"}`);
659
+ if (codesFile) {
660
+ lines.push(`Codes exported to ${codesFile}`);
661
+ if (page1.campaign.code_mode === "shared") lines.push("Anyone with this code can claim it once per wallet.");
662
+ } else if (exportError) {
663
+ lines.push("Codes could not be exported, see the error below.");
664
+ }
665
+ print(lines.join("\n"), { json: false });
666
+ }
667
+ if (result.exportError) throw new Error(result.exportError);
668
+ return result;
669
+ }
670
+ async function campaignList(opts) {
671
+ const token = requireToken();
672
+ const api = resolveApi(opts.api);
673
+ const campaigns = [];
674
+ let page = 1;
675
+ for (; ; ) {
676
+ const { body } = await apiRequest({
677
+ api,
678
+ token,
679
+ method: "GET",
680
+ path: `/api/admin/campaigns?limit=100&page=${page}`
681
+ });
682
+ campaigns.push(...body.campaigns);
683
+ if (!Number.isFinite(body.pages) || page >= body.pages || page >= MAX_PAGES) break;
684
+ page += 1;
685
+ }
686
+ if (opts.json) {
687
+ print({ campaigns }, { json: true });
688
+ return;
689
+ }
690
+ const rows = campaigns.map((c) => ({
691
+ id: c.id,
692
+ name: c.name,
693
+ status: c.status,
694
+ "claimed/capacity": `${c.codes_claimed}/${c.total_codes}`,
695
+ prefix: c.code_prefix,
696
+ created: c.created_at
697
+ }));
698
+ print(table(rows), { json: false });
699
+ }
700
+ async function campaignStatus(id, opts) {
701
+ const token = requireToken();
702
+ const api = resolveApi(opts.api);
703
+ const { body } = await apiRequest({
704
+ api,
705
+ token,
706
+ method: "GET",
707
+ path: `/api/admin/campaign/${id}?page=1&limit=200`
708
+ });
709
+ if (opts.json) {
710
+ print(body, { json: true });
711
+ return;
712
+ }
713
+ const c = body.campaign;
714
+ const lines = [
715
+ `Campaign: ${c.id}`,
716
+ `Name: ${c.name}`,
717
+ `Status: ${c.status}`,
718
+ `Prefix: ${c.code_prefix}`,
719
+ `Mode: ${c.code_mode}`,
720
+ `Progress: ${c.codes_claimed}/${c.total_codes}`,
721
+ `Queue pending: ${body.queue.pending}`,
722
+ `Created: ${c.created_at}`
723
+ ];
724
+ print(lines.join("\n"), { json: false });
725
+ }
726
+ function errorText(body) {
727
+ if (body && typeof body === "object" && typeof body.error === "string") {
728
+ return body.error;
729
+ }
730
+ return "";
731
+ }
732
+ async function campaignEnd(id, opts) {
733
+ const token = requireToken();
734
+ const api = resolveApi(opts.api);
735
+ const waitMs = opts.waitMs ?? DEFAULT_END_WAIT_MS;
736
+ const waitTimeoutMs = opts.waitTimeoutMs ?? DEFAULT_END_WAIT_TIMEOUT_MS;
737
+ const deadline = Date.now() + waitTimeoutMs;
738
+ for (; ; ) {
739
+ const res = await apiRequest({
740
+ api,
741
+ token,
742
+ method: "PATCH",
743
+ path: `/api/admin/campaign/${id}`,
744
+ body: { status: "ended" },
745
+ allow: [409]
746
+ });
747
+ if (res.status === 200) {
748
+ if (opts.json) print(res.body, { json: true });
749
+ else print(`Campaign ${id} ended, refunded ${formatLovelace(res.body.refunded ?? 0)} tADA`, { json: false });
750
+ return;
751
+ }
752
+ const message = errorText(res.body);
753
+ if (!message.includes("closing")) throw new ApiError(409, message || "HTTP 409", res.body);
754
+ if (!opts.wait) throw new Error("Payouts are still settling, run again with --wait");
755
+ if (Date.now() >= deadline) {
756
+ throw new Error(`Campaign ${id} payouts are still settling after ${Math.round(waitTimeoutMs / 6e4)} minutes. Run again to keep waiting.`);
757
+ }
758
+ process.stderr.write("Payouts are still settling, retrying...\n");
759
+ await sleep(waitMs);
760
+ }
761
+ }
762
+ async function setCampaignStatus(id, status, opts, verb) {
763
+ const token = requireToken();
764
+ const api = resolveApi(opts.api);
765
+ const { body } = await apiRequest({
766
+ api,
767
+ token,
768
+ method: "PATCH",
769
+ path: `/api/admin/campaign/${id}`,
770
+ body: { status }
771
+ });
772
+ if (opts.json) print(body, { json: true });
773
+ else print(`Campaign ${id} ${verb}`, { json: false });
774
+ }
775
+ async function campaignPause(id, opts) {
776
+ await setCampaignStatus(id, "paused", opts, "paused");
777
+ }
778
+ async function campaignResume(id, opts) {
779
+ await setCampaignStatus(id, "active", opts, "resumed");
780
+ }
781
+
782
+ // src/commands/claim.ts
783
+ var STATUS_MESSAGES = {
784
+ notfound: "Unknown code",
785
+ alreadyclaimed: "This code was already claimed",
786
+ expired: "This campaign has expired",
787
+ ratelimited: "Too many attempts from this network, wait 15 minutes",
788
+ soldout: "All claims of this campaign are used up",
789
+ walletlimitreached: "This wallet reached the claim limit",
790
+ nostakekey: "Use a base address with a staking part",
791
+ invalidaddress: "The address was not accepted",
792
+ notclaimable: "This campaign is not accepting claims right now",
793
+ maintenance: "The faucet is in maintenance",
794
+ invalidrequest: "The faucet rejected the request",
795
+ missingcode: "The faucet rejected the request",
796
+ error: "The faucet reported an error"
797
+ };
798
+ function resolveClaimTarget(input, faucetOpt, api) {
799
+ if (input.startsWith("web+cardano:")) {
800
+ const parsed = parseClaimUri(input);
801
+ if (!parsed) throw new UsageError("Not a valid CIP-99 claim URI");
802
+ return parsed;
803
+ }
804
+ if (faucetOpt) {
805
+ return { faucetUrl: faucetOpt, code: input };
806
+ }
807
+ const split = splitFullCode(input);
808
+ if (!split) throw new UsageError("This does not look like a Claimpaign code (expected PREFIX_code)");
809
+ const shortCode = normalizeShortCode(split.shortCode);
810
+ if (!shortCode) throw new UsageError("This does not look like a Claimpaign code");
811
+ return { faucetUrl: `${api}/api/claim/${split.prefix.toUpperCase()}`, code: shortCode };
812
+ }
813
+ function formatAccepted(body) {
814
+ const ada = Number(body.lovelaces ?? 0) / 1e6;
815
+ const parts = [`Accepted: ${formatAda(ada)} tADA`];
816
+ if (body.tokens && Object.keys(body.tokens).length > 0) {
817
+ const tokenList = Object.entries(body.tokens).map(([unit, qty]) => `${unit}:${qty}`).join(", ");
818
+ parts.push(`tokens ${tokenList}`);
819
+ }
820
+ if (typeof body.queue_position === "number") {
821
+ parts.push(`queue position ${body.queue_position}`);
822
+ }
823
+ return parts.join(", ");
824
+ }
825
+ async function claim(input, address, opts) {
826
+ const api = resolveApi(opts.api);
827
+ const { faucetUrl, code } = resolveClaimTarget(input, opts.faucet, api);
828
+ if (!address.startsWith("addr_test")) {
829
+ throw new UsageError("This tool claims on the Cardano preprod testnet only, mainnet addresses (addr1...) are not accepted.");
830
+ }
831
+ const url = new URL(faucetUrl);
832
+ const { status, body: rawBody } = await apiRequest({
833
+ api: url.origin,
834
+ method: "POST",
835
+ path: url.pathname + url.search,
836
+ body: { code, address },
837
+ allow: [400, 401, 403, 404, 409, 410, 422, 429, 500, 503]
838
+ });
839
+ if (!rawBody || typeof rawBody !== "object") {
840
+ throw new Error(`The faucet answered with an unexpected response (HTTP ${status})`);
841
+ }
842
+ const body = rawBody;
843
+ if (body.status === "accepted") {
844
+ if (opts.json) {
845
+ print(body, { json: true });
846
+ return;
847
+ }
848
+ print(formatAccepted(body), { json: false });
849
+ return;
850
+ }
851
+ if (opts.json) print(body, { json: true });
852
+ const base = STATUS_MESSAGES[body.status] ?? `The faucet answered with status ${body.status}`;
853
+ throw new Error(body.message ? `${base} (${body.message})` : base);
854
+ }
855
+
856
+ // src/cli.ts
857
+ var { version } = createRequire(import.meta.url)("../package.json");
858
+ function buildProgram() {
859
+ const program = new Command("claimpaign").description("Claimpaign sandbox campaigns and CIP-99 claims from the terminal").version(version).option("--api <url>", "API base URL (default https://claimpaign.com, or CLAIMPAIGN_API)").option("--json", "machine readable output", false).exitOverride();
860
+ program.command("login").description("Store a sandbox API key").action(async () => {
861
+ const opts = program.opts();
862
+ await login({ api: opts.api, json: opts.json });
863
+ });
864
+ program.command("logout").description("Remove the stored sandbox API key").action(async () => {
865
+ await logout();
866
+ if (!program.opts().json) process.stdout.write("Logged out.\n");
867
+ });
868
+ program.command("balance").description("Show the sandbox credit balance").action(async () => {
869
+ const opts = program.opts();
870
+ await balance({ api: opts.api, json: opts.json });
871
+ });
872
+ program.command("deposit").description("Show the organization wallet address and how to add credits").action(async () => {
873
+ const opts = program.opts();
874
+ await deposit({ api: opts.api, json: opts.json });
875
+ });
876
+ const campaign = program.command("campaign").description("Manage sandbox campaigns");
877
+ campaign.command("create").description("Create a sandbox campaign and export its codes").option("--name <text>", "campaign name, required to start a new campaign, not needed to resume a pending one").option("--claims <n>", "number of claim codes, required to start a new campaign, not needed to resume a pending one").option("--ada <tADA>", "ada per claim, in tADA").option("--token <policy.assethex:qty>", "token bundle item, repeatable", (value, previous) => [...previous, value], []).option("--shared", "one shared code for every claim", false).option("--prefix <PREFIX>", "claim code prefix, derived from the name when omitted").option("--expires <ISO>", "expiry timestamp").option("--description <text>", "campaign description").option("--out <dir>", "directory for the exported codes CSV (default the current directory)").option("--fresh", "discard a pending creation attempt and start a new one", false).action(async (cmdOpts) => {
878
+ const opts = program.opts();
879
+ await campaignCreate({
880
+ api: opts.api,
881
+ json: opts.json,
882
+ name: cmdOpts.name,
883
+ claims: cmdOpts.claims !== void 0 ? Number(cmdOpts.claims) : void 0,
884
+ ada: cmdOpts.ada !== void 0 ? Number(cmdOpts.ada) : void 0,
885
+ token: cmdOpts.token,
886
+ shared: cmdOpts.shared,
887
+ prefix: cmdOpts.prefix,
888
+ expires: cmdOpts.expires,
889
+ description: cmdOpts.description,
890
+ out: cmdOpts.out,
891
+ fresh: cmdOpts.fresh
892
+ });
893
+ });
894
+ campaign.command("list").description("List sandbox campaigns").action(async () => {
895
+ const opts = program.opts();
896
+ await campaignList({ api: opts.api, json: opts.json });
897
+ });
898
+ campaign.command("status <id>").description("Show a sandbox campaign's status, progress and claim queue").action(async (id) => {
899
+ const opts = program.opts();
900
+ await campaignStatus(id, { api: opts.api, json: opts.json });
901
+ });
902
+ campaign.command("codes <id>").description("Export a campaign's codes as CSV, QR images and/or a print-ready PDF").option("--csv <file>", "write a CSV file").option("--qr-dir <dir>", "write one QR PNG per code into this directory").option("--pdf <file>", "write a print-ready PDF with one card per code").option("--fallback", "use the HTTPS fallback URL instead of the wallet deep link for QR and PDF", false).option("--all", "include already claimed codes", false).action(async (id, cmdOpts) => {
903
+ const opts = program.opts();
904
+ await campaignCodes(id, {
905
+ api: opts.api,
906
+ json: opts.json,
907
+ csv: cmdOpts.csv,
908
+ qrDir: cmdOpts.qrDir,
909
+ pdf: cmdOpts.pdf,
910
+ fallback: cmdOpts.fallback,
911
+ all: cmdOpts.all
912
+ });
913
+ });
914
+ campaign.command("end <id>").description("End a sandbox campaign and refund unclaimed credits").option("--wait", "keep retrying while payouts are settling", false).action(async (id, cmdOpts) => {
915
+ const opts = program.opts();
916
+ await campaignEnd(id, { api: opts.api, json: opts.json, wait: cmdOpts.wait });
917
+ });
918
+ campaign.command("pause <id>").description("Pause a sandbox campaign").action(async (id) => {
919
+ const opts = program.opts();
920
+ await campaignPause(id, { api: opts.api, json: opts.json });
921
+ });
922
+ campaign.command("resume <id>").description("Resume a paused sandbox campaign").action(async (id) => {
923
+ const opts = program.opts();
924
+ await campaignResume(id, { api: opts.api, json: opts.json });
925
+ });
926
+ program.command("claim <uri-or-code> <address>").description("Claim a CIP-99 code on the Cardano preprod testnet").option("--faucet <url>", "post a bare code to this faucet url instead of deriving one from --api").action(async (input, address, cmdOpts) => {
927
+ const opts = program.opts();
928
+ await claim(input, address, { api: opts.api, json: opts.json, faucet: cmdOpts.faucet });
929
+ });
930
+ return program;
931
+ }
932
+ async function run(argv) {
933
+ try {
934
+ await buildProgram().parseAsync(argv);
935
+ return 0;
936
+ } catch (err) {
937
+ if (err instanceof CommanderError) {
938
+ if (err.code === "commander.helpDisplayed" || err.code === "commander.version" || err.code === "commander.help") return 0;
939
+ return 2;
940
+ }
941
+ if (err instanceof CancelledError) {
942
+ process.stderr.write("Cancelled\n");
943
+ return 130;
944
+ }
945
+ process.stderr.write(`Error: ${err?.message ?? String(err)}
946
+ `);
947
+ return err instanceof UsageError ? 2 : 1;
948
+ }
949
+ }
950
+
951
+ // src/bin.ts
952
+ process.exitCode = await run(process.argv);
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "claimpaign",
3
+ "version": "0.1.0",
4
+ "description": "Command line tool for Claimpaign sandbox campaigns and CIP-99 claims",
5
+ "type": "module",
6
+ "bin": {
7
+ "claimpaign": "dist/bin.js"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "README.md",
12
+ "LICENSE"
13
+ ],
14
+ "engines": {
15
+ "node": ">=20"
16
+ },
17
+ "scripts": {
18
+ "build": "tsup",
19
+ "dev": "tsx src/bin.ts",
20
+ "test": "vitest run",
21
+ "typecheck": "tsc --noEmit",
22
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/Lichtstaub/claimpaign-cli.git"
27
+ },
28
+ "license": "Apache-2.0",
29
+ "dependencies": {
30
+ "commander": "^13.1.0",
31
+ "pdf-lib": "^1.17.1",
32
+ "qrcode": "^1.5.4"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^22.20.4",
36
+ "@types/qrcode": "^1.5.6",
37
+ "tsup": "^8.5.1",
38
+ "tsx": "^4.23.15",
39
+ "typescript": "^5.9.3",
40
+ "vitest": "^3.2.7"
41
+ }
42
+ }