@swarm-tips/client 0.4.5 → 0.4.7

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.7",
6
+ "documentNamespace": "https://swarm.tips/sbom/client/0.4.7",
7
7
  "creationInfo": {
8
- "created": "2026-11-15T20:57:08.285Z",
8
+ "created": "2026-11-17T05:34:07.531Z",
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.7",
19
+ "downloadLocation": "https://www.npmjs.com/package/@swarm-tips/client/v/0.4.7",
20
20
  "filesAnalyzed": false,
21
21
  "licenseConcluded": "MIT",
22
22
  "licenseDeclared": "MIT"
package/dist/agent.d.ts CHANGED
@@ -8,6 +8,10 @@ import type { Verdict } from "./vow/types.js";
8
8
  export type SwarmNetwork = "mainnet" | "devnet";
9
9
  /** Default EVM gas price ceiling (`maxFeePerGas` = 50 gwei). */
10
10
  export declare const DEFAULT_MAX_NETWORK_FEE_WEI = 50000000000n;
11
+ /** Recoupable SOL advance (`0.0031 SOL` = `3_100_000` lamports = `3_000_000` rent + `100_000` first-task gas budget) fronted by `/agent/onboard`. */
12
+ export declare const ONBOARD_ADVANCE_LAMPORTS = 3100000;
13
+ /** Minimum SOL balance (`0.003 SOL` = `3_000_000` lamports) required for self-paid `AgentState` initialization + lifecycle fees. */
14
+ export declare const MIN_SELF_PAID_SOLANA_BALANCE_LAMPORTS = 3000000;
11
15
  export interface SwarmAgentOptions {
12
16
  signer?: SwarmSigner;
13
17
  token?: string | (() => Promise<string | undefined>);
@@ -16,6 +20,8 @@ export interface SwarmAgentOptions {
16
20
  shillbotUrl?: string;
17
21
  gameUrl?: string;
18
22
  mcpUrl?: string;
23
+ /** Automatically call `onboard()` when a Solana wallet lacks SOL for self-paid claim/submit; default `true`. */
24
+ autoOnboard?: boolean;
19
25
  /** Maximum SOL escrow spend allowed per task creation; default `0n` (C9). */
20
26
  maxEscrowSpendLamports?: bigint;
21
27
  /** Maximum ETH/EVM escrow spend allowed per task creation; default `0n` (C9). */
@@ -39,7 +45,11 @@ export interface ExecutedTaskResult<TConfirm = unknown> {
39
45
  }
40
46
  export interface ExecuteTaskOptions {
41
47
  sponsor?: "auto" | "true" | "none";
48
+ /** Automatically call `onboard()` if `?sponsor=auto` returns self-paid on an underfunded wallet; default `true`. */
49
+ autoOnboard?: boolean;
42
50
  connection?: Connection;
51
+ /** Optional explicit sponsor fee payer pubkey (base58). */
52
+ feePayer?: string;
43
53
  /** Explicit authorized payout destination pubkey (base58) when `set_payout_to` is expected. */
44
54
  payoutTo?: string;
45
55
  extra?: Record<string, unknown>;
@@ -59,6 +69,7 @@ export declare class SwarmAgent {
59
69
  readonly shillbotUrl: string;
60
70
  readonly gameUrl: string;
61
71
  readonly mcpUrl: string;
72
+ readonly autoOnboard: boolean;
62
73
  readonly maxEscrowSpendLamports: bigint;
63
74
  readonly maxEscrowSpendWei: bigint;
64
75
  readonly maxNetworkFeeLamports: bigint;
@@ -70,6 +81,7 @@ export declare class SwarmAgent {
70
81
  private readonly swarmClient;
71
82
  private readonly inboxClient;
72
83
  private readonly gameClient;
84
+ private autoOnboardAttempted;
73
85
  readonly auth: {
74
86
  getToken: () => Promise<string | undefined>;
75
87
  authenticate: () => Promise<string>;
@@ -107,12 +119,18 @@ export declare class SwarmAgent {
107
119
  buildVerify: (id: string) => Promise<PreparedTransactionResponse>;
108
120
  verifyAndExecute: (id: string, opts?: {
109
121
  connection?: Connection;
122
+ payoutTo?: string;
110
123
  }) => Promise<ExecutedTaskResult>;
111
124
  buildFinalize: (id: string) => Promise<PreparedTransactionResponse>;
112
125
  finalizeAndExecute: (id: string, opts?: {
113
126
  connection?: Connection;
114
127
  payoutTo?: string;
115
128
  }) => Promise<ExecutedTaskResult>;
129
+ buildExpire: (id: string) => Promise<PreparedTransactionResponse>;
130
+ expireAndExecute: (id: string, opts?: {
131
+ connection?: Connection;
132
+ chain?: string;
133
+ }) => Promise<ExecutedTaskResult>;
116
134
  nextAction: (task: Record<string, unknown>) => NextTaskAction;
117
135
  verifyVow: (urlOrJson: string | Record<string, unknown>, opts?: {
118
136
  rpcUrl?: string;
@@ -126,6 +144,7 @@ export declare class SwarmAgent {
126
144
  get: <TCampaign = unknown>(id: string) => Promise<TCampaign>;
127
145
  tasks: <TTask = unknown>(id: string) => Promise<TaskListResponse<TTask>>;
128
146
  metrics: <TMetrics = unknown>(id: string) => Promise<TMetrics>;
147
+ pendingApproval: <TTask = unknown>(network?: SwarmNetwork) => Promise<TaskListResponse<TTask> | TTask[]>;
129
148
  create: <TResponse = {
130
149
  campaign_id: string;
131
150
  }>(body: unknown) => Promise<TResponse>;
@@ -139,6 +158,11 @@ export declare class SwarmAgent {
139
158
  connection?: Connection;
140
159
  chain?: string;
141
160
  }) => Promise<ExecutedTaskResult>;
161
+ expire: (id: string) => Promise<PreparedTransactionResponse>;
162
+ expireAndExecute: (id: string, opts?: {
163
+ connection?: Connection;
164
+ chain?: string;
165
+ }) => Promise<ExecutedTaskResult>;
142
166
  };
143
167
  readonly inbox: {
144
168
  list: (opts?: InboxListOptions) => Promise<InboxListPage>;
@@ -183,8 +207,29 @@ export declare class SwarmAgent {
183
207
  }) => Promise<T>;
184
208
  };
185
209
  constructor(options?: SwarmAgentOptions);
210
+ /** Bootstrap a zero-funds Solana agent wallet via recoupable Advance PDA fronting (`3_100_000` lamports). */
211
+ onboard<TResponse = unknown>(): Promise<TResponse>;
212
+ /** Claim a task and execute the prepared transaction (with automatic `$0` wallet onboarding when enabled). */
213
+ claimTask(id: string, opts?: ExecuteTaskOptions): Promise<ExecutedTaskResult>;
214
+ /** Submit work for a task and execute the prepared transaction (with automatic `$0` wallet onboarding when enabled). */
215
+ submitWork(id: string, contentId: string, opts?: ExecuteTaskOptions): Promise<ExecutedTaskResult>;
186
216
  private requireSigner;
187
217
  private executeClaimOrSubmit;
218
+ /**
219
+ * Resolve an authorized `payoutTo` pubkey (`P1-2` / `HIGH-02`):
220
+ * - If caller explicitly passed `explicitPayoutTo`, return it verbatim.
221
+ * - Otherwise, NEVER trust `advance_backer` from the API response alone:
222
+ * 1. Verify `advancePda(advance_backer, walletAddress) === prepared.payout_to`.
223
+ * 2. Fetch the PDA on-chain via `connection.getAccountInfo(derived, "confirmed")` and require:
224
+ * - account exists (`acct !== null && acct.lamports > 0`),
225
+ * - `acct.owner.equals(EXTENSION_CREDIT_PROGRAM_ID)`,
226
+ * - valid 113-byte `Advance` account (`sha256("account:Advance")[0..8]`) with
227
+ * `backer === advance_backer`, `recipient === walletAddress`, and
228
+ * `recouped_lamports < advance_lamports`.
229
+ * 3. On any mismatch or RPC error, return `undefined` so `validatePreparedTransaction`
230
+ * rejects any `set_payout_to` fail-closed.
231
+ */
232
+ private static resolveVerifiedAdvancePayoutTo;
188
233
  private executePreparedAction;
189
234
  private executeEvmAction;
190
235
  private executeSolanaAction;
package/dist/agent.js CHANGED
@@ -1,15 +1,21 @@
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). */
12
12
  export const DEFAULT_MAX_NETWORK_FEE_WEI = 50000000000n;
13
+ /** Recoupable SOL advance (`0.0031 SOL` = `3_100_000` lamports = `3_000_000` rent + `100_000` first-task gas budget) fronted by `/agent/onboard`. */
14
+ export const ONBOARD_ADVANCE_LAMPORTS = 3_100_000;
15
+ /** Minimum SOL balance (`0.003 SOL` = `3_000_000` lamports) required for self-paid `AgentState` initialization + lifecycle fees. */
16
+ export const MIN_SELF_PAID_SOLANA_BALANCE_LAMPORTS = 3_000_000;
17
+ /** Minimum SOL balance (`50_000` lamports) required for standalone post-claim `submit_work` fee payment. */
18
+ const MIN_POST_CLAIM_SUBMIT_SOLANA_BALANCE_LAMPORTS = 50_000;
13
19
  const DEFAULT_SOLANA_RPC = {
14
20
  mainnet: "https://api.mainnet-beta.solana.com",
15
21
  devnet: "https://api.devnet.solana.com",
@@ -95,6 +101,7 @@ export class SwarmAgent {
95
101
  shillbotUrl;
96
102
  gameUrl;
97
103
  mcpUrl;
104
+ autoOnboard;
98
105
  maxEscrowSpendLamports;
99
106
  maxEscrowSpendWei;
100
107
  maxNetworkFeeLamports;
@@ -106,6 +113,7 @@ export class SwarmAgent {
106
113
  swarmClient;
107
114
  inboxClient;
108
115
  gameClient;
116
+ autoOnboardAttempted = false;
109
117
  auth;
110
118
  discovery;
111
119
  tasks;
@@ -119,6 +127,7 @@ export class SwarmAgent {
119
127
  this.shillbotUrl = (options.shillbotUrl ?? "https://api.shillbot.org").replace(/\/$/, "");
120
128
  this.gameUrl = (options.gameUrl ?? "https://api.coordination.game").replace(/\/$/, "");
121
129
  this.mcpUrl = (options.mcpUrl ?? "https://mcp.swarm.tips").replace(/\/$/, "");
130
+ this.autoOnboard = options.autoOnboard ?? true;
122
131
  this.maxEscrowSpendLamports = options.maxEscrowSpendLamports ?? 0n;
123
132
  this.maxEscrowSpendWei = options.maxEscrowSpendWei ?? 0n;
124
133
  this.maxNetworkFeeLamports = options.maxNetworkFeeLamports ?? 100000n;
@@ -203,7 +212,7 @@ export class SwarmAgent {
203
212
  return Array.isArray(res) ? res : (res.tasks ?? []);
204
213
  },
205
214
  earnings: () => self.shillbotClient.earnings(),
206
- onboard: () => self.shillbotClient.onboard(),
215
+ onboard: () => self.onboard(),
207
216
  claim: (id, sponsor = "auto") => self.shillbotClient.claimTask(id, sponsor),
208
217
  claimAndExecute: (id, opts) => self.executeClaimOrSubmit(id, "claim", undefined, opts),
209
218
  submit: (id, body) => self.shillbotClient.submitTask(id, body),
@@ -218,6 +227,7 @@ export class SwarmAgent {
218
227
  const prepared = await self.tasks.buildVerify(id);
219
228
  return self.executePreparedAction(id, "verify", prepared, {
220
229
  connection: opts?.connection,
230
+ payoutTo: opts?.payoutTo,
221
231
  });
222
232
  },
223
233
  buildFinalize: (id) => self.shillbotClient.buildFinalize(id),
@@ -228,6 +238,14 @@ export class SwarmAgent {
228
238
  payoutTo: opts?.payoutTo,
229
239
  });
230
240
  },
241
+ buildExpire: (id) => self.shillbotClient.buildExpire(id),
242
+ async expireAndExecute(id, opts) {
243
+ const prepared = await self.tasks.buildExpire(id);
244
+ return self.executePreparedAction(id, "expire", prepared, {
245
+ connection: opts?.connection,
246
+ chain: opts?.chain,
247
+ });
248
+ },
231
249
  nextAction: (task) => SwarmAgent.adviseNextAction(task),
232
250
  async verifyVow(urlOrJson, opts) {
233
251
  const customAgentRpc = self.rpcUrl !== DEFAULT_SOLANA_RPC[self.network] ? self.rpcUrl : undefined;
@@ -247,6 +265,7 @@ export class SwarmAgent {
247
265
  get: (id) => self.shillbotClient.campaign(id),
248
266
  tasks: (id) => self.shillbotClient.campaignTasks(id),
249
267
  metrics: (id) => self.shillbotClient.campaignMetrics(id),
268
+ pendingApproval: (net) => self.shillbotClient.listPendingApproval(net),
250
269
  create: (body) => self.shillbotClient.createCampaign(body),
251
270
  fund: (id, body) => self.shillbotClient.fundCampaignTask(id, body),
252
271
  async fundAndExecute(id, body, opts) {
@@ -290,6 +309,14 @@ export class SwarmAgent {
290
309
  chain: opts?.chain,
291
310
  });
292
311
  },
312
+ expire: (id) => self.shillbotClient.buildExpire(id),
313
+ async expireAndExecute(id, opts) {
314
+ const prepared = await self.shillbotClient.buildExpire(id);
315
+ return self.executePreparedAction(id, "expire", prepared, {
316
+ connection: opts?.connection,
317
+ chain: opts?.chain,
318
+ });
319
+ },
293
320
  };
294
321
  this.inbox = {
295
322
  list: (opts) => self.inboxClient.listMessages(opts),
@@ -320,6 +347,18 @@ export class SwarmAgent {
320
347
  },
321
348
  };
322
349
  }
350
+ /** Bootstrap a zero-funds Solana agent wallet via recoupable Advance PDA fronting (`3_100_000` lamports). */
351
+ onboard() {
352
+ return this.shillbotClient.onboard();
353
+ }
354
+ /** Claim a task and execute the prepared transaction (with automatic `$0` wallet onboarding when enabled). */
355
+ claimTask(id, opts) {
356
+ return this.executeClaimOrSubmit(id, "claim", undefined, opts);
357
+ }
358
+ /** Submit work for a task and execute the prepared transaction (with automatic `$0` wallet onboarding when enabled). */
359
+ submitWork(id, contentId, opts) {
360
+ return this.executeClaimOrSubmit(id, "submit", contentId, opts);
361
+ }
323
362
  requireSigner() {
324
363
  if (!this.signer) {
325
364
  throw new SwarmClientError({
@@ -333,35 +372,84 @@ export class SwarmAgent {
333
372
  async executeClaimOrSubmit(id, action, contentId, opts) {
334
373
  const sponsorMode = opts?.sponsor ?? "auto";
335
374
  const sponsorQuery = sponsorMode === "none" ? "false" : sponsorMode === "true" ? "true" : "auto";
336
- let prepared;
337
- try {
375
+ const shouldAutoOnboard = (opts?.autoOnboard ?? this.autoOnboard) !== false;
376
+ const requestPrepared = (query) => {
338
377
  if (action === "claim") {
339
- prepared = await this.shillbotClient.claimTask(id, sponsorQuery);
340
- }
341
- else {
342
- const suffix = sponsorMode !== "none" ? `?sponsor=${encodeURIComponent(sponsorQuery)}` : "";
343
- prepared = await this.shillbotClient.post(`/tasks/${encodeURIComponent(id)}/submit${suffix}`, { content_id: contentId, ...(opts?.extra ?? {}) });
378
+ return this.shillbotClient.claimTask(id, query);
344
379
  }
380
+ const suffix = sponsorMode !== "none" ? `?sponsor=${encodeURIComponent(query)}` : "";
381
+ return this.shillbotClient.post(`/tasks/${encodeURIComponent(id)}/submit${suffix}`, { content_id: contentId, ...(opts?.extra ?? {}) });
382
+ };
383
+ let prepared;
384
+ try {
385
+ prepared = await requestPrepared(sponsorQuery);
345
386
  }
346
387
  catch (err) {
347
388
  if ((action === "claim" || action === "submit") &&
348
389
  sponsorMode !== "none" &&
390
+ shouldAutoOnboard &&
391
+ !this.autoOnboardAttempted &&
349
392
  err instanceof SwarmClientError &&
350
393
  err.code === "HTTP_ERROR" &&
351
394
  (err.status === 400 || err.status === 403 || err.status === 412) &&
352
395
  /onboard|agent_state|bootstrap/i.test(err.message)) {
353
- await this.shillbotClient.onboard();
354
- if (action === "claim") {
355
- prepared = await this.shillbotClient.claimTask(id, sponsorQuery);
356
- }
357
- else {
358
- prepared = await this.shillbotClient.post(`/tasks/${encodeURIComponent(id)}/submit?sponsor=${encodeURIComponent(sponsorQuery)}`, { content_id: contentId, ...(opts?.extra ?? {}) });
359
- }
396
+ this.autoOnboardAttempted = true;
397
+ await this.onboard();
398
+ prepared = await requestPrepared(sponsorQuery);
360
399
  }
361
400
  else {
362
401
  throw err;
363
402
  }
364
403
  }
404
+ const connection = this.signer?.chain === "solana"
405
+ ? (opts?.connection ?? new Connection(this.rpcUrl, "confirmed"))
406
+ : opts?.connection;
407
+ // When a Solana wallet holds less than MIN_SELF_PAID_SOLANA_BALANCE_LAMPORTS (3_000_000 lamports
408
+ // for claim / atomic claim+submit) or MIN_POST_CLAIM_SUBMIT_SOLANA_BALANCE_LAMPORTS (50_000 lamports
409
+ // for standalone submit) and receives a self-paid HTTP 200 transaction, onboard once and re-request.
410
+ if (prepared.transaction &&
411
+ sponsorMode !== "none" &&
412
+ shouldAutoOnboard &&
413
+ !this.autoOnboardAttempted &&
414
+ connection &&
415
+ this.signer?.chain === "solana" &&
416
+ typeof connection.getBalance === "function") {
417
+ let initialFeePayer;
418
+ let bundlesClaim = action === "claim";
419
+ try {
420
+ const initialInspected = inspectTransaction(prepared.transaction);
421
+ initialFeePayer = initialInspected.fee_payer;
422
+ if (!bundlesClaim) {
423
+ const claimDisc = shillbotInstructionDiscriminator("claim_task");
424
+ const claimSessionDisc = shillbotInstructionDiscriminator("claim_task_session");
425
+ bundlesClaim = initialInspected.instructions.some((ix) => {
426
+ if (ix.program_id !== SHILLBOT_PROGRAM_ID_B58)
427
+ return false;
428
+ const d = Buffer.from(ix.data_base64, "base64");
429
+ return (d.length >= 8 &&
430
+ (d.subarray(0, 8).equals(claimDisc) || d.subarray(0, 8).equals(claimSessionDisc)));
431
+ });
432
+ }
433
+ }
434
+ catch {
435
+ // Malformed transaction will fail closed during validation below.
436
+ }
437
+ if (initialFeePayer === this.signer.address) {
438
+ const balanceLamports = await connection.getBalance(new PublicKey(this.signer.address));
439
+ const minRequiredLamports = bundlesClaim
440
+ ? MIN_SELF_PAID_SOLANA_BALANCE_LAMPORTS
441
+ : MIN_POST_CLAIM_SUBMIT_SOLANA_BALANCE_LAMPORTS;
442
+ if (balanceLamports < minRequiredLamports) {
443
+ this.autoOnboardAttempted = true;
444
+ await this.onboard();
445
+ prepared = await requestPrepared("auto");
446
+ }
447
+ }
448
+ }
449
+ let resolvedPayoutTo = connection && this.signer?.chain === "solana"
450
+ ? await SwarmAgent.resolveVerifiedAdvancePayoutTo(prepared, this.signer.address, connection, opts?.payoutTo)
451
+ : opts?.payoutTo;
452
+ let payoutToResolved = Boolean(connection && this.signer?.chain === "solana");
365
453
  // If Solana transaction is a gasless sponsor template (fee_payer !== wallet & unsigned by sponsor),
366
454
  // exchange it via POST /tasks/{id}/sponsor before signing locally.
367
455
  if (prepared.transaction &&
@@ -372,10 +460,12 @@ export class SwarmAgent {
372
460
  network: this.network,
373
461
  wallet: this.signer.address,
374
462
  taskPda: prepared.task_pda,
375
- ...(opts?.payoutTo !== undefined ? { payoutTo: opts.payoutTo } : {}),
463
+ ...(opts?.feePayer !== undefined ? { feePayer: opts.feePayer } : {}),
464
+ ...(resolvedPayoutTo !== undefined ? { payoutTo: resolvedPayoutTo } : {}),
376
465
  });
377
466
  if (inspected.fee_payer !== this.signer.address &&
378
467
  !isFeePayerAlreadySigned(prepared.transaction)) {
468
+ const prevPayoutTo = prepared.payout_to;
379
469
  const sponsored = await this.shillbotClient.sponsorTask(id, {
380
470
  action,
381
471
  unsigned_transaction: prepared.transaction,
@@ -385,13 +475,70 @@ export class SwarmAgent {
385
475
  ...sponsored,
386
476
  task_pda: sponsored.task_pda ?? prepared.task_pda,
387
477
  };
478
+ if (opts?.payoutTo === undefined && prepared.payout_to !== prevPayoutTo) {
479
+ resolvedPayoutTo = undefined;
480
+ payoutToResolved = false;
481
+ }
388
482
  }
389
483
  }
390
484
  return this.executePreparedAction(id, action, prepared, {
391
- connection: opts?.connection,
392
- payoutTo: opts?.payoutTo,
485
+ connection,
486
+ feePayer: opts?.feePayer,
487
+ payoutTo: resolvedPayoutTo,
488
+ payoutToResolved,
393
489
  });
394
490
  }
491
+ /**
492
+ * Resolve an authorized `payoutTo` pubkey (`P1-2` / `HIGH-02`):
493
+ * - If caller explicitly passed `explicitPayoutTo`, return it verbatim.
494
+ * - Otherwise, NEVER trust `advance_backer` from the API response alone:
495
+ * 1. Verify `advancePda(advance_backer, walletAddress) === prepared.payout_to`.
496
+ * 2. Fetch the PDA on-chain via `connection.getAccountInfo(derived, "confirmed")` and require:
497
+ * - account exists (`acct !== null && acct.lamports > 0`),
498
+ * - `acct.owner.equals(EXTENSION_CREDIT_PROGRAM_ID)`,
499
+ * - valid 113-byte `Advance` account (`sha256("account:Advance")[0..8]`) with
500
+ * `backer === advance_backer`, `recipient === walletAddress`, and
501
+ * `recouped_lamports < advance_lamports`.
502
+ * 3. On any mismatch or RPC error, return `undefined` so `validatePreparedTransaction`
503
+ * rejects any `set_payout_to` fail-closed.
504
+ */
505
+ static async resolveVerifiedAdvancePayoutTo(prepared, walletAddress, connection, explicitPayoutTo) {
506
+ if (explicitPayoutTo !== undefined) {
507
+ return explicitPayoutTo;
508
+ }
509
+ if (!walletAddress || !prepared.payout_to || !prepared.advance_backer) {
510
+ return undefined;
511
+ }
512
+ try {
513
+ const expectedBacker = new PublicKey(prepared.advance_backer);
514
+ const expectedRecipient = new PublicKey(walletAddress);
515
+ const derived = advancePda(expectedBacker, expectedRecipient);
516
+ if (derived.toBase58() !== prepared.payout_to) {
517
+ return undefined;
518
+ }
519
+ const acct = await connection.getAccountInfo(derived, "confirmed");
520
+ if (!acct || acct.lamports <= 0) {
521
+ return undefined;
522
+ }
523
+ if (!acct.owner.equals(EXTENSION_CREDIT_PROGRAM_ID)) {
524
+ return undefined;
525
+ }
526
+ const decoded = decodeExtensionCreditAdvance(acct.data);
527
+ if (!decoded) {
528
+ return undefined;
529
+ }
530
+ if (!decoded.backer.equals(expectedBacker) ||
531
+ !decoded.recipient.equals(expectedRecipient) ||
532
+ decoded.advanceLamports === 0n ||
533
+ decoded.recoupedLamports >= decoded.advanceLamports) {
534
+ return undefined;
535
+ }
536
+ return derived.toBase58();
537
+ }
538
+ catch {
539
+ return undefined;
540
+ }
541
+ }
395
542
  async executePreparedAction(id, action, prepared, opts) {
396
543
  const signer = this.requireSigner();
397
544
  if (prepared.evm_call && signer.chain === "evm") {
@@ -503,18 +650,22 @@ export class SwarmAgent {
503
650
  message: `Estimated Solana network fee ${estimatedFeeLamports} lamports exceeds maxNetworkFeeLamports (${this.maxNetworkFeeLamports})`,
504
651
  });
505
652
  }
653
+ const connection = opts.connection ?? new Connection(this.rpcUrl, "confirmed");
654
+ const resolvedPayoutTo = opts.payoutToResolved
655
+ ? opts.payoutTo
656
+ : await SwarmAgent.resolveVerifiedAdvancePayoutTo(prepared, signer.address, connection, opts.payoutTo);
506
657
  const expected = {
507
658
  action,
508
659
  network: this.network,
509
660
  wallet: signer.address,
510
661
  taskPda: prepared.task_pda,
511
- ...(opts.payoutTo !== undefined ? { payoutTo: opts.payoutTo } : {}),
662
+ ...(opts.feePayer !== undefined ? { feePayer: opts.feePayer } : {}),
663
+ ...(resolvedPayoutTo !== undefined ? { payoutTo: resolvedPayoutTo } : {}),
512
664
  ...(action === "create" && opts.expectedEscrowLamports !== undefined
513
665
  ? { escrowLamports: opts.expectedEscrowLamports }
514
666
  : {}),
515
667
  };
516
668
  validatePreparedTransaction(prepared.transaction, expected);
517
- const connection = opts.connection ?? new Connection(this.rpcUrl, "confirmed");
518
669
  const signature = await signBroadcastPreparedTransaction({
519
670
  connection,
520
671
  transaction: prepared.transaction,
@@ -15,10 +15,11 @@ export declare function readSecureKeypairFile(filePath: string): string;
15
15
  export interface LoadCliSignerOptions {
16
16
  keypairFile?: string;
17
17
  env?: Record<string, string | undefined>;
18
- evmChainId?: number;
18
+ evmChainId?: number | string;
19
19
  evmRpcUrl?: string;
20
20
  }
21
21
  /**
22
- * Load a non-custodial `SwarmSigner` from `--keypair-file` or `SWARM_*` environment variables.
22
+ * Load a non-custodial `SwarmSigner` from `--keypair-file` (Solana JSON/base58 or
23
+ * `0x`-prefixed 32-byte hex EVM private key) or `SWARM_*` environment variables.
23
24
  */
24
25
  export declare function loadSignerFromCliOrEnv(options?: LoadCliSignerOptions): SwarmSigner | undefined;
@@ -57,13 +57,30 @@ export function readSecureKeypairFile(filePath) {
57
57
  }
58
58
  }
59
59
  /**
60
- * Load a non-custodial `SwarmSigner` from `--keypair-file` or `SWARM_*` environment variables.
60
+ * Load a non-custodial `SwarmSigner` from `--keypair-file` (Solana JSON/base58 or
61
+ * `0x`-prefixed 32-byte hex EVM private key) or `SWARM_*` environment variables.
61
62
  */
62
63
  export function loadSignerFromCliOrEnv(options = {}) {
63
64
  const env = options.env ?? process.env;
64
- const keyfilePath = options.keypairFile ?? env.SWARM_SOLANA_KEYPAIR_PATH;
65
+ const resolvedEvmChainId = options.evmChainId ?? env.SWARM_EVM_CHAIN_ID?.trim();
66
+ const resolvedEvmRpcUrl = options.evmRpcUrl ?? env.SWARM_EVM_RPC_URL?.trim();
67
+ const keyfilePath = options.keypairFile ?? env.SWARM_SOLANA_KEYPAIR_PATH ?? env.SWARM_EVM_KEYPAIR_PATH;
65
68
  if (keyfilePath) {
66
69
  const raw = readSecureKeypairFile(keyfilePath);
70
+ if (/^0x/i.test(raw)) {
71
+ if (!/^0x[0-9a-fA-F]{64}$/.test(raw)) {
72
+ throw new CliUsageError(`Invalid EVM private key in ${resolve(keyfilePath)}: Expected a 0x-prefixed 32-byte hex EVM private key`);
73
+ }
74
+ try {
75
+ return fromEvmPrivateKey(raw, {
76
+ chainId: resolvedEvmChainId,
77
+ rpcUrl: resolvedEvmRpcUrl,
78
+ });
79
+ }
80
+ catch (err) {
81
+ throw new CliUsageError(`Invalid EVM private key in ${resolve(keyfilePath)}: ${err instanceof Error ? err.message : String(err)}`);
82
+ }
83
+ }
67
84
  try {
68
85
  return fromSolanaSecretKey(raw);
69
86
  }
@@ -85,8 +102,8 @@ export function loadSignerFromCliOrEnv(options = {}) {
85
102
  const normalized = (evmPriv.startsWith("0x") ? evmPriv : `0x${evmPriv}`);
86
103
  try {
87
104
  return fromEvmPrivateKey(normalized, {
88
- chainId: options.evmChainId,
89
- rpcUrl: options.evmRpcUrl,
105
+ chainId: resolvedEvmChainId,
106
+ rpcUrl: resolvedEvmRpcUrl,
90
107
  });
91
108
  }
92
109
  catch (err) {