@swarm-tips/client 0.2.12 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +59 -18
  2. package/SBOM.spdx.json +5 -5
  3. package/dist/agent.d.ts +176 -0
  4. package/dist/agent.js +561 -0
  5. package/dist/auth/token-manager.d.ts +33 -0
  6. package/dist/auth/token-manager.js +175 -0
  7. package/dist/cli/keyfile.d.ts +24 -0
  8. package/dist/cli/keyfile.js +97 -0
  9. package/dist/cli/swarm.d.ts +14 -0
  10. package/dist/cli/swarm.js +516 -0
  11. package/dist/contracts/generated/shillbot.d.ts +9 -3
  12. package/dist/contracts/idl/shillbot.json +9 -3
  13. package/dist/coordination-game/api.d.ts +4 -4
  14. package/dist/coordination-game/api.js +8 -8
  15. package/dist/errors.d.ts +1 -1
  16. package/dist/generated/openapi.d.ts +1963 -0
  17. package/dist/generated/openapi.js +8 -0
  18. package/dist/http.d.ts +6 -3
  19. package/dist/http.js +18 -4
  20. package/dist/inbox/client.d.ts +16 -1
  21. package/dist/inbox/client.js +48 -2
  22. package/dist/inbox/index.d.ts +1 -1
  23. package/dist/index.d.ts +7 -2
  24. package/dist/index.js +7 -2
  25. package/dist/shillbot/api.d.ts +49 -2
  26. package/dist/shillbot/api.js +377 -33
  27. package/dist/signer/evm.d.ts +25 -0
  28. package/dist/signer/evm.js +249 -0
  29. package/dist/signer/index.d.ts +3 -0
  30. package/dist/signer/index.js +3 -0
  31. package/dist/signer/solana.d.ts +24 -0
  32. package/dist/signer/solana.js +183 -0
  33. package/dist/signer/types.d.ts +30 -0
  34. package/dist/signer/types.js +31 -0
  35. package/dist/swarm/index.d.ts +1 -0
  36. package/dist/swarm/index.js +9 -2
  37. package/dist/version.d.ts +1 -0
  38. package/dist/version.js +1 -0
  39. package/dist/vow/decoders/shillbot.d.ts +1 -0
  40. package/dist/vow/decoders/shillbot.js +2 -0
  41. package/dist/vow/types.d.ts +1 -0
  42. package/dist/vow/verify.d.ts +3 -2
  43. package/dist/vow/verify.js +8 -3
  44. package/package.json +5 -3
@@ -0,0 +1,516 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, realpathSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import { SwarmAgent } from "../agent.js";
5
+ import { SwarmClientError } from "../errors.js";
6
+ import { validatePreparedTransaction } from "../shillbot/api.js";
7
+ import { inspectTransaction } from "../shillbot/index.js";
8
+ import { CLIENT_VERSION } from "../version.js";
9
+ import { CliUsageError, assertNoSecretCliFlags, loadSignerFromCliOrEnv, } from "./keyfile.js";
10
+ const BOOLEAN_FLAGS = new Set([
11
+ "--json",
12
+ "--yes",
13
+ "--help",
14
+ "-h",
15
+ "--version",
16
+ "-v",
17
+ "--no-exec",
18
+ "--unmute",
19
+ "--cursor",
20
+ ]);
21
+ function parseCliArgs(argv) {
22
+ assertNoSecretCliFlags(argv);
23
+ const positionals = [];
24
+ const flags = new Map();
25
+ for (let i = 0; i < argv.length; i += 1) {
26
+ const token = argv[i];
27
+ if (!token.startsWith("-") || token === "-") {
28
+ positionals.push(token);
29
+ continue;
30
+ }
31
+ const eqIndex = token.indexOf("=");
32
+ if (eqIndex !== -1) {
33
+ const key = token.slice(0, eqIndex);
34
+ const val = token.slice(eqIndex + 1);
35
+ flags.set(key, val);
36
+ continue;
37
+ }
38
+ if (BOOLEAN_FLAGS.has(token)) {
39
+ flags.set(token, true);
40
+ continue;
41
+ }
42
+ const next = argv[i + 1];
43
+ if (next === undefined || (next.startsWith("--") && next.length > 2)) {
44
+ throw new CliUsageError(`Flag ${token} requires a value.`);
45
+ }
46
+ flags.set(token, next);
47
+ i += 1;
48
+ }
49
+ return { positionals, flags };
50
+ }
51
+ function getStringFlag(flags, name) {
52
+ const val = flags.get(name);
53
+ return typeof val === "string" ? val : undefined;
54
+ }
55
+ function getIntFlag(flags, name) {
56
+ const raw = getStringFlag(flags, name);
57
+ if (raw === undefined)
58
+ return undefined;
59
+ if (!/^\d+$/.test(raw.trim())) {
60
+ throw new CliUsageError(`Invalid integer for ${name}: ${raw}`);
61
+ }
62
+ return Number(raw.trim());
63
+ }
64
+ function getBigIntFlag(flags, name) {
65
+ const raw = getStringFlag(flags, name);
66
+ if (raw === undefined)
67
+ return undefined;
68
+ if (!/^\d+$/.test(raw.trim())) {
69
+ throw new CliUsageError(`Invalid non-negative integer for ${name}: ${raw}`);
70
+ }
71
+ return BigInt(raw.trim());
72
+ }
73
+ async function readStdinText(io) {
74
+ if (io?.stdin) {
75
+ return (await io.stdin()).trim();
76
+ }
77
+ if (process.stdin.isTTY) {
78
+ return "";
79
+ }
80
+ return await new Promise((resolvePromise, rejectPromise) => {
81
+ const chunks = [];
82
+ process.stdin.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
83
+ process.stdin.on("end", () => resolvePromise(Buffer.concat(chunks).toString("utf8").trim()));
84
+ process.stdin.on("error", rejectPromise);
85
+ });
86
+ }
87
+ const HELP_TEXT = `swarm v${CLIENT_VERSION} — Unified non-custodial CLI for Swarm Tips, Shillbot, Inbox & Coordination Game
88
+
89
+ Usage:
90
+ swarm <command> [subcommand] [options]
91
+ npx -y @swarm-tips/client <command> [subcommand] [options]
92
+
93
+ Commands:
94
+ auth whoami | token
95
+ listings [--limit N] [--category CAT] [--chain CHAIN]
96
+ reputation <wallet>
97
+ tasks list [--limit N] | mine | earnings | next <task-json-or-id>
98
+ tasks claim <id> [--no-exec]
99
+ tasks submit <id> --content <str> [--no-exec]
100
+ tasks verify <id> [--no-exec]
101
+ tasks finalize <id> [--no-exec]
102
+ inbox list [--status pending|all] [--limit N]
103
+ inbox open <msg_id...>
104
+ inbox send <to_wallet> <body> [--thread <id>] [--intent <intent>]
105
+ inbox ack <msg_id> [--cursor]
106
+ inbox mute <thread_id> [--unmute]
107
+ topics read <open-challenge|subcontract> [--limit N]
108
+ topics publish <topic> <body> [--ref <id>] [--reply-to <id>] [--intent <intent>]
109
+ tx inspect [--tx <base64>]
110
+ tx verify --action <claim|submit|verify|finalize|approve|create> --wallet <pubkey> [--task-pda <pda>] [--tx <base64>]
111
+ vow-verify <file-or-url> [--rpc <url>]
112
+
113
+ Global Options:
114
+ --json Output structured JSON (auto-enabled when stdout is non-TTY)
115
+ --network <mainnet|devnet> Target network (default: mainnet)
116
+ --keypair-file <path> Solana keypair file (must be chmod 600 on POSIX)
117
+ --rpc-url <url> Override Solana RPC URL
118
+ --max-spend-lamports <n> Max SOL escrow spend cap (default: 0)
119
+ --max-spend-wei <n> Max EVM escrow spend cap (default: 0)
120
+ --help, -h Show this help text
121
+ --version, -v Print CLI version
122
+
123
+ Environment Variables:
124
+ SWARM_SOLANA_KEYPAIR_PATH Path to chmod 600 Solana keypair JSON/base58 file
125
+ SWARM_SOLANA_SECRET_KEY Base58 or JSON 64-byte Solana secret key
126
+ SWARM_EVM_PRIVATE_KEY 0x-prefixed 32-byte EVM private key
127
+ SWARM_AUTH_TOKEN Pre-minted Bearer JWT
128
+ `;
129
+ const VALID_ACTIONS = new Set([
130
+ "create",
131
+ "claim",
132
+ "submit",
133
+ "approve",
134
+ "verify",
135
+ "finalize",
136
+ ]);
137
+ function writeOutput(stdout, jsonMode, payload) {
138
+ if (jsonMode) {
139
+ stdout.write(`${JSON.stringify(payload)}\n`);
140
+ return;
141
+ }
142
+ stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
143
+ }
144
+ function writeError(stdout, stderr, jsonMode, message, code) {
145
+ if (jsonMode) {
146
+ stdout.write(`${JSON.stringify({ ok: false, ...(code ? { code } : {}), error: message })}\n`);
147
+ }
148
+ else {
149
+ stderr.write(`Error: ${message}\n`);
150
+ }
151
+ }
152
+ export async function runSwarmCli(argv, io = {}) {
153
+ const stdout = io.stdout ?? process.stdout;
154
+ const stderr = io.stderr ?? process.stderr;
155
+ const env = io.env ?? process.env;
156
+ let parsed;
157
+ try {
158
+ parsed = parseCliArgs(argv);
159
+ }
160
+ catch (err) {
161
+ const msg = err instanceof Error ? err.message : String(err);
162
+ stderr.write(`${msg}\n`);
163
+ return err instanceof CliUsageError ? err.exitCode : 2;
164
+ }
165
+ const { positionals, flags } = parsed;
166
+ const jsonMode = Boolean(flags.get("--json")) || stdout.isTTY === false;
167
+ if (flags.get("--version") || flags.get("-v")) {
168
+ if (jsonMode) {
169
+ writeOutput(stdout, true, { version: CLIENT_VERSION });
170
+ }
171
+ else {
172
+ stdout.write(`${CLIENT_VERSION}\n`);
173
+ }
174
+ return 0;
175
+ }
176
+ if (positionals.length === 0 || flags.get("--help") || flags.get("-h")) {
177
+ stdout.write(HELP_TEXT);
178
+ return 0;
179
+ }
180
+ try {
181
+ const rawNetwork = getStringFlag(flags, "--network") ?? env.SWARM_NETWORK ?? "mainnet";
182
+ if (rawNetwork !== "mainnet" && rawNetwork !== "devnet") {
183
+ throw new CliUsageError(`Invalid --network "${rawNetwork}". Expected "mainnet" or "devnet".`);
184
+ }
185
+ const network = rawNetwork;
186
+ const rpcUrl = getStringFlag(flags, "--rpc-url") ?? getStringFlag(flags, "--rpc") ?? env.SWARM_RPC_URL;
187
+ const maxEscrowSpendLamports = getBigIntFlag(flags, "--max-spend-lamports");
188
+ const maxEscrowSpendWei = getBigIntFlag(flags, "--max-spend-wei");
189
+ const [cmd, sub, ...rest] = positionals;
190
+ // Pure offline transaction inspection & C10 verification need no keypair file unless omitted --wallet
191
+ if (cmd === "tx") {
192
+ if (sub === "inspect") {
193
+ const txB64 = getStringFlag(flags, "--tx") ?? rest[0] ?? (await readStdinText(io));
194
+ if (!txB64) {
195
+ throw new CliUsageError("Usage: swarm tx inspect [--tx <base64>] (or pipe base64 via stdin)");
196
+ }
197
+ try {
198
+ const inspection = inspectTransaction(txB64);
199
+ writeOutput(stdout, jsonMode, { ok: true, inspection });
200
+ return 0;
201
+ }
202
+ catch (err) {
203
+ const message = err instanceof Error ? err.message : String(err);
204
+ writeOutput(stdout, jsonMode, { ok: false, error: message });
205
+ return 1;
206
+ }
207
+ }
208
+ if (sub === "verify") {
209
+ const rawAction = getStringFlag(flags, "--action");
210
+ if (!rawAction || !VALID_ACTIONS.has(rawAction)) {
211
+ throw new CliUsageError("Usage: swarm tx verify --action <claim|submit|verify|finalize|approve|create> --wallet <pubkey> [--task-pda <pda>] [--tx <base64>]");
212
+ }
213
+ const wallet = getStringFlag(flags, "--wallet");
214
+ if (!wallet) {
215
+ throw new CliUsageError("Missing required --wallet <pubkey> for `swarm tx verify`.");
216
+ }
217
+ const txB64 = getStringFlag(flags, "--tx") ?? rest[0] ?? (await readStdinText(io));
218
+ if (!txB64) {
219
+ throw new CliUsageError("Missing transaction payload: pass --tx <base64> or pipe via stdin.");
220
+ }
221
+ const taskPda = getStringFlag(flags, "--task-pda");
222
+ const feePayer = getStringFlag(flags, "--fee-payer");
223
+ const escrowLamports = getBigIntFlag(flags, "--escrow-lamports");
224
+ try {
225
+ const inspection = validatePreparedTransaction(txB64, {
226
+ action: rawAction,
227
+ network,
228
+ wallet,
229
+ ...(taskPda ? { taskPda } : {}),
230
+ ...(feePayer ? { feePayer } : {}),
231
+ ...(escrowLamports !== undefined ? { escrowLamports } : {}),
232
+ });
233
+ writeOutput(stdout, jsonMode, { ok: true, inspection });
234
+ return 0;
235
+ }
236
+ catch (err) {
237
+ const message = err instanceof Error ? err.message : String(err);
238
+ writeOutput(stdout, jsonMode, { ok: false, error: message });
239
+ return 1;
240
+ }
241
+ }
242
+ throw new CliUsageError("Usage: swarm tx <inspect|verify> [options]");
243
+ }
244
+ const signer = loadSignerFromCliOrEnv({
245
+ keypairFile: getStringFlag(flags, "--keypair-file"),
246
+ env,
247
+ evmRpcUrl: env.SWARM_EVM_RPC_URL,
248
+ });
249
+ const agent = new SwarmAgent({
250
+ signer,
251
+ token: env.SWARM_AUTH_TOKEN,
252
+ network,
253
+ rpcUrl,
254
+ shillbotUrl: env.SWARM_SHILLBOT_URL,
255
+ gameUrl: env.SWARM_GAME_URL,
256
+ mcpUrl: env.SWARM_MCP_URL,
257
+ maxEscrowSpendLamports,
258
+ maxEscrowSpendWei,
259
+ fetch: io.fetch,
260
+ });
261
+ if (cmd === "auth") {
262
+ if (sub === "whoami") {
263
+ if (!signer && !agent.auth.walletAddress) {
264
+ throw new CliUsageError("No wallet configured. Pass --keypair-file <path> (chmod 600) or set SWARM_SOLANA_KEYPAIR_PATH, SWARM_SOLANA_SECRET_KEY, or SWARM_EVM_PRIVATE_KEY.");
265
+ }
266
+ writeOutput(stdout, jsonMode, {
267
+ wallet: signer?.address ?? agent.auth.walletAddress,
268
+ chain: signer?.chain ?? "unknown",
269
+ network,
270
+ });
271
+ return 0;
272
+ }
273
+ if (sub === "token") {
274
+ const token = (await agent.auth.getToken()) ?? (await agent.auth.authenticate());
275
+ writeOutput(stdout, jsonMode, {
276
+ wallet: agent.auth.walletAddress,
277
+ network,
278
+ token,
279
+ });
280
+ return 0;
281
+ }
282
+ throw new CliUsageError("Usage: swarm auth <whoami|token>");
283
+ }
284
+ if (cmd === "listings") {
285
+ const items = await agent.discovery.listings({
286
+ limit: getIntFlag(flags, "--limit"),
287
+ category: getStringFlag(flags, "--category"),
288
+ chain: getStringFlag(flags, "--chain"),
289
+ });
290
+ writeOutput(stdout, jsonMode, { listings: items, count: items.length });
291
+ return 0;
292
+ }
293
+ if (cmd === "reputation") {
294
+ const targetWallet = sub ?? signer?.address ?? agent.auth.walletAddress;
295
+ if (!targetWallet) {
296
+ throw new CliUsageError("Usage: swarm reputation <wallet>");
297
+ }
298
+ const rep = await agent.discovery.reputation(targetWallet, network);
299
+ writeOutput(stdout, jsonMode, rep);
300
+ return 0;
301
+ }
302
+ if (cmd === "tasks") {
303
+ const noExec = Boolean(flags.get("--no-exec"));
304
+ if (sub === "list") {
305
+ const res = await agent.tasks.listAvailable(getIntFlag(flags, "--limit") ?? 50);
306
+ writeOutput(stdout, jsonMode, res);
307
+ return 0;
308
+ }
309
+ if (sub === "mine") {
310
+ const tasks = await agent.tasks.mine();
311
+ writeOutput(stdout, jsonMode, { tasks });
312
+ return 0;
313
+ }
314
+ if (sub === "earnings") {
315
+ const res = await agent.tasks.earnings();
316
+ writeOutput(stdout, jsonMode, res);
317
+ return 0;
318
+ }
319
+ if (sub === "next") {
320
+ const arg = rest[0] ?? (await readStdinText(io));
321
+ if (!arg) {
322
+ throw new CliUsageError("Usage: swarm tasks next <task-json-or-id>");
323
+ }
324
+ const taskObj = arg.trim().startsWith("{")
325
+ ? JSON.parse(arg)
326
+ : await agent.tasks.get(arg.trim());
327
+ writeOutput(stdout, jsonMode, agent.tasks.nextAction(taskObj));
328
+ return 0;
329
+ }
330
+ if (sub === "claim") {
331
+ const id = rest[0];
332
+ if (!id)
333
+ throw new CliUsageError("Usage: swarm tasks claim <task_id> [--no-exec]");
334
+ const res = noExec ? await agent.tasks.claim(id) : await agent.tasks.claimAndExecute(id);
335
+ writeOutput(stdout, jsonMode, res);
336
+ return 0;
337
+ }
338
+ if (sub === "submit") {
339
+ const id = rest[0];
340
+ const content = getStringFlag(flags, "--content");
341
+ if (!id || !content) {
342
+ throw new CliUsageError("Usage: swarm tasks submit <task_id> --content <str> [--no-exec]");
343
+ }
344
+ const res = noExec
345
+ ? await agent.tasks.submit(id, { content_id: content })
346
+ : await agent.tasks.submitAndExecute(id, content);
347
+ writeOutput(stdout, jsonMode, res);
348
+ return 0;
349
+ }
350
+ if (sub === "verify") {
351
+ const id = rest[0];
352
+ if (!id)
353
+ throw new CliUsageError("Usage: swarm tasks verify <task_id> [--no-exec]");
354
+ const res = noExec
355
+ ? await agent.tasks.buildVerify(id)
356
+ : await agent.tasks.verifyAndExecute(id);
357
+ writeOutput(stdout, jsonMode, res);
358
+ return 0;
359
+ }
360
+ if (sub === "finalize") {
361
+ const id = rest[0];
362
+ if (!id)
363
+ throw new CliUsageError("Usage: swarm tasks finalize <task_id> [--no-exec]");
364
+ const res = noExec
365
+ ? await agent.tasks.buildFinalize(id)
366
+ : await agent.tasks.finalizeAndExecute(id);
367
+ writeOutput(stdout, jsonMode, res);
368
+ return 0;
369
+ }
370
+ throw new CliUsageError("Usage: swarm tasks <list|mine|earnings|next|claim|submit|verify|finalize> ...");
371
+ }
372
+ if (cmd === "inbox") {
373
+ if (sub === "list") {
374
+ const rawStatus = getStringFlag(flags, "--status");
375
+ if (rawStatus && rawStatus !== "pending" && rawStatus !== "all") {
376
+ throw new CliUsageError('Invalid --status: expected "pending" or "all".');
377
+ }
378
+ const res = await agent.inbox.list({
379
+ status: rawStatus ?? "pending",
380
+ limit: getIntFlag(flags, "--limit"),
381
+ });
382
+ writeOutput(stdout, jsonMode, res);
383
+ return 0;
384
+ }
385
+ if (sub === "open") {
386
+ if (rest.length === 0)
387
+ throw new CliUsageError("Usage: swarm inbox open <msg_id...>");
388
+ const res = await agent.inbox.open(rest);
389
+ writeOutput(stdout, jsonMode, res);
390
+ return 0;
391
+ }
392
+ if (sub === "send") {
393
+ const [toWallet, body] = rest;
394
+ if (!toWallet || !body) {
395
+ throw new CliUsageError("Usage: swarm inbox send <to_wallet> <body> [--thread <id>] [--intent <intent>]");
396
+ }
397
+ const res = await agent.inbox.send(toWallet, body, {
398
+ threadId: getStringFlag(flags, "--thread"),
399
+ intent: getStringFlag(flags, "--intent"),
400
+ deliveryKey: getStringFlag(flags, "--delivery-key"),
401
+ });
402
+ writeOutput(stdout, jsonMode, res);
403
+ return 0;
404
+ }
405
+ if (sub === "ack") {
406
+ const target = rest[0];
407
+ if (!target)
408
+ throw new CliUsageError("Usage: swarm inbox ack <msg_id>");
409
+ if (flags.get("--cursor")) {
410
+ await agent.inbox.ack(target);
411
+ writeOutput(stdout, jsonMode, { ok: true, up_to: target });
412
+ }
413
+ else {
414
+ const res = await agent.inbox.ackIds([target]);
415
+ writeOutput(stdout, jsonMode, res);
416
+ }
417
+ return 0;
418
+ }
419
+ if (sub === "mute") {
420
+ const threadId = rest[0];
421
+ if (!threadId)
422
+ throw new CliUsageError("Usage: swarm inbox mute <thread_id> [--unmute]");
423
+ const muted = !flags.get("--unmute");
424
+ const res = await agent.inbox.mute(threadId, muted);
425
+ writeOutput(stdout, jsonMode, res);
426
+ return 0;
427
+ }
428
+ throw new CliUsageError("Usage: swarm inbox <list|open|send|ack|mute> ...");
429
+ }
430
+ if (cmd === "topics") {
431
+ if (sub === "read") {
432
+ const topic = rest[0];
433
+ if (topic !== "open-challenge" && topic !== "subcontract") {
434
+ throw new CliUsageError("Usage: swarm topics read <open-challenge|subcontract>");
435
+ }
436
+ const res = await agent.topics.read(topic, {
437
+ limit: getIntFlag(flags, "--limit"),
438
+ });
439
+ writeOutput(stdout, jsonMode, res);
440
+ return 0;
441
+ }
442
+ if (sub === "publish") {
443
+ const [topic, body] = rest;
444
+ if ((topic !== "open-challenge" && topic !== "subcontract") || !body) {
445
+ throw new CliUsageError("Usage: swarm topics publish <open-challenge|subcontract> <body> [--ref <id>]");
446
+ }
447
+ const res = await agent.topics.publish(topic, body, {
448
+ refId: getStringFlag(flags, "--ref"),
449
+ replyTo: getStringFlag(flags, "--reply-to"),
450
+ intent: getStringFlag(flags, "--intent"),
451
+ });
452
+ writeOutput(stdout, jsonMode, res);
453
+ return 0;
454
+ }
455
+ throw new CliUsageError("Usage: swarm topics <read|publish> ...");
456
+ }
457
+ if (cmd === "vow-verify") {
458
+ const target = sub;
459
+ if (!target) {
460
+ throw new CliUsageError("Usage: swarm vow-verify <file-or-url> [--rpc <url>]");
461
+ }
462
+ let payload;
463
+ if (target === "-") {
464
+ payload = await readStdinText(io);
465
+ }
466
+ else if (/^https?:\/\//i.test(target)) {
467
+ payload = target;
468
+ }
469
+ else {
470
+ try {
471
+ payload = JSON.parse(readFileSync(target, "utf8"));
472
+ }
473
+ catch (err) {
474
+ throw new CliUsageError(`Failed to read VOW JSON file ${target}: ${err instanceof Error ? err.message : String(err)}`);
475
+ }
476
+ }
477
+ const verdict = await agent.tasks.verifyVow(payload, { rpcUrl });
478
+ writeOutput(stdout, jsonMode, verdict);
479
+ return verdict.valid ? 0 : 1;
480
+ }
481
+ throw new CliUsageError(`Unknown command "${cmd}". Run \`swarm --help\` for usage.`);
482
+ }
483
+ catch (err) {
484
+ if (err instanceof CliUsageError) {
485
+ stderr.write(`${err.message}\n`);
486
+ return err.exitCode;
487
+ }
488
+ if (err instanceof SwarmClientError) {
489
+ const exitCode = err.code === "AUTH_REQUIRED" ? 2 : 1;
490
+ writeError(stdout, stderr, jsonMode, err.message, err.code);
491
+ return exitCode;
492
+ }
493
+ const message = err instanceof Error ? err.message : String(err);
494
+ writeError(stdout, stderr, jsonMode, message);
495
+ return 1;
496
+ }
497
+ }
498
+ function isDirectExecution() {
499
+ const entry = process.argv[1];
500
+ if (!entry)
501
+ return false;
502
+ try {
503
+ return realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url));
504
+ }
505
+ catch {
506
+ return false;
507
+ }
508
+ }
509
+ if (isDirectExecution()) {
510
+ runSwarmCli(process.argv.slice(2)).then((code) => {
511
+ process.exitCode = code;
512
+ }, (err) => {
513
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
514
+ process.exitCode = 2;
515
+ });
516
+ }
@@ -2114,9 +2114,10 @@ export type Shillbot = {
2114
2114
  {
2115
2115
  "name": "switchboardFeed";
2116
2116
  "docs": [
2117
- "The Switchboard pull feed account containing the oracle-attested composite score.",
2118
- "`PullFeedAccountData::parse()` which checks the account discriminator.",
2119
- "Account ownership is verified by Switchboard's `Owner` implementation."
2117
+ "The oracle authority signer (`GlobalState.oracle_authority` or",
2118
+ "`GlobalState.authority`) or legacy Switchboard pull feed account.",
2119
+ "/ `global_state.authority`, or validated against `global_state.switchboard_feed`",
2120
+ "and parsed via `PullFeedAccountData::parse()`."
2120
2121
  ];
2121
2122
  }
2122
2123
  ];
@@ -2888,6 +2889,11 @@ export type Shillbot = {
2888
2889
  "code": 6056;
2889
2890
  "name": "invalidAccountOwner";
2890
2891
  "msg": "Account is not owned by this program";
2892
+ },
2893
+ {
2894
+ "code": 6057;
2895
+ "name": "invalidTimeoutOrdering";
2896
+ "msg": "verification_timeout must exceed attestation_delay + staleness_window";
2891
2897
  }
2892
2898
  ];
2893
2899
  "types": [
@@ -2108,9 +2108,10 @@
2108
2108
  {
2109
2109
  "name": "switchboard_feed",
2110
2110
  "docs": [
2111
- "The Switchboard pull feed account containing the oracle-attested composite score.",
2112
- "`PullFeedAccountData::parse()` which checks the account discriminator.",
2113
- "Account ownership is verified by Switchboard's `Owner` implementation."
2111
+ "The oracle authority signer (`GlobalState.oracle_authority` or",
2112
+ "`GlobalState.authority`) or legacy Switchboard pull feed account.",
2113
+ "/ `global_state.authority`, or validated against `global_state.switchboard_feed`",
2114
+ "and parsed via `PullFeedAccountData::parse()`."
2114
2115
  ]
2115
2116
  }
2116
2117
  ],
@@ -2882,6 +2883,11 @@
2882
2883
  "code": 6056,
2883
2884
  "name": "InvalidAccountOwner",
2884
2885
  "msg": "Account is not owned by this program"
2886
+ },
2887
+ {
2888
+ "code": 6057,
2889
+ "name": "InvalidTimeoutOrdering",
2890
+ "msg": "verification_timeout must exceed attestation_delay + staleness_window"
2885
2891
  }
2886
2892
  ],
2887
2893
  "types": [
@@ -135,12 +135,12 @@ export declare class CoordinationGameApiClient {
135
135
  chain: string;
136
136
  session_key: string;
137
137
  tournament_id: number;
138
- }): Promise<XQueueResponse>;
138
+ }, token?: string): Promise<XQueueResponse>;
139
139
  crossChainStatus(by: {
140
140
  handle: string;
141
141
  } | {
142
142
  wallet: string;
143
- }): Promise<XQueueResponse>;
143
+ }, token?: string): Promise<XQueueResponse>;
144
144
  crossChainCommit(body: {
145
145
  wallet: string;
146
146
  commit: string;
@@ -177,8 +177,8 @@ export declare class CoordinationGameApiClient {
177
177
  player_wallet?: string;
178
178
  chain: string;
179
179
  tournament_id: number;
180
- }): Promise<EvmJoinResponse>;
181
- evmGameStatus(wallet: string): Promise<EvmJoinResponse>;
180
+ }, token?: string): Promise<EvmJoinResponse>;
181
+ evmGameStatus(wallet: string, token?: string): Promise<EvmJoinResponse>;
182
182
  evmGameCommitted(body: {
183
183
  game_id: string;
184
184
  wallet: string;
@@ -19,14 +19,14 @@ export class CoordinationGameApiClient {
19
19
  committed(body, token) { return this.http.post("/games/committed", body, token); }
20
20
  bothCommitted(body, token) { return this.http.post("/games/both-committed", body, token); }
21
21
  resolved(body, token) { return this.http.post("/games/resolved", body, token); }
22
- joinCrossChainQueue(body) {
23
- return this.http.post("/internal/xqueue/join", body);
22
+ joinCrossChainQueue(body, token) {
23
+ return this.http.post("/internal/xqueue/join", body, token);
24
24
  }
25
- crossChainStatus(by) {
25
+ crossChainStatus(by, token) {
26
26
  const query = "handle" in by
27
27
  ? `handle=${encodeURIComponent(by.handle)}`
28
28
  : `wallet=${encodeURIComponent(by.wallet)}`;
29
- return this.http.get(`/internal/xqueue/status?${query}`);
29
+ return this.http.get(`/internal/xqueue/status?${query}`, token);
30
30
  }
31
31
  crossChainCommit(body) {
32
32
  return this.http.post("/internal/xqueue/commit", body);
@@ -43,11 +43,11 @@ export class CoordinationGameApiClient {
43
43
  : `wallet=${encodeURIComponent(by.wallet)}`;
44
44
  return this.http.get(`/internal/xqueue/gameplay?${query}`);
45
45
  }
46
- joinEvmGame(body) {
47
- return this.http.post("/internal/evmgame/join", body);
46
+ joinEvmGame(body, token) {
47
+ return this.http.post("/internal/evmgame/join", body, token);
48
48
  }
49
- evmGameStatus(wallet) {
50
- return this.http.get(`/internal/evmgame/status?wallet=${encodeURIComponent(wallet)}`);
49
+ evmGameStatus(wallet, token) {
50
+ return this.http.get(`/internal/evmgame/status?wallet=${encodeURIComponent(wallet)}`, token);
51
51
  }
52
52
  evmGameCommitted(body) {
53
53
  return this.http.post("/internal/evmgame/committed", body);
package/dist/errors.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type SwarmClientErrorCode = "INVALID_ARGUMENT" | "INVALID_RESPONSE" | "NETWORK_ERROR" | "HTTP_ERROR" | "TIMEOUT" | "TRANSACTION_MISMATCH" | "TRANSACTION_FAILED" | "STORAGE_ERROR" | "WEBSOCKET_ERROR";
1
+ export type SwarmClientErrorCode = "INVALID_ARGUMENT" | "INVALID_RESPONSE" | "NETWORK_ERROR" | "HTTP_ERROR" | "TIMEOUT" | "TRANSACTION_MISMATCH" | "TRANSACTION_FAILED" | "SPEND_CAP_EXCEEDED" | "AUTH_REQUIRED" | "STORAGE_ERROR" | "WEBSOCKET_ERROR";
2
2
  export interface SwarmClientErrorOptions {
3
3
  code: SwarmClientErrorCode;
4
4
  operation: string;