@swarm-tips/client 0.4.6 → 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.
@@ -1,117 +1,315 @@
1
1
  /**
2
2
  * Ephemeral EVM session key — the Base-game analog of the Solana session
3
3
  * keypair (`session.ts`). One main-wallet popup funds the session address with
4
- * stake + gas; the session key then signs createGame/joinGame/commitGuess/
5
- * revealGuess locally.
4
+ * gas (while stake is escrowed to the player's on-chain ledger); the session key
5
+ * then signs createGame/joinGame/commitGuess/revealGuess locally.
6
6
  *
7
- * Under the shipped v3 WALLET-AS-PLAYER design the session key is a gas-only
8
- * DELEGATE, not the player: the wallet is `game.player1/2` on-chain, and the
9
- * payout is credited to the wallet and realized with `withdrawFor`. There is
10
- * therefore NO sweep, and no `evm-sweep.ts` — that file never existed under v3.
11
- *
12
- * The private key lives in sessionStorage (cleared on tab close) bound to the
13
- * main wallet, with a 24h TTL — same guards as the Solana session. Only gas
14
- * dust ever sits on the session address.
7
+ * Persistence invariant (`P1-5`): active EVM session keys are persisted in
8
+ * `localStorage` first (mirroring to `sessionStorage`, and falling back to
9
+ * `sessionStorage` when `localStorage` is unavailable) and retained until the
10
+ * delegate's on-chain ETH balance is swept to `0`, so closing and reopening a
11
+ * browser tab never orphans funded ETH in an ephemeral EVM session key. Legacy
12
+ * keys stored only in `sessionStorage` are transparently migrated to `localStorage`.
15
13
  */
16
14
  import { bytesToHex, createPublicClient, createWalletClient, fallback, hexToBytes, http, } from "viem";
17
15
  import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
18
- const SESSION_KEY = "coordination-evm-session";
19
- const SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
16
+ export const EVM_SESSION_STORAGE_KEY = "coordination-evm-session";
17
+ const SESSION_KEY = EVM_SESSION_STORAGE_KEY;
20
18
  const PRIVATE_KEY_RE = /^0x[0-9a-fA-F]{64}$/;
21
- /** Generate a fresh ephemeral secp256k1 private key for session signing. */
22
- export function generateEvmSessionKey() {
23
- return generatePrivateKey();
19
+ function isStorageLike(candidate) {
20
+ return (Boolean(candidate) &&
21
+ typeof candidate === "object" &&
22
+ typeof candidate.getItem === "function" &&
23
+ typeof candidate.setItem === "function" &&
24
+ typeof candidate.removeItem === "function");
24
25
  }
25
- /**
26
- * Read the session key from sessionStorage. Returns null if no session
27
- * exists, the session has expired (24h TTL), or it belongs to a different
28
- * main wallet. Any invalid stored value is removed.
29
- */
30
- export function getStoredEvmSession(storage, walletAddress, now = Date.now) {
31
- const raw = storage.getItem(SESSION_KEY);
32
- if (raw === null)
33
- return null;
34
- let stored;
26
+ function getSafeGlobalStorage(kind) {
35
27
  try {
36
- stored = JSON.parse(raw);
28
+ if (typeof globalThis.window === "undefined" &&
29
+ typeof process !== "undefined" &&
30
+ Boolean(process.versions?.node) &&
31
+ Object.getOwnPropertyDescriptor(globalThis, kind)?.get &&
32
+ !process.execArgv.some((arg) => arg.startsWith("--localstorage-file="))) {
33
+ return null;
34
+ }
35
+ const candidate = globalThis[kind];
36
+ if (!isStorageLike(candidate))
37
+ return null;
38
+ // Probe read access (Safari/Firefox private mode may throw on storage access).
39
+ candidate.getItem("__swarm_evm_session_probe__");
40
+ return candidate;
37
41
  }
38
42
  catch {
39
- storage.removeItem(SESSION_KEY);
40
43
  return null;
41
44
  }
42
- if (typeof stored.privateKey !== "string" ||
43
- !PRIVATE_KEY_RE.test(stored.privateKey) ||
44
- typeof stored.createdAt !== "number" ||
45
- typeof stored.wallet !== "string") {
46
- storage.removeItem(SESSION_KEY);
45
+ }
46
+ function resolveStoragePair(input) {
47
+ if (input === undefined || input === null) {
48
+ return {
49
+ local: getSafeGlobalStorage("localStorage"),
50
+ session: getSafeGlobalStorage("sessionStorage"),
51
+ };
52
+ }
53
+ if (!isStorageLike(input)) {
54
+ return {
55
+ local: input.localStorage !== undefined ? input.localStorage : getSafeGlobalStorage("localStorage"),
56
+ session: input.sessionStorage !== undefined
57
+ ? input.sessionStorage
58
+ : getSafeGlobalStorage("sessionStorage"),
59
+ };
60
+ }
61
+ const globalSession = getSafeGlobalStorage("sessionStorage");
62
+ const globalLocal = getSafeGlobalStorage("localStorage");
63
+ if (globalSession && input === globalSession) {
64
+ return { local: globalLocal, session: input };
65
+ }
66
+ if (globalLocal && input === globalLocal) {
67
+ return { local: input, session: globalSession };
68
+ }
69
+ return { local: input, session: null };
70
+ }
71
+ function safeGetItem(storage, key) {
72
+ if (!storage)
47
73
  return null;
74
+ try {
75
+ return storage.getItem(key);
48
76
  }
49
- if (walletAddress &&
50
- stored.wallet.toLowerCase() !== walletAddress.toLowerCase()) {
51
- storage.removeItem(SESSION_KEY);
77
+ catch {
52
78
  return null;
53
79
  }
54
- if (now() - stored.createdAt > SESSION_TTL_MS) {
55
- storage.removeItem(SESSION_KEY);
80
+ }
81
+ function safeSetItem(storage, key, value) {
82
+ if (!storage)
83
+ return false;
84
+ try {
85
+ storage.setItem(key, value);
86
+ return true;
87
+ }
88
+ catch {
89
+ return false;
90
+ }
91
+ }
92
+ function safeRemoveItem(storage, key) {
93
+ if (!storage)
94
+ return;
95
+ try {
96
+ storage.removeItem(key);
97
+ }
98
+ catch {
99
+ // Ignore storage removal errors.
100
+ }
101
+ }
102
+ function parseStoredEvmSession(raw) {
103
+ let parsed;
104
+ try {
105
+ parsed = JSON.parse(raw);
106
+ }
107
+ catch {
56
108
  return null;
57
109
  }
58
- return stored.privateKey;
110
+ if (!parsed ||
111
+ typeof parsed !== "object" ||
112
+ typeof parsed.privateKey !== "string" ||
113
+ !PRIVATE_KEY_RE.test(parsed.privateKey) ||
114
+ typeof parsed.createdAt !== "number" ||
115
+ typeof parsed.wallet !== "string") {
116
+ return null;
117
+ }
118
+ return parsed;
119
+ }
120
+ /** Generate a fresh ephemeral secp256k1 private key for session signing. */
121
+ export function generateEvmSessionKey() {
122
+ return generatePrivateKey();
123
+ }
124
+ /**
125
+ * Read the persisted EVM session key from `localStorage` first, falling back to
126
+ * `sessionStorage` and migrating legacy `sessionStorage`-only keys into `localStorage`.
127
+ * Retains valid keys across tab closes and past 24h until explicitly cleared after
128
+ * on-chain ETH balance is swept to `0`.
129
+ */
130
+ export function getStoredEvmSession(storage, walletAddress, _now = Date.now) {
131
+ const { local, session } = resolveStoragePair(storage);
132
+ const rawLocal = safeGetItem(local, SESSION_KEY);
133
+ if (rawLocal !== null) {
134
+ const parsedLocal = parseStoredEvmSession(rawLocal);
135
+ if (!parsedLocal) {
136
+ safeRemoveItem(local, SESSION_KEY);
137
+ }
138
+ else if (!walletAddress ||
139
+ parsedLocal.wallet.toLowerCase() === walletAddress.toLowerCase()) {
140
+ if (session && safeGetItem(session, SESSION_KEY) !== rawLocal) {
141
+ safeSetItem(session, SESSION_KEY, rawLocal);
142
+ }
143
+ return parsedLocal.privateKey;
144
+ }
145
+ }
146
+ const rawSession = safeGetItem(session, SESSION_KEY);
147
+ if (rawSession !== null) {
148
+ const parsedSession = parseStoredEvmSession(rawSession);
149
+ if (!parsedSession) {
150
+ safeRemoveItem(session, SESSION_KEY);
151
+ return null;
152
+ }
153
+ if (walletAddress &&
154
+ parsedSession.wallet.toLowerCase() !== walletAddress.toLowerCase()) {
155
+ return null;
156
+ }
157
+ // Migrate legacy sessionStorage key into localStorage so tab close cannot orphan ETH.
158
+ if (local && rawLocal === null) {
159
+ safeSetItem(local, SESSION_KEY, rawSession);
160
+ }
161
+ return parsedSession.privateKey;
162
+ }
163
+ return null;
59
164
  }
60
- /** Persist the session key in sessionStorage, bound to the main wallet. */
165
+ export function loadSessionKey(walletOrStorage, optionsOrWallet) {
166
+ if (typeof walletOrStorage === "string" || walletOrStorage === undefined) {
167
+ const storage = typeof optionsOrWallet === "object" ? optionsOrWallet : undefined;
168
+ return getStoredEvmSession(storage, walletOrStorage);
169
+ }
170
+ const walletAddress = typeof optionsOrWallet === "string" ? optionsOrWallet : undefined;
171
+ return getStoredEvmSession(walletOrStorage, walletAddress);
172
+ }
173
+ /**
174
+ * Persist the EVM session key in `localStorage` first, mirroring to `sessionStorage`
175
+ * (and falling back to `sessionStorage` when `localStorage` is unavailable).
176
+ */
61
177
  export function storeEvmSession(storage, privateKey, walletAddress, now = Date.now) {
62
- const stored = {
178
+ const { local, session } = resolveStoragePair(storage);
179
+ const serialized = JSON.stringify({
63
180
  privateKey,
64
181
  createdAt: now(),
65
182
  wallet: walletAddress,
66
- };
67
- storage.setItem(SESSION_KEY, JSON.stringify(stored));
183
+ });
184
+ const wroteLocal = safeSetItem(local, SESSION_KEY, serialized);
185
+ const wroteSession = safeSetItem(session, SESSION_KEY, serialized);
186
+ if (!wroteLocal && !wroteSession) {
187
+ console.warn("[evm-session] failed to persist EVM session key in localStorage/sessionStorage");
188
+ }
189
+ }
190
+ /** Ergonomic helper to persist an EVM session key in `localStorage` + `sessionStorage`. */
191
+ export function saveSessionKey(privateKey, walletAddress, options) {
192
+ storeEvmSession(options, privateKey, walletAddress, options?.now);
68
193
  }
69
- /** Remove the session key from sessionStorage. */
194
+ /** Remove the EVM session key from both `localStorage` and `sessionStorage`. */
70
195
  export function clearEvmSession(storage) {
71
- storage.removeItem(SESSION_KEY);
196
+ const { local, session } = resolveStoragePair(storage);
197
+ safeRemoveItem(local, SESSION_KEY);
198
+ safeRemoveItem(session, SESSION_KEY);
199
+ }
200
+ /** A plain native-ETH transfer uses 21,000 gas. */
201
+ export const SWEEP_GAS_LIMIT = 21000n;
202
+ /**
203
+ * Compute the native ETH amount to sweep from a session key back to the main wallet:
204
+ * `balance - 1.25 * (21_000 * maxFeePerGas)`, clamped at `0n`.
205
+ */
206
+ export function sweepValueWei(balance, maxFeePerGas) {
207
+ if (balance <= 0n || maxFeePerGas <= 0n)
208
+ return 0n;
209
+ const cost = SWEEP_GAS_LIMIT * maxFeePerGas;
210
+ const reserve = cost + cost / 4n;
211
+ const value = balance - reserve;
212
+ return value > 0n ? value : 0n;
213
+ }
214
+ /**
215
+ * Sweep leftover ETH from an EVM session key back to `mainWallet`, clearing
216
+ * persisted storage **only** once the session address's on-chain balance reaches `0n`.
217
+ * If the sweep fails or non-zero balance remains on-chain, the key is retained in
218
+ * `localStorage` so funded ETH is never orphaned.
219
+ */
220
+ export async function sweepEvmSession(sessionKey, mainWallet, chain, rpcUrls, options = {}) {
221
+ const pub = options.readClient ?? evmReadClient(chain, rpcUrls);
222
+ const sessionAddr = evmSessionAddress(sessionKey);
223
+ const balance = await pub.getBalance({ address: sessionAddr });
224
+ if (balance === 0n) {
225
+ clearEvmSession(options.storage);
226
+ return 0n;
227
+ }
228
+ const fees = pub.estimateFeesPerGas
229
+ ? await pub.estimateFeesPerGas()
230
+ : { maxFeePerGas: undefined, maxPriorityFeePerGas: undefined };
231
+ const maxFeePerGas = fees.maxFeePerGas ?? (pub.getGasPrice ? await pub.getGasPrice() : 0n);
232
+ const exactCost = SWEEP_GAS_LIMIT * maxFeePerGas;
233
+ const value = options.exact
234
+ ? balance > exactCost && maxFeePerGas > 0n
235
+ ? balance - exactCost
236
+ : 0n
237
+ : sweepValueWei(balance, maxFeePerGas);
238
+ if (value > 0n) {
239
+ const maxPriorityFeePerGas = options.exact
240
+ ? maxFeePerGas
241
+ : (fees.maxPriorityFeePerGas ?? maxFeePerGas);
242
+ const hash = options.walletClient
243
+ ? await options.walletClient.sendTransaction({
244
+ account: options.walletClient.account ?? privateKeyToAccount(sessionKey),
245
+ chain: null,
246
+ to: mainWallet,
247
+ value,
248
+ gas: SWEEP_GAS_LIMIT,
249
+ maxFeePerGas,
250
+ maxPriorityFeePerGas,
251
+ })
252
+ : await evmSessionClient(sessionKey, chain, rpcUrls).sendTransaction({
253
+ account: privateKeyToAccount(sessionKey),
254
+ chain: null,
255
+ to: mainWallet,
256
+ value,
257
+ gas: SWEEP_GAS_LIMIT,
258
+ maxFeePerGas,
259
+ maxPriorityFeePerGas,
260
+ });
261
+ const receipt = await pub.waitForTransactionReceipt({ hash });
262
+ if (receipt?.status && receipt.status !== "success") {
263
+ throw new Error(`EVM session sweep reverted (tx ${hash}); retaining session key`);
264
+ }
265
+ }
266
+ const remaining = await pub.getBalance({ address: sessionAddr });
267
+ if (remaining === 0n) {
268
+ clearEvmSession(options.storage);
269
+ }
270
+ return value;
72
271
  }
73
272
  // --- Committed-guess preimage persistence (the EVM analog of the Solana
74
- // pendingR store). The preimage R is generated at commit and needed again at
75
- // reveal; keeping it only in a React ref means a page reload mid-game strands
76
- // the reveal. Persist it (keyed by gameId so a stale one from a prior game is
77
- // never reused) in sessionStorage — same tab lifetime as the session key,
78
- // and it never leaves the browser, so the commit-reveal anonymity barrier
79
- // holds. ---
273
+ // pendingR store). Mirrored to localStorage + sessionStorage so neither a
274
+ // reload nor a tab close mid-game strands a committed reveal. ---
80
275
  const PENDING_GUESS_KEY = "coordination-evm-pending-guess";
81
- /** Persist the committed guess preimage for `gameId` so a reload can still reveal. */
276
+ /** Persist the committed guess preimage for `gameId` so a reload/reopen can still reveal. */
82
277
  export function persistEvmGuess(storage, gameId, r) {
83
- try {
84
- storage.setItem(PENDING_GUESS_KEY, JSON.stringify({ gameId, r: bytesToHex(r) }));
85
- }
86
- catch (e) {
87
- console.warn("[evm-session] guess persist failed (in-memory only)", e);
278
+ const { local, session } = resolveStoragePair(storage);
279
+ const serialized = JSON.stringify({ gameId, r: bytesToHex(r) });
280
+ const wroteLocal = safeSetItem(local, PENDING_GUESS_KEY, serialized);
281
+ const wroteSession = safeSetItem(session, PENDING_GUESS_KEY, serialized);
282
+ if (!wroteLocal && !wroteSession) {
283
+ console.warn("[evm-session] guess persist failed (in-memory only)");
88
284
  }
89
285
  }
90
- /** The persisted preimage for `gameId`, or null (missing / different game /
91
- * unreadable). A mismatched gameId guards against revealing a stale guess. */
286
+ /** The persisted preimage for `gameId`, or null (missing / different game / unreadable). */
92
287
  export function loadEvmGuess(storage, gameId) {
93
- try {
94
- const raw = storage.getItem(PENDING_GUESS_KEY);
288
+ const { local, session } = resolveStoragePair(storage);
289
+ for (const candidate of [local, session]) {
290
+ const raw = safeGetItem(candidate, PENDING_GUESS_KEY);
95
291
  if (raw === null)
96
- return null;
97
- const stored = JSON.parse(raw);
98
- if (stored.gameId !== gameId || typeof stored.r !== "string")
99
- return null;
100
- return hexToBytes(stored.r);
101
- }
102
- catch (e) {
103
- console.warn("[evm-session] guess load failed", e);
104
- return null;
292
+ continue;
293
+ try {
294
+ const stored = JSON.parse(raw);
295
+ if (stored.gameId === gameId && typeof stored.r === "string") {
296
+ if (candidate === session && local && safeGetItem(local, PENDING_GUESS_KEY) === null) {
297
+ safeSetItem(local, PENDING_GUESS_KEY, raw);
298
+ }
299
+ return hexToBytes(stored.r);
300
+ }
301
+ }
302
+ catch (e) {
303
+ console.warn("[evm-session] guess load failed", e);
304
+ }
105
305
  }
306
+ return null;
106
307
  }
107
308
  /** Drop the persisted guess once the game is done. */
108
309
  export function clearEvmGuess(storage) {
109
- try {
110
- storage.removeItem(PENDING_GUESS_KEY);
111
- }
112
- catch (e) {
113
- console.debug("[evm-session] guess clear failed", e);
114
- }
310
+ const { local, session } = resolveStoragePair(storage);
311
+ safeRemoveItem(local, PENDING_GUESS_KEY);
312
+ safeRemoveItem(session, PENDING_GUESS_KEY);
115
313
  }
116
314
  /** 0x address of a session private key. */
117
315
  export function evmSessionAddress(privateKey) {
@@ -4,4 +4,4 @@ export * from "./outcome-oracle.js";
4
4
  export * from "./battery.js";
5
5
  export * from "./protocol.js";
6
6
  export * from "./chains.js";
7
- export type { XLegPayload, XMatchPayload, XOutcomeCertPayload, XSettleSigsResponse, XSolSettleTxResponse, } from "./api.js";
7
+ export type { EvmGameJoinInput, XLegPayload, XMatchPayload, XOutcomeCertPayload, XQueueJoinInput, XSettleSigsResponse, XSolSettleTxResponse, } from "./api.js";
package/dist/errors.d.ts CHANGED
@@ -16,4 +16,8 @@ export declare class SwarmClientError extends Error {
16
16
  readonly status?: number;
17
17
  constructor(options: SwarmClientErrorOptions);
18
18
  }
19
+ /** Specialized `SwarmClientError` (`code === "TRANSACTION_MISMATCH"`) thrown by transaction verifiers. */
20
+ export declare class TransactionMismatchError extends SwarmClientError {
21
+ constructor(options: Omit<SwarmClientErrorOptions, "code">);
22
+ }
19
23
  export declare function errorMessage(error: unknown, fallback: string): string;
package/dist/errors.js CHANGED
@@ -15,6 +15,12 @@ export class SwarmClientError extends Error {
15
15
  this.status = options.status;
16
16
  }
17
17
  }
18
+ /** Specialized `SwarmClientError` (`code === "TRANSACTION_MISMATCH"`) thrown by transaction verifiers. */
19
+ export class TransactionMismatchError extends SwarmClientError {
20
+ constructor(options) {
21
+ super({ ...options, code: "TRANSACTION_MISMATCH" });
22
+ }
23
+ }
18
24
  export function errorMessage(error, fallback) {
19
25
  return error instanceof Error && error.message ? error.message : fallback;
20
26
  }
package/dist/index.d.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  /** The unified client package version, synchronized from package.json. */
2
2
  export { CLIENT_VERSION } from "./version.js";
3
3
  export declare const CLIENT_MANIFEST_SCHEMA: "swarm.client-manifest/v1";
4
- export { SwarmClientError } from "./errors.js";
4
+ export { SwarmClientError, TransactionMismatchError } from "./errors.js";
5
5
  export type { SwarmClientErrorCode, SwarmClientErrorOptions } from "./errors.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";
6
+ export { DEFAULT_MAX_NETWORK_FEE_WEI, MIN_SELF_PAID_SOLANA_BALANCE_LAMPORTS, ONBOARD_ADVANCE_LAMPORTS, SwarmAgent, createSwarmAgent, extractCreateEscrowLamports, type ExecuteTaskOptions, type ExecutedTaskResult, type NextTaskAction, type SwarmAgentOptions, type SwarmNetwork, type TaskLifecycleStep, } from "./agent.js";
7
7
  export { WalletTokenManager, type TokenProvider, type WalletTokenManagerOptions, } from "./auth/token-manager.js";
8
8
  export { fromEvmPrivateKey, fromEvmWalletClient, fromSolanaKeypair, fromSolanaSecretKey, fromSolanaWalletAdapter, redactSigner, type EvmCallRequest, type EvmPrivateKeyOptions, type EvmSwarmSigner, type EvmTransactionSigner, type EvmWalletClientLike, type SolanaSwarmSigner, type SolanaWalletAdapterLike, type SwarmSigner, } from "./signer/index.js";
9
- export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_ESCROW_DEPLOYMENTS, SHILLBOT_EVM_SELECTORS, SHILLBOT_INSTRUCTION_SPECS, buildOnChainActionProofRef, estimateSolanaNetworkFeeLamports, formatOnChainActionAttributionMessage, normalizeEvmChainId, validateComputeBudgetInstruction, validateComputeBudgetInstructions, validatePreparedEvmCall, validatePreparedTransaction, verifyBuiltTransaction, type AuthoritySlotRule, type BuildOnChainActionProofRefParams, type BuildVerifyOptions, type ExpireTaskState, type PreparedEvmCallExpectation, type PreparedTransactionExpectation, type PreparedTransactionResponse, type ShillbotInstructionName, type ShillbotInstructionSpec, type ValidatedEvmCall, type VerificationDataResponse, type VerifyBuiltTransactionExpectation, } from "./shillbot/api.js";
9
+ export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_ESCROW_DEPLOYMENTS, SHILLBOT_EVM_SELECTORS, SHILLBOT_INSTRUCTION_SPECS, buildOnChainActionProofRef, deriveAdvancePda, estimateSolanaNetworkFeeLamports, formatOnChainActionAttributionMessage, normalizeEvmChainId, validateComputeBudgetInstruction, validateComputeBudgetInstructions, validatePreparedEvmCall, validatePreparedTransaction, verifyBuiltTransaction, type AuthoritySlotRule, type BuildOnChainActionProofRefParams, type BuildVerifyOptions, type ExpireTaskState, type PreparedEvmCallExpectation, type PreparedTransactionExpectation, type PreparedTransactionResponse, type ShillbotInstructionName, type ShillbotInstructionSpec, type ValidatedEvmCall, type VerificationDataResponse, type VerifyBuiltTransactionExpectation, } from "./shillbot/api.js";
10
10
  export { ADVANCE_ACCOUNT_SPACE, EXTENSION_CREDIT_PROGRAM_ID, advanceAccountDiscriminator, advancePda, decodeExtensionCreditAdvance, type DecodedAdvanceAccount, } from "./shillbot/index.js";
11
11
  export { VALID_TOPICS, isValidTopicId, type TopicId, } from "./inbox/types.js";
12
12
  export { DEFAULT_MAX_VOW_BYTES, fetchVowAttestationJson, validateVowUrl, verifyVow, type FetchVowOptions, type VerifyVowOptions, } from "./vow/verify.js";
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /** The unified client package version, synchronized from package.json. */
2
2
  export { CLIENT_VERSION } from "./version.js";
3
3
  export const CLIENT_MANIFEST_SCHEMA = "swarm.client-manifest/v1";
4
- export { SwarmClientError } from "./errors.js";
5
- export { DEFAULT_MAX_NETWORK_FEE_WEI, SwarmAgent, createSwarmAgent, extractCreateEscrowLamports, } from "./agent.js";
4
+ export { SwarmClientError, TransactionMismatchError } from "./errors.js";
5
+ export { DEFAULT_MAX_NETWORK_FEE_WEI, MIN_SELF_PAID_SOLANA_BALANCE_LAMPORTS, ONBOARD_ADVANCE_LAMPORTS, 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 { 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";
8
+ export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_ESCROW_DEPLOYMENTS, SHILLBOT_EVM_SELECTORS, SHILLBOT_INSTRUCTION_SPECS, buildOnChainActionProofRef, deriveAdvancePda, estimateSolanaNetworkFeeLamports, formatOnChainActionAttributionMessage, normalizeEvmChainId, validateComputeBudgetInstruction, validateComputeBudgetInstructions, validatePreparedEvmCall, validatePreparedTransaction, verifyBuiltTransaction, } from "./shillbot/api.js";
9
9
  export { ADVANCE_ACCOUNT_SPACE, EXTENSION_CREDIT_PROGRAM_ID, advanceAccountDiscriminator, advancePda, decodeExtensionCreditAdvance, } from "./shillbot/index.js";
10
10
  export { VALID_TOPICS, isValidTopicId, } from "./inbox/types.js";
11
11
  export { DEFAULT_MAX_VOW_BYTES, fetchVowAttestationJson, validateVowUrl, verifyVow, } from "./vow/verify.js";
@@ -1,6 +1,6 @@
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 TransactionIntent, type WalletSignCallback } from "./index.js";
3
+ import { EXTENSION_CREDIT_PROGRAM_ID, 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;
@@ -52,7 +52,10 @@ export declare class ShillbotApiClient {
52
52
  listTasks<TTask = unknown>(limit?: number): Promise<TaskListResponse<TTask>>;
53
53
  getTask<TTask = unknown>(id: string, network?: "mainnet" | "devnet"): Promise<TTask>;
54
54
  listAgentTasks<TTask = unknown>(): Promise<TTask[] | TaskListResponse<TTask>>;
55
- listPendingApproval<TTask = unknown>(): Promise<TTask[] | TaskListResponse<TTask>>;
55
+ listPendingApproval<TTask = unknown>(networkOrOpts?: "mainnet" | "devnet" | {
56
+ network?: "mainnet" | "devnet";
57
+ token?: string;
58
+ }): Promise<TTask[] | TaskListResponse<TTask>>;
56
59
  listCampaigns<TCampaign = unknown>(): Promise<TCampaign[] | CampaignListResponse<TCampaign>>;
57
60
  campaign<TCampaign = unknown>(id: string): Promise<TCampaign>;
58
61
  campaignTasks<TTask = unknown>(id: string): Promise<TaskListResponse<TTask>>;
@@ -78,14 +81,15 @@ export declare class ShillbotApiClient {
78
81
  buildExpire(id: string): Promise<PreparedTransactionResponse>;
79
82
  confirmTask<TResponse = unknown>(id: string, body: ConfirmTransactionRequest): Promise<TResponse>;
80
83
  }
81
- import { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, type AuthoritySlotRule, type ExpireTaskState, type ShillbotInstructionName, type ShillbotInstructionSpec, type VerifyBuiltTransactionExpectation } from "./verify-tx.js";
82
- export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, type AuthoritySlotRule, type ExpireTaskState, type ShillbotInstructionName, type ShillbotInstructionSpec, type VerifyBuiltTransactionExpectation, };
84
+ import { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, deriveAdvancePda, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, type AuthoritySlotRule, type ExpireTaskState, type ShillbotInstructionName, type ShillbotInstructionSpec, type VerifyBuiltTransactionExpectation } from "./verify-tx.js";
85
+ export { EXTENSION_CREDIT_PROGRAM_ID, MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, deriveAdvancePda, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, type AuthoritySlotRule, type ExpireTaskState, type ShillbotInstructionName, type ShillbotInstructionSpec, type VerifyBuiltTransactionExpectation, };
83
86
  export interface PreparedTransactionExpectation {
84
87
  action: Action;
85
88
  network: "mainnet" | "devnet";
86
89
  wallet: string;
87
90
  taskPda?: string;
88
91
  feePayer?: string;
92
+ sponsor?: string;
89
93
  payoutTo?: string;
90
94
  expireTaskState?: ExpireTaskState;
91
95
  oracleAuthority?: string;
@@ -55,8 +55,13 @@ export class ShillbotApiClient {
55
55
  listAgentTasks() {
56
56
  return this.get("/agent/tasks");
57
57
  }
58
- listPendingApproval() {
59
- return this.get("/tasks?status=pending_approval");
58
+ listPendingApproval(networkOrOpts) {
59
+ const network = typeof networkOrOpts === "string" ? networkOrOpts : networkOrOpts?.network;
60
+ const token = typeof networkOrOpts === "object" && networkOrOpts !== null
61
+ ? networkOrOpts.token
62
+ : undefined;
63
+ const suffix = network ? `?network=${encodeURIComponent(network)}` : "";
64
+ return this.http.get(`/client/pending-approval${suffix}`, token);
60
65
  }
61
66
  listCampaigns() {
62
67
  return this.get("/campaigns");
@@ -178,8 +183,8 @@ export class ShillbotApiClient {
178
183
  return this.post(`/tasks/${encodeURIComponent(id)}/confirm`, body);
179
184
  }
180
185
  }
181
- import { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, } from "./verify-tx.js";
182
- export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, };
186
+ import { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, deriveAdvancePda, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, } from "./verify-tx.js";
187
+ export { EXTENSION_CREDIT_PROGRAM_ID, MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, deriveAdvancePda, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, };
183
188
  const SWITCHBOARD_PROGRAM_IDS = {
184
189
  mainnet: "SBondMDrcV3K4kxZR1HNVT7osZxAHVHgYXL5Ze1oMUv",
185
190
  devnet: "Aio4gaXjXzJNVLtzwtNVmSqGKpANtXhybbkhtAC94ji2",
@@ -151,4 +151,4 @@ export declare const buildExpire: (request: Omit<ExpireBuild, "action">) => Buil
151
151
  export { buildSwitchboardCrankAndVerify } from "./switchboard.js";
152
152
  export type { SwitchboardVerifyRequest } from "./switchboard.js";
153
153
  export * from "./payout-oracle.js";
154
- 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";
154
+ export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, deriveAdvancePda, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, type AuthoritySlotRule, type ShillbotInstructionName, type ShillbotInstructionSpec, type VerifyBuiltTransactionExpectation, } from "./verify-tx.js";
@@ -481,4 +481,4 @@ export const buildExpire = (request) => buildTransaction({ ...request, action: "
481
481
  export { buildSwitchboardCrankAndVerify } from "./switchboard.js";
482
482
  export * from "./payout-oracle.js";
483
483
  import { validateComputeBudgetInstructions } from "./verify-tx.js";
484
- export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, } from "./verify-tx.js";
484
+ export { MAX_COMPUTE_UNIT_LIMIT, MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS, SHILLBOT_INSTRUCTION_SPECS, deriveAdvancePda, validateComputeBudgetInstruction, validateComputeBudgetInstructions, verifyBuiltTransaction, } from "./verify-tx.js";
@@ -1,4 +1,6 @@
1
- import { type Action, type Network, type TransactionInspection } from "./index.js";
1
+ import { advancePda, type Action, type Network, type TransactionInspection } from "./index.js";
2
+ /** Alias for `advancePda` (`seeds = [b"advance", sponsorPubkey, agentPubkey]`). */
3
+ export declare const deriveAdvancePda: typeof advancePda;
2
4
  /** Default maximum allowed Solana priority fee price per compute unit (`100_000` micro-lamports/CU). */
3
5
  export declare const MAX_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 100000n;
4
6
  /** Solana runtime ceiling for `ComputeBudget::SetComputeUnitLimit` (`1_400_000` CUs). */
@@ -27,10 +29,13 @@ export interface VerifyBuiltTransactionExpectation {
27
29
  wallet: string;
28
30
  taskPda?: string;
29
31
  feePayer?: string;
32
+ /** Optional alias for `feePayer` when pinning a known gas sponsor pubkey. */
33
+ sponsor?: string;
30
34
  /**
31
35
  * Explicit authorized payout destination pubkey (base58).
32
- * Required whenever a `set_payout_to` instruction is present; otherwise any
33
- * `set_payout_to` instruction is rejected fail-closed.
36
+ * Required whenever a `set_payout_to` instruction is present on self-paid transactions;
37
+ * on sponsored `claim`/`submit` (`fee_payer !== wallet`), deterministic
38
+ * `advancePda(fee_payer, wallet)` is also authorized.
34
39
  */
35
40
  payoutTo?: string;
36
41
  /**