@swarm-tips/client 0.4.1 → 0.4.3

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.
@@ -1469,6 +1469,59 @@
1469
1469
  ],
1470
1470
  "args": []
1471
1471
  },
1472
+ {
1473
+ "name": "set_devnet_enabled",
1474
+ "discriminator": [
1475
+ 186,
1476
+ 145,
1477
+ 8,
1478
+ 221,
1479
+ 180,
1480
+ 97,
1481
+ 214,
1482
+ 209
1483
+ ],
1484
+ "accounts": [
1485
+ {
1486
+ "name": "global_state",
1487
+ "writable": true,
1488
+ "pda": {
1489
+ "seeds": [
1490
+ {
1491
+ "kind": "const",
1492
+ "value": [
1493
+ 115,
1494
+ 104,
1495
+ 105,
1496
+ 108,
1497
+ 108,
1498
+ 98,
1499
+ 111,
1500
+ 116,
1501
+ 95,
1502
+ 103,
1503
+ 108,
1504
+ 111,
1505
+ 98,
1506
+ 97,
1507
+ 108
1508
+ ]
1509
+ }
1510
+ ]
1511
+ }
1512
+ },
1513
+ {
1514
+ "name": "authority",
1515
+ "signer": true
1516
+ }
1517
+ ],
1518
+ "args": [
1519
+ {
1520
+ "name": "enabled",
1521
+ "type": "bool"
1522
+ }
1523
+ ]
1524
+ },
1472
1525
  {
1473
1526
  "name": "set_payout_to",
1474
1527
  "docs": [
@@ -2375,6 +2428,19 @@
2375
2428
  105
2376
2429
  ]
2377
2430
  },
2431
+ {
2432
+ "name": "DevnetEnabledUpdated",
2433
+ "discriminator": [
2434
+ 134,
2435
+ 199,
2436
+ 123,
2437
+ 224,
2438
+ 220,
2439
+ 73,
2440
+ 89,
2441
+ 126
2442
+ ]
2443
+ },
2378
2444
  {
2379
2445
  "name": "EmergencyReturn",
2380
2446
  "discriminator": [
@@ -2905,6 +2971,31 @@
2905
2971
  "code": 6058,
2906
2972
  "name": "InvalidInstructionBundle",
2907
2973
  "msg": "OnChainAction claim must be bundled atomically at top-level with submit_work"
2974
+ },
2975
+ {
2976
+ "code": 6059,
2977
+ "name": "DevnetOnly",
2978
+ "msg": "Instruction or verification mode is restricted to devnet"
2979
+ },
2980
+ {
2981
+ "code": 6060,
2982
+ "name": "BelowMinimumEscrow",
2983
+ "msg": "Escrow amount is below the minimum required for this platform"
2984
+ },
2985
+ {
2986
+ "code": 6061,
2987
+ "name": "DeadlineTooFarInFuture",
2988
+ "msg": "Task deadline exceeds maximum allowed horizon"
2989
+ },
2990
+ {
2991
+ "code": 6062,
2992
+ "name": "VerificationTimeoutExceeded",
2993
+ "msg": "Verification timeout window has elapsed since submission"
2994
+ },
2995
+ {
2996
+ "code": 6063,
2997
+ "name": "StrikeCooldownActive",
2998
+ "msg": "Agent is in cooldown after a score-0 reopened submission"
2908
2999
  }
2909
3000
  ],
2910
3001
  "types": [
@@ -3000,17 +3091,13 @@
3000
3091
  "type": "u64"
3001
3092
  },
3002
3093
  {
3003
- "name": "_reserved",
3094
+ "name": "last_strike_at",
3004
3095
  "docs": [
3005
- "Reserved space for future fields without reallocation. Reduced from",
3006
- "32 to 8 bytes when the three counters above were claimed."
3096
+ "Unix timestamp of the most recent score-0 reopened submission for this",
3097
+ "agent (`0` = none). Carved from the 8-byte `_reserved` slot so",
3098
+ "`AgentState::SPACE` stays `90` and existing accounts read `0`."
3007
3099
  ],
3008
- "type": {
3009
- "array": [
3010
- "u8",
3011
- 8
3012
- ]
3013
- }
3100
+ "type": "i64"
3014
3101
  },
3015
3102
  {
3016
3103
  "name": "bump",
@@ -3229,6 +3316,18 @@
3229
3316
  ]
3230
3317
  }
3231
3318
  },
3319
+ {
3320
+ "name": "DevnetEnabledUpdated",
3321
+ "type": {
3322
+ "kind": "struct",
3323
+ "fields": [
3324
+ {
3325
+ "name": "devnet_enabled",
3326
+ "type": "bool"
3327
+ }
3328
+ ]
3329
+ }
3330
+ },
3232
3331
  {
3233
3332
  "name": "EmergencyReturn",
3234
3333
  "type": {
@@ -3430,17 +3529,25 @@
3430
3529
  ],
3431
3530
  "type": "i64"
3432
3531
  },
3532
+ {
3533
+ "name": "devnet_enabled",
3534
+ "docs": [
3535
+ "Whether devnet-only verification paths (`verify_task` and kind-0",
3536
+ "`OnChainAction`) are enabled. Carved from `_reserved` — existing",
3537
+ "zero-initialized mainnet accounts read `false` without migration."
3538
+ ],
3539
+ "type": "bool"
3540
+ },
3433
3541
  {
3434
3542
  "name": "_reserved",
3435
3543
  "docs": [
3436
3544
  "Reserved space for future fields without reallocation.",
3437
- "32 → 12 by D2/D3 → 4 by the 2026-07-07",
3438
- "`dispute_resolution_window_seconds` carve."
3545
+ "32 → 12 by D2/D3 → 4 by dispute-window carve → 3 by `devnet_enabled`."
3439
3546
  ],
3440
3547
  "type": {
3441
3548
  "array": [
3442
3549
  "u8",
3443
- 4
3550
+ 3
3444
3551
  ]
3445
3552
  }
3446
3553
  },
@@ -1,4 +1,4 @@
1
- export declare const OPENAPI_VERSION: "0.3.0";
1
+ export declare const OPENAPI_VERSION: "0.4.2";
2
2
  export declare const OPENAPI_SERVERS: readonly ["https://mcp.swarm.tips", "https://api.shillbot.org", "https://api.coordination.game"];
3
3
  export type OpenApiServerUrl = (typeof OPENAPI_SERVERS)[number];
4
4
  export interface OpenApiSchemas {
@@ -113,6 +113,7 @@ export interface OpenApiSchemas {
113
113
  created_at: string;
114
114
  experiment_cohort: string;
115
115
  lean_policy?: number | null;
116
+ onchain_action_spec?: Record<string, unknown> | null;
116
117
  policy_id?: string | null;
117
118
  spent_lamports: number;
118
119
  status: OpenApiSchemas["CampaignStatus"];
@@ -167,6 +168,7 @@ export interface OpenApiSchemas {
167
168
  daily_cap_lamports?: number | null;
168
169
  experiment_cohort?: string | null;
169
170
  lean_policy?: number | null;
171
+ onchain_action?: Record<string, unknown> | null;
170
172
  platform?: number;
171
173
  requires_approval?: boolean;
172
174
  statement_lean?: string | null;
@@ -208,6 +210,7 @@ export interface OpenApiSchemas {
208
210
  };
209
211
  EvmStakedRequest: {
210
212
  game_id: string;
213
+ wallet?: string | null;
211
214
  };
212
215
  ExperimentParams: {
213
216
  cohort_name?: string;
@@ -306,6 +309,12 @@ export interface OpenApiSchemas {
306
309
  NetworkQuery: {
307
310
  network?: string | null;
308
311
  };
312
+ OnChainActionInstructions: {
313
+ atomic_claim_and_submit: boolean;
314
+ content_id_format: string;
315
+ guidance: string;
316
+ status: string;
317
+ };
309
318
  OnboardResponse: {
310
319
  message: string;
311
320
  signature: string;
@@ -323,12 +332,15 @@ export interface OpenApiSchemas {
323
332
  wins: number;
324
333
  };
325
334
  PreflightTaskRequest: {
326
- proof_lean: string;
335
+ agent_wallet?: string | null;
336
+ content_id?: string | null;
337
+ proof_lean?: string;
327
338
  };
328
339
  PreflightTaskResponse: {
329
340
  detail: string;
330
341
  lean_policy: number;
331
342
  ok: boolean;
343
+ status?: string | null;
332
344
  task_id: string;
333
345
  };
334
346
  QueueRequest: {
@@ -475,6 +487,8 @@ export interface OpenApiSchemas {
475
487
  gameplay_instructions?: null | OpenApiSchemas["GamePlayInstructions"];
476
488
  lean_policy?: number | null;
477
489
  lean_proof_instructions?: null | OpenApiSchemas["LeanProofInstructions"];
490
+ onchain_action_instructions?: null | OpenApiSchemas["OnChainActionInstructions"];
491
+ onchain_action_spec?: Record<string, unknown> | null;
478
492
  payment_amount?: number | null;
479
493
  platform: number;
480
494
  quality_threshold: number;
@@ -487,6 +501,7 @@ export interface OpenApiSchemas {
487
501
  task_id: string;
488
502
  task_nonce?: string | null;
489
503
  task_pda?: string | null;
504
+ trust_level?: string | null;
490
505
  website_instructions?: null | OpenApiSchemas["WebsiteInstructions"];
491
506
  };
492
507
  TaskState: "open" | "claimed" | "submitted" | "approved" | "verified" | "finalized" | "disputed" | "resolved" | "expired";
@@ -1,6 +1,6 @@
1
1
  // AUTO-GENERATED by scripts/sync-generated.mjs from services/mcp-server/openapi.merged.json.
2
2
  // Do not edit by hand — run `pnpm --filter @swarm-tips/client sync:generated`.
3
- export const OPENAPI_VERSION = "0.3.0";
3
+ export const OPENAPI_VERSION = "0.4.2";
4
4
  export const OPENAPI_SERVERS = [
5
5
  "https://mcp.swarm.tips",
6
6
  "https://api.shillbot.org",
@@ -158,9 +158,8 @@ export interface ReportReceipt {
158
158
  hidden: boolean;
159
159
  already_reported: boolean;
160
160
  }
161
- /** Known public topic boards. `open-challenge` = game matchmaking,
162
- * `subcontract` = Shillbot task handoff. */
163
- export type TopicId = "open-challenge" | "subcontract";
161
+ import { VALID_TOPICS, isValidTopicId, type TopicId } from "./types.js";
162
+ export { VALID_TOPICS, isValidTopicId, type TopicId };
164
163
  export interface SendReceipt {
165
164
  msg_id: string;
166
165
  thread_id: string;
@@ -281,4 +280,3 @@ export declare class InboxClient {
281
280
  private readCachedSession;
282
281
  private writeCachedSession;
283
282
  }
284
- export {};
@@ -24,6 +24,8 @@
24
24
  * bs58(ed25519 detached over the nonce UTF-8 bytes) — use `solanaNonceSigner`
25
25
  * from this package; EVM = the `personal_sign` hex string as-is.
26
26
  */
27
+ import { VALID_TOPICS, isValidTopicId } from "./types.js";
28
+ export { VALID_TOPICS, isValidTopicId };
27
29
  /** Non-2xx responses and client-side boundary rejections. `status` is the
28
30
  * HTTP status, or 0 for errors raised before any request was made. */
29
31
  export class InboxApiError extends Error {
@@ -233,8 +235,9 @@ export class InboxClient {
233
235
  * needed. `minTrust` drops posts whose author trust is below it
234
236
  * server-side. Hidden (auto-moderated) posts are always dropped. */
235
237
  async readTopic(topicId, opts = {}) {
236
- if (!topicId)
237
- throw new InboxApiError(0, "topicId is required");
238
+ if (!isValidTopicId(topicId)) {
239
+ throw new InboxApiError(0, `topicId must be one of ${VALID_TOPICS.join(", ")}`);
240
+ }
238
241
  const params = new URLSearchParams({ topic_id: topicId });
239
242
  if (opts.cursor)
240
243
  params.set("cursor", opts.cursor);
@@ -261,8 +264,9 @@ export class InboxClient {
261
264
  * inbox send). Rejects empty / oversize bodies client-side; quota
262
265
  * rejections surface as InboxApiError with the server's message. */
263
266
  async publishPost(topicId, body, opts = {}) {
264
- if (!topicId)
265
- throw new InboxApiError(0, "topicId is required");
267
+ if (!isValidTopicId(topicId)) {
268
+ throw new InboxApiError(0, `topicId must be one of ${VALID_TOPICS.join(", ")}`);
269
+ }
266
270
  const bytes = new TextEncoder().encode(body).length;
267
271
  if (bytes === 0 || bytes > MAX_BODY_BYTES) {
268
272
  throw new InboxApiError(0, `body must be 1..${MAX_BODY_BYTES} bytes (got ${bytes})`);
@@ -282,8 +286,9 @@ export class InboxClient {
282
286
  /** Report a post for moderation. Session-gated. Idempotent per reporter —
283
287
  * a repeat report returns `already_reported: true`. */
284
288
  async reportPost(topicId, postId, reason) {
285
- if (!topicId)
286
- throw new InboxApiError(0, "topicId is required");
289
+ if (!isValidTopicId(topicId)) {
290
+ throw new InboxApiError(0, `topicId must be one of ${VALID_TOPICS.join(", ")}`);
291
+ }
287
292
  if (!postId)
288
293
  throw new InboxApiError(0, "postId is required");
289
294
  const payload = {
@@ -1,2 +1,2 @@
1
- export { InboxClient, InboxApiError, type InboxClientOpts, type InboxMessage, type MessageReference, type MessageEnvelope, type InboxListOptions, type InboxListPage, type OpenMessageResult, type OpenedMessage, type AckMessageResult, type InboxSession, type MessagePage, type NonceSigner, type SendReceipt, type MuteReceipt, type TopicId, type TopicPost, type TopicPage, type PublishReceipt, type ReportReceipt, } from "./client.js";
1
+ export { InboxClient, InboxApiError, type InboxClientOpts, type InboxMessage, type MessageReference, type MessageEnvelope, type InboxListOptions, type InboxListPage, type OpenMessageResult, type OpenedMessage, type AckMessageResult, type InboxSession, type MessagePage, type NonceSigner, type SendReceipt, type MuteReceipt, VALID_TOPICS, isValidTopicId, type TopicId, type TopicPost, type TopicPage, type PublishReceipt, type ReportReceipt, } from "./client.js";
2
2
  export { solanaNonceSigner } from "./solana.js";
@@ -1,4 +1,4 @@
1
1
  // Shared browser client for the agent-inbox REST twins
2
2
  // (mcp.swarm.tips /internal/inbox/*).
3
- export { InboxClient, InboxApiError, } from "./client.js";
3
+ export { InboxClient, InboxApiError, VALID_TOPICS, isValidTopicId, } from "./client.js";
4
4
  export { solanaNonceSigner } from "./solana.js";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Canonical public topic boards supported by the Swarm MCP inbox/topics service:
3
+ * - `open-challenge`: Coordination Game matchmaking
4
+ * - `subcontract`: Shillbot task handoff
5
+ * - `town-square`: Open general coordination board
6
+ */
7
+ export declare const VALID_TOPICS: readonly ["open-challenge", "subcontract", "town-square"];
8
+ export type TopicId = (typeof VALID_TOPICS)[number];
9
+ export declare function isValidTopicId(value: unknown): value is TopicId;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Canonical public topic boards supported by the Swarm MCP inbox/topics service:
3
+ * - `open-challenge`: Coordination Game matchmaking
4
+ * - `subcontract`: Shillbot task handoff
5
+ * - `town-square`: Open general coordination board
6
+ */
7
+ export const VALID_TOPICS = ["open-challenge", "subcontract", "town-square"];
8
+ export function isValidTopicId(value) {
9
+ return typeof value === "string" && VALID_TOPICS.includes(value);
10
+ }
package/dist/index.d.ts CHANGED
@@ -3,8 +3,10 @@ export { CLIENT_VERSION } from "./version.js";
3
3
  export declare const CLIENT_MANIFEST_SCHEMA: "swarm.client-manifest/v1";
4
4
  export { SwarmClientError } from "./errors.js";
5
5
  export type { SwarmClientErrorCode, SwarmClientErrorOptions } from "./errors.js";
6
- export { SwarmAgent, createSwarmAgent, type ExecuteTaskOptions, type ExecutedTaskResult, type NextTaskAction, type SwarmAgentOptions, type SwarmNetwork, type TaskLifecycleStep, } from "./agent.js";
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
- export { fromEvmPrivateKey, fromEvmWalletClient, fromSolanaKeypair, fromSolanaSecretKey, fromSolanaWalletAdapter, redactSigner, type EvmCallRequest, type EvmPrivateKeyOptions, type EvmSwarmSigner, type EvmWalletClientLike, type SolanaSwarmSigner, type SolanaWalletAdapterLike, type SwarmSigner, } from "./signer/index.js";
9
- export { SHILLBOT_ESCROW_DEPLOYMENTS, SHILLBOT_EVM_SELECTORS, buildOnChainActionProofRef, estimateSolanaNetworkFeeLamports, formatOnChainActionAttributionMessage, validatePreparedEvmCall, validatePreparedTransaction, type BuildOnChainActionProofRefParams, type BuildVerifyOptions, type PreparedEvmCallExpectation, type PreparedTransactionExpectation, type PreparedTransactionResponse, type ValidatedEvmCall, type VerificationDataResponse, } from "./shillbot/api.js";
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";
10
+ export { VALID_TOPICS, isValidTopicId, type TopicId, } from "./inbox/types.js";
11
+ export { DEFAULT_MAX_VOW_BYTES, fetchVowAttestationJson, validateVowUrl, verifyVow, type FetchVowOptions, type VerifyVowOptions, } from "./vow/verify.js";
10
12
  export { OPENAPI_SERVERS, OPENAPI_VERSION, type OpenApiOperationId, type OpenApiOperations, type OpenApiPaths, type OpenApiSchemas, type OpenApiServerUrl, } from "./generated/openapi.js";
package/dist/index.js CHANGED
@@ -2,8 +2,10 @@
2
2
  export { CLIENT_VERSION } from "./version.js";
3
3
  export const CLIENT_MANIFEST_SCHEMA = "swarm.client-manifest/v1";
4
4
  export { SwarmClientError } from "./errors.js";
5
- export { SwarmAgent, createSwarmAgent, } from "./agent.js";
5
+ export { DEFAULT_MAX_NETWORK_FEE_WEI, SwarmAgent, createSwarmAgent, extractCreateEscrowLamports, } from "./agent.js";
6
6
  export { WalletTokenManager, } from "./auth/token-manager.js";
7
7
  export { fromEvmPrivateKey, fromEvmWalletClient, fromSolanaKeypair, fromSolanaSecretKey, fromSolanaWalletAdapter, redactSigner, } from "./signer/index.js";
8
- export { SHILLBOT_ESCROW_DEPLOYMENTS, SHILLBOT_EVM_SELECTORS, buildOnChainActionProofRef, estimateSolanaNetworkFeeLamports, formatOnChainActionAttributionMessage, validatePreparedEvmCall, validatePreparedTransaction, } from "./shillbot/api.js";
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 { VALID_TOPICS, isValidTopicId, } from "./inbox/types.js";
10
+ export { DEFAULT_MAX_VOW_BYTES, fetchVowAttestationJson, validateVowUrl, verifyVow, } from "./vow/verify.js";
9
11
  export { OPENAPI_SERVERS, OPENAPI_VERSION, } from "./generated/openapi.js";
@@ -70,13 +70,19 @@ export declare class ShillbotApiClient {
70
70
  buildFinalize(id: string): Promise<PreparedTransactionResponse>;
71
71
  confirmTask<TResponse = unknown>(id: string, body: ConfirmTransactionRequest): Promise<TResponse>;
72
72
  }
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, };
73
75
  export interface PreparedTransactionExpectation {
74
76
  action: Action;
75
77
  network: "mainnet" | "devnet";
76
78
  wallet: string;
77
79
  taskPda?: string;
78
80
  feePayer?: string;
81
+ payoutTo?: string;
82
+ oracleAuthority?: string;
79
83
  escrowLamports?: bigint;
84
+ contentId?: string;
85
+ maxComputeUnitPriceMicroLamports?: bigint;
80
86
  allowedProgramIds?: string[];
81
87
  }
82
88
  /** Canonical deployed ShillbotEscrow EVM contracts keyed by CAIP-2 chain ID. */
@@ -94,6 +100,7 @@ export interface ValidatedEvmCall {
94
100
  value: bigint;
95
101
  chain: string;
96
102
  }
103
+ export declare function normalizeEvmChainId(chain: string | number): string;
97
104
  /**
98
105
  * C10 fail-closed local validator for server-prepared EVM `ShillbotEscrow` calls.
99
106
  * Verifies canonical contract address for `chain`, 4-byte function selector for
@@ -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;
@@ -156,6 +156,8 @@ export class ShillbotApiClient {
156
156
  return this.post(`/tasks/${encodeURIComponent(id)}/confirm`, body);
157
157
  }
158
158
  }
159
+ import { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, } from "./verify-tx.js";
160
+ export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, };
159
161
  const SWITCHBOARD_PROGRAM_IDS = {
160
162
  mainnet: "SBondMDrcV3K4kxZR1HNVT7osZxAHVHgYXL5Ze1oMUv",
161
163
  devnet: "Aio4gaXjXzJNVLtzwtNVmSqGKpANtXhybbkhtAC94ji2",
@@ -173,15 +175,27 @@ export const SHILLBOT_EVM_SELECTORS = {
173
175
  verify: "0x3bae608b", // verifyTaskAttested(uint64,uint64,bytes)
174
176
  finalize: "0xcb26e65b", // finalizeTask(uint64)
175
177
  };
176
- function normalizeEvmChainId(chain) {
178
+ export function normalizeEvmChainId(chain) {
179
+ if (typeof chain === "number") {
180
+ if (!Number.isSafeInteger(chain) || chain <= 0) {
181
+ throw new SwarmClientError({
182
+ code: "INVALID_ARGUMENT",
183
+ operation: "shillbot.normalizeEvmChainId",
184
+ message: `Invalid EVM chain ID: ${String(chain)}`,
185
+ });
186
+ }
187
+ return `eip155:${chain}`;
188
+ }
177
189
  const trimmed = chain.trim().toLowerCase();
178
- if (trimmed === "base-sepolia" || trimmed === "84532")
190
+ if (/^\d+$/.test(trimmed))
191
+ return `eip155:${trimmed}`;
192
+ if (trimmed === "base-sepolia")
179
193
  return "eip155:84532";
180
- if (trimmed === "base" || trimmed === "8453")
194
+ if (trimmed === "base")
181
195
  return "eip155:8453";
182
- if (trimmed === "ethereum" || trimmed === "1")
196
+ if (trimmed === "ethereum")
183
197
  return "eip155:1";
184
- if (trimmed === "ethereum-sepolia" || trimmed === "sepolia" || trimmed === "11155111") {
198
+ if (trimmed === "ethereum-sepolia" || trimmed === "sepolia") {
185
199
  return "eip155:11155111";
186
200
  }
187
201
  return trimmed;
@@ -219,7 +233,7 @@ export function validatePreparedEvmCall(evmCall, expected) {
219
233
  const callChain = typeof raw.chain === "string"
220
234
  ? normalizeEvmChainId(raw.chain)
221
235
  : typeof raw.chain_id === "number"
222
- ? `eip155:${raw.chain_id}`
236
+ ? normalizeEvmChainId(raw.chain_id)
223
237
  : undefined;
224
238
  const expectedChain = expected.chain ? normalizeEvmChainId(expected.chain) : undefined;
225
239
  if (callChain && expectedChain && callChain !== expectedChain) {
@@ -313,6 +327,7 @@ export function estimateSolanaNetworkFeeLamports(inspected, wallet) {
313
327
  const computeBudgetId = ComputeBudgetProgram.programId.toBase58();
314
328
  let computeUnitLimit;
315
329
  let microLamportsPerCu = 0n;
330
+ let additionalFeeLamports = 0n;
316
331
  let nonComputeBudgetIxCount = 0;
317
332
  for (const ix of inspected.instructions) {
318
333
  if (ix.program_id !== computeBudgetId) {
@@ -323,150 +338,46 @@ export function estimateSolanaNetworkFeeLamports(inspected, wallet) {
323
338
  if (data.length === 0)
324
339
  continue;
325
340
  const tag = data[0];
341
+ if (tag === 0 && data.length >= 9) {
342
+ // Legacy RequestUnitsDeprecated: u32 units + u32 additionalFeeLamports (never early-return!)
343
+ computeUnitLimit = BigInt(data.readUInt32LE(1));
344
+ additionalFeeLamports += BigInt(data.readUInt32LE(5));
345
+ continue;
346
+ }
347
+ if (tag === 1) {
348
+ // RequestHeapFrame(u32 bytes): does not alter fee, continue checking subsequent instructions!
349
+ continue;
350
+ }
326
351
  if (tag === 2 && data.length >= 5) {
327
352
  computeUnitLimit = BigInt(data.readUInt32LE(1));
353
+ continue;
328
354
  }
329
- else if (tag === 3 && data.length >= 9) {
355
+ if (tag === 3 && data.length >= 9) {
330
356
  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;
357
+ const price = view.getBigUint64(0, true);
358
+ if (price > microLamportsPerCu) {
359
+ microLamportsPerCu = price;
360
+ }
361
+ continue;
337
362
  }
338
363
  }
339
364
  const effectiveUnits = computeUnitLimit ?? BigInt(Math.max(1, nonComputeBudgetIxCount)) * 200000n;
340
365
  const priorityFeeLamports = (effectiveUnits * microLamportsPerCu + 999999n) / 1000000n;
341
366
  const baseSignatureFeeLamports = BigInt(Math.max(1, inspected.signers.length)) * 5000n;
342
- return baseSignatureFeeLamports + priorityFeeLamports;
367
+ return baseSignatureFeeLamports + priorityFeeLamports + additionalFeeLamports;
343
368
  }
344
369
  export function permittedPreparedProgramIds(action, network) {
345
370
  return action === "verify"
346
371
  ? [SWITCHBOARD_PROGRAM_IDS[network], Secp256k1Program.programId.toBase58()]
347
372
  : [];
348
373
  }
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
374
  /**
361
375
  * Fail-closed local validation for a server-prepared Shillbot transaction.
362
376
  * The network is an explicit part of the expectation; callers must construct
363
377
  * their Connection for that same network before signing.
364
378
  */
365
379
  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;
380
+ return verifyBuiltTransaction(encoded, expected, "shillbot.validatePreparedTransaction");
470
381
  }
471
382
  /**
472
383
  * Format the canonical EIP-191 message signed by an agent's EVM referral wallet