@swarm-tips/client 0.2.13 → 0.4.0

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.
@@ -0,0 +1,8 @@
1
+ // AUTO-GENERATED by scripts/sync-generated.mjs from services/mcp-server/openapi.merged.json.
2
+ // Do not edit by hand — run `pnpm --filter @swarm-tips/client sync:generated`.
3
+ export const OPENAPI_VERSION = "0.3.0";
4
+ export const OPENAPI_SERVERS = [
5
+ "https://mcp.swarm.tips",
6
+ "https://api.shillbot.org",
7
+ "https://api.coordination.game",
8
+ ];
package/dist/http.d.ts CHANGED
@@ -3,17 +3,20 @@ export interface HttpClientOptions {
3
3
  baseUrl: string;
4
4
  fetch?: FetchLike;
5
5
  network?: string;
6
- getToken?: () => string | null | undefined;
6
+ getToken?: () => Promise<string | null | undefined> | string | null | undefined;
7
+ onUnauthorized?: () => Promise<void> | void;
7
8
  }
8
9
  export declare class HttpClient {
9
10
  readonly baseUrl: string;
10
11
  readonly network?: string;
11
- private readonly fetchImpl;
12
- private readonly getToken?;
12
+ readonly fetchImpl: FetchLike;
13
+ readonly getToken?: () => Promise<string | null | undefined> | string | null | undefined;
14
+ private readonly onUnauthorized?;
13
15
  constructor(options: HttpClientOptions);
14
16
  withNetwork(path: string): string;
15
17
  request<T>(path: string, init?: RequestInit & {
16
18
  token?: string | null;
19
+ _retried?: boolean;
17
20
  }): Promise<T>;
18
21
  get<T>(path: string, token?: string | null): Promise<T>;
19
22
  post<T>(path: string, body?: unknown, token?: string | null): Promise<T>;
package/dist/http.js CHANGED
@@ -4,6 +4,7 @@ export class HttpClient {
4
4
  network;
5
5
  fetchImpl;
6
6
  getToken;
7
+ onUnauthorized;
7
8
  constructor(options) {
8
9
  this.baseUrl = options.baseUrl.replace(/\/$/, "");
9
10
  this.network = options.network;
@@ -18,6 +19,7 @@ export class HttpClient {
18
19
  ? (input, init) => options.fetch(input, init)
19
20
  : candidate.bind(globalThis);
20
21
  this.getToken = options.getToken;
22
+ this.onUnauthorized = options.onUnauthorized;
21
23
  }
22
24
  withNetwork(path) {
23
25
  if (!this.network || this.network === "mainnet" || /[?&]network=/.test(path))
@@ -27,14 +29,15 @@ export class HttpClient {
27
29
  }
28
30
  async request(path, init = {}) {
29
31
  const operation = `${init.method ?? "GET"} ${path}`;
30
- const token = init.token ?? this.getToken?.();
32
+ const token = init.token ?? (await this.getToken?.());
33
+ const { token: _token, _retried, ...fetchInit } = init;
31
34
  const headers = {
32
- ...init.headers,
35
+ ...fetchInit.headers,
33
36
  };
34
37
  // A Content-Type header on a bodyless GET turns an otherwise simple
35
38
  // cross-origin read into a CORS preflight. Public browser reads should not
36
39
  // require OPTIONS for a body that does not exist.
37
- if (init.body !== undefined && !headers["Content-Type"]) {
40
+ if (fetchInit.body !== undefined && !headers["Content-Type"]) {
38
41
  headers["Content-Type"] = "application/json";
39
42
  }
40
43
  if (token)
@@ -42,7 +45,7 @@ export class HttpClient {
42
45
  let response;
43
46
  try {
44
47
  response = await this.fetchImpl(`${this.baseUrl}${this.withNetwork(path)}`, {
45
- ...init,
48
+ ...fetchInit,
46
49
  headers,
47
50
  });
48
51
  }
@@ -55,6 +58,17 @@ export class HttpClient {
55
58
  cause,
56
59
  });
57
60
  }
61
+ if (response.status === 401 &&
62
+ !_retried &&
63
+ init.token === undefined &&
64
+ this.onUnauthorized &&
65
+ this.getToken) {
66
+ await this.onUnauthorized();
67
+ const freshToken = await this.getToken();
68
+ if (freshToken && freshToken !== token) {
69
+ return this.request(path, { ...init, _retried: true });
70
+ }
71
+ }
58
72
  if (!response.ok) {
59
73
  const raw = await response.text().catch(() => "");
60
74
  let message = `HTTP ${response.status}`;
@@ -166,6 +166,10 @@ export interface SendReceipt {
166
166
  thread_id: string;
167
167
  sends_remaining_today?: number;
168
168
  }
169
+ export interface MuteReceipt {
170
+ thread_id: string;
171
+ muted: boolean;
172
+ }
169
173
  /** Non-2xx responses and client-side boundary rejections. `status` is the
170
174
  * HTTP status, or 0 for errors raised before any request was made. */
171
175
  export declare class InboxApiError extends Error {
@@ -185,11 +189,19 @@ export interface InboxClientOpts {
185
189
  storage?: StorageLike | null;
186
190
  /** fetch implementation — tests inject a mock. */
187
191
  fetchFn?: typeof fetch;
192
+ /** Unified Bearer token provider. When returning a token, sends
193
+ * `Authorization: Bearer <token>` and NEVER sends `X-Inbox-Session` or
194
+ * calls `/internal/inbox/session` (C1). */
195
+ getToken?: () => Promise<string | undefined> | string | undefined;
196
+ /** Optional hook invoked once before retrying a 401 in Bearer mode. */
197
+ onUnauthorized?: () => Promise<void> | void;
188
198
  }
189
199
  export declare class InboxClient {
190
200
  private readonly baseUrl;
191
201
  private readonly storage;
192
202
  private readonly fetchFn;
203
+ private readonly getToken?;
204
+ private readonly onUnauthorized?;
193
205
  private session;
194
206
  private wallet;
195
207
  private signNonce;
@@ -239,6 +251,8 @@ export declare class InboxClient {
239
251
  /** Advance the read watermark up to a msg_id cursor. NOTE: the watermark is
240
252
  * mailbox-global — acking a cursor also acks every older message. */
241
253
  ack(upToCursor: string): Promise<void>;
254
+ /** Mute or unmute a thread in the authenticated mailbox. */
255
+ muteThread(threadId: string, muted?: boolean): Promise<MuteReceipt>;
242
256
  /** Read a page of a public topic board, newest first. OPEN — no session
243
257
  * needed. `minTrust` drops posts whose author trust is below it
244
258
  * server-side. Hidden (auto-moderated) posts are always dropped. */
@@ -257,11 +271,12 @@ export declare class InboxClient {
257
271
  }): Promise<PublishReceipt>;
258
272
  /** Report a post for moderation. Session-gated. Idempotent per reporter —
259
273
  * a repeat report returns `already_reported: true`. */
260
- reportPost(topicId: TopicId, postId: string): Promise<ReportReceipt>;
274
+ reportPost(topicId: TopicId, postId: string, reason?: string): Promise<ReportReceipt>;
261
275
  private getUnauthed;
262
276
  private mintSession;
263
277
  private postUnauthed;
264
278
  private authed;
279
+ private doBearerFetch;
265
280
  private doFetch;
266
281
  private readCachedSession;
267
282
  private writeCachedSession;
@@ -77,6 +77,8 @@ export class InboxClient {
77
77
  baseUrl;
78
78
  storage;
79
79
  fetchFn;
80
+ getToken;
81
+ onUnauthorized;
80
82
  session = null;
81
83
  wallet = null;
82
84
  signNonce = null;
@@ -86,6 +88,8 @@ export class InboxClient {
86
88
  this.fetchFn =
87
89
  opts.fetchFn ??
88
90
  ((input, init) => fetch(input, init));
91
+ this.getToken = opts.getToken;
92
+ this.onUnauthorized = opts.onUnauthorized;
89
93
  }
90
94
  /** True when a cached session exists for `wallet` — opening the inbox will
91
95
  * not prompt a wallet signature. */
@@ -215,6 +219,15 @@ export class InboxClient {
215
219
  body: JSON.stringify({ up_to_cursor: upToCursor }),
216
220
  });
217
221
  }
222
+ /** Mute or unmute a thread in the authenticated mailbox. */
223
+ async muteThread(threadId, muted = true) {
224
+ if (!threadId)
225
+ throw new InboxApiError(0, "threadId is required");
226
+ return this.authed("/internal/inbox/mute", {
227
+ method: "POST",
228
+ body: JSON.stringify({ thread_id: threadId, muted }),
229
+ });
230
+ }
218
231
  // -- topic boards ---------------------------------------------------------
219
232
  /** Read a page of a public topic board, newest first. OPEN — no session
220
233
  * needed. `minTrust` drops posts whose author trust is below it
@@ -268,14 +281,20 @@ export class InboxClient {
268
281
  }
269
282
  /** Report a post for moderation. Session-gated. Idempotent per reporter —
270
283
  * a repeat report returns `already_reported: true`. */
271
- async reportPost(topicId, postId) {
284
+ async reportPost(topicId, postId, reason) {
272
285
  if (!topicId)
273
286
  throw new InboxApiError(0, "topicId is required");
274
287
  if (!postId)
275
288
  throw new InboxApiError(0, "postId is required");
289
+ const payload = {
290
+ topic_id: topicId,
291
+ post_id: postId,
292
+ };
293
+ if (reason !== undefined)
294
+ payload["reason"] = reason;
276
295
  return this.authed("/internal/topics/report", {
277
296
  method: "POST",
278
- body: JSON.stringify({ topic_id: topicId, post_id: postId }),
297
+ body: JSON.stringify(payload),
279
298
  });
280
299
  }
281
300
  // -- internals ------------------------------------------------------------
@@ -314,6 +333,24 @@ export class InboxClient {
314
333
  return parseBody(res);
315
334
  }
316
335
  async authed(path, init) {
336
+ if (this.getToken) {
337
+ const token = await this.getToken();
338
+ if (token) {
339
+ const res = await this.doBearerFetch(path, init, token);
340
+ if (res.status === 401 && this.onUnauthorized) {
341
+ await this.onUnauthorized();
342
+ const freshToken = await this.getToken();
343
+ if (freshToken && freshToken !== token) {
344
+ const retry = await this.doBearerFetch(path, init, freshToken);
345
+ return parseBody(retry);
346
+ }
347
+ }
348
+ return parseBody(res);
349
+ }
350
+ if (!this.session) {
351
+ throw new InboxApiError(0, "no Bearer token or inbox session — authenticate signer or call createSession first");
352
+ }
353
+ }
317
354
  const session = this.session;
318
355
  if (!session) {
319
356
  throw new InboxApiError(0, "no inbox session — call createSession first");
@@ -329,6 +366,15 @@ export class InboxClient {
329
366
  }
330
367
  return parseBody(res);
331
368
  }
369
+ doBearerFetch(path, init, token) {
370
+ // C1 invariant: NEVER send X-Inbox-Session when authenticating with Authorization: Bearer.
371
+ const headers = {
372
+ Authorization: `Bearer ${token}`,
373
+ };
374
+ if (init.body !== undefined)
375
+ headers["Content-Type"] = "application/json";
376
+ return this.fetchFn(`${this.baseUrl}${path}`, { ...init, headers });
377
+ }
332
378
  doFetch(path, init, sessionId) {
333
379
  const headers = { "X-Inbox-Session": sessionId };
334
380
  if (init.body !== undefined)
@@ -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 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, type TopicId, type TopicPost, type TopicPage, type PublishReceipt, type ReportReceipt, } from "./client.js";
2
2
  export { solanaNonceSigner } from "./solana.js";
package/dist/index.d.ts CHANGED
@@ -1,5 +1,10 @@
1
- /** The unified client package version. Functional APIs live in typed subpaths. */
2
- export declare const CLIENT_VERSION: "0.2.4";
1
+ /** The unified client package version, synchronized from package.json. */
2
+ 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";
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";
10
+ export { OPENAPI_SERVERS, OPENAPI_VERSION, type OpenApiOperationId, type OpenApiOperations, type OpenApiPaths, type OpenApiSchemas, type OpenApiServerUrl, } from "./generated/openapi.js";
package/dist/index.js CHANGED
@@ -1,4 +1,9 @@
1
- /** The unified client package version. Functional APIs live in typed subpaths. */
2
- export const CLIENT_VERSION = "0.2.4";
1
+ /** The unified client package version, synchronized from package.json. */
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";
6
+ export { WalletTokenManager, } from "./auth/token-manager.js";
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";
9
+ export { OPENAPI_SERVERS, OPENAPI_VERSION, } from "./generated/openapi.js";
@@ -1,14 +1,28 @@
1
1
  import { Connection, type BlockhashWithExpiryBlockHeight } from "@solana/web3.js";
2
2
  import { HttpClient, type HttpClientOptions } from "../http.js";
3
- import { type Action, type TransactionInspection, type WalletSignCallback } from "./index.js";
3
+ import { type Action, type TransactionInspection, type TransactionIntent, type WalletSignCallback } from "./index.js";
4
4
  export type { Action } from "./index.js";
5
5
  export interface PreparedTransactionResponse {
6
6
  message?: string;
7
7
  task_id?: string;
8
8
  transaction: string;
9
9
  task_pda?: string;
10
+ transaction_intent?: TransactionIntent;
10
11
  evm_call?: unknown;
11
12
  }
13
+ export interface VerificationDataResponse {
14
+ task_id?: string;
15
+ task_pda: string;
16
+ composite_score: number;
17
+ verification_hash: string;
18
+ global_state?: string;
19
+ switchboard_feed: string;
20
+ }
21
+ export interface BuildVerifyOptions {
22
+ payer?: string;
23
+ mcpBaseUrl?: string;
24
+ network?: "mainnet" | "devnet";
25
+ }
12
26
  export interface ConfirmTransactionRequest {
13
27
  tx_signature: string;
14
28
  action: Action;
@@ -29,6 +43,7 @@ export declare class ShillbotApiClient {
29
43
  post<T>(path: string, body?: unknown): Promise<T>;
30
44
  patch<T>(path: string, body?: unknown): Promise<T>;
31
45
  listTasks<TTask = unknown>(limit?: number): Promise<TaskListResponse<TTask>>;
46
+ getTask<TTask = unknown>(id: string): Promise<TTask>;
32
47
  listAgentTasks<TTask = unknown>(): Promise<TTask[] | TaskListResponse<TTask>>;
33
48
  listPendingApproval<TTask = unknown>(): Promise<TTask[] | TaskListResponse<TTask>>;
34
49
  listCampaigns<TCampaign = unknown>(): Promise<TCampaign[] | CampaignListResponse<TCampaign>>;
@@ -43,9 +58,15 @@ export declare class ShillbotApiClient {
43
58
  onboard<TResponse = unknown>(): Promise<TResponse>;
44
59
  earnings<TResponse = unknown>(): Promise<TResponse>;
45
60
  claimTask(id: string, sponsor?: string): Promise<PreparedTransactionResponse>;
61
+ sponsorTask(id: string, body: {
62
+ action: "claim" | "submit";
63
+ unsigned_transaction: string;
64
+ }): Promise<PreparedTransactionResponse>;
46
65
  submitTask(id: string, body: unknown): Promise<PreparedTransactionResponse>;
66
+ preflightTask<TResponse = unknown>(id: string, body?: unknown): Promise<TResponse>;
47
67
  approveTask(id: string): Promise<PreparedTransactionResponse>;
48
- buildVerify(id: string): Promise<PreparedTransactionResponse>;
68
+ getVerificationData(id: string, network?: "mainnet" | "devnet"): Promise<VerificationDataResponse>;
69
+ buildVerify(id: string, opts?: BuildVerifyOptions): Promise<PreparedTransactionResponse>;
49
70
  buildFinalize(id: string): Promise<PreparedTransactionResponse>;
50
71
  confirmTask<TResponse = unknown>(id: string, body: ConfirmTransactionRequest): Promise<TResponse>;
51
72
  }
@@ -58,6 +79,33 @@ export interface PreparedTransactionExpectation {
58
79
  escrowLamports?: bigint;
59
80
  allowedProgramIds?: string[];
60
81
  }
82
+ /** Canonical deployed ShillbotEscrow EVM contracts keyed by CAIP-2 chain ID. */
83
+ export declare const SHILLBOT_ESCROW_DEPLOYMENTS: Readonly<Record<string, `0x${string}`>>;
84
+ /** Canonical 4-byte function selectors for `ShillbotEscrow.sol` lifecycle actions. */
85
+ export declare const SHILLBOT_EVM_SELECTORS: Readonly<Record<Action, `0x${string}`>>;
86
+ export interface PreparedEvmCallExpectation {
87
+ action: Action;
88
+ chain?: string;
89
+ maxValueWei?: bigint;
90
+ }
91
+ export interface ValidatedEvmCall {
92
+ to: `0x${string}`;
93
+ data: `0x${string}`;
94
+ value: bigint;
95
+ chain: string;
96
+ }
97
+ /**
98
+ * C10 fail-closed local validator for server-prepared EVM `ShillbotEscrow` calls.
99
+ * Verifies canonical contract address for `chain`, 4-byte function selector for
100
+ * `action`, and `value_wei <= maxValueWei` (strictly `0n` on non-create actions).
101
+ */
102
+ export declare function validatePreparedEvmCall(evmCall: unknown, expected: PreparedEvmCallExpectation): ValidatedEvmCall;
103
+ /**
104
+ * Estimate the maximum Solana network fee (base signature fees + ComputeBudget
105
+ * priority fee) charged to `wallet` for an inspected transaction. Returns `0n`
106
+ * when a third-party sponsor is the `fee_payer`.
107
+ */
108
+ export declare function estimateSolanaNetworkFeeLamports(inspected: TransactionInspection, wallet: string): bigint;
61
109
  export declare function permittedPreparedProgramIds(action: Action, network: "mainnet" | "devnet"): string[];
62
110
  /**
63
111
  * Fail-closed local validation for a server-prepared Shillbot transaction.
@@ -65,6 +113,30 @@ export declare function permittedPreparedProgramIds(action: Action, network: "ma
65
113
  * their Connection for that same network before signing.
66
114
  */
67
115
  export declare function validatePreparedTransaction(encoded: string, expected: PreparedTransactionExpectation): TransactionInspection;
116
+ export interface BuildOnChainActionProofRefParams {
117
+ /** CAIP-2 target chain ID (e.g. `"eip155:56"`, `"eip155:8453"`, `"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"`). */
118
+ targetChainId: string;
119
+ /** Transaction hash (`0x` + 64 hex chars on EVM) or base58 signature (on Solana). */
120
+ txId: string;
121
+ /** Zero-based log index within the EVM receipt or matched instruction index on Solana. */
122
+ index: number;
123
+ /**
124
+ * Optional 65-byte EIP-191 signature (`0x` + 130 hex chars or `Uint8Array`)
125
+ * over `formatOnChainActionAttributionMessage(targetChainId, agentSolanaPubkey)`
126
+ * binding an EVM referral address to the Solana settlement wallet (`M2a`).
127
+ */
128
+ attributionSignature?: string | Uint8Array;
129
+ }
130
+ /**
131
+ * Format the canonical EIP-191 message signed by an agent's EVM referral wallet
132
+ * to bind cross-chain EVM conversions to their Solana settlement pubkey (`M2a`).
133
+ */
134
+ export declare function formatOnChainActionAttributionMessage(targetChainId: string, agentSolanaPubkey: string): string;
135
+ /**
136
+ * Build a canonical `content_id` proof reference for `PlatformType::OnChainAction = 11`:
137
+ * `<caip2>:<tx_id>:<index>[:sig:<base64url_nopad_65B>]`.
138
+ */
139
+ export declare function buildOnChainActionProofRef(params: BuildOnChainActionProofRefParams): string;
68
140
  export declare function signBroadcastPreparedTransaction(input: {
69
141
  connection: Connection;
70
142
  transaction: string;