@swarm-tips/client 0.4.9 → 0.4.11

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.
@@ -40,7 +40,7 @@ export class ShillbotApiClient {
40
40
  listTasks(limit = 50) {
41
41
  return this.http.get(`/tasks?limit=${encodeURIComponent(String(limit))}`, null);
42
42
  }
43
- async getTask(id, network) {
43
+ async getTask(id, networkOrOpts) {
44
44
  const trimmed = id.trim();
45
45
  if (!trimmed) {
46
46
  throw new SwarmClientError({
@@ -49,8 +49,12 @@ export class ShillbotApiClient {
49
49
  message: "Task id is required",
50
50
  });
51
51
  }
52
+ const network = typeof networkOrOpts === "string" ? networkOrOpts : networkOrOpts?.network;
53
+ const token = typeof networkOrOpts === "object" && networkOrOpts !== null && "token" in networkOrOpts
54
+ ? networkOrOpts.token
55
+ : null;
52
56
  const suffix = network ? `?network=${encodeURIComponent(network)}` : "";
53
- return this.http.get(`/tasks/${encodeURIComponent(trimmed)}${suffix}`, null);
57
+ return this.http.get(`/tasks/${encodeURIComponent(trimmed)}${suffix}`, token);
54
58
  }
55
59
  listAgentTasks() {
56
60
  return this.get("/agent/tasks");
@@ -270,6 +274,126 @@ export const SHILLBOT_EVM_SELECTORS = {
270
274
  finalize: "0xcb26e65b", // finalizeTask(uint64)
271
275
  expire: "0x5e9f3d19", // expireTask(uint64)
272
276
  };
277
+ /** Canonical ABI for `ShillbotEscrow.sol` lifecycle functions (`P2-27`). */
278
+ export const SHILLBOT_ESCROW_ABI = [
279
+ {
280
+ type: "function",
281
+ name: "createTask",
282
+ stateMutability: "payable",
283
+ inputs: [
284
+ { name: "statementCommitment", type: "bytes32" },
285
+ { name: "policyId", type: "bytes32" },
286
+ { name: "verificationKind", type: "uint8" },
287
+ { name: "deadline", type: "uint64" },
288
+ { name: "requiresApproval", type: "bool" },
289
+ ],
290
+ outputs: [{ name: "taskId", type: "uint64" }],
291
+ },
292
+ {
293
+ type: "function",
294
+ name: "claimTask",
295
+ stateMutability: "nonpayable",
296
+ inputs: [{ name: "taskId", type: "uint64" }],
297
+ outputs: [],
298
+ },
299
+ {
300
+ type: "function",
301
+ name: "submitWork",
302
+ stateMutability: "nonpayable",
303
+ inputs: [
304
+ { name: "taskId", type: "uint64" },
305
+ { name: "contentIdHash", type: "bytes32" },
306
+ { name: "artifactHash", type: "bytes32" },
307
+ ],
308
+ outputs: [],
309
+ },
310
+ {
311
+ type: "function",
312
+ name: "approveTask",
313
+ stateMutability: "nonpayable",
314
+ inputs: [{ name: "taskId", type: "uint64" }],
315
+ outputs: [],
316
+ },
317
+ {
318
+ type: "function",
319
+ name: "verifyTaskAttested",
320
+ stateMutability: "nonpayable",
321
+ inputs: [
322
+ { name: "taskId", type: "uint64" },
323
+ { name: "score", type: "uint64" },
324
+ { name: "sig", type: "bytes" },
325
+ ],
326
+ outputs: [],
327
+ },
328
+ {
329
+ type: "function",
330
+ name: "finalizeTask",
331
+ stateMutability: "nonpayable",
332
+ inputs: [{ name: "taskId", type: "uint64" }],
333
+ outputs: [],
334
+ },
335
+ {
336
+ type: "function",
337
+ name: "expireTask",
338
+ stateMutability: "nonpayable",
339
+ inputs: [{ name: "taskId", type: "uint64" }],
340
+ outputs: [],
341
+ },
342
+ ];
343
+ const SHILLBOT_EVM_FUNCTION_NAMES = {
344
+ create: "createTask",
345
+ claim: "claimTask",
346
+ submit: "submitWork",
347
+ approve: "approveTask",
348
+ verify: "verifyTaskAttested",
349
+ finalize: "finalizeTask",
350
+ expire: "expireTask",
351
+ };
352
+ function parseExpectedUintArg(value, field) {
353
+ let parsed;
354
+ if (typeof value === "bigint") {
355
+ parsed = value;
356
+ }
357
+ else if (typeof value === "number") {
358
+ if (!Number.isSafeInteger(value) || value < 0) {
359
+ throw new SwarmClientError({
360
+ code: "INVALID_ARGUMENT",
361
+ operation: "shillbot.validatePreparedEvmCall",
362
+ message: `Expected ${field} must be a non-negative safe integer`,
363
+ });
364
+ }
365
+ parsed = BigInt(value);
366
+ }
367
+ else if (typeof value === "string" && /^\d+$/.test(value.trim())) {
368
+ parsed = BigInt(value.trim());
369
+ }
370
+ else {
371
+ throw new SwarmClientError({
372
+ code: "INVALID_ARGUMENT",
373
+ operation: "shillbot.validatePreparedEvmCall",
374
+ message: `Expected ${field} must be a non-negative integer`,
375
+ });
376
+ }
377
+ if (parsed < 0n || parsed > 0xffffffffffffffffn) {
378
+ throw new SwarmClientError({
379
+ code: "INVALID_ARGUMENT",
380
+ operation: "shillbot.validatePreparedEvmCall",
381
+ message: `Expected ${field} is out of uint64 range`,
382
+ });
383
+ }
384
+ return parsed;
385
+ }
386
+ function normalizeExpectedBytes32(value, field) {
387
+ const trimmed = value.trim();
388
+ if (!/^0x[0-9a-fA-F]{64}$/.test(trimmed)) {
389
+ throw new SwarmClientError({
390
+ code: "INVALID_ARGUMENT",
391
+ operation: "shillbot.validatePreparedEvmCall",
392
+ message: `Expected ${field} must be a 32-byte 0x-prefixed hex string`,
393
+ });
394
+ }
395
+ return trimmed.toLowerCase();
396
+ }
273
397
  export function normalizeEvmChainId(chain) {
274
398
  if (typeof chain === "number") {
275
399
  if (!Number.isSafeInteger(chain) || chain <= 0) {
@@ -296,9 +420,9 @@ export function normalizeEvmChainId(chain) {
296
420
  return trimmed;
297
421
  }
298
422
  /**
299
- * C10 fail-closed local validator for server-prepared EVM `ShillbotEscrow` calls.
300
- * Verifies canonical contract address for `chain`, 4-byte function selector for
301
- * `action`, and `value_wei <= maxValueWei` (strictly `0n` on non-create actions).
423
+ * C10 + P2-27 fail-closed local validator for server-prepared EVM `ShillbotEscrow` calls.
424
+ * Verifies canonical contract address for `chain`, 4-byte function selector and full ABI-decoded
425
+ * calldata arguments for `action`, and `value_wei <= maxValueWei` (strictly `0n` on non-create actions).
302
426
  */
303
427
  export function validatePreparedEvmCall(evmCall, expected) {
304
428
  if (!evmCall || typeof evmCall !== "object") {
@@ -355,7 +479,8 @@ export function validatePreparedEvmCall(evmCall, expected) {
355
479
  });
356
480
  }
357
481
  const expectedSelector = SHILLBOT_EVM_SELECTORS[expected.action];
358
- if (!expectedSelector) {
482
+ const expectedFnName = SHILLBOT_EVM_FUNCTION_NAMES[expected.action];
483
+ if (!expectedSelector || !expectedFnName) {
359
484
  throw new SwarmClientError({
360
485
  code: "INVALID_ARGUMENT",
361
486
  operation: "shillbot.validatePreparedEvmCall",
@@ -370,6 +495,205 @@ export function validatePreparedEvmCall(evmCall, expected) {
370
495
  message: `Function selector ${actualSelector} does not match expected ${expectedSelector} for ${expected.action}`,
371
496
  });
372
497
  }
498
+ // Decode calldata via a zero-dependency pure-TS canonical ABI decoder (so CLI and
499
+ // Solana-only consumers never require optional peerDependency `viem` at runtime)
500
+ // and verify exact canonical encoding + arguments (P2-27).
501
+ const argHex = raw.data.slice(10).toLowerCase();
502
+ const decodeFailure = (detail) => {
503
+ throw new SwarmClientError({
504
+ code: "TRANSACTION_MISMATCH",
505
+ operation: "shillbot.validatePreparedEvmCall",
506
+ message: `Prepared EVM call data failed ABI decoding for ${expectedFnName}: ${detail}`,
507
+ });
508
+ };
509
+ const readWordHex = (wordIdx) => argHex.slice(wordIdx * 64, (wordIdx + 1) * 64);
510
+ const readCanonicalUint = (wordIdx, maxBits, label) => {
511
+ const word = readWordHex(wordIdx);
512
+ const zeroPrefixChars = (256 - maxBits) / 4;
513
+ if (!/^0+$/.test(word.slice(0, zeroPrefixChars))) {
514
+ decodeFailure(`has non-canonical high bits for ${label}`);
515
+ }
516
+ return BigInt(`0x${word.slice(zeroPrefixChars)}`);
517
+ };
518
+ const readCanonicalBool = (wordIdx, label) => {
519
+ const word = readWordHex(wordIdx);
520
+ if (word === `${"0".repeat(63)}0`)
521
+ return false;
522
+ if (word === `${"0".repeat(63)}1`)
523
+ return true;
524
+ decodeFailure(`has non-canonical bool encoding for ${label}`);
525
+ return false;
526
+ };
527
+ const readBytes32 = (wordIdx) => `0x${readWordHex(wordIdx)}`;
528
+ if (expectedFnName === "createTask") {
529
+ if (argHex.length !== 5 * 64) {
530
+ decodeFailure("has invalid calldata length or trailing bytes");
531
+ }
532
+ const statementCommitment = readBytes32(0);
533
+ const policyId = readBytes32(1);
534
+ const verificationKind = Number(readCanonicalUint(2, 8, "verificationKind"));
535
+ const deadline = readCanonicalUint(3, 64, "deadline");
536
+ const requiresApproval = readCanonicalBool(4, "requiresApproval");
537
+ if (expected.statementCommitment !== undefined) {
538
+ const want = normalizeExpectedBytes32(expected.statementCommitment, "statementCommitment");
539
+ if (statementCommitment !== want) {
540
+ throw new SwarmClientError({
541
+ code: "TRANSACTION_MISMATCH",
542
+ operation: "shillbot.validatePreparedEvmCall",
543
+ message: `createTask statementCommitment ${statementCommitment} differs from expected ${want}`,
544
+ });
545
+ }
546
+ }
547
+ if (expected.policyId !== undefined) {
548
+ const want = normalizeExpectedBytes32(expected.policyId, "policyId");
549
+ if (policyId !== want) {
550
+ throw new SwarmClientError({
551
+ code: "TRANSACTION_MISMATCH",
552
+ operation: "shillbot.validatePreparedEvmCall",
553
+ message: `createTask policyId ${policyId} differs from expected ${want}`,
554
+ });
555
+ }
556
+ }
557
+ if (expected.verificationKind !== undefined) {
558
+ if (!Number.isInteger(expected.verificationKind) ||
559
+ expected.verificationKind < 0 ||
560
+ expected.verificationKind > 255) {
561
+ throw new SwarmClientError({
562
+ code: "INVALID_ARGUMENT",
563
+ operation: "shillbot.validatePreparedEvmCall",
564
+ message: "Expected verificationKind must be an integer in [0, 255]",
565
+ });
566
+ }
567
+ if (verificationKind !== expected.verificationKind) {
568
+ throw new SwarmClientError({
569
+ code: "TRANSACTION_MISMATCH",
570
+ operation: "shillbot.validatePreparedEvmCall",
571
+ message: `createTask verificationKind ${verificationKind} differs from expected ${expected.verificationKind}`,
572
+ });
573
+ }
574
+ }
575
+ if (expected.deadline !== undefined) {
576
+ const want = parseExpectedUintArg(expected.deadline, "deadline");
577
+ if (deadline !== want) {
578
+ throw new SwarmClientError({
579
+ code: "TRANSACTION_MISMATCH",
580
+ operation: "shillbot.validatePreparedEvmCall",
581
+ message: `createTask deadline ${deadline} differs from expected ${want}`,
582
+ });
583
+ }
584
+ }
585
+ if (expected.requiresApproval !== undefined && requiresApproval !== expected.requiresApproval) {
586
+ throw new SwarmClientError({
587
+ code: "TRANSACTION_MISMATCH",
588
+ operation: "shillbot.validatePreparedEvmCall",
589
+ message: `createTask requiresApproval ${requiresApproval} differs from expected ${expected.requiresApproval}`,
590
+ });
591
+ }
592
+ }
593
+ else if (expectedFnName === "claimTask" ||
594
+ expectedFnName === "approveTask" ||
595
+ expectedFnName === "finalizeTask" ||
596
+ expectedFnName === "expireTask") {
597
+ if (argHex.length !== 64) {
598
+ decodeFailure("has invalid calldata length or trailing bytes");
599
+ }
600
+ const taskId = readCanonicalUint(0, 64, "taskId");
601
+ if (expected.taskId !== undefined) {
602
+ const want = parseExpectedUintArg(expected.taskId, "taskId");
603
+ if (taskId !== want) {
604
+ throw new SwarmClientError({
605
+ code: "TRANSACTION_MISMATCH",
606
+ operation: "shillbot.validatePreparedEvmCall",
607
+ message: `${expectedFnName} taskId ${taskId} differs from expected ${want}`,
608
+ });
609
+ }
610
+ }
611
+ }
612
+ else if (expectedFnName === "submitWork") {
613
+ if (argHex.length !== 3 * 64) {
614
+ decodeFailure("has invalid calldata length or trailing bytes");
615
+ }
616
+ const taskId = readCanonicalUint(0, 64, "taskId");
617
+ const contentIdHash = readBytes32(1);
618
+ const artifactHash = readBytes32(2);
619
+ if (expected.taskId !== undefined) {
620
+ const want = parseExpectedUintArg(expected.taskId, "taskId");
621
+ if (taskId !== want) {
622
+ throw new SwarmClientError({
623
+ code: "TRANSACTION_MISMATCH",
624
+ operation: "shillbot.validatePreparedEvmCall",
625
+ message: `submitWork taskId ${taskId} differs from expected ${want}`,
626
+ });
627
+ }
628
+ }
629
+ if (expected.contentIdHash !== undefined) {
630
+ const want = normalizeExpectedBytes32(expected.contentIdHash, "contentIdHash");
631
+ if (contentIdHash !== want) {
632
+ throw new SwarmClientError({
633
+ code: "TRANSACTION_MISMATCH",
634
+ operation: "shillbot.validatePreparedEvmCall",
635
+ message: `submitWork contentIdHash ${contentIdHash} differs from expected ${want}`,
636
+ });
637
+ }
638
+ }
639
+ if (expected.artifactHash !== undefined) {
640
+ const want = normalizeExpectedBytes32(expected.artifactHash, "artifactHash");
641
+ if (artifactHash !== want) {
642
+ throw new SwarmClientError({
643
+ code: "TRANSACTION_MISMATCH",
644
+ operation: "shillbot.validatePreparedEvmCall",
645
+ message: `submitWork artifactHash ${artifactHash} differs from expected ${want}`,
646
+ });
647
+ }
648
+ }
649
+ }
650
+ else if (expectedFnName === "verifyTaskAttested") {
651
+ // Head: taskId (uint64), score (uint64), sig offset (0x60 = 96 bytes); Tail: length + padded bytes.
652
+ if (argHex.length < 4 * 64 || argHex.length % 64 !== 0) {
653
+ decodeFailure("has truncated or unaligned dynamic bytes calldata");
654
+ }
655
+ const taskId = readCanonicalUint(0, 64, "taskId");
656
+ const score = readCanonicalUint(1, 64, "score");
657
+ const sigOffset = BigInt(`0x${readWordHex(2)}`);
658
+ if (sigOffset !== 96n) {
659
+ decodeFailure("has non-canonical dynamic bytes offset");
660
+ }
661
+ const sigLenBig = BigInt(`0x${readWordHex(3)}`);
662
+ if (sigLenBig > 65536n) {
663
+ decodeFailure("has oversized sig byte length");
664
+ }
665
+ const sigLen = Number(sigLenBig);
666
+ const paddedBytes = Math.ceil(sigLen / 32) * 32;
667
+ const expectedHexLen = (4 * 32 + paddedBytes) * 2;
668
+ if (argHex.length !== expectedHexLen) {
669
+ decodeFailure("is non-canonical or has trailing bytes");
670
+ }
671
+ const sigHex = argHex.slice(4 * 64);
672
+ const paddingHex = sigHex.slice(sigLen * 2);
673
+ if (paddingHex.length > 0 && !/^0+$/.test(paddingHex)) {
674
+ decodeFailure("has non-zero trailing padding bytes in sig");
675
+ }
676
+ if (expected.taskId !== undefined) {
677
+ const want = parseExpectedUintArg(expected.taskId, "taskId");
678
+ if (taskId !== want) {
679
+ throw new SwarmClientError({
680
+ code: "TRANSACTION_MISMATCH",
681
+ operation: "shillbot.validatePreparedEvmCall",
682
+ message: `verifyTaskAttested taskId ${taskId} differs from expected ${want}`,
683
+ });
684
+ }
685
+ }
686
+ if (expected.score !== undefined) {
687
+ const want = parseExpectedUintArg(expected.score, "score");
688
+ if (score !== want) {
689
+ throw new SwarmClientError({
690
+ code: "TRANSACTION_MISMATCH",
691
+ operation: "shillbot.validatePreparedEvmCall",
692
+ message: `verifyTaskAttested score ${score} differs from expected ${want}`,
693
+ });
694
+ }
695
+ }
696
+ }
373
697
  let valueWei;
374
698
  try {
375
699
  const rawVal = raw.value_wei ?? raw.value ?? "0";
@@ -462,8 +786,8 @@ export function estimateSolanaNetworkFeeLamports(inspected, wallet) {
462
786
  return baseSignatureFeeLamports + priorityFeeLamports + additionalFeeLamports;
463
787
  }
464
788
  export function permittedPreparedProgramIds(action, network) {
465
- if (action === "verify") {
466
- return [SWITCHBOARD_PROGRAM_IDS[network], Secp256k1Program.programId.toBase58()];
789
+ if (action === "verify" && network === "devnet") {
790
+ return [SWITCHBOARD_PROGRAM_IDS.devnet, Secp256k1Program.programId.toBase58()];
467
791
  }
468
792
  if (action === "finalize") {
469
793
  return [EXTENSION_CREDIT_PROGRAM_ID.toBase58()];
@@ -360,8 +360,8 @@ export function verifyIntent(encoded, intent) {
360
360
  const allowedPrograms = new Set([
361
361
  shillbotProgramId,
362
362
  COMPUTE_BUDGET_PROGRAM_ID,
363
- ...(intent.action === "verify"
364
- ? [SWITCHBOARD_PROGRAM_IDS[intent.network], SECP256K1_PROGRAM_ID]
363
+ ...(intent.action === "verify" && intent.network === "devnet"
364
+ ? [SWITCHBOARD_PROGRAM_IDS.devnet, SECP256K1_PROGRAM_ID]
365
365
  : []),
366
366
  ...(intent.action === "finalize" ? [extensionCreditId] : []),
367
367
  ]);
@@ -382,6 +382,44 @@ export function verifyIntent(encoded, intent) {
382
382
  const payoutDiscriminator = shillbotInstructionDiscriminator("set_payout_to");
383
383
  const companions = shillbotInstructions.filter((ix) => ix !== lifecycle[0]);
384
384
  const lifecycleIndex = inspected.instructions.indexOf(lifecycle[0]);
385
+ const switchboardPullFeedDiscriminator = Buffer.from(sha256.arrayBuffer("global:pull_feed_submit_response_consensus")).subarray(0, 8);
386
+ const secpEntries = inspected.instructions
387
+ .map((ix, txIndex) => ({ ix, txIndex }))
388
+ .filter((entry) => entry.ix.program_id === SECP256K1_PROGRAM_ID);
389
+ const switchboardEntries = inspected.instructions
390
+ .map((ix, txIndex) => ({ ix, txIndex }))
391
+ .filter((entry) => entry.ix.program_id === SWITCHBOARD_PROGRAM_IDS.mainnet ||
392
+ entry.ix.program_id === SWITCHBOARD_PROGRAM_IDS.devnet);
393
+ if (secpEntries.length > 0 || switchboardEntries.length > 0) {
394
+ if (intent.network !== "devnet" || intent.action !== "verify") {
395
+ throw new Error("Switchboard/Secp256k1 crank instructions are only permitted on devnet verify_task");
396
+ }
397
+ if (secpEntries.length !== 1 || switchboardEntries.length !== 1) {
398
+ throw new Error("devnet verify_task Switchboard crank requires exactly 1 Secp256k1 and 1 Switchboard instruction");
399
+ }
400
+ const secpEntry = secpEntries[0];
401
+ const sbEntry = switchboardEntries[0];
402
+ if (sbEntry.ix.program_id !== SWITCHBOARD_PROGRAM_IDS.devnet) {
403
+ throw new Error(`unexpected Switchboard program ${sbEntry.ix.program_id}`);
404
+ }
405
+ const secpData = Buffer.from(secpEntry.ix.data_base64, "base64");
406
+ if (secpData.length === 0 || secpData[0] === 0) {
407
+ throw new Error("Secp256k1 companion instruction must carry at least 1 signature");
408
+ }
409
+ if (secpEntry.txIndex + 1 !== sbEntry.txIndex ||
410
+ sbEntry.txIndex >= lifecycleIndex) {
411
+ throw new Error("Switchboard crank must follow exact order Secp256k1 -> Switchboard -> verify_task");
412
+ }
413
+ const sbData = Buffer.from(sbEntry.ix.data_base64, "base64");
414
+ if (sbData.length < 8 ||
415
+ !sbData.subarray(0, 8).equals(switchboardPullFeedDiscriminator)) {
416
+ throw new Error("Switchboard companion instruction must be pull_feed_submit_response_consensus");
417
+ }
418
+ const expectedFeed = lifecycle[0].accounts[2];
419
+ if (!expectedFeed || !sbEntry.ix.accounts.includes(expectedFeed)) {
420
+ throw new Error("Switchboard companion instruction does not reference expected feed");
421
+ }
422
+ }
385
423
  if (intent.action === "claim" &&
386
424
  companions.some((ix) => Buffer.from(ix.data_base64, "base64")
387
425
  .subarray(0, 8)
@@ -1,4 +1,5 @@
1
1
  import { Buffer } from "buffer";
2
+ import { sha256 } from "js-sha256";
2
3
  import { ComputeBudgetProgram, PublicKey, SYSVAR_INSTRUCTIONS_PUBKEY, Secp256k1Program, } from "@solana/web3.js";
3
4
  import { SHILLBOT_PROGRAM_ID, shillbotInstructionDiscriminator } from "../contracts/index.js";
4
5
  import { SwarmClientError, TransactionMismatchError } from "../errors.js";
@@ -17,6 +18,7 @@ const SWITCHBOARD_PROGRAM_IDS = {
17
18
  mainnet: "SBondMDrcV3K4kxZR1HNVT7osZxAHVHgYXL5Ze1oMUv",
18
19
  devnet: "Aio4gaXjXzJNVLtzwtNVmSqGKpANtXhybbkhtAC94ji2",
19
20
  };
21
+ const SWITCHBOARD_PULL_FEED_SUBMIT_DISCRIMINATOR = Buffer.from(sha256.arrayBuffer("global:pull_feed_submit_response_consensus")).subarray(0, 8);
20
22
  /**
21
23
  * Exact Anchor account-index and authority-slot specification for every Shillbot instruction,
22
24
  * derived directly from `programs/shillbot/src/instructions/*.rs` and `shillbot.json` IDL.
@@ -494,17 +496,16 @@ export function verifyBuiltTransaction(encoded, expected, operation = "shillbot.
494
496
  if (explicitFeePayer && inspected.fee_payer !== explicitFeePayer) {
495
497
  throw txMismatch(operation, "Fee payer differs from expectation");
496
498
  }
497
- const isVerifyContext = expected.action === "verify" ||
498
- expected.instructionName === "verify_task" ||
499
- expected.instructionName === "verify_task_attested";
499
+ const allowSwitchboardContext = expected.network === "devnet" &&
500
+ (expected.action === "verify" || expected.instructionName === "verify_task");
500
501
  const isFinalizeContext = expected.action === "finalize" || expected.instructionName === "finalize_task";
501
502
  const shillbotId = SHILLBOT_PROGRAM_ID.toBase58();
502
503
  const extensionCreditId = EXTENSION_CREDIT_PROGRAM_ID.toBase58();
503
504
  const alwaysAllowed = new Set([
504
505
  shillbotId,
505
506
  ComputeBudgetProgram.programId.toBase58(),
506
- ...(isVerifyContext
507
- ? [SWITCHBOARD_PROGRAM_IDS[expected.network], Secp256k1Program.programId.toBase58()]
507
+ ...(allowSwitchboardContext
508
+ ? [SWITCHBOARD_PROGRAM_IDS.devnet, Secp256k1Program.programId.toBase58()]
508
509
  : []),
509
510
  ...(isFinalizeContext ? [extensionCreditId] : []),
510
511
  ...(expected.allowedProgramIds ?? []),
@@ -584,6 +585,49 @@ export function verifyBuiltTransaction(encoded, expected, operation = "shillbot.
584
585
  throw txMismatch(operation, `route_and_recoup advance account (${advanceAcct}) does not match canonical Advance PDA (${derivedAdvance})`);
585
586
  }
586
587
  }
588
+ // Validate Switchboard / Secp256k1 companions strictly (mirrors Rust `shillbot-chain`, P1-15).
589
+ // Runs BEFORE any `companions.length === 0` or `set_payout_to` early returns so injected
590
+ // Switchboard / Secp256k1 instructions can never slip past `verify_task_attested` or mainnet.
591
+ const switchboardProgramIds = new Set(Object.values(SWITCHBOARD_PROGRAM_IDS));
592
+ const secp256k1ProgramId = Secp256k1Program.programId.toBase58();
593
+ const secpIxs = inspected.instructions
594
+ .map((ix, txIndex) => ({ ix, txIndex }))
595
+ .filter((entry) => entry.ix.program_id === secp256k1ProgramId);
596
+ const switchboardIxs = inspected.instructions
597
+ .map((ix, txIndex) => ({ ix, txIndex }))
598
+ .filter((entry) => switchboardProgramIds.has(entry.ix.program_id));
599
+ if (secpIxs.length > 0 || switchboardIxs.length > 0) {
600
+ if (expected.network !== "devnet") {
601
+ throw txMismatch(operation, "Unexpected program: Switchboard/Secp256k1 crank instructions are forbidden on mainnet");
602
+ }
603
+ if (primary.spec.name !== "verify_task") {
604
+ throw txMismatch(operation, `Unexpected program: Switchboard/Secp256k1 crank instructions are forbidden on ${primary.spec.name}`);
605
+ }
606
+ if (secpIxs.length !== 1 || switchboardIxs.length !== 1) {
607
+ throw txMismatch(operation, `Devnet verify_task Switchboard crank requires exactly 1 Secp256k1 and 1 Switchboard instruction (got ${secpIxs.length} secp256k1, ${switchboardIxs.length} switchboard)`);
608
+ }
609
+ const secpEntry = secpIxs[0];
610
+ const sbEntry = switchboardIxs[0];
611
+ if (sbEntry.ix.program_id !== SWITCHBOARD_PROGRAM_IDS.devnet) {
612
+ throw txMismatch(operation, `Unexpected Switchboard program ${sbEntry.ix.program_id} on devnet`);
613
+ }
614
+ const secpData = Buffer.from(secpEntry.ix.data_base64, "base64");
615
+ if (secpData.length === 0 || secpData[0] === 0) {
616
+ throw txMismatch(operation, "Secp256k1 companion instruction must carry at least 1 signature");
617
+ }
618
+ if (secpEntry.txIndex + 1 !== sbEntry.txIndex || sbEntry.txIndex >= primary.txIndex) {
619
+ throw txMismatch(operation, "Switchboard crank must follow exact order Secp256k1 -> Switchboard -> verify_task");
620
+ }
621
+ const sbData = Buffer.from(sbEntry.ix.data_base64, "base64");
622
+ if (sbData.length < 8 ||
623
+ !sbData.subarray(0, 8).equals(SWITCHBOARD_PULL_FEED_SUBMIT_DISCRIMINATOR)) {
624
+ throw txMismatch(operation, "Switchboard companion instruction must be pull_feed_submit_response_consensus");
625
+ }
626
+ const expectedFeed = expected.oracleAuthority ?? primary.ix.accounts[2];
627
+ if (!sbEntry.ix.accounts.includes(expectedFeed)) {
628
+ throw txMismatch(operation, `Switchboard companion instruction does not reference expected feed ${expectedFeed}`);
629
+ }
630
+ }
587
631
  // Instruction-specific payload validation
588
632
  if (primary.spec.name === "create_task") {
589
633
  if (primary.data.length < 24) {
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const CLIENT_VERSION = "0.4.9";
1
+ export declare const CLIENT_VERSION = "0.4.11";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLIENT_VERSION = "0.4.9";
1
+ export const CLIENT_VERSION = "0.4.11";
@@ -31,7 +31,7 @@ export interface VowV1Attestation {
31
31
  * verifier MUST return one of these strings (with the named field
32
32
  * substituted into `field_mismatch:<field>` and `schema_invalid:<field>`).
33
33
  */
34
- export type FailureReason = `schema_invalid:${string}` | "account_closed" | "owner_mismatch" | "discriminator_mismatch" | `field_mismatch:${string}` | "score_above_max" | "state_invalid";
34
+ export type FailureReason = `schema_invalid:${string}` | "network_mismatch" | "account_closed" | "owner_mismatch" | "discriminator_mismatch" | `field_mismatch:${string}` | "score_above_max" | "state_invalid";
35
35
  /**
36
36
  * @deprecated Renamed to {@link VowV1Attestation} when the standard became VOW
37
37
  * (Verifiable On-chain Work) on 2026-07-10. The wire format is `vow/v1`; this
@@ -37,6 +37,8 @@ export declare function fetchVowAttestationJson(rawUrl: string, opts?: FetchVowO
37
37
  * Enforces SSRF host/IP validation, `redirect: "error"`, and a 2 MiB streaming body cap.
38
38
  */
39
39
  export declare function verifyVow(urlOrJson: string | Record<string, unknown>, opts?: VerifyVowOptions): Promise<Verdict>;
40
+ /** Canonical Solana cluster genesis hashes (full 44-char base58 + 32-char CAIP-2 prefix, P2-26). */
41
+ export declare const SOLANA_GENESIS_HASHES: Readonly<Record<"mainnet" | "devnet", readonly string[]>>;
40
42
  /**
41
43
  * Step-by-step verifier per `docs/specs/vow-v1.md` §4.
42
44
  *
@@ -47,7 +49,7 @@ export declare function verifyVow(urlOrJson: string | Record<string, unknown>, o
47
49
  *
48
50
  * Splitting lets unit tests cover the pure parts without an RPC.
49
51
  */
50
- export declare function verifyV1(attestation: unknown, protocol: ProtocolHandler, rpc: Connection, expectedScoreMax?: bigint | number | string): Promise<Verdict>;
52
+ export declare function verifyV1(attestation: unknown, protocol: ProtocolHandler, rpc: Connection, expectedScoreMax?: bigint | number | string, expectedNetwork?: "mainnet" | "devnet"): Promise<Verdict>;
51
53
  /**
52
54
  * Pure step 1 + step 6 of the protocol. Returns null on success or
53
55
  * the first failure reason.
@@ -57,4 +59,4 @@ export declare function verifyV1Schema(attestation: unknown): FailureReason | nu
57
59
  * Steps 2-5 + 7 — touches RPC. Returns null on success or the first
58
60
  * failure reason.
59
61
  */
60
- export declare function verifyV1OnChain(a: AasV1Attestation, protocol: ProtocolHandler, rpc: Connection, expectedScoreMax?: bigint | number | string): Promise<FailureReason | null>;
62
+ export declare function verifyV1OnChain(a: AasV1Attestation, protocol: ProtocolHandler, rpc: Connection, expectedScoreMax?: bigint | number | string, expectedNetwork?: "mainnet" | "devnet"): Promise<FailureReason | null>;
@@ -449,16 +449,22 @@ export async function verifyVow(urlOrJson, opts) {
449
449
  }
450
450
  }
451
451
  }
452
- const defaultNet = opts?.network ?? "mainnet";
453
- const net = attestation &&
454
- typeof attestation === "object" &&
455
- attestation.network === "devnet"
456
- ? "devnet"
457
- : defaultNet;
452
+ const expectedNetwork = opts?.network ?? "mainnet";
458
453
  const conn = opts?.connection ??
459
- new Connection(opts?.rpcUrl ?? DEFAULT_VOW_SOLANA_RPC[net], "confirmed");
460
- return verifyV1(attestation, opts?.protocol ?? shillbotProtocol, conn, opts?.expectedScoreMax);
454
+ new Connection(opts?.rpcUrl ?? DEFAULT_VOW_SOLANA_RPC[expectedNetwork], "confirmed");
455
+ return verifyV1(attestation, opts?.protocol ?? shillbotProtocol, conn, opts?.expectedScoreMax, expectedNetwork);
461
456
  }
457
+ /** Canonical Solana cluster genesis hashes (full 44-char base58 + 32-char CAIP-2 prefix, P2-26). */
458
+ export const SOLANA_GENESIS_HASHES = {
459
+ mainnet: [
460
+ "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d",
461
+ "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
462
+ ],
463
+ devnet: [
464
+ "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG",
465
+ "EtWTRABZaYq6iMfeYKouRu166VU2xqa1",
466
+ ],
467
+ };
462
468
  /**
463
469
  * Step-by-step verifier per `docs/specs/vow-v1.md` §4.
464
470
  *
@@ -469,7 +475,7 @@ export async function verifyVow(urlOrJson, opts) {
469
475
  *
470
476
  * Splitting lets unit tests cover the pure parts without an RPC.
471
477
  */
472
- export async function verifyV1(attestation, protocol, rpc, expectedScoreMax) {
478
+ export async function verifyV1(attestation, protocol, rpc, expectedScoreMax, expectedNetwork = "mainnet") {
473
479
  const checkedAt = nowRfc3339();
474
480
  const rpcEndpoint = rpc.rpcEndpoint;
475
481
  const schemaFail = verifyV1Schema(attestation);
@@ -483,7 +489,7 @@ export async function verifyV1(attestation, protocol, rpc, expectedScoreMax) {
483
489
  };
484
490
  }
485
491
  const a = asV1(attestation);
486
- const onChainFail = await verifyV1OnChain(a, protocol, rpc, expectedScoreMax);
492
+ const onChainFail = await verifyV1OnChain(a, protocol, rpc, expectedScoreMax, expectedNetwork);
487
493
  if (onChainFail) {
488
494
  return {
489
495
  valid: false,
@@ -519,7 +525,22 @@ export function verifyV1Schema(attestation) {
519
525
  * Steps 2-5 + 7 — touches RPC. Returns null on success or the first
520
526
  * failure reason.
521
527
  */
522
- export async function verifyV1OnChain(a, protocol, rpc, expectedScoreMax) {
528
+ export async function verifyV1OnChain(a, protocol, rpc, expectedScoreMax, expectedNetwork = "mainnet") {
529
+ // P2-26 — network pin check BEFORE any RPC calls so a devnet attestation
530
+ // can never downgrade a mainnet verifier (fail closed with `network_mismatch`).
531
+ const allowedGenesisHashes = SOLANA_GENESIS_HASHES[expectedNetwork];
532
+ if (!allowedGenesisHashes || a.network !== expectedNetwork) {
533
+ return "network_mismatch";
534
+ }
535
+ // Verify the RPC cluster's genesis hash when the connection exposes `getGenesisHash`.
536
+ const maybeGetGenesisHash = rpc.getGenesisHash;
537
+ if (typeof maybeGetGenesisHash === "function") {
538
+ const genesisHash = await maybeGetGenesisHash.call(rpc);
539
+ if (typeof genesisHash !== "string" ||
540
+ !allowedGenesisHashes.includes(genesisHash)) {
541
+ return "network_mismatch";
542
+ }
543
+ }
523
544
  const expectedMax = BigInt(expectedScoreMax ?? protocol.scoreMax ?? DEFAULT_SCORE_MAX);
524
545
  if (BigInt(a.score_max) !== expectedMax) {
525
546
  return "field_mismatch:score_max";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swarm-tips/client",
3
- "version": "0.4.9",
3
+ "version": "0.4.11",
4
4
  "mcpName": "io.github.corsur/swarm-tips",
5
5
  "description": "Typed browser and Node.js clients for Swarm Tips, Shillbot, and Coordination Game",
6
6
  "type": "module",