@swarm-tips/client 0.4.2 → 0.4.4

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.
Files changed (40) hide show
  1. package/README.md +3 -2
  2. package/SBOM.spdx.json +5 -5
  3. package/dist/agent.d.ts +17 -1
  4. package/dist/agent.js +71 -54
  5. package/dist/cli/swarm.d.ts +5 -0
  6. package/dist/cli/swarm.js +48 -21
  7. package/dist/contracts/generated/coordination_game.d.ts +179 -1
  8. package/dist/contracts/generated/shillbot.d.ts +119 -12
  9. package/dist/contracts/idl/coordination_game.json +180 -2
  10. package/dist/contracts/idl/shillbot.json +119 -12
  11. package/dist/generated/openapi.d.ts +17 -2
  12. package/dist/generated/openapi.js +1 -1
  13. package/dist/http.js +1 -1
  14. package/dist/inbox/client.d.ts +2 -4
  15. package/dist/inbox/client.js +11 -6
  16. package/dist/inbox/index.d.ts +1 -1
  17. package/dist/inbox/index.js +1 -1
  18. package/dist/inbox/types.d.ts +9 -0
  19. package/dist/inbox/types.js +10 -0
  20. package/dist/index.d.ts +5 -3
  21. package/dist/index.js +4 -2
  22. package/dist/shillbot/api.d.ts +8 -1
  23. package/dist/shillbot/api.js +53 -133
  24. package/dist/shillbot/index.d.ts +1 -0
  25. package/dist/shillbot/index.js +3 -0
  26. package/dist/shillbot/verify-tx.d.ts +62 -0
  27. package/dist/shillbot/verify-tx.js +643 -0
  28. package/dist/signer/evm.d.ts +1 -1
  29. package/dist/signer/evm.js +72 -2
  30. package/dist/signer/index.d.ts +1 -1
  31. package/dist/signer/solana.d.ts +3 -2
  32. package/dist/signer/solana.js +36 -9
  33. package/dist/signer/types.d.ts +4 -1
  34. package/dist/version.d.ts +1 -1
  35. package/dist/version.js +1 -1
  36. package/dist/vow/index.d.ts +1 -1
  37. package/dist/vow/index.js +1 -1
  38. package/dist/vow/verify.d.ts +36 -0
  39. package/dist/vow/verify.js +458 -1
  40. package/package.json +1 -1
@@ -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 { SHILLBOT_PROGRAM_ID, inspectTransaction, shillbotInstructionDiscriminator, signAndBroadcast, } from "./index.js";
5
+ import { signAndBroadcast, } from "./index.js";
6
6
  function decodeJwtWallet(token) {
7
7
  if (!token)
8
8
  return undefined;
@@ -38,10 +38,19 @@ export class ShillbotApiClient {
38
38
  return this.http.patch(path, body);
39
39
  }
40
40
  listTasks(limit = 50) {
41
- return this.get(`/tasks?limit=${encodeURIComponent(String(limit))}`);
41
+ return this.http.get(`/tasks?limit=${encodeURIComponent(String(limit))}`, null);
42
42
  }
43
- getTask(id) {
44
- return this.get(`/tasks/${encodeURIComponent(id)}`);
43
+ async getTask(id, network) {
44
+ const trimmed = id.trim();
45
+ if (!trimmed) {
46
+ throw new SwarmClientError({
47
+ code: "INVALID_ARGUMENT",
48
+ operation: "shillbot.getTask",
49
+ message: "Task id is required",
50
+ });
51
+ }
52
+ const suffix = network ? `?network=${encodeURIComponent(network)}` : "";
53
+ return this.http.get(`/tasks/${encodeURIComponent(trimmed)}${suffix}`, null);
45
54
  }
46
55
  listAgentTasks() {
47
56
  return this.get("/agent/tasks");
@@ -156,6 +165,8 @@ export class ShillbotApiClient {
156
165
  return this.post(`/tasks/${encodeURIComponent(id)}/confirm`, body);
157
166
  }
158
167
  }
168
+ import { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, } from "./verify-tx.js";
169
+ export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, };
159
170
  const SWITCHBOARD_PROGRAM_IDS = {
160
171
  mainnet: "SBondMDrcV3K4kxZR1HNVT7osZxAHVHgYXL5Ze1oMUv",
161
172
  devnet: "Aio4gaXjXzJNVLtzwtNVmSqGKpANtXhybbkhtAC94ji2",
@@ -173,15 +184,27 @@ export const SHILLBOT_EVM_SELECTORS = {
173
184
  verify: "0x3bae608b", // verifyTaskAttested(uint64,uint64,bytes)
174
185
  finalize: "0xcb26e65b", // finalizeTask(uint64)
175
186
  };
176
- function normalizeEvmChainId(chain) {
187
+ export function normalizeEvmChainId(chain) {
188
+ if (typeof chain === "number") {
189
+ if (!Number.isSafeInteger(chain) || chain <= 0) {
190
+ throw new SwarmClientError({
191
+ code: "INVALID_ARGUMENT",
192
+ operation: "shillbot.normalizeEvmChainId",
193
+ message: `Invalid EVM chain ID: ${String(chain)}`,
194
+ });
195
+ }
196
+ return `eip155:${chain}`;
197
+ }
177
198
  const trimmed = chain.trim().toLowerCase();
178
- if (trimmed === "base-sepolia" || trimmed === "84532")
199
+ if (/^\d+$/.test(trimmed))
200
+ return `eip155:${trimmed}`;
201
+ if (trimmed === "base-sepolia")
179
202
  return "eip155:84532";
180
- if (trimmed === "base" || trimmed === "8453")
203
+ if (trimmed === "base")
181
204
  return "eip155:8453";
182
- if (trimmed === "ethereum" || trimmed === "1")
205
+ if (trimmed === "ethereum")
183
206
  return "eip155:1";
184
- if (trimmed === "ethereum-sepolia" || trimmed === "sepolia" || trimmed === "11155111") {
207
+ if (trimmed === "ethereum-sepolia" || trimmed === "sepolia") {
185
208
  return "eip155:11155111";
186
209
  }
187
210
  return trimmed;
@@ -219,7 +242,7 @@ export function validatePreparedEvmCall(evmCall, expected) {
219
242
  const callChain = typeof raw.chain === "string"
220
243
  ? normalizeEvmChainId(raw.chain)
221
244
  : typeof raw.chain_id === "number"
222
- ? `eip155:${raw.chain_id}`
245
+ ? normalizeEvmChainId(raw.chain_id)
223
246
  : undefined;
224
247
  const expectedChain = expected.chain ? normalizeEvmChainId(expected.chain) : undefined;
225
248
  if (callChain && expectedChain && callChain !== expectedChain) {
@@ -313,6 +336,7 @@ export function estimateSolanaNetworkFeeLamports(inspected, wallet) {
313
336
  const computeBudgetId = ComputeBudgetProgram.programId.toBase58();
314
337
  let computeUnitLimit;
315
338
  let microLamportsPerCu = 0n;
339
+ let additionalFeeLamports = 0n;
316
340
  let nonComputeBudgetIxCount = 0;
317
341
  for (const ix of inspected.instructions) {
318
342
  if (ix.program_id !== computeBudgetId) {
@@ -323,150 +347,46 @@ export function estimateSolanaNetworkFeeLamports(inspected, wallet) {
323
347
  if (data.length === 0)
324
348
  continue;
325
349
  const tag = data[0];
350
+ if (tag === 0 && data.length >= 9) {
351
+ // Legacy RequestUnitsDeprecated: u32 units + u32 additionalFeeLamports (never early-return!)
352
+ computeUnitLimit = BigInt(data.readUInt32LE(1));
353
+ additionalFeeLamports += BigInt(data.readUInt32LE(5));
354
+ continue;
355
+ }
356
+ if (tag === 1) {
357
+ // RequestHeapFrame(u32 bytes): does not alter fee, continue checking subsequent instructions!
358
+ continue;
359
+ }
326
360
  if (tag === 2 && data.length >= 5) {
327
361
  computeUnitLimit = BigInt(data.readUInt32LE(1));
362
+ continue;
328
363
  }
329
- else if (tag === 3 && data.length >= 9) {
364
+ if (tag === 3 && data.length >= 9) {
330
365
  const view = new DataView(data.buffer, data.byteOffset + 1, 8);
331
- microLamportsPerCu = view.getBigUint64(0, true);
332
- }
333
- else if (tag === 1 && data.length >= 9) {
334
- // Legacy RequestUnitsDeprecated: u32 units + u32 additionalFeeLamports
335
- const additionalFee = BigInt(data.readUInt32LE(5));
336
- return BigInt(inspected.signers.length) * 5000n + additionalFee;
366
+ const price = view.getBigUint64(0, true);
367
+ if (price > microLamportsPerCu) {
368
+ microLamportsPerCu = price;
369
+ }
370
+ continue;
337
371
  }
338
372
  }
339
373
  const effectiveUnits = computeUnitLimit ?? BigInt(Math.max(1, nonComputeBudgetIxCount)) * 200000n;
340
374
  const priorityFeeLamports = (effectiveUnits * microLamportsPerCu + 999999n) / 1000000n;
341
375
  const baseSignatureFeeLamports = BigInt(Math.max(1, inspected.signers.length)) * 5000n;
342
- return baseSignatureFeeLamports + priorityFeeLamports;
376
+ return baseSignatureFeeLamports + priorityFeeLamports + additionalFeeLamports;
343
377
  }
344
378
  export function permittedPreparedProgramIds(action, network) {
345
379
  return action === "verify"
346
380
  ? [SWITCHBOARD_PROGRAM_IDS[network], Secp256k1Program.programId.toBase58()]
347
381
  : [];
348
382
  }
349
- function lifecycleName(action) {
350
- if (action === "create")
351
- return "create_task";
352
- if (action === "submit")
353
- return "submit_work";
354
- return `${action}_task`;
355
- }
356
- function matchesDiscriminator(dataBase64, action) {
357
- const data = Buffer.from(dataBase64, "base64");
358
- return data.subarray(0, 8).equals(shillbotInstructionDiscriminator(lifecycleName(action)));
359
- }
360
383
  /**
361
384
  * Fail-closed local validation for a server-prepared Shillbot transaction.
362
385
  * The network is an explicit part of the expectation; callers must construct
363
386
  * their Connection for that same network before signing.
364
387
  */
365
388
  export function validatePreparedTransaction(encoded, expected) {
366
- if (expected.network !== "mainnet" && expected.network !== "devnet") {
367
- throw new SwarmClientError({
368
- code: "INVALID_ARGUMENT",
369
- operation: "shillbot.validatePreparedTransaction",
370
- message: "Unsupported network",
371
- });
372
- }
373
- const inspected = inspectTransaction(encoded);
374
- if (!inspected.signers.includes(expected.wallet)) {
375
- throw new SwarmClientError({
376
- code: "TRANSACTION_MISMATCH",
377
- operation: "shillbot.validatePreparedTransaction",
378
- message: "Wallet is not a required signer",
379
- });
380
- }
381
- if (expected.feePayer && inspected.fee_payer !== expected.feePayer) {
382
- throw new SwarmClientError({
383
- code: "TRANSACTION_MISMATCH",
384
- operation: "shillbot.validatePreparedTransaction",
385
- message: "Fee payer differs from expectation",
386
- });
387
- }
388
- const shillbotId = SHILLBOT_PROGRAM_ID.toBase58();
389
- const shillbotIxs = inspected.instructions.filter((instruction) => instruction.program_id === shillbotId);
390
- const lifecycle = shillbotIxs.filter((instruction) => matchesDiscriminator(instruction.data_base64, expected.action));
391
- const companions = shillbotIxs.filter((instruction) => instruction !== lifecycle[0]);
392
- const claimDisc = shillbotInstructionDiscriminator("claim_task");
393
- const payoutDisc = shillbotInstructionDiscriminator("set_payout_to");
394
- const hasDisc = (ix, disc) => Buffer.from(ix.data_base64, "base64").subarray(0, 8).equals(disc);
395
- const ixPos = (ix) => inspected.instructions.indexOf(ix);
396
- const validClaimCompanion = (ix) => hasDisc(ix, claimDisc) &&
397
- ix.accounts.length >= 4 &&
398
- (!expected.taskPda || ix.accounts[0] === expected.taskPda) &&
399
- ix.accounts[0] === lifecycle[0]?.accounts[0] &&
400
- ix.accounts[3] === expected.wallet;
401
- const validPayoutCompanion = (ix) => hasDisc(ix, payoutDisc) &&
402
- ix.accounts.length === 2 &&
403
- (!expected.taskPda || ix.accounts[0] === expected.taskPda) &&
404
- ix.accounts[0] === lifecycle[0]?.accounts[0] &&
405
- ix.accounts[1] === expected.wallet;
406
- const validCompanions = companions.length === 0 ||
407
- (expected.action === "claim" &&
408
- companions.length === 1 &&
409
- validPayoutCompanion(companions[0]) &&
410
- ixPos(companions[0]) > ixPos(lifecycle[0])) ||
411
- (expected.action === "submit" &&
412
- companions.length === 1 &&
413
- validClaimCompanion(companions[0]) &&
414
- ixPos(lifecycle[0]) === ixPos(companions[0]) + 1) ||
415
- (expected.action === "submit" &&
416
- companions.length === 2 &&
417
- validClaimCompanion(companions[0]) &&
418
- validPayoutCompanion(companions[1]) &&
419
- ixPos(companions[1]) === ixPos(companions[0]) + 1 &&
420
- ixPos(lifecycle[0]) === ixPos(companions[1]) + 1);
421
- if (lifecycle.length !== 1 || !validCompanions) {
422
- throw new SwarmClientError({
423
- code: "TRANSACTION_MISMATCH",
424
- operation: "shillbot.validatePreparedTransaction",
425
- message: "Expected exactly one matching Shillbot lifecycle instruction",
426
- });
427
- }
428
- const taskAccountIndex = expected.action === "create" ? 1 : 0;
429
- if (expected.taskPda && lifecycle[0].accounts[taskAccountIndex] !== expected.taskPda) {
430
- throw new SwarmClientError({
431
- code: "TRANSACTION_MISMATCH",
432
- operation: "shillbot.validatePreparedTransaction",
433
- message: "Task PDA differs from expectation",
434
- });
435
- }
436
- const alwaysAllowed = new Set([
437
- shillbotId,
438
- ComputeBudgetProgram.programId.toBase58(),
439
- ...permittedPreparedProgramIds(expected.action, expected.network),
440
- ...(expected.allowedProgramIds ?? []),
441
- ]);
442
- const unrelated = inspected.instructions.find((instruction) => !alwaysAllowed.has(instruction.program_id));
443
- if (unrelated) {
444
- throw new SwarmClientError({
445
- code: "TRANSACTION_MISMATCH",
446
- operation: "shillbot.validatePreparedTransaction",
447
- message: `Unexpected program ${unrelated.program_id}`,
448
- });
449
- }
450
- if (expected.action === "create" && expected.escrowLamports !== undefined) {
451
- const data = Buffer.from(lifecycle[0].data_base64, "base64");
452
- if (data.length < 24) {
453
- throw new SwarmClientError({
454
- code: "TRANSACTION_MISMATCH",
455
- operation: "shillbot.validatePreparedTransaction",
456
- message: "Create instruction is truncated",
457
- });
458
- }
459
- const view = new DataView(data.buffer, data.byteOffset + 16, 8);
460
- const amount = view.getBigUint64(0, true);
461
- if (amount !== expected.escrowLamports) {
462
- throw new SwarmClientError({
463
- code: "TRANSACTION_MISMATCH",
464
- operation: "shillbot.validatePreparedTransaction",
465
- message: `Escrow amount ${amount} differs from expected ${expected.escrowLamports}`,
466
- });
467
- }
468
- }
469
- return inspected;
389
+ return verifyBuiltTransaction(encoded, expected, "shillbot.validatePreparedTransaction");
470
390
  }
471
391
  /**
472
392
  * Format the canonical EIP-191 message signed by an agent's EVM referral wallet
@@ -113,3 +113,4 @@ export declare const buildFinalize: (request: Omit<FinalizeBuild, "action">) =>
113
113
  export { buildSwitchboardCrankAndVerify } from "./switchboard.js";
114
114
  export type { SwitchboardVerifyRequest } from "./switchboard.js";
115
115
  export * from "./payout-oracle.js";
116
+ export { 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";
@@ -281,6 +281,7 @@ export function verifyIntent(encoded, intent) {
281
281
  throw new Error(`unexpected companion program ${ix.program_id}`);
282
282
  }
283
283
  }
284
+ validateComputeBudgetInstructions(inspected.instructions);
284
285
  const expectedDiscriminator = shillbotInstructionDiscriminator(intent.action === "submit" ? "submit_work" : `${intent.action}_task`);
285
286
  const lifecycle = inspected.instructions.filter((ix) => ix.program_id === shillbotProgramId &&
286
287
  Buffer.from(ix.data_base64, "base64")
@@ -372,3 +373,5 @@ export const buildVerify = (request) => buildTransaction({ ...request, action: "
372
373
  export const buildFinalize = (request) => buildTransaction({ ...request, action: "finalize" });
373
374
  export { buildSwitchboardCrankAndVerify } from "./switchboard.js";
374
375
  export * from "./payout-oracle.js";
376
+ import { validateComputeBudgetInstructions } from "./verify-tx.js";
377
+ export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, } from "./verify-tx.js";
@@ -0,0 +1,62 @@
1
+ import { type Action, type Network, type TransactionInspection } from "./index.js";
2
+ /** Default maximum allowed Solana priority fee price per compute unit (`100_000` micro-lamports/CU). */
3
+ export declare const MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 100000n;
4
+ /** Solana runtime ceiling for `ComputeBudget::SetComputeUnitLimit` (`1_400_000` CUs). */
5
+ export declare const MAX_COMPUTE_UNIT_LIMIT = 1400000;
6
+ export type ShillbotInstructionName = "initialize" | "create_task" | "claim_task" | "claim_task_session" | "set_payout_to" | "submit_work" | "submit_work_session" | "approve_task" | "verify_task" | "verify_task_attested" | "challenge_task" | "finalize_task" | "expire_task" | "resolve_challenge" | "resolve_challenge_default" | "update_params" | "transfer_authority" | "update_treasury" | "update_oracle_authority" | "emergency_return" | "create_session" | "revoke_session" | "register_identity" | "revoke_identity" | "close_agent_state" | "migrate_agent_state" | "migrate_task";
7
+ export type AuthoritySlotRule = number | "fee_payer" | "verify_task" | "verify_task_attested";
8
+ export interface ShillbotInstructionSpec {
9
+ readonly name: ShillbotInstructionName;
10
+ readonly minAccounts: number;
11
+ readonly exactAccounts?: number;
12
+ readonly taskSlot: number | null;
13
+ readonly authoritySlot: AuthoritySlotRule;
14
+ /** True when third-party gas sponsorship (`fee_payer !== wallet`) is permitted by protocol design. */
15
+ readonly allowsSponsoredFeePayer: boolean;
16
+ }
17
+ /**
18
+ * Exact Anchor account-index and authority-slot specification for every Shillbot instruction,
19
+ * derived directly from `programs/shillbot/src/instructions/*.rs` and `shillbot.json` IDL.
20
+ */
21
+ export declare const SHILLBOT_INSTRUCTION_SPECS: Readonly<Record<ShillbotInstructionName, ShillbotInstructionSpec>>;
22
+ export interface VerifyBuiltTransactionExpectation {
23
+ action?: Action;
24
+ instructionName?: ShillbotInstructionName;
25
+ network: Network;
26
+ wallet: string;
27
+ taskPda?: string;
28
+ feePayer?: string;
29
+ /**
30
+ * Explicit authorized payout destination pubkey (base58).
31
+ * Required whenever a `set_payout_to` instruction is present; otherwise any
32
+ * `set_payout_to` instruction is rejected fail-closed.
33
+ */
34
+ payoutTo?: string;
35
+ oracleAuthority?: string;
36
+ escrowLamports?: bigint;
37
+ contentId?: string;
38
+ maxComputeUnitPriceMicroLamports?: bigint;
39
+ allowedProgramIds?: string[];
40
+ }
41
+ /**
42
+ * Validate a single `ComputeBudget111111111111111111111111111111` instruction's tag,
43
+ * byte length, and value bounds. Never early-returns from a multi-instruction loop.
44
+ */
45
+ export declare function validateComputeBudgetInstruction(data: Uint8Array, maxComputeUnitPriceMicroLamports?: bigint, operation?: string): void;
46
+ /**
47
+ * Validate every `ComputeBudget` instruction in an inspected transaction without
48
+ * short-circuiting on `RequestHeapFrame` (tag 1) or any preceding instruction.
49
+ */
50
+ export declare function validateComputeBudgetInstructions(instructions: TransactionInspection["instructions"], maxComputeUnitPriceMicroLamports?: bigint, operation?: string): void;
51
+ /**
52
+ * Strict fail-closed local validator for built or server-prepared Shillbot Solana transactions.
53
+ *
54
+ * Enforces:
55
+ * - Allowed program IDs (Shillbot + ComputeBudget, plus Switchboard + Secp256k1 only on `verify`).
56
+ * - Full loop validation of all `ComputeBudget` instructions (no early return on `RequestHeapFrame`),
57
+ * capping `SetComputeUnitPrice <= MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS` (`100_000` micro-lamports/CU).
58
+ * - Exact Anchor account-index positions for `task` PDA and authority signer slots per discriminator.
59
+ * - Explicit `set_payout_to` opt-in guard: rejects any `set_payout_to` instruction unless
60
+ * `expected.payoutTo` is explicitly provided AND matches `ix.data[8..40]` and `accounts == [task, wallet]`.
61
+ */
62
+ export declare function verifyBuiltTransaction(encoded: string, expected: VerifyBuiltTransactionExpectation, operation?: string): TransactionInspection;