@swarm-tips/client 0.4.5 → 0.4.6

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.
package/SBOM.spdx.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "spdxVersion": "SPDX-2.3",
3
3
  "dataLicense": "CC0-1.0",
4
4
  "SPDXID": "SPDXRef-DOCUMENT",
5
- "name": "@swarm-tips/client-0.4.5",
6
- "documentNamespace": "https://swarm.tips/sbom/client/0.4.5",
5
+ "name": "@swarm-tips/client-0.4.6",
6
+ "documentNamespace": "https://swarm.tips/sbom/client/0.4.6",
7
7
  "creationInfo": {
8
- "created": "2026-11-15T20:57:08.285Z",
8
+ "created": "2026-11-17T04:19:23.433Z",
9
9
  "creators": [
10
10
  "Tool: sdk/client/scripts/generate-sbom.mjs",
11
11
  "Organization: Swarm Tips"
@@ -15,8 +15,8 @@
15
15
  {
16
16
  "name": "@swarm-tips/client",
17
17
  "SPDXID": "SPDXRef-Package",
18
- "versionInfo": "0.4.5",
19
- "downloadLocation": "https://www.npmjs.com/package/@swarm-tips/client/v/0.4.5",
18
+ "versionInfo": "0.4.6",
19
+ "downloadLocation": "https://www.npmjs.com/package/@swarm-tips/client/v/0.4.6",
20
20
  "filesAnalyzed": false,
21
21
  "licenseConcluded": "MIT",
22
22
  "licenseDeclared": "MIT"
package/dist/agent.d.ts CHANGED
@@ -107,12 +107,18 @@ export declare class SwarmAgent {
107
107
  buildVerify: (id: string) => Promise<PreparedTransactionResponse>;
108
108
  verifyAndExecute: (id: string, opts?: {
109
109
  connection?: Connection;
110
+ payoutTo?: string;
110
111
  }) => Promise<ExecutedTaskResult>;
111
112
  buildFinalize: (id: string) => Promise<PreparedTransactionResponse>;
112
113
  finalizeAndExecute: (id: string, opts?: {
113
114
  connection?: Connection;
114
115
  payoutTo?: string;
115
116
  }) => Promise<ExecutedTaskResult>;
117
+ buildExpire: (id: string) => Promise<PreparedTransactionResponse>;
118
+ expireAndExecute: (id: string, opts?: {
119
+ connection?: Connection;
120
+ chain?: string;
121
+ }) => Promise<ExecutedTaskResult>;
116
122
  nextAction: (task: Record<string, unknown>) => NextTaskAction;
117
123
  verifyVow: (urlOrJson: string | Record<string, unknown>, opts?: {
118
124
  rpcUrl?: string;
@@ -139,6 +145,11 @@ export declare class SwarmAgent {
139
145
  connection?: Connection;
140
146
  chain?: string;
141
147
  }) => Promise<ExecutedTaskResult>;
148
+ expire: (id: string) => Promise<PreparedTransactionResponse>;
149
+ expireAndExecute: (id: string, opts?: {
150
+ connection?: Connection;
151
+ chain?: string;
152
+ }) => Promise<ExecutedTaskResult>;
142
153
  };
143
154
  readonly inbox: {
144
155
  list: (opts?: InboxListOptions) => Promise<InboxListPage>;
@@ -185,6 +196,21 @@ export declare class SwarmAgent {
185
196
  constructor(options?: SwarmAgentOptions);
186
197
  private requireSigner;
187
198
  private executeClaimOrSubmit;
199
+ /**
200
+ * Resolve an authorized `payoutTo` pubkey (`P1-2` / `HIGH-02`):
201
+ * - If caller explicitly passed `explicitPayoutTo`, return it verbatim.
202
+ * - Otherwise, NEVER trust `advance_backer` from the API response alone:
203
+ * 1. Verify `advancePda(advance_backer, walletAddress) === prepared.payout_to`.
204
+ * 2. Fetch the PDA on-chain via `connection.getAccountInfo(derived, "confirmed")` and require:
205
+ * - account exists (`acct !== null && acct.lamports > 0`),
206
+ * - `acct.owner.equals(EXTENSION_CREDIT_PROGRAM_ID)`,
207
+ * - valid 113-byte `Advance` account (`sha256("account:Advance")[0..8]`) with
208
+ * `backer === advance_backer`, `recipient === walletAddress`, and
209
+ * `recouped_lamports < advance_lamports`.
210
+ * 3. On any mismatch or RPC error, return `undefined` so `validatePreparedTransaction`
211
+ * rejects any `set_payout_to` fail-closed.
212
+ */
213
+ private static resolveVerifiedAdvancePayoutTo;
188
214
  private executePreparedAction;
189
215
  private executeEvmAction;
190
216
  private executeSolanaAction;
package/dist/agent.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { Buffer } from "buffer";
2
- import { Connection, Transaction, VersionedTransaction } from "@solana/web3.js";
2
+ import { Connection, PublicKey, Transaction, VersionedTransaction } from "@solana/web3.js";
3
3
  import { WalletTokenManager } from "./auth/token-manager.js";
4
4
  import { CoordinationGameApiClient } from "./coordination-game/api.js";
5
5
  import { SwarmClientError } from "./errors.js";
6
6
  import { InboxClient, } from "./inbox/client.js";
7
7
  import { ShillbotApiClient, estimateSolanaNetworkFeeLamports, normalizeEvmChainId, signBroadcastPreparedTransaction, validatePreparedEvmCall, validatePreparedTransaction, } from "./shillbot/api.js";
8
- import { SHILLBOT_PROGRAM_ID, inspectTransaction, shillbotInstructionDiscriminator, } from "./shillbot/index.js";
8
+ import { EXTENSION_CREDIT_PROGRAM_ID, SHILLBOT_PROGRAM_ID, advancePda, decodeExtensionCreditAdvance, inspectTransaction, shillbotInstructionDiscriminator, } from "./shillbot/index.js";
9
9
  import { SwarmClient, } from "./swarm/index.js";
10
10
  import { verifyVow } from "./vow/verify.js";
11
11
  /** Default EVM gas price ceiling (`maxFeePerGas` = 50 gwei). */
@@ -218,6 +218,7 @@ export class SwarmAgent {
218
218
  const prepared = await self.tasks.buildVerify(id);
219
219
  return self.executePreparedAction(id, "verify", prepared, {
220
220
  connection: opts?.connection,
221
+ payoutTo: opts?.payoutTo,
221
222
  });
222
223
  },
223
224
  buildFinalize: (id) => self.shillbotClient.buildFinalize(id),
@@ -228,6 +229,14 @@ export class SwarmAgent {
228
229
  payoutTo: opts?.payoutTo,
229
230
  });
230
231
  },
232
+ buildExpire: (id) => self.shillbotClient.buildExpire(id),
233
+ async expireAndExecute(id, opts) {
234
+ const prepared = await self.tasks.buildExpire(id);
235
+ return self.executePreparedAction(id, "expire", prepared, {
236
+ connection: opts?.connection,
237
+ chain: opts?.chain,
238
+ });
239
+ },
231
240
  nextAction: (task) => SwarmAgent.adviseNextAction(task),
232
241
  async verifyVow(urlOrJson, opts) {
233
242
  const customAgentRpc = self.rpcUrl !== DEFAULT_SOLANA_RPC[self.network] ? self.rpcUrl : undefined;
@@ -290,6 +299,14 @@ export class SwarmAgent {
290
299
  chain: opts?.chain,
291
300
  });
292
301
  },
302
+ expire: (id) => self.shillbotClient.buildExpire(id),
303
+ async expireAndExecute(id, opts) {
304
+ const prepared = await self.shillbotClient.buildExpire(id);
305
+ return self.executePreparedAction(id, "expire", prepared, {
306
+ connection: opts?.connection,
307
+ chain: opts?.chain,
308
+ });
309
+ },
293
310
  };
294
311
  this.inbox = {
295
312
  list: (opts) => self.inboxClient.listMessages(opts),
@@ -362,6 +379,13 @@ export class SwarmAgent {
362
379
  throw err;
363
380
  }
364
381
  }
382
+ const connection = this.signer?.chain === "solana"
383
+ ? (opts?.connection ?? new Connection(this.rpcUrl, "confirmed"))
384
+ : opts?.connection;
385
+ let resolvedPayoutTo = connection && this.signer?.chain === "solana"
386
+ ? await SwarmAgent.resolveVerifiedAdvancePayoutTo(prepared, this.signer.address, connection, opts?.payoutTo)
387
+ : opts?.payoutTo;
388
+ let payoutToResolved = Boolean(connection && this.signer?.chain === "solana");
365
389
  // If Solana transaction is a gasless sponsor template (fee_payer !== wallet & unsigned by sponsor),
366
390
  // exchange it via POST /tasks/{id}/sponsor before signing locally.
367
391
  if (prepared.transaction &&
@@ -372,10 +396,11 @@ export class SwarmAgent {
372
396
  network: this.network,
373
397
  wallet: this.signer.address,
374
398
  taskPda: prepared.task_pda,
375
- ...(opts?.payoutTo !== undefined ? { payoutTo: opts.payoutTo } : {}),
399
+ ...(resolvedPayoutTo !== undefined ? { payoutTo: resolvedPayoutTo } : {}),
376
400
  });
377
401
  if (inspected.fee_payer !== this.signer.address &&
378
402
  !isFeePayerAlreadySigned(prepared.transaction)) {
403
+ const prevPayoutTo = prepared.payout_to;
379
404
  const sponsored = await this.shillbotClient.sponsorTask(id, {
380
405
  action,
381
406
  unsigned_transaction: prepared.transaction,
@@ -385,13 +410,69 @@ export class SwarmAgent {
385
410
  ...sponsored,
386
411
  task_pda: sponsored.task_pda ?? prepared.task_pda,
387
412
  };
413
+ if (opts?.payoutTo === undefined && prepared.payout_to !== prevPayoutTo) {
414
+ resolvedPayoutTo = undefined;
415
+ payoutToResolved = false;
416
+ }
388
417
  }
389
418
  }
390
419
  return this.executePreparedAction(id, action, prepared, {
391
- connection: opts?.connection,
392
- payoutTo: opts?.payoutTo,
420
+ connection,
421
+ payoutTo: resolvedPayoutTo,
422
+ payoutToResolved,
393
423
  });
394
424
  }
425
+ /**
426
+ * Resolve an authorized `payoutTo` pubkey (`P1-2` / `HIGH-02`):
427
+ * - If caller explicitly passed `explicitPayoutTo`, return it verbatim.
428
+ * - Otherwise, NEVER trust `advance_backer` from the API response alone:
429
+ * 1. Verify `advancePda(advance_backer, walletAddress) === prepared.payout_to`.
430
+ * 2. Fetch the PDA on-chain via `connection.getAccountInfo(derived, "confirmed")` and require:
431
+ * - account exists (`acct !== null && acct.lamports > 0`),
432
+ * - `acct.owner.equals(EXTENSION_CREDIT_PROGRAM_ID)`,
433
+ * - valid 113-byte `Advance` account (`sha256("account:Advance")[0..8]`) with
434
+ * `backer === advance_backer`, `recipient === walletAddress`, and
435
+ * `recouped_lamports < advance_lamports`.
436
+ * 3. On any mismatch or RPC error, return `undefined` so `validatePreparedTransaction`
437
+ * rejects any `set_payout_to` fail-closed.
438
+ */
439
+ static async resolveVerifiedAdvancePayoutTo(prepared, walletAddress, connection, explicitPayoutTo) {
440
+ if (explicitPayoutTo !== undefined) {
441
+ return explicitPayoutTo;
442
+ }
443
+ if (!walletAddress || !prepared.payout_to || !prepared.advance_backer) {
444
+ return undefined;
445
+ }
446
+ try {
447
+ const expectedBacker = new PublicKey(prepared.advance_backer);
448
+ const expectedRecipient = new PublicKey(walletAddress);
449
+ const derived = advancePda(expectedBacker, expectedRecipient);
450
+ if (derived.toBase58() !== prepared.payout_to) {
451
+ return undefined;
452
+ }
453
+ const acct = await connection.getAccountInfo(derived, "confirmed");
454
+ if (!acct || acct.lamports <= 0) {
455
+ return undefined;
456
+ }
457
+ if (!acct.owner.equals(EXTENSION_CREDIT_PROGRAM_ID)) {
458
+ return undefined;
459
+ }
460
+ const decoded = decodeExtensionCreditAdvance(acct.data);
461
+ if (!decoded) {
462
+ return undefined;
463
+ }
464
+ if (!decoded.backer.equals(expectedBacker) ||
465
+ !decoded.recipient.equals(expectedRecipient) ||
466
+ decoded.advanceLamports === 0n ||
467
+ decoded.recoupedLamports >= decoded.advanceLamports) {
468
+ return undefined;
469
+ }
470
+ return derived.toBase58();
471
+ }
472
+ catch {
473
+ return undefined;
474
+ }
475
+ }
395
476
  async executePreparedAction(id, action, prepared, opts) {
396
477
  const signer = this.requireSigner();
397
478
  if (prepared.evm_call && signer.chain === "evm") {
@@ -503,18 +584,21 @@ export class SwarmAgent {
503
584
  message: `Estimated Solana network fee ${estimatedFeeLamports} lamports exceeds maxNetworkFeeLamports (${this.maxNetworkFeeLamports})`,
504
585
  });
505
586
  }
587
+ const connection = opts.connection ?? new Connection(this.rpcUrl, "confirmed");
588
+ const resolvedPayoutTo = opts.payoutToResolved
589
+ ? opts.payoutTo
590
+ : await SwarmAgent.resolveVerifiedAdvancePayoutTo(prepared, signer.address, connection, opts.payoutTo);
506
591
  const expected = {
507
592
  action,
508
593
  network: this.network,
509
594
  wallet: signer.address,
510
595
  taskPda: prepared.task_pda,
511
- ...(opts.payoutTo !== undefined ? { payoutTo: opts.payoutTo } : {}),
596
+ ...(resolvedPayoutTo !== undefined ? { payoutTo: resolvedPayoutTo } : {}),
512
597
  ...(action === "create" && opts.expectedEscrowLamports !== undefined
513
598
  ? { escrowLamports: opts.expectedEscrowLamports }
514
599
  : {}),
515
600
  };
516
601
  validatePreparedTransaction(prepared.transaction, expected);
517
- const connection = opts.connection ?? new Connection(this.rpcUrl, "confirmed");
518
602
  const signature = await signBroadcastPreparedTransaction({
519
603
  connection,
520
604
  transaction: prepared.transaction,
package/dist/cli/swarm.js CHANGED
@@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url";
4
4
  import { SwarmAgent } from "../agent.js";
5
5
  import { SwarmClientError } from "../errors.js";
6
6
  import { VALID_TOPICS, isValidTopicId } from "../inbox/types.js";
7
- import { validatePreparedTransaction } from "../shillbot/api.js";
7
+ import { validatePreparedTransaction, } from "../shillbot/api.js";
8
8
  import { inspectTransaction } from "../shillbot/index.js";
9
9
  import { CLIENT_VERSION } from "../version.js";
10
10
  import { CliUsageError, assertNoSecretCliFlags, loadSignerFromCliOrEnv, } from "./keyfile.js";
@@ -106,6 +106,7 @@ Commands:
106
106
  tasks submit <id> --content <str> [--payout-to <pubkey>] [--no-exec]
107
107
  tasks verify <id> [--no-exec]
108
108
  tasks finalize <id> [--no-exec]
109
+ tasks expire <id> [--no-exec] (client escrow refund past claim/submit deadline or past submitted_at + verification_timeout)
109
110
  inbox list [--status pending|all] [--limit N]
110
111
  inbox open <msg_id...>
111
112
  inbox send <to_wallet> <body> [--thread <id>] [--intent <intent>]
@@ -114,7 +115,7 @@ Commands:
114
115
  topics read <open-challenge|subcontract|town-square> [--limit N]
115
116
  topics publish <open-challenge|subcontract|town-square> <body> [--ref <id>] [--reply-to <id>] [--intent <intent>]
116
117
  tx inspect [--tx <base64>]
117
- tx verify --action <claim|submit|verify|finalize|approve|create> --wallet <pubkey> [--task-pda <pda>] [--payout-to <pubkey>] [--tx <base64>]
118
+ tx verify --action <claim|submit|verify|finalize|expire|approve|create> --wallet <pubkey> [--task-pda <pda>] [--payout-to <pubkey>] [--expire-task-state <open|claimed|submitted|approved>] [--tx <base64>]
118
119
  vow-verify <file-or-url> [--rpc <url>]
119
120
 
120
121
  Global Options:
@@ -140,6 +141,13 @@ const VALID_ACTIONS = new Set([
140
141
  "approve",
141
142
  "verify",
142
143
  "finalize",
144
+ "expire",
145
+ ]);
146
+ const VALID_EXPIRE_STATES = new Set([
147
+ "open",
148
+ "claimed",
149
+ "submitted",
150
+ "approved",
143
151
  ]);
144
152
  function writeOutput(stdout, jsonMode, payload) {
145
153
  if (jsonMode) {
@@ -215,7 +223,7 @@ export async function runSwarmCli(argv, io = {}) {
215
223
  if (sub === "verify") {
216
224
  const rawAction = getStringFlag(flags, "--action");
217
225
  if (!rawAction || !VALID_ACTIONS.has(rawAction)) {
218
- throw new CliUsageError("Usage: swarm tx verify --action <claim|submit|verify|finalize|approve|create> --wallet <pubkey> [--task-pda <pda>] [--tx <base64>]");
226
+ throw new CliUsageError("Usage: swarm tx verify --action <claim|submit|verify|finalize|expire|approve|create> --wallet <pubkey> [--task-pda <pda>] [--tx <base64>]");
219
227
  }
220
228
  const wallet = getStringFlag(flags, "--wallet");
221
229
  if (!wallet) {
@@ -228,6 +236,12 @@ export async function runSwarmCli(argv, io = {}) {
228
236
  const taskPda = getStringFlag(flags, "--task-pda");
229
237
  const feePayer = getStringFlag(flags, "--fee-payer");
230
238
  const payoutTo = getStringFlag(flags, "--payout-to");
239
+ const rawExpireState = getStringFlag(flags, "--expire-task-state")?.trim().toLowerCase();
240
+ if (rawExpireState !== undefined &&
241
+ !VALID_EXPIRE_STATES.has(rawExpireState)) {
242
+ throw new CliUsageError(`Invalid --expire-task-state "${rawExpireState}". Expected open, claimed, submitted, or approved.`);
243
+ }
244
+ const expireTaskState = rawExpireState;
231
245
  const oracleAuthority = getStringFlag(flags, "--oracle-authority");
232
246
  const escrowLamports = getBigIntFlag(flags, "--escrow-lamports");
233
247
  try {
@@ -238,6 +252,7 @@ export async function runSwarmCli(argv, io = {}) {
238
252
  ...(taskPda ? { taskPda } : {}),
239
253
  ...(feePayer ? { feePayer } : {}),
240
254
  ...(payoutTo ? { payoutTo } : {}),
255
+ ...(expireTaskState ? { expireTaskState } : {}),
241
256
  ...(oracleAuthority ? { oracleAuthority } : {}),
242
257
  ...(escrowLamports !== undefined ? { escrowLamports } : {}),
243
258
  });
@@ -391,7 +406,17 @@ export async function runSwarmCli(argv, io = {}) {
391
406
  writeOutput(stdout, jsonMode, res);
392
407
  return 0;
393
408
  }
394
- throw new CliUsageError("Usage: swarm tasks <list|get|mine|earnings|next|claim|submit|verify|finalize> ...");
409
+ if (sub === "expire") {
410
+ const id = rest[0];
411
+ if (!id)
412
+ throw new CliUsageError("Usage: swarm tasks expire <task_id> [--no-exec]");
413
+ const res = noExec
414
+ ? await agent.tasks.buildExpire(id)
415
+ : await agent.tasks.expireAndExecute(id);
416
+ writeOutput(stdout, jsonMode, res);
417
+ return 0;
418
+ }
419
+ throw new CliUsageError("Usage: swarm tasks <list|get|mine|earnings|next|claim|submit|verify|finalize|expire> ...");
395
420
  }
396
421
  if (cmd === "inbox") {
397
422
  if (sub === "list") {
package/dist/index.d.ts CHANGED
@@ -6,7 +6,8 @@ export type { SwarmClientErrorCode, SwarmClientErrorOptions } from "./errors.js"
6
6
  export { DEFAULT_MAX_NETWORK_FEE_WEI, SwarmAgent, createSwarmAgent, extractCreateEscrowLamports, type ExecuteTaskOptions, type ExecutedTaskResult, type NextTaskAction, type SwarmAgentOptions, type SwarmNetwork, type TaskLifecycleStep, } from "./agent.js";
7
7
  export { WalletTokenManager, type TokenProvider, type WalletTokenManagerOptions, } from "./auth/token-manager.js";
8
8
  export { fromEvmPrivateKey, fromEvmWalletClient, fromSolanaKeypair, fromSolanaSecretKey, fromSolanaWalletAdapter, redactSigner, type EvmCallRequest, type EvmPrivateKeyOptions, type EvmSwarmSigner, type EvmTransactionSigner, type EvmWalletClientLike, type SolanaSwarmSigner, type SolanaWalletAdapterLike, type SwarmSigner, } from "./signer/index.js";
9
- export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_ESCROW_DEPLOYMENTS, SHILLBOT_EVM_SELECTORS, SHILLBOT_INSTRUCTION_SPECS, buildOnChainActionProofRef, estimateSolanaNetworkFeeLamports, formatOnChainActionAttributionMessage, normalizeEvmChainId, validateComputeBudgetInstruction, validateComputeBudgetInstructions, validatePreparedEvmCall, validatePreparedTransaction, verifyBuiltTransaction, type AuthoritySlotRule, type BuildOnChainActionProofRefParams, type BuildVerifyOptions, type PreparedEvmCallExpectation, type PreparedTransactionExpectation, type PreparedTransactionResponse, type ShillbotInstructionName, type ShillbotInstructionSpec, type ValidatedEvmCall, type VerificationDataResponse, type VerifyBuiltTransactionExpectation, } from "./shillbot/api.js";
9
+ export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_ESCROW_DEPLOYMENTS, SHILLBOT_EVM_SELECTORS, SHILLBOT_INSTRUCTION_SPECS, buildOnChainActionProofRef, estimateSolanaNetworkFeeLamports, formatOnChainActionAttributionMessage, normalizeEvmChainId, validateComputeBudgetInstruction, validateComputeBudgetInstructions, validatePreparedEvmCall, validatePreparedTransaction, verifyBuiltTransaction, type AuthoritySlotRule, type BuildOnChainActionProofRefParams, type BuildVerifyOptions, type ExpireTaskState, type PreparedEvmCallExpectation, type PreparedTransactionExpectation, type PreparedTransactionResponse, type ShillbotInstructionName, type ShillbotInstructionSpec, type ValidatedEvmCall, type VerificationDataResponse, type VerifyBuiltTransactionExpectation, } from "./shillbot/api.js";
10
+ export { ADVANCE_ACCOUNT_SPACE, EXTENSION_CREDIT_PROGRAM_ID, advanceAccountDiscriminator, advancePda, decodeExtensionCreditAdvance, type DecodedAdvanceAccount, } from "./shillbot/index.js";
10
11
  export { VALID_TOPICS, isValidTopicId, type TopicId, } from "./inbox/types.js";
11
12
  export { DEFAULT_MAX_VOW_BYTES, fetchVowAttestationJson, validateVowUrl, verifyVow, type FetchVowOptions, type VerifyVowOptions, } from "./vow/verify.js";
12
13
  export { OPENAPI_SERVERS, OPENAPI_VERSION, type OpenApiOperationId, type OpenApiOperations, type OpenApiPaths, type OpenApiSchemas, type OpenApiServerUrl, } from "./generated/openapi.js";
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ export { DEFAULT_MAX_NETWORK_FEE_WEI, SwarmAgent, createSwarmAgent, extractCreat
6
6
  export { WalletTokenManager, } from "./auth/token-manager.js";
7
7
  export { fromEvmPrivateKey, fromEvmWalletClient, fromSolanaKeypair, fromSolanaSecretKey, fromSolanaWalletAdapter, redactSigner, } from "./signer/index.js";
8
8
  export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_ESCROW_DEPLOYMENTS, SHILLBOT_EVM_SELECTORS, SHILLBOT_INSTRUCTION_SPECS, buildOnChainActionProofRef, estimateSolanaNetworkFeeLamports, formatOnChainActionAttributionMessage, normalizeEvmChainId, validateComputeBudgetInstruction, validateComputeBudgetInstructions, validatePreparedEvmCall, validatePreparedTransaction, verifyBuiltTransaction, } from "./shillbot/api.js";
9
+ export { ADVANCE_ACCOUNT_SPACE, EXTENSION_CREDIT_PROGRAM_ID, advanceAccountDiscriminator, advancePda, decodeExtensionCreditAdvance, } from "./shillbot/index.js";
9
10
  export { VALID_TOPICS, isValidTopicId, } from "./inbox/types.js";
10
11
  export { DEFAULT_MAX_VOW_BYTES, fetchVowAttestationJson, validateVowUrl, verifyVow, } from "./vow/verify.js";
11
12
  export { OPENAPI_SERVERS, OPENAPI_VERSION, } from "./generated/openapi.js";
@@ -9,6 +9,8 @@ export interface PreparedTransactionResponse {
9
9
  task_pda?: string;
10
10
  transaction_intent?: TransactionIntent;
11
11
  evm_call?: unknown;
12
+ payout_to?: string;
13
+ advance_backer?: string;
12
14
  }
13
15
  export interface VerificationDataResponse {
14
16
  task_id?: string;
@@ -17,6 +19,11 @@ export interface VerificationDataResponse {
17
19
  verification_hash: string;
18
20
  global_state?: string;
19
21
  switchboard_feed: string;
22
+ required_payout_to?: string;
23
+ advance_backer?: string;
24
+ verification_kind?: number;
25
+ co_signed_transaction?: string;
26
+ evm_verify_call?: unknown;
20
27
  }
21
28
  export interface BuildVerifyOptions {
22
29
  payer?: string;
@@ -68,10 +75,11 @@ export declare class ShillbotApiClient {
68
75
  getVerificationData(id: string, network?: "mainnet" | "devnet"): Promise<VerificationDataResponse>;
69
76
  buildVerify(id: string, opts?: BuildVerifyOptions): Promise<PreparedTransactionResponse>;
70
77
  buildFinalize(id: string): Promise<PreparedTransactionResponse>;
78
+ buildExpire(id: string): Promise<PreparedTransactionResponse>;
71
79
  confirmTask<TResponse = unknown>(id: string, body: ConfirmTransactionRequest): Promise<TResponse>;
72
80
  }
73
- import { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, type AuthoritySlotRule, type ShillbotInstructionName, type ShillbotInstructionSpec, type VerifyBuiltTransactionExpectation } from "./verify-tx.js";
74
- export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, type AuthoritySlotRule, type ShillbotInstructionName, type ShillbotInstructionSpec, type VerifyBuiltTransactionExpectation, };
81
+ import { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, type AuthoritySlotRule, type ExpireTaskState, type ShillbotInstructionName, type ShillbotInstructionSpec, type VerifyBuiltTransactionExpectation } from "./verify-tx.js";
82
+ export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, type AuthoritySlotRule, type ExpireTaskState, type ShillbotInstructionName, type ShillbotInstructionSpec, type VerifyBuiltTransactionExpectation, };
75
83
  export interface PreparedTransactionExpectation {
76
84
  action: Action;
77
85
  network: "mainnet" | "devnet";
@@ -79,6 +87,7 @@ export interface PreparedTransactionExpectation {
79
87
  taskPda?: string;
80
88
  feePayer?: string;
81
89
  payoutTo?: string;
90
+ expireTaskState?: ExpireTaskState;
82
91
  oracleAuthority?: string;
83
92
  escrowLamports?: bigint;
84
93
  contentId?: string;
@@ -2,7 +2,7 @@ import { Buffer } from "buffer";
2
2
  import { ComputeBudgetProgram, Secp256k1Program, } from "@solana/web3.js";
3
3
  import { HttpClient } from "../http.js";
4
4
  import { SwarmClientError } from "../errors.js";
5
- import { signAndBroadcast, } from "./index.js";
5
+ import { EXTENSION_CREDIT_PROGRAM_ID, signAndBroadcast, } from "./index.js";
6
6
  function decodeJwtWallet(token) {
7
7
  if (!token)
8
8
  return undefined;
@@ -139,6 +139,16 @@ export class ShillbotApiClient {
139
139
  throw err;
140
140
  }
141
141
  const vdata = await this.getVerificationData(id, resolvedNetwork);
142
+ if (vdata.evm_verify_call || vdata.co_signed_transaction) {
143
+ return {
144
+ task_id: vdata.task_id ?? id,
145
+ transaction: vdata.co_signed_transaction ?? "",
146
+ task_pda: vdata.task_pda,
147
+ ...(vdata.evm_verify_call !== undefined ? { evm_call: vdata.evm_verify_call } : {}),
148
+ ...(vdata.required_payout_to ? { payout_to: vdata.required_payout_to } : {}),
149
+ ...(vdata.advance_backer ? { advance_backer: vdata.advance_backer } : {}),
150
+ };
151
+ }
142
152
  const fallback = await postMcpBuildVerify({
143
153
  task_id: id,
144
154
  ...(payer ? { payer } : {}),
@@ -161,6 +171,9 @@ export class ShillbotApiClient {
161
171
  buildFinalize(id) {
162
172
  return this.post(`/tasks/${encodeURIComponent(id)}/build-finalize`);
163
173
  }
174
+ buildExpire(id) {
175
+ return this.post(`/tasks/${encodeURIComponent(id)}/build-expire`);
176
+ }
164
177
  confirmTask(id, body) {
165
178
  return this.post(`/tasks/${encodeURIComponent(id)}/confirm`, body);
166
179
  }
@@ -183,6 +196,7 @@ export const SHILLBOT_EVM_SELECTORS = {
183
196
  approve: "0x97312249", // approveTask(uint64)
184
197
  verify: "0x3bae608b", // verifyTaskAttested(uint64,uint64,bytes)
185
198
  finalize: "0xcb26e65b", // finalizeTask(uint64)
199
+ expire: "0x5e9f3d19", // expireTask(uint64)
186
200
  };
187
201
  export function normalizeEvmChainId(chain) {
188
202
  if (typeof chain === "number") {
@@ -376,9 +390,13 @@ export function estimateSolanaNetworkFeeLamports(inspected, wallet) {
376
390
  return baseSignatureFeeLamports + priorityFeeLamports + additionalFeeLamports;
377
391
  }
378
392
  export function permittedPreparedProgramIds(action, network) {
379
- return action === "verify"
380
- ? [SWITCHBOARD_PROGRAM_IDS[network], Secp256k1Program.programId.toBase58()]
381
- : [];
393
+ if (action === "verify") {
394
+ return [SWITCHBOARD_PROGRAM_IDS[network], Secp256k1Program.programId.toBase58()];
395
+ }
396
+ if (action === "finalize") {
397
+ return [EXTENSION_CREDIT_PROGRAM_ID.toBase58()];
398
+ }
399
+ return [];
382
400
  }
383
401
  /**
384
402
  * Fail-closed local validation for a server-prepared Shillbot transaction.
@@ -1,8 +1,31 @@
1
- import { Connection, Transaction, TransactionInstruction, VersionedTransaction, type BlockhashWithExpiryBlockHeight } from "@solana/web3.js";
1
+ import { Buffer } from "buffer";
2
+ import { Connection, PublicKey, Transaction, TransactionInstruction, VersionedTransaction, type BlockhashWithExpiryBlockHeight } from "@solana/web3.js";
2
3
  export { COORDINATION_GAME_IDL, COORDINATION_GAME_PROGRAM_ID, SHILLBOT_IDL, SHILLBOT_PROGRAM_ID, agentStatePda, buildShillbotInstruction, clientStatePda, globalStatePda, shillbotInstructionDiscriminator, taskPda, } from "../contracts/index.js";
3
4
  export type { BuildShillbotInstructionRequest, CoordinationGame, Shillbot, } from "../contracts/index.js";
4
5
  export declare const SCHEMA_VERSION: "swarm.shillbot.transaction-intent/v1";
5
- export type Action = "create" | "claim" | "submit" | "approve" | "verify" | "finalize";
6
+ export declare const EXTENSION_CREDIT_PROGRAM_ID: PublicKey;
7
+ export declare function advancePda(backer: PublicKey | string, agent: PublicKey | string): PublicKey;
8
+ export declare function routeAndRecoupDiscriminator(): Buffer;
9
+ /** Exact Anchor account byte length of `extension-credit` `Advance` (`8 + 32 + 32 + 8 + 8 + 8 + 1 + 16 = 113`). */
10
+ export declare const ADVANCE_ACCOUNT_SPACE = 113;
11
+ export declare function advanceAccountDiscriminator(): Buffer;
12
+ export interface DecodedAdvanceAccount {
13
+ backer: PublicKey;
14
+ recipient: PublicKey;
15
+ advanceLamports: bigint;
16
+ recoupedLamports: bigint;
17
+ }
18
+ /**
19
+ * Decode an on-chain `extension-credit` `Advance` account (`programs/extension-credit/src/state/advance.rs`).
20
+ * Returns `null` if the length (`113` bytes) or 8-byte Anchor discriminator (`account:Advance`) does not match.
21
+ */
22
+ export declare function decodeExtensionCreditAdvance(data: Uint8Array): DecodedAdvanceAccount | null;
23
+ export declare function buildRouteAndRecoupInstruction(accounts: {
24
+ advance: PublicKey | string;
25
+ backer: PublicKey | string;
26
+ recipient: PublicKey | string;
27
+ }): TransactionInstruction;
28
+ export type Action = "create" | "claim" | "submit" | "approve" | "verify" | "finalize" | "expire";
6
29
  export type Risk = "earn" | "spend" | "escrow_control";
7
30
  export type Network = "mainnet" | "devnet";
8
31
  export type TransactionVersion = "legacy" | "v0";
@@ -85,8 +108,22 @@ export interface FinalizeBuild extends CommonBuild {
85
108
  agent: string;
86
109
  client: string;
87
110
  treasury: string;
111
+ /** Optional true agent pubkey whose `AgentState` PDA is appended as remaining account `[5]`. */
112
+ agentStateOwner?: string;
113
+ /** Optional `extension-credit` backer pubkey to bundle atomic `route_and_recoup` after `finalize_task`. */
114
+ recoupBacker?: string;
115
+ /** Optional `extension-credit` recipient pubkey (defaults to `agentStateOwner ?? wallet`) for `route_and_recoup`. */
116
+ recoupRecipient?: string;
117
+ }
118
+ export interface ExpireBuild extends CommonBuild {
119
+ action: "expire";
120
+ taskPda: string;
121
+ /** Campaign client receiving the escrow refund (defaults to `wallet`). */
122
+ client?: string;
123
+ /** Optional claimed agent pubkey whose `AgentState` PDA is appended as remaining account `[3]`. */
124
+ claimedAgent?: string;
88
125
  }
89
- export type BuildRequest = CreateBuild | ClaimBuild | ApproveBuild | SubmitBuild | VerifyBuild | FinalizeBuild;
126
+ export type BuildRequest = CreateBuild | ClaimBuild | ApproveBuild | SubmitBuild | VerifyBuild | FinalizeBuild | ExpireBuild;
90
127
  export declare function buildInstruction(request: BuildRequest): TransactionInstruction;
91
128
  export declare function intentDigest(intent: Omit<TransactionIntent, "digest">): string;
92
129
  export declare function buildTransaction(request: BuildRequest): BuiltTransaction;
@@ -110,6 +147,7 @@ export declare const buildSubmit: (request: Omit<SubmitBuild, "action">) => Buil
110
147
  export declare const buildApprove: (request: Omit<ApproveBuild, "action">) => BuiltTransaction;
111
148
  export declare const buildVerify: (request: Omit<VerifyBuild, "action">) => BuiltTransaction;
112
149
  export declare const buildFinalize: (request: Omit<FinalizeBuild, "action">) => BuiltTransaction;
150
+ export declare const buildExpire: (request: Omit<ExpireBuild, "action">) => BuiltTransaction;
113
151
  export { buildSwitchboardCrankAndVerify } from "./switchboard.js";
114
152
  export type { SwitchboardVerifyRequest } from "./switchboard.js";
115
153
  export * from "./payout-oracle.js";
@@ -2,9 +2,60 @@ import { Buffer } from "buffer";
2
2
  import { sha256 } from "js-sha256";
3
3
  import { BN, SHILLBOT_PROGRAM_ID, agentStatePda, buildShillbotInstruction, clientStatePda, globalStatePda, shillbotInstructionDiscriminator, taskPda, } from "../contracts/index.js";
4
4
  import bs58 from "bs58";
5
- import { PublicKey, Transaction, TransactionMessage, VersionedTransaction, } from "@solana/web3.js";
5
+ import { PublicKey, Transaction, TransactionInstruction, TransactionMessage, VersionedTransaction, } from "@solana/web3.js";
6
6
  export { COORDINATION_GAME_IDL, COORDINATION_GAME_PROGRAM_ID, SHILLBOT_IDL, SHILLBOT_PROGRAM_ID, agentStatePda, buildShillbotInstruction, clientStatePda, globalStatePda, shillbotInstructionDiscriminator, taskPda, } from "../contracts/index.js";
7
7
  export const SCHEMA_VERSION = "swarm.shillbot.transaction-intent/v1";
8
+ export const EXTENSION_CREDIT_PROGRAM_ID = new PublicKey("Ec628D7GH3hwgnVf1gqrUh83qcZprYjmTzvtdHHEr7oh");
9
+ export function advancePda(backer, agent) {
10
+ return PublicKey.findProgramAddressSync([
11
+ Buffer.from("advance"),
12
+ new PublicKey(backer).toBuffer(),
13
+ new PublicKey(agent).toBuffer(),
14
+ ], EXTENSION_CREDIT_PROGRAM_ID)[0];
15
+ }
16
+ export function routeAndRecoupDiscriminator() {
17
+ return Buffer.from(sha256.arrayBuffer("global:route_and_recoup")).subarray(0, 8);
18
+ }
19
+ /** Exact Anchor account byte length of `extension-credit` `Advance` (`8 + 32 + 32 + 8 + 8 + 8 + 1 + 16 = 113`). */
20
+ export const ADVANCE_ACCOUNT_SPACE = 113;
21
+ export function advanceAccountDiscriminator() {
22
+ return Buffer.from(sha256.arrayBuffer("account:Advance")).subarray(0, 8);
23
+ }
24
+ /**
25
+ * Decode an on-chain `extension-credit` `Advance` account (`programs/extension-credit/src/state/advance.rs`).
26
+ * Returns `null` if the length (`113` bytes) or 8-byte Anchor discriminator (`account:Advance`) does not match.
27
+ */
28
+ export function decodeExtensionCreditAdvance(data) {
29
+ const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
30
+ if (buf.length !== ADVANCE_ACCOUNT_SPACE) {
31
+ return null;
32
+ }
33
+ if (!buf.subarray(0, 8).equals(advanceAccountDiscriminator())) {
34
+ return null;
35
+ }
36
+ const backer = new PublicKey(buf.subarray(8, 40));
37
+ const recipient = new PublicKey(buf.subarray(40, 72));
38
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
39
+ const advanceLamports = view.getBigUint64(72, true);
40
+ const recoupedLamports = view.getBigUint64(80, true);
41
+ return {
42
+ backer,
43
+ recipient,
44
+ advanceLamports,
45
+ recoupedLamports,
46
+ };
47
+ }
48
+ export function buildRouteAndRecoupInstruction(accounts) {
49
+ return new TransactionInstruction({
50
+ programId: EXTENSION_CREDIT_PROGRAM_ID,
51
+ keys: [
52
+ { pubkey: new PublicKey(accounts.advance), isSigner: false, isWritable: true },
53
+ { pubkey: new PublicKey(accounts.backer), isSigner: false, isWritable: true },
54
+ { pubkey: new PublicKey(accounts.recipient), isSigner: false, isWritable: true },
55
+ ],
56
+ data: routeAndRecoupDiscriminator(),
57
+ });
58
+ }
8
59
  export function buildInstruction(request) {
9
60
  const wallet = new PublicKey(request.wallet);
10
61
  if (request.action === "create") {
@@ -77,8 +128,26 @@ export function buildInstruction(request) {
77
128
  },
78
129
  });
79
130
  }
131
+ if (request.action === "expire") {
132
+ const ix = buildShillbotInstruction({
133
+ name: "expire_task",
134
+ accounts: {
135
+ task,
136
+ global_state: globalStatePda(),
137
+ client: request.client ?? wallet,
138
+ },
139
+ });
140
+ if (request.claimedAgent) {
141
+ ix.keys.push({
142
+ pubkey: agentStatePda(new PublicKey(request.claimedAgent)),
143
+ isSigner: false,
144
+ isWritable: true,
145
+ });
146
+ }
147
+ return ix;
148
+ }
80
149
  const finalize = request;
81
- return buildShillbotInstruction({
150
+ const ix = buildShillbotInstruction({
82
151
  name: "finalize_task",
83
152
  accounts: {
84
153
  task,
@@ -88,6 +157,14 @@ export function buildInstruction(request) {
88
157
  treasury: finalize.treasury,
89
158
  },
90
159
  });
160
+ if (finalize.agentStateOwner) {
161
+ ix.keys.push({
162
+ pubkey: agentStatePda(new PublicKey(finalize.agentStateOwner)),
163
+ isSigner: false,
164
+ isWritable: true,
165
+ });
166
+ }
167
+ return ix;
91
168
  }
92
169
  function payoutInstruction(request) {
93
170
  if (!request.payoutTo)
@@ -115,7 +192,7 @@ export function intentDigest(intent) {
115
192
  function actionRisk(action) {
116
193
  if (action === "create")
117
194
  return "spend";
118
- if (action === "approve")
195
+ if (action === "approve" || action === "expire")
119
196
  return "escrow_control";
120
197
  return "earn";
121
198
  }
@@ -146,10 +223,20 @@ export function buildTransaction(request) {
146
223
  ? request.crankInstructions
147
224
  : request.action === "claim"
148
225
  ? [payoutInstruction(request)].filter((ix) => ix !== undefined)
149
- : [];
150
- // set_payout_to authorizes against task.agent, which claim_task establishes.
151
- // Keep the two operations atomic, but execute the claim first.
152
- const instructions = request.action === "claim"
226
+ : request.action === "finalize" && request.recoupBacker
227
+ ? [
228
+ buildRouteAndRecoupInstruction({
229
+ advance: request.agent,
230
+ backer: request.recoupBacker,
231
+ recipient: request.recoupRecipient ??
232
+ request.agentStateOwner ??
233
+ request.wallet,
234
+ }),
235
+ ]
236
+ : [];
237
+ // set_payout_to authorizes against task.agent (after claim_task), and
238
+ // route_and_recoup sweeps after finalize_task lands escrow in the Advance PDA.
239
+ const instructions = request.action === "claim" || request.action === "finalize"
153
240
  ? [lifecycle, ...companions]
154
241
  : [...companions, lifecycle];
155
242
  const unsignedTx = serializeUnsigned(payer, request.recentBlockhash, instructions, request.version ?? (request.action === "verify" ? "v0" : "legacy"));
@@ -269,12 +356,14 @@ export function verifyIntent(encoded, intent) {
269
356
  if (!inspected.signers.includes(intent.wallet))
270
357
  throw new Error("wallet is not a required signer");
271
358
  const shillbotProgramId = SHILLBOT_PROGRAM_ID.toBase58();
359
+ const extensionCreditId = EXTENSION_CREDIT_PROGRAM_ID.toBase58();
272
360
  const allowedPrograms = new Set([
273
361
  shillbotProgramId,
274
362
  COMPUTE_BUDGET_PROGRAM_ID,
275
363
  ...(intent.action === "verify"
276
364
  ? [SWITCHBOARD_PROGRAM_IDS[intent.network], SECP256K1_PROGRAM_ID]
277
365
  : []),
366
+ ...(intent.action === "finalize" ? [extensionCreditId] : []),
278
367
  ]);
279
368
  for (const ix of inspected.instructions) {
280
369
  if (!allowedPrograms.has(ix.program_id)) {
@@ -313,6 +402,23 @@ export function verifyIntent(encoded, intent) {
313
402
  .toString("hex"))) {
314
403
  throw new Error("unexpected Shillbot companion instruction");
315
404
  }
405
+ const creditInstructions = inspected.instructions.filter((ix) => ix.program_id === extensionCreditId);
406
+ if (creditInstructions.length > 0) {
407
+ if (intent.action !== "finalize" || creditInstructions.length !== 1) {
408
+ throw new Error("unexpected extension-credit companion instruction");
409
+ }
410
+ const creditIx = creditInstructions[0];
411
+ if (inspected.instructions.indexOf(creditIx) <= lifecycleIndex) {
412
+ throw new Error("route_and_recoup must follow finalize_task");
413
+ }
414
+ const creditData = Buffer.from(creditIx.data_base64, "base64");
415
+ if (creditData.length !== 8 ||
416
+ !creditData.equals(routeAndRecoupDiscriminator()) ||
417
+ creditIx.accounts.length !== 3 ||
418
+ creditIx.accounts[0] !== intent.accounts[2]) {
419
+ throw new Error("malformed route_and_recoup companion instruction");
420
+ }
421
+ }
316
422
  if (lifecycle[0].accounts.join(",") !== intent.accounts.join(",")) {
317
423
  throw new Error("lifecycle accounts differ from intent");
318
424
  }
@@ -371,6 +477,7 @@ export const buildSubmit = (request) => buildTransaction({ ...request, action: "
371
477
  export const buildApprove = (request) => buildTransaction({ ...request, action: "approve" });
372
478
  export const buildVerify = (request) => buildTransaction({ ...request, action: "verify" });
373
479
  export const buildFinalize = (request) => buildTransaction({ ...request, action: "finalize" });
480
+ export const buildExpire = (request) => buildTransaction({ ...request, action: "expire" });
374
481
  export { buildSwitchboardCrankAndVerify } from "./switchboard.js";
375
482
  export * from "./payout-oracle.js";
376
483
  import { validateComputeBudgetInstructions } from "./verify-tx.js";
@@ -19,6 +19,7 @@ export interface ShillbotInstructionSpec {
19
19
  * derived directly from `programs/shillbot/src/instructions/*.rs` and `shillbot.json` IDL.
20
20
  */
21
21
  export declare const SHILLBOT_INSTRUCTION_SPECS: Readonly<Record<ShillbotInstructionName, ShillbotInstructionSpec>>;
22
+ export type ExpireTaskState = "open" | "claimed" | "submitted" | "approved";
22
23
  export interface VerifyBuiltTransactionExpectation {
23
24
  action?: Action;
24
25
  instructionName?: ShillbotInstructionName;
@@ -32,6 +33,12 @@ export interface VerifyBuiltTransactionExpectation {
32
33
  * `set_payout_to` instruction is rejected fail-closed.
33
34
  */
34
35
  payoutTo?: string;
36
+ /**
37
+ * Optional task state when validating `expire_task`: enforces exact 3 accounts
38
+ * `[task, global_state, client]` on `open | submitted | approved` (rejecting the
39
+ * 4-account `AgentState` form) and exact 4 accounts on `claimed`.
40
+ */
41
+ expireTaskState?: ExpireTaskState;
35
42
  oracleAuthority?: string;
36
43
  escrowLamports?: bigint;
37
44
  contentId?: string;
@@ -52,7 +59,8 @@ export declare function validateComputeBudgetInstructions(instructions: Transact
52
59
  * Strict fail-closed local validator for built or server-prepared Shillbot Solana transactions.
53
60
  *
54
61
  * Enforces:
55
- * - Allowed program IDs (Shillbot + ComputeBudget, plus Switchboard + Secp256k1 only on `verify`).
62
+ * - Allowed program IDs (Shillbot + ComputeBudget, Switchboard + Secp256k1 on `verify` / score-0 reopen,
63
+ * and `extension-credit` `route_and_recoup` strictly on `finalize`).
56
64
  * - Full loop validation of all `ComputeBudget` instructions (no early return on `RequestHeapFrame`),
57
65
  * capping `SetComputeUnitPrice <= MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS` (`100_000` micro-lamports/CU).
58
66
  * - Exact Anchor account-index positions for `task` PDA and authority signer slots per discriminator.
@@ -2,7 +2,7 @@ import { Buffer } from "buffer";
2
2
  import { ComputeBudgetProgram, PublicKey, Secp256k1Program } from "@solana/web3.js";
3
3
  import { SHILLBOT_PROGRAM_ID, shillbotInstructionDiscriminator } from "../contracts/index.js";
4
4
  import { SwarmClientError } from "../errors.js";
5
- import { inspectTransaction, } from "./index.js";
5
+ import { EXTENSION_CREDIT_PROGRAM_ID, advancePda, inspectTransaction, routeAndRecoupDiscriminator, } from "./index.js";
6
6
  /** Default maximum allowed Solana priority fee price per compute unit (`100_000` micro-lamports/CU). */
7
7
  export const MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 100000n;
8
8
  /** Solana runtime ceiling for `ComputeBudget::SetComputeUnitLimit` (`1_400_000` CUs). */
@@ -327,6 +327,8 @@ function allowedInstructionNamesForAction(action) {
327
327
  return ["verify_task", "verify_task_attested"];
328
328
  case "finalize":
329
329
  return ["finalize_task"];
330
+ case "expire":
331
+ return ["expire_task"];
330
332
  default:
331
333
  return [];
332
334
  }
@@ -435,7 +437,8 @@ function verifyInstructionAuthorityAndShape(decoded, inspected, expected, operat
435
437
  * Strict fail-closed local validator for built or server-prepared Shillbot Solana transactions.
436
438
  *
437
439
  * Enforces:
438
- * - Allowed program IDs (Shillbot + ComputeBudget, plus Switchboard + Secp256k1 only on `verify`).
440
+ * - Allowed program IDs (Shillbot + ComputeBudget, Switchboard + Secp256k1 on `verify` / score-0 reopen,
441
+ * and `extension-credit` `route_and_recoup` strictly on `finalize`).
439
442
  * - Full loop validation of all `ComputeBudget` instructions (no early return on `RequestHeapFrame`),
440
443
  * capping `SetComputeUnitPrice <= MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS` (`100_000` micro-lamports/CU).
441
444
  * - Exact Anchor account-index positions for `task` PDA and authority signer slots per discriminator.
@@ -482,13 +485,16 @@ export function verifyBuiltTransaction(encoded, expected, operation = "shillbot.
482
485
  const isVerifyContext = expected.action === "verify" ||
483
486
  expected.instructionName === "verify_task" ||
484
487
  expected.instructionName === "verify_task_attested";
488
+ const isFinalizeContext = expected.action === "finalize" || expected.instructionName === "finalize_task";
485
489
  const shillbotId = SHILLBOT_PROGRAM_ID.toBase58();
490
+ const extensionCreditId = EXTENSION_CREDIT_PROGRAM_ID.toBase58();
486
491
  const alwaysAllowed = new Set([
487
492
  shillbotId,
488
493
  ComputeBudgetProgram.programId.toBase58(),
489
494
  ...(isVerifyContext
490
495
  ? [SWITCHBOARD_PROGRAM_IDS[expected.network], Secp256k1Program.programId.toBase58()]
491
496
  : []),
497
+ ...(isFinalizeContext ? [extensionCreditId] : []),
492
498
  ...(expected.allowedProgramIds ?? []),
493
499
  ]);
494
500
  const unrelated = inspected.instructions.find((instruction) => !alwaysAllowed.has(instruction.program_id));
@@ -529,6 +535,43 @@ export function verifyBuiltTransaction(encoded, expected, operation = "shillbot.
529
535
  }
530
536
  }
531
537
  verifyInstructionAuthorityAndShape(primary, inspected, expected, operation);
538
+ // Validate optional `extension-credit::route_and_recoup` companion on `finalize`
539
+ const creditIxs = inspected.instructions
540
+ .map((ix, txIndex) => ({ ix, txIndex }))
541
+ .filter((entry) => entry.ix.program_id === extensionCreditId);
542
+ if (creditIxs.length > 0) {
543
+ if (!isFinalizeContext || primary.spec.name !== "finalize_task") {
544
+ throw txMismatch(operation, "extension-credit instruction only permitted on finalize_task");
545
+ }
546
+ if (creditIxs.length !== 1) {
547
+ throw txMismatch(operation, "At most one extension-credit instruction is permitted");
548
+ }
549
+ const { ix: creditIx, txIndex: creditTxIndex } = creditIxs[0];
550
+ if (creditTxIndex <= primary.txIndex) {
551
+ throw txMismatch(operation, "route_and_recoup must execute after finalize_task");
552
+ }
553
+ const creditData = Buffer.from(creditIx.data_base64, "base64");
554
+ if (creditData.length !== 8 || !creditData.equals(routeAndRecoupDiscriminator())) {
555
+ throw txMismatch(operation, "Unsupported or malformed extension-credit instruction");
556
+ }
557
+ if (creditIx.accounts.length !== 3) {
558
+ throw txMismatch(operation, `route_and_recoup requires exact 3 accounts [advance, backer, recipient], got ${creditIx.accounts.length}`);
559
+ }
560
+ const [advanceAcct, backerAcct, recipientAcct] = creditIx.accounts;
561
+ if (advanceAcct !== primary.ix.accounts[2]) {
562
+ throw txMismatch(operation, `route_and_recoup advance account (${advanceAcct}) must match finalize_task payout slot [2] (${primary.ix.accounts[2]})`);
563
+ }
564
+ if (expectedPayoutPubkey && advanceAcct !== expectedPayoutPubkey.toBase58()) {
565
+ throw txMismatch(operation, `route_and_recoup advance account (${advanceAcct}) differs from expected.payoutTo (${expectedPayoutPubkey.toBase58()})`);
566
+ }
567
+ if (recipientAcct !== expected.wallet) {
568
+ throw txMismatch(operation, `route_and_recoup recipient (${recipientAcct}) must equal caller wallet (${expected.wallet})`);
569
+ }
570
+ const derivedAdvance = advancePda(backerAcct, recipientAcct).toBase58();
571
+ if (advanceAcct !== derivedAdvance) {
572
+ throw txMismatch(operation, `route_and_recoup advance account (${advanceAcct}) does not match canonical Advance PDA (${derivedAdvance})`);
573
+ }
574
+ }
532
575
  // Instruction-specific payload validation
533
576
  if (primary.spec.name === "create_task") {
534
577
  if (primary.data.length < 24) {
@@ -566,6 +609,31 @@ export function verifyBuiltTransaction(encoded, expected, operation = "shillbot.
566
609
  throw txMismatch(operation, `finalize_task payout recipient slot [2] (${primary.ix.accounts[2]}) differs from expected.payoutTo ${expectedPayoutPubkey.toBase58()}`);
567
610
  }
568
611
  }
612
+ else if (primary.spec.name === "expire_task") {
613
+ if (primary.data.length !== 8) {
614
+ throw txMismatch(operation, `expire_task instruction data must be exact 8-byte discriminator, got ${primary.data.length}`);
615
+ }
616
+ if (primary.ix.accounts.length !== 3 && primary.ix.accounts.length !== 4) {
617
+ throw txMismatch(operation, `expire_task requires 3 accounts (or 4 when expiring a Claimed task), got ${primary.ix.accounts.length}`);
618
+ }
619
+ if (expected.expireTaskState !== undefined) {
620
+ if (expected.expireTaskState === "open" ||
621
+ expected.expireTaskState === "submitted" ||
622
+ expected.expireTaskState === "approved") {
623
+ if (primary.ix.accounts.length !== 3) {
624
+ throw txMismatch(operation, `expire_task on ${expected.expireTaskState} task requires exact 3 accounts [task, global_state, client], got ${primary.ix.accounts.length}`);
625
+ }
626
+ }
627
+ else if (expected.expireTaskState === "claimed") {
628
+ if (primary.ix.accounts.length !== 4) {
629
+ throw txMismatch(operation, `expire_task on claimed task requires exact 4 accounts [task, global_state, client, agent_state], got ${primary.ix.accounts.length}`);
630
+ }
631
+ }
632
+ else {
633
+ throw invalidArg(operation, `Unsupported expireTaskState: ${String(expected.expireTaskState)}`);
634
+ }
635
+ }
636
+ }
569
637
  // Validate companion Shillbot instructions (strictly fail-closed)
570
638
  const validateClaimCompanion = (claimIx) => {
571
639
  if (primary.spec.name === "submit_work") {
@@ -590,6 +658,9 @@ export function verifyBuiltTransaction(encoded, expected, operation = "shillbot.
590
658
  const isSubmitLifecycle = expected.action === "submit" ||
591
659
  primary.spec.name === "submit_work" ||
592
660
  primary.spec.name === "submit_work_session";
661
+ const isVerifyLifecycle = expected.action === "verify" ||
662
+ primary.spec.name === "verify_task" ||
663
+ primary.spec.name === "verify_task_attested";
593
664
  if (companions.length === 0) {
594
665
  if (expectedPayoutPubkey &&
595
666
  primary.spec.name !== "set_payout_to" &&
@@ -598,6 +669,15 @@ export function verifyBuiltTransaction(encoded, expected, operation = "shillbot.
598
669
  }
599
670
  return inspected;
600
671
  }
672
+ if (isVerifyLifecycle &&
673
+ companions.length === 1 &&
674
+ companions[0].spec.name === "set_payout_to") {
675
+ if (companions[0].txIndex >= primary.txIndex) {
676
+ throw txMismatch(operation, "set_payout_to must precede verify instruction");
677
+ }
678
+ validateSetPayoutToInstruction(companions[0], expected.wallet, primary.ix.accounts[0], expectedPayoutPubkey, operation);
679
+ return inspected;
680
+ }
601
681
  if (isClaimLifecycle &&
602
682
  companions.length === 1 &&
603
683
  companions[0].spec.name === "set_payout_to") {
@@ -610,30 +690,64 @@ export function verifyBuiltTransaction(encoded, expected, operation = "shillbot.
610
690
  validateSetPayoutToInstruction(companions[0], expected.wallet, primary.ix.accounts[0], expectedPayoutPubkey, operation);
611
691
  return inspected;
612
692
  }
693
+ // Optional leading score-0 reopen (`verify_task` or `verify_task_attested` with score == 0)
694
+ // before `[claim_task, (set_payout_to?), submit_work]` (1d / Q4).
695
+ let submitCompanions = companions;
613
696
  if (isSubmitLifecycle &&
614
- companions.length === 1 &&
615
- (companions[0].spec.name === "claim_task" ||
616
- companions[0].spec.name === "claim_task_session")) {
697
+ (companions[0].spec.name === "verify_task" ||
698
+ companions[0].spec.name === "verify_task_attested")) {
699
+ const reopenIx = companions[0];
700
+ if (reopenIx.data.length !== 48 || reopenIx.ix.accounts.length < 3) {
701
+ throw txMismatch(operation, "Malformed score-0 reopen verify companion");
702
+ }
703
+ if (reopenIx.ix.accounts[0] !== primary.ix.accounts[0]) {
704
+ throw txMismatch(operation, "Score-0 reopen verify companion targets a different task PDA");
705
+ }
706
+ const scoreView = new DataView(reopenIx.data.buffer, reopenIx.data.byteOffset + 8, 8);
707
+ if (scoreView.getBigUint64(0, true) !== 0n) {
708
+ throw txMismatch(operation, "Reopen verify companion in submit bundle must have composite_score === 0");
709
+ }
710
+ if (reopenIx.spec.name === "verify_task_attested") {
711
+ const attester = reopenIx.ix.accounts[2];
712
+ if (!inspected.signers.includes(attester)) {
713
+ throw txMismatch(operation, "verify_task_attested reopen attester must be a signer");
714
+ }
715
+ if (expected.oracleAuthority && attester !== expected.oracleAuthority) {
716
+ throw txMismatch(operation, "verify_task_attested reopen attester mismatch");
717
+ }
718
+ }
719
+ else if (expected.oracleAuthority && reopenIx.ix.accounts[2] !== expected.oracleAuthority) {
720
+ throw txMismatch(operation, "verify_task reopen oracle mismatch");
721
+ }
722
+ submitCompanions = companions.slice(1);
723
+ if (submitCompanions.length > 0 && reopenIx.txIndex >= submitCompanions[0].txIndex) {
724
+ throw txMismatch(operation, "Score-0 reopen verify must precede claim_task");
725
+ }
726
+ }
727
+ if (isSubmitLifecycle &&
728
+ submitCompanions.length === 1 &&
729
+ (submitCompanions[0].spec.name === "claim_task" ||
730
+ submitCompanions[0].spec.name === "claim_task_session")) {
617
731
  if (expectedPayoutPubkey) {
618
732
  throw txMismatch(operation, "Expected set_payout_to instruction matching expected.payoutTo, but none was present");
619
733
  }
620
- if (primary.txIndex !== companions[0].txIndex + 1 ||
621
- !validateClaimCompanion(companions[0])) {
734
+ if (primary.txIndex !== submitCompanions[0].txIndex + 1 ||
735
+ !validateClaimCompanion(submitCompanions[0])) {
622
736
  throw txMismatch(operation, "Expected exactly one matching Shillbot lifecycle instruction");
623
737
  }
624
738
  return inspected;
625
739
  }
626
740
  if (isSubmitLifecycle &&
627
- companions.length === 2 &&
628
- companions[0].spec.name === "claim_task" &&
629
- companions[1].spec.name === "set_payout_to") {
741
+ submitCompanions.length === 2 &&
742
+ submitCompanions[0].spec.name === "claim_task" &&
743
+ submitCompanions[1].spec.name === "set_payout_to") {
630
744
  if (primary.spec.name !== "submit_work" ||
631
- companions[1].txIndex !== companions[0].txIndex + 1 ||
632
- primary.txIndex !== companions[1].txIndex + 1 ||
633
- !validateClaimCompanion(companions[0])) {
745
+ submitCompanions[1].txIndex !== submitCompanions[0].txIndex + 1 ||
746
+ primary.txIndex !== submitCompanions[1].txIndex + 1 ||
747
+ !validateClaimCompanion(submitCompanions[0])) {
634
748
  throw txMismatch(operation, "Expected exactly one matching Shillbot lifecycle instruction");
635
749
  }
636
- validateSetPayoutToInstruction(companions[1], expected.wallet, primary.ix.accounts[0], expectedPayoutPubkey, operation);
750
+ validateSetPayoutToInstruction(submitCompanions[1], expected.wallet, primary.ix.accounts[0], expectedPayoutPubkey, operation);
637
751
  return inspected;
638
752
  }
639
753
  if (companions.some((c) => c.spec.name === "set_payout_to")) {
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const CLIENT_VERSION = "0.4.5";
1
+ export declare const CLIENT_VERSION = "0.4.6";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLIENT_VERSION = "0.4.5";
1
+ export const CLIENT_VERSION = "0.4.6";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swarm-tips/client",
3
- "version": "0.4.5",
3
+ "version": "0.4.6",
4
4
  "description": "Typed browser and Node.js clients for Swarm Tips, Shillbot, and Coordination Game",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",