@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.
@@ -126,15 +126,27 @@ export class ShillbotApiClient {
126
126
  approveTask(id) {
127
127
  return this.post(`/tasks/${encodeURIComponent(id)}/approve`);
128
128
  }
129
- getVerificationData(id, network) {
130
- const suffix = network && network !== "mainnet" ? `?network=${encodeURIComponent(network)}` : "";
129
+ getVerificationData(id, network, attemptId) {
130
+ const params = [];
131
+ if (network && network !== "mainnet") {
132
+ params.push(`network=${encodeURIComponent(network)}`);
133
+ }
134
+ const trimmedAttempt = attemptId?.trim();
135
+ if (trimmedAttempt) {
136
+ params.push(`attempt_id=${encodeURIComponent(trimmedAttempt)}`);
137
+ }
138
+ const suffix = params.length > 0 ? `?${params.join("&")}` : "";
131
139
  return this.post(`/tasks/${encodeURIComponent(id)}/build-verify${suffix}`);
132
140
  }
133
- async buildVerify(id, opts) {
141
+ async buildVerify(id, optsOrAttemptId) {
142
+ const opts = typeof optsOrAttemptId === "string"
143
+ ? { attemptId: optsOrAttemptId }
144
+ : optsOrAttemptId;
134
145
  const mcpBaseUrl = (opts?.mcpBaseUrl ?? "https://mcp.swarm.tips").replace(/\/$/, "");
135
146
  const resolvedNetwork = opts?.network ?? (this.http.network === "devnet" ? "devnet" : "mainnet");
136
147
  const token = await this.http.getToken?.();
137
148
  const payer = opts?.payer ?? decodeJwtWallet(token);
149
+ const attemptId = opts?.attemptId?.trim() || undefined;
138
150
  const postMcpBuildVerify = async (payload) => {
139
151
  const mcpHttp = new HttpClient({
140
152
  baseUrl: mcpBaseUrl,
@@ -143,6 +155,59 @@ export class ShillbotApiClient {
143
155
  });
144
156
  return mcpHttp.post("/internal/build-verify-tx", payload);
145
157
  };
158
+ const normalizePrepared = (raw, fallbackTaskPda) => {
159
+ const resolvedTx = raw.transaction || raw.co_signed_transaction || "";
160
+ const resolvedPayoutTo = raw.payout_to ?? raw.required_payout_to ?? undefined;
161
+ return {
162
+ ...raw,
163
+ task_id: raw.task_id ?? id,
164
+ transaction: resolvedTx,
165
+ task_pda: raw.task_pda ?? fallbackTaskPda,
166
+ transaction_intent: raw.transaction_intent,
167
+ ...(resolvedPayoutTo ? { payout_to: resolvedPayoutTo } : {}),
168
+ };
169
+ };
170
+ const formatVerificationData = (vdata) => ({
171
+ task_id: vdata.task_id ?? id,
172
+ transaction: vdata.co_signed_transaction ?? "",
173
+ task_pda: vdata.task_pda,
174
+ ...(vdata.evm_verify_call !== undefined ? { evm_call: vdata.evm_verify_call } : {}),
175
+ ...(vdata.required_payout_to
176
+ ? {
177
+ payout_to: vdata.required_payout_to,
178
+ required_payout_to: vdata.required_payout_to,
179
+ }
180
+ : {}),
181
+ ...(vdata.advance_backer ? { advance_backer: vdata.advance_backer } : {}),
182
+ ...(vdata.co_signed_transaction
183
+ ? { co_signed_transaction: vdata.co_signed_transaction }
184
+ : {}),
185
+ ...(vdata.attempt_id ? { attempt_id: vdata.attempt_id } : {}),
186
+ ...(vdata.onboarded_advance_tx !== undefined
187
+ ? { onboarded_advance_tx: vdata.onboarded_advance_tx }
188
+ : {}),
189
+ });
190
+ // When targeting a specific M2 Open-Competition attemptId, call shillbot-api
191
+ // `POST /tasks/:id/build-verify?attempt_id=...` directly (returns `co_signed_transaction`
192
+ // + proof-gated `onboarded_advance_tx` + `required_payout_to` in 1 hop).
193
+ if (attemptId) {
194
+ const vdata = await this.getVerificationData(id, resolvedNetwork, attemptId);
195
+ if (vdata.evm_verify_call || vdata.co_signed_transaction) {
196
+ return formatVerificationData(vdata);
197
+ }
198
+ const fallback = await postMcpBuildVerify({
199
+ task_id: id,
200
+ ...(payer ? { payer } : {}),
201
+ network: resolvedNetwork,
202
+ attempt_id: attemptId,
203
+ task_pda: vdata.task_pda,
204
+ score: vdata.composite_score,
205
+ hash: vdata.verification_hash,
206
+ feed: vdata.switchboard_feed,
207
+ ...(vdata.global_state ? { global_state: vdata.global_state } : {}),
208
+ });
209
+ return normalizePrepared(fallback, vdata.task_pda);
210
+ }
146
211
  const oneHopBody = {
147
212
  task_id: id,
148
213
  network: resolvedNetwork,
@@ -150,13 +215,7 @@ export class ShillbotApiClient {
150
215
  };
151
216
  try {
152
217
  const direct = await postMcpBuildVerify(oneHopBody);
153
- return {
154
- ...direct,
155
- task_id: direct.task_id ?? id,
156
- transaction: direct.transaction,
157
- task_pda: direct.task_pda,
158
- transaction_intent: direct.transaction_intent,
159
- };
218
+ return normalizePrepared(direct);
160
219
  }
161
220
  catch (err) {
162
221
  if (!(err instanceof SwarmClientError) ||
@@ -166,14 +225,7 @@ export class ShillbotApiClient {
166
225
  }
167
226
  const vdata = await this.getVerificationData(id, resolvedNetwork);
168
227
  if (vdata.evm_verify_call || vdata.co_signed_transaction) {
169
- return {
170
- task_id: vdata.task_id ?? id,
171
- transaction: vdata.co_signed_transaction ?? "",
172
- task_pda: vdata.task_pda,
173
- ...(vdata.evm_verify_call !== undefined ? { evm_call: vdata.evm_verify_call } : {}),
174
- ...(vdata.required_payout_to ? { payout_to: vdata.required_payout_to } : {}),
175
- ...(vdata.advance_backer ? { advance_backer: vdata.advance_backer } : {}),
176
- };
228
+ return formatVerificationData(vdata);
177
229
  }
178
230
  const fallback = await postMcpBuildVerify({
179
231
  task_id: id,
@@ -185,13 +237,7 @@ export class ShillbotApiClient {
185
237
  feed: vdata.switchboard_feed,
186
238
  ...(vdata.global_state ? { global_state: vdata.global_state } : {}),
187
239
  });
188
- return {
189
- ...fallback,
190
- task_id: fallback.task_id ?? id,
191
- transaction: fallback.transaction,
192
- task_pda: fallback.task_pda ?? vdata.task_pda,
193
- transaction_intent: fallback.transaction_intent,
194
- };
240
+ return normalizePrepared(fallback, vdata.task_pda);
195
241
  }
196
242
  }
197
243
  buildFinalize(id) {
@@ -224,6 +270,126 @@ export const SHILLBOT_EVM_SELECTORS = {
224
270
  finalize: "0xcb26e65b", // finalizeTask(uint64)
225
271
  expire: "0x5e9f3d19", // expireTask(uint64)
226
272
  };
273
+ /** Canonical ABI for `ShillbotEscrow.sol` lifecycle functions (`P2-27`). */
274
+ export const SHILLBOT_ESCROW_ABI = [
275
+ {
276
+ type: "function",
277
+ name: "createTask",
278
+ stateMutability: "payable",
279
+ inputs: [
280
+ { name: "statementCommitment", type: "bytes32" },
281
+ { name: "policyId", type: "bytes32" },
282
+ { name: "verificationKind", type: "uint8" },
283
+ { name: "deadline", type: "uint64" },
284
+ { name: "requiresApproval", type: "bool" },
285
+ ],
286
+ outputs: [{ name: "taskId", type: "uint64" }],
287
+ },
288
+ {
289
+ type: "function",
290
+ name: "claimTask",
291
+ stateMutability: "nonpayable",
292
+ inputs: [{ name: "taskId", type: "uint64" }],
293
+ outputs: [],
294
+ },
295
+ {
296
+ type: "function",
297
+ name: "submitWork",
298
+ stateMutability: "nonpayable",
299
+ inputs: [
300
+ { name: "taskId", type: "uint64" },
301
+ { name: "contentIdHash", type: "bytes32" },
302
+ { name: "artifactHash", type: "bytes32" },
303
+ ],
304
+ outputs: [],
305
+ },
306
+ {
307
+ type: "function",
308
+ name: "approveTask",
309
+ stateMutability: "nonpayable",
310
+ inputs: [{ name: "taskId", type: "uint64" }],
311
+ outputs: [],
312
+ },
313
+ {
314
+ type: "function",
315
+ name: "verifyTaskAttested",
316
+ stateMutability: "nonpayable",
317
+ inputs: [
318
+ { name: "taskId", type: "uint64" },
319
+ { name: "score", type: "uint64" },
320
+ { name: "sig", type: "bytes" },
321
+ ],
322
+ outputs: [],
323
+ },
324
+ {
325
+ type: "function",
326
+ name: "finalizeTask",
327
+ stateMutability: "nonpayable",
328
+ inputs: [{ name: "taskId", type: "uint64" }],
329
+ outputs: [],
330
+ },
331
+ {
332
+ type: "function",
333
+ name: "expireTask",
334
+ stateMutability: "nonpayable",
335
+ inputs: [{ name: "taskId", type: "uint64" }],
336
+ outputs: [],
337
+ },
338
+ ];
339
+ const SHILLBOT_EVM_FUNCTION_NAMES = {
340
+ create: "createTask",
341
+ claim: "claimTask",
342
+ submit: "submitWork",
343
+ approve: "approveTask",
344
+ verify: "verifyTaskAttested",
345
+ finalize: "finalizeTask",
346
+ expire: "expireTask",
347
+ };
348
+ function parseExpectedUintArg(value, field) {
349
+ let parsed;
350
+ if (typeof value === "bigint") {
351
+ parsed = value;
352
+ }
353
+ else if (typeof value === "number") {
354
+ if (!Number.isSafeInteger(value) || value < 0) {
355
+ throw new SwarmClientError({
356
+ code: "INVALID_ARGUMENT",
357
+ operation: "shillbot.validatePreparedEvmCall",
358
+ message: `Expected ${field} must be a non-negative safe integer`,
359
+ });
360
+ }
361
+ parsed = BigInt(value);
362
+ }
363
+ else if (typeof value === "string" && /^\d+$/.test(value.trim())) {
364
+ parsed = BigInt(value.trim());
365
+ }
366
+ else {
367
+ throw new SwarmClientError({
368
+ code: "INVALID_ARGUMENT",
369
+ operation: "shillbot.validatePreparedEvmCall",
370
+ message: `Expected ${field} must be a non-negative integer`,
371
+ });
372
+ }
373
+ if (parsed < 0n || parsed > 0xffffffffffffffffn) {
374
+ throw new SwarmClientError({
375
+ code: "INVALID_ARGUMENT",
376
+ operation: "shillbot.validatePreparedEvmCall",
377
+ message: `Expected ${field} is out of uint64 range`,
378
+ });
379
+ }
380
+ return parsed;
381
+ }
382
+ function normalizeExpectedBytes32(value, field) {
383
+ const trimmed = value.trim();
384
+ if (!/^0x[0-9a-fA-F]{64}$/.test(trimmed)) {
385
+ throw new SwarmClientError({
386
+ code: "INVALID_ARGUMENT",
387
+ operation: "shillbot.validatePreparedEvmCall",
388
+ message: `Expected ${field} must be a 32-byte 0x-prefixed hex string`,
389
+ });
390
+ }
391
+ return trimmed.toLowerCase();
392
+ }
227
393
  export function normalizeEvmChainId(chain) {
228
394
  if (typeof chain === "number") {
229
395
  if (!Number.isSafeInteger(chain) || chain <= 0) {
@@ -250,9 +416,9 @@ export function normalizeEvmChainId(chain) {
250
416
  return trimmed;
251
417
  }
252
418
  /**
253
- * C10 fail-closed local validator for server-prepared EVM `ShillbotEscrow` calls.
254
- * Verifies canonical contract address for `chain`, 4-byte function selector for
255
- * `action`, and `value_wei <= maxValueWei` (strictly `0n` on non-create actions).
419
+ * C10 + P2-27 fail-closed local validator for server-prepared EVM `ShillbotEscrow` calls.
420
+ * Verifies canonical contract address for `chain`, 4-byte function selector and full ABI-decoded
421
+ * calldata arguments for `action`, and `value_wei <= maxValueWei` (strictly `0n` on non-create actions).
256
422
  */
257
423
  export function validatePreparedEvmCall(evmCall, expected) {
258
424
  if (!evmCall || typeof evmCall !== "object") {
@@ -309,7 +475,8 @@ export function validatePreparedEvmCall(evmCall, expected) {
309
475
  });
310
476
  }
311
477
  const expectedSelector = SHILLBOT_EVM_SELECTORS[expected.action];
312
- if (!expectedSelector) {
478
+ const expectedFnName = SHILLBOT_EVM_FUNCTION_NAMES[expected.action];
479
+ if (!expectedSelector || !expectedFnName) {
313
480
  throw new SwarmClientError({
314
481
  code: "INVALID_ARGUMENT",
315
482
  operation: "shillbot.validatePreparedEvmCall",
@@ -324,6 +491,205 @@ export function validatePreparedEvmCall(evmCall, expected) {
324
491
  message: `Function selector ${actualSelector} does not match expected ${expectedSelector} for ${expected.action}`,
325
492
  });
326
493
  }
494
+ // Decode calldata via a zero-dependency pure-TS canonical ABI decoder (so CLI and
495
+ // Solana-only consumers never require optional peerDependency `viem` at runtime)
496
+ // and verify exact canonical encoding + arguments (P2-27).
497
+ const argHex = raw.data.slice(10).toLowerCase();
498
+ const decodeFailure = (detail) => {
499
+ throw new SwarmClientError({
500
+ code: "TRANSACTION_MISMATCH",
501
+ operation: "shillbot.validatePreparedEvmCall",
502
+ message: `Prepared EVM call data failed ABI decoding for ${expectedFnName}: ${detail}`,
503
+ });
504
+ };
505
+ const readWordHex = (wordIdx) => argHex.slice(wordIdx * 64, (wordIdx + 1) * 64);
506
+ const readCanonicalUint = (wordIdx, maxBits, label) => {
507
+ const word = readWordHex(wordIdx);
508
+ const zeroPrefixChars = (256 - maxBits) / 4;
509
+ if (!/^0+$/.test(word.slice(0, zeroPrefixChars))) {
510
+ decodeFailure(`has non-canonical high bits for ${label}`);
511
+ }
512
+ return BigInt(`0x${word.slice(zeroPrefixChars)}`);
513
+ };
514
+ const readCanonicalBool = (wordIdx, label) => {
515
+ const word = readWordHex(wordIdx);
516
+ if (word === `${"0".repeat(63)}0`)
517
+ return false;
518
+ if (word === `${"0".repeat(63)}1`)
519
+ return true;
520
+ decodeFailure(`has non-canonical bool encoding for ${label}`);
521
+ return false;
522
+ };
523
+ const readBytes32 = (wordIdx) => `0x${readWordHex(wordIdx)}`;
524
+ if (expectedFnName === "createTask") {
525
+ if (argHex.length !== 5 * 64) {
526
+ decodeFailure("has invalid calldata length or trailing bytes");
527
+ }
528
+ const statementCommitment = readBytes32(0);
529
+ const policyId = readBytes32(1);
530
+ const verificationKind = Number(readCanonicalUint(2, 8, "verificationKind"));
531
+ const deadline = readCanonicalUint(3, 64, "deadline");
532
+ const requiresApproval = readCanonicalBool(4, "requiresApproval");
533
+ if (expected.statementCommitment !== undefined) {
534
+ const want = normalizeExpectedBytes32(expected.statementCommitment, "statementCommitment");
535
+ if (statementCommitment !== want) {
536
+ throw new SwarmClientError({
537
+ code: "TRANSACTION_MISMATCH",
538
+ operation: "shillbot.validatePreparedEvmCall",
539
+ message: `createTask statementCommitment ${statementCommitment} differs from expected ${want}`,
540
+ });
541
+ }
542
+ }
543
+ if (expected.policyId !== undefined) {
544
+ const want = normalizeExpectedBytes32(expected.policyId, "policyId");
545
+ if (policyId !== want) {
546
+ throw new SwarmClientError({
547
+ code: "TRANSACTION_MISMATCH",
548
+ operation: "shillbot.validatePreparedEvmCall",
549
+ message: `createTask policyId ${policyId} differs from expected ${want}`,
550
+ });
551
+ }
552
+ }
553
+ if (expected.verificationKind !== undefined) {
554
+ if (!Number.isInteger(expected.verificationKind) ||
555
+ expected.verificationKind < 0 ||
556
+ expected.verificationKind > 255) {
557
+ throw new SwarmClientError({
558
+ code: "INVALID_ARGUMENT",
559
+ operation: "shillbot.validatePreparedEvmCall",
560
+ message: "Expected verificationKind must be an integer in [0, 255]",
561
+ });
562
+ }
563
+ if (verificationKind !== expected.verificationKind) {
564
+ throw new SwarmClientError({
565
+ code: "TRANSACTION_MISMATCH",
566
+ operation: "shillbot.validatePreparedEvmCall",
567
+ message: `createTask verificationKind ${verificationKind} differs from expected ${expected.verificationKind}`,
568
+ });
569
+ }
570
+ }
571
+ if (expected.deadline !== undefined) {
572
+ const want = parseExpectedUintArg(expected.deadline, "deadline");
573
+ if (deadline !== want) {
574
+ throw new SwarmClientError({
575
+ code: "TRANSACTION_MISMATCH",
576
+ operation: "shillbot.validatePreparedEvmCall",
577
+ message: `createTask deadline ${deadline} differs from expected ${want}`,
578
+ });
579
+ }
580
+ }
581
+ if (expected.requiresApproval !== undefined && requiresApproval !== expected.requiresApproval) {
582
+ throw new SwarmClientError({
583
+ code: "TRANSACTION_MISMATCH",
584
+ operation: "shillbot.validatePreparedEvmCall",
585
+ message: `createTask requiresApproval ${requiresApproval} differs from expected ${expected.requiresApproval}`,
586
+ });
587
+ }
588
+ }
589
+ else if (expectedFnName === "claimTask" ||
590
+ expectedFnName === "approveTask" ||
591
+ expectedFnName === "finalizeTask" ||
592
+ expectedFnName === "expireTask") {
593
+ if (argHex.length !== 64) {
594
+ decodeFailure("has invalid calldata length or trailing bytes");
595
+ }
596
+ const taskId = readCanonicalUint(0, 64, "taskId");
597
+ if (expected.taskId !== undefined) {
598
+ const want = parseExpectedUintArg(expected.taskId, "taskId");
599
+ if (taskId !== want) {
600
+ throw new SwarmClientError({
601
+ code: "TRANSACTION_MISMATCH",
602
+ operation: "shillbot.validatePreparedEvmCall",
603
+ message: `${expectedFnName} taskId ${taskId} differs from expected ${want}`,
604
+ });
605
+ }
606
+ }
607
+ }
608
+ else if (expectedFnName === "submitWork") {
609
+ if (argHex.length !== 3 * 64) {
610
+ decodeFailure("has invalid calldata length or trailing bytes");
611
+ }
612
+ const taskId = readCanonicalUint(0, 64, "taskId");
613
+ const contentIdHash = readBytes32(1);
614
+ const artifactHash = readBytes32(2);
615
+ if (expected.taskId !== undefined) {
616
+ const want = parseExpectedUintArg(expected.taskId, "taskId");
617
+ if (taskId !== want) {
618
+ throw new SwarmClientError({
619
+ code: "TRANSACTION_MISMATCH",
620
+ operation: "shillbot.validatePreparedEvmCall",
621
+ message: `submitWork taskId ${taskId} differs from expected ${want}`,
622
+ });
623
+ }
624
+ }
625
+ if (expected.contentIdHash !== undefined) {
626
+ const want = normalizeExpectedBytes32(expected.contentIdHash, "contentIdHash");
627
+ if (contentIdHash !== want) {
628
+ throw new SwarmClientError({
629
+ code: "TRANSACTION_MISMATCH",
630
+ operation: "shillbot.validatePreparedEvmCall",
631
+ message: `submitWork contentIdHash ${contentIdHash} differs from expected ${want}`,
632
+ });
633
+ }
634
+ }
635
+ if (expected.artifactHash !== undefined) {
636
+ const want = normalizeExpectedBytes32(expected.artifactHash, "artifactHash");
637
+ if (artifactHash !== want) {
638
+ throw new SwarmClientError({
639
+ code: "TRANSACTION_MISMATCH",
640
+ operation: "shillbot.validatePreparedEvmCall",
641
+ message: `submitWork artifactHash ${artifactHash} differs from expected ${want}`,
642
+ });
643
+ }
644
+ }
645
+ }
646
+ else if (expectedFnName === "verifyTaskAttested") {
647
+ // Head: taskId (uint64), score (uint64), sig offset (0x60 = 96 bytes); Tail: length + padded bytes.
648
+ if (argHex.length < 4 * 64 || argHex.length % 64 !== 0) {
649
+ decodeFailure("has truncated or unaligned dynamic bytes calldata");
650
+ }
651
+ const taskId = readCanonicalUint(0, 64, "taskId");
652
+ const score = readCanonicalUint(1, 64, "score");
653
+ const sigOffset = BigInt(`0x${readWordHex(2)}`);
654
+ if (sigOffset !== 96n) {
655
+ decodeFailure("has non-canonical dynamic bytes offset");
656
+ }
657
+ const sigLenBig = BigInt(`0x${readWordHex(3)}`);
658
+ if (sigLenBig > 65536n) {
659
+ decodeFailure("has oversized sig byte length");
660
+ }
661
+ const sigLen = Number(sigLenBig);
662
+ const paddedBytes = Math.ceil(sigLen / 32) * 32;
663
+ const expectedHexLen = (4 * 32 + paddedBytes) * 2;
664
+ if (argHex.length !== expectedHexLen) {
665
+ decodeFailure("is non-canonical or has trailing bytes");
666
+ }
667
+ const sigHex = argHex.slice(4 * 64);
668
+ const paddingHex = sigHex.slice(sigLen * 2);
669
+ if (paddingHex.length > 0 && !/^0+$/.test(paddingHex)) {
670
+ decodeFailure("has non-zero trailing padding bytes in sig");
671
+ }
672
+ if (expected.taskId !== undefined) {
673
+ const want = parseExpectedUintArg(expected.taskId, "taskId");
674
+ if (taskId !== want) {
675
+ throw new SwarmClientError({
676
+ code: "TRANSACTION_MISMATCH",
677
+ operation: "shillbot.validatePreparedEvmCall",
678
+ message: `verifyTaskAttested taskId ${taskId} differs from expected ${want}`,
679
+ });
680
+ }
681
+ }
682
+ if (expected.score !== undefined) {
683
+ const want = parseExpectedUintArg(expected.score, "score");
684
+ if (score !== want) {
685
+ throw new SwarmClientError({
686
+ code: "TRANSACTION_MISMATCH",
687
+ operation: "shillbot.validatePreparedEvmCall",
688
+ message: `verifyTaskAttested score ${score} differs from expected ${want}`,
689
+ });
690
+ }
691
+ }
692
+ }
327
693
  let valueWei;
328
694
  try {
329
695
  const rawVal = raw.value_wei ?? raw.value ?? "0";
@@ -416,8 +782,8 @@ export function estimateSolanaNetworkFeeLamports(inspected, wallet) {
416
782
  return baseSignatureFeeLamports + priorityFeeLamports + additionalFeeLamports;
417
783
  }
418
784
  export function permittedPreparedProgramIds(action, network) {
419
- if (action === "verify") {
420
- return [SWITCHBOARD_PROGRAM_IDS[network], Secp256k1Program.programId.toBase58()];
785
+ if (action === "verify" && network === "devnet") {
786
+ return [SWITCHBOARD_PROGRAM_IDS.devnet, Secp256k1Program.programId.toBase58()];
421
787
  }
422
788
  if (action === "finalize") {
423
789
  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)