@swarm-tips/client 0.4.8 → 0.4.10

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.
@@ -1,5 +1,6 @@
1
1
  import { Buffer } from "buffer";
2
- import { ComputeBudgetProgram, PublicKey, Secp256k1Program } from "@solana/web3.js";
2
+ import { sha256 } from "js-sha256";
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";
5
6
  import { EXTENSION_CREDIT_PROGRAM_ID, advancePda, inspectTransaction, routeAndRecoupDiscriminator, } from "./index.js";
@@ -9,12 +10,15 @@ export const deriveAdvancePda = advancePda;
9
10
  export const MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 100000n;
10
11
  /** Solana runtime ceiling for `ComputeBudget::SetComputeUnitLimit` (`1_400_000` CUs). */
11
12
  export const MAX_COMPUTE_UNIT_LIMIT = 1_400_000;
13
+ /** Full passing composite score (`1_000_000`) required on M2 Open-Competition 1-tx verify bundles. */
14
+ const MAX_VERIFY_SCORE = 1000000n;
12
15
  const MIN_HEAP_FRAME_BYTES = 32 * 1024;
13
16
  const MAX_HEAP_FRAME_BYTES = 256 * 1024;
14
17
  const SWITCHBOARD_PROGRAM_IDS = {
15
18
  mainnet: "SBondMDrcV3K4kxZR1HNVT7osZxAHVHgYXL5Ze1oMUv",
16
19
  devnet: "Aio4gaXjXzJNVLtzwtNVmSqGKpANtXhybbkhtAC94ji2",
17
20
  };
21
+ const SWITCHBOARD_PULL_FEED_SUBMIT_DISCRIMINATOR = Buffer.from(sha256.arrayBuffer("global:pull_feed_submit_response_consensus")).subarray(0, 8);
18
22
  /**
19
23
  * Exact Anchor account-index and authority-slot specification for every Shillbot instruction,
20
24
  * derived directly from `programs/shillbot/src/instructions/*.rs` and `shillbot.json` IDL.
@@ -492,17 +496,16 @@ export function verifyBuiltTransaction(encoded, expected, operation = "shillbot.
492
496
  if (explicitFeePayer && inspected.fee_payer !== explicitFeePayer) {
493
497
  throw txMismatch(operation, "Fee payer differs from expectation");
494
498
  }
495
- const isVerifyContext = expected.action === "verify" ||
496
- expected.instructionName === "verify_task" ||
497
- expected.instructionName === "verify_task_attested";
499
+ const allowSwitchboardContext = expected.network === "devnet" &&
500
+ (expected.action === "verify" || expected.instructionName === "verify_task");
498
501
  const isFinalizeContext = expected.action === "finalize" || expected.instructionName === "finalize_task";
499
502
  const shillbotId = SHILLBOT_PROGRAM_ID.toBase58();
500
503
  const extensionCreditId = EXTENSION_CREDIT_PROGRAM_ID.toBase58();
501
504
  const alwaysAllowed = new Set([
502
505
  shillbotId,
503
506
  ComputeBudgetProgram.programId.toBase58(),
504
- ...(isVerifyContext
505
- ? [SWITCHBOARD_PROGRAM_IDS[expected.network], Secp256k1Program.programId.toBase58()]
507
+ ...(allowSwitchboardContext
508
+ ? [SWITCHBOARD_PROGRAM_IDS.devnet, Secp256k1Program.programId.toBase58()]
506
509
  : []),
507
510
  ...(isFinalizeContext ? [extensionCreditId] : []),
508
511
  ...(expected.allowedProgramIds ?? []),
@@ -582,6 +585,49 @@ export function verifyBuiltTransaction(encoded, expected, operation = "shillbot.
582
585
  throw txMismatch(operation, `route_and_recoup advance account (${advanceAcct}) does not match canonical Advance PDA (${derivedAdvance})`);
583
586
  }
584
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
+ }
585
631
  // Instruction-specific payload validation
586
632
  if (primary.spec.name === "create_task") {
587
633
  if (primary.data.length < 24) {
@@ -707,6 +753,112 @@ export function verifyBuiltTransaction(encoded, expected, operation = "shillbot.
707
753
  validateSetPayoutToInstruction(companions[0], expected.wallet, primary.ix.accounts[0], expectedPayoutPubkey, operation);
708
754
  return inspected;
709
755
  }
756
+ // M2 Open-Competition 1-tx verify bundle:
757
+ // `[ComputeBudget?, claim_task(sysvar), set_payout_to?, submit_work, verify_task_attested(MAX_SCORE)]`
758
+ const isM2VerifyNoPayout = isVerifyLifecycle &&
759
+ primary.spec.name === "verify_task_attested" &&
760
+ companions.length === 2 &&
761
+ companions[0].spec.name === "claim_task" &&
762
+ companions[1].spec.name === "submit_work";
763
+ const isM2VerifyWithPayout = isVerifyLifecycle &&
764
+ primary.spec.name === "verify_task_attested" &&
765
+ companions.length === 3 &&
766
+ companions[0].spec.name === "claim_task" &&
767
+ companions[1].spec.name === "set_payout_to" &&
768
+ companions[2].spec.name === "submit_work";
769
+ if (isM2VerifyNoPayout || isM2VerifyWithPayout) {
770
+ const disallowedInM2 = new Set([
771
+ SWITCHBOARD_PROGRAM_IDS[expected.network],
772
+ Secp256k1Program.programId.toBase58(),
773
+ ]);
774
+ for (const extraAllowed of expected.allowedProgramIds ?? []) {
775
+ disallowedInM2.delete(extraAllowed);
776
+ }
777
+ const unexpectedProgramInM2 = inspected.instructions.find((ix) => disallowedInM2.has(ix.program_id));
778
+ if (unexpectedProgramInM2) {
779
+ throw txMismatch(operation, `Unexpected program ${unexpectedProgramInM2.program_id} in M2 verify bundle`);
780
+ }
781
+ if (inspected.fee_payer !== expected.wallet) {
782
+ throw txMismatch(operation, `M2 verify bundle requires fee_payer ${expected.wallet}, got ${inspected.fee_payer}`);
783
+ }
784
+ if (primary.ix.accounts[2] === inspected.fee_payer) {
785
+ throw txMismatch(operation, "M2 verify bundle attester cannot be fee_payer");
786
+ }
787
+ if (primary.ix.accounts.length !== 3) {
788
+ throw txMismatch(operation, `M2 verify_task_attested must carry exact 3 accounts [task, global_state, attester], got ${primary.ix.accounts.length}`);
789
+ }
790
+ const scoreView = new DataView(primary.data.buffer, primary.data.byteOffset + 8, 8);
791
+ const verifyScore = scoreView.getBigUint64(0, true);
792
+ if (verifyScore !== MAX_VERIFY_SCORE) {
793
+ throw txMismatch(operation, `M2 verify bundle requires MAX_SCORE (${MAX_VERIFY_SCORE}), got ${verifyScore}`);
794
+ }
795
+ if (!primary.data.subarray(16, 48).some((b) => b !== 0)) {
796
+ throw txMismatch(operation, "M2 verify_task_attested verification_hash must be non-zero");
797
+ }
798
+ const lifecycleTaskPda = primary.ix.accounts[0];
799
+ const claimIx = companions[0];
800
+ const payoutIx = isM2VerifyWithPayout ? companions[1] : undefined;
801
+ const submitIx = isM2VerifyWithPayout ? companions[2] : companions[1];
802
+ if (payoutIx) {
803
+ if (payoutIx.txIndex !== claimIx.txIndex + 1 ||
804
+ submitIx.txIndex !== payoutIx.txIndex + 1 ||
805
+ primary.txIndex !== submitIx.txIndex + 1) {
806
+ throw txMismatch(operation, "M2 verify bundle instructions must execute in strict order claim_task < set_payout_to < submit_work < verify_task_attested");
807
+ }
808
+ }
809
+ else {
810
+ if (expectedPayoutPubkey) {
811
+ throw txMismatch(operation, "Expected set_payout_to instruction matching expected.payoutTo, but none was present");
812
+ }
813
+ if (submitIx.txIndex !== claimIx.txIndex + 1 ||
814
+ primary.txIndex !== submitIx.txIndex + 1) {
815
+ throw txMismatch(operation, "M2 verify bundle instructions must execute in strict order claim_task < submit_work < verify_task_attested");
816
+ }
817
+ }
818
+ // Validate companion claim_task
819
+ const validClaimAccounts = claimIx.ix.accounts.length === SHILLBOT_INSTRUCTION_SPECS.claim_task.minAccounts ||
820
+ (claimIx.ix.accounts.length === 6 &&
821
+ claimIx.ix.accounts[5] === SYSVAR_INSTRUCTIONS_PUBKEY.toBase58());
822
+ if (claimIx.data.length !== 8 || !validClaimAccounts) {
823
+ throw txMismatch(operation, "Malformed claim_task companion in M2 verify bundle");
824
+ }
825
+ if (claimIx.ix.accounts[0] !== lifecycleTaskPda) {
826
+ throw txMismatch(operation, "M2 verify bundle claim_task account [0] does not match expected task PDA");
827
+ }
828
+ if (claimIx.ix.accounts[3] !== expected.wallet ||
829
+ !inspected.signers.includes(claimIx.ix.accounts[3])) {
830
+ throw txMismatch(operation, "M2 verify bundle claim_task authority slot [3] does not match expected wallet signer");
831
+ }
832
+ // Validate optional companion set_payout_to
833
+ if (payoutIx) {
834
+ validateSetPayoutToInstruction(payoutIx, expected.wallet, lifecycleTaskPda, expectedPayoutPubkey, operation);
835
+ }
836
+ // Validate companion submit_work
837
+ if (submitIx.ix.accounts.length !== SHILLBOT_INSTRUCTION_SPECS.submit_work.minAccounts) {
838
+ throw txMismatch(operation, `M2 verify bundle submit_work must carry exact 4 accounts, got ${submitIx.ix.accounts.length}`);
839
+ }
840
+ if (submitIx.ix.accounts[0] !== lifecycleTaskPda) {
841
+ throw txMismatch(operation, "M2 verify bundle submit_work account [0] does not match expected task PDA");
842
+ }
843
+ if (submitIx.ix.accounts[3] !== expected.wallet ||
844
+ !inspected.signers.includes(submitIx.ix.accounts[3])) {
845
+ throw txMismatch(operation, "M2 verify bundle submit_work authority slot [3] does not match expected wallet signer");
846
+ }
847
+ if (submitIx.data.length < 12) {
848
+ throw txMismatch(operation, "M2 verify bundle submit_work instruction is truncated");
849
+ }
850
+ const submitContentLen = submitIx.data.readUInt32LE(8);
851
+ if (submitIx.data.length !== 12 + submitContentLen) {
852
+ throw txMismatch(operation, "M2 verify bundle submit_work content_id length mismatch");
853
+ }
854
+ if (expected.contentId !== undefined) {
855
+ const actualContent = submitIx.data.subarray(12, 12 + submitContentLen).toString("utf8");
856
+ if (actualContent !== expected.contentId) {
857
+ throw txMismatch(operation, "M2 verify bundle submit_work content_id differs from expectation");
858
+ }
859
+ }
860
+ return inspected;
861
+ }
710
862
  if ((isClaimLifecycle || isSubmitLifecycle) &&
711
863
  companions.length === 1 &&
712
864
  companions[0].spec.name === "set_payout_to") {
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const CLIENT_VERSION = "0.4.8";
1
+ export declare const CLIENT_VERSION = "0.4.10";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLIENT_VERSION = "0.4.8";
1
+ export const CLIENT_VERSION = "0.4.10";
@@ -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.8",
3
+ "version": "0.4.10",
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",