@swarm-tips/client 0.4.5 → 0.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,43 +1,98 @@
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
- import { type Chain, type Hex, type PublicClient, type WalletClient } from "viem";
14
+ import { type Account, type Chain, type Hex, type PublicClient, type WalletClient } from "viem";
15
+ export declare const EVM_SESSION_STORAGE_KEY = "coordination-evm-session";
17
16
  export interface SessionStorageLike {
18
17
  getItem(key: string): string | null;
19
18
  setItem(key: string, value: string): void;
20
19
  removeItem(key: string): void;
21
20
  }
21
+ export interface EvmSessionStoragePair {
22
+ localStorage?: SessionStorageLike | null;
23
+ sessionStorage?: SessionStorageLike | null;
24
+ }
25
+ export type EvmSessionStorageInput = SessionStorageLike | EvmSessionStoragePair | null | undefined;
22
26
  /** Generate a fresh ephemeral secp256k1 private key for session signing. */
23
27
  export declare function generateEvmSessionKey(): Hex;
24
28
  /**
25
- * Read the session key from sessionStorage. Returns null if no session
26
- * exists, the session has expired (24h TTL), or it belongs to a different
27
- * main wallet. Any invalid stored value is removed.
28
- */
29
- export declare function getStoredEvmSession(storage: SessionStorageLike, walletAddress?: string, now?: () => number): Hex | null;
30
- /** Persist the session key in sessionStorage, bound to the main wallet. */
31
- export declare function storeEvmSession(storage: SessionStorageLike, privateKey: Hex, walletAddress: string, now?: () => number): void;
32
- /** Remove the session key from sessionStorage. */
33
- export declare function clearEvmSession(storage: SessionStorageLike): void;
34
- /** Persist the committed guess preimage for `gameId` so a reload can still reveal. */
35
- export declare function persistEvmGuess(storage: SessionStorageLike, gameId: string, r: Uint8Array): void;
36
- /** The persisted preimage for `gameId`, or null (missing / different game /
37
- * unreadable). A mismatched gameId guards against revealing a stale guess. */
38
- export declare function loadEvmGuess(storage: SessionStorageLike, gameId: string): Uint8Array | null;
29
+ * Read the persisted EVM session key from `localStorage` first, falling back to
30
+ * `sessionStorage` and migrating legacy `sessionStorage`-only keys into `localStorage`.
31
+ * Retains valid keys across tab closes and past 24h until explicitly cleared after
32
+ * on-chain ETH balance is swept to `0`.
33
+ */
34
+ export declare function getStoredEvmSession(storage?: EvmSessionStorageInput, walletAddress?: string, _now?: () => number): Hex | null;
35
+ /**
36
+ * Ergonomic loader for persisted EVM session keys (`localStorage` primary,
37
+ * `sessionStorage` fallback + legacy migration).
38
+ */
39
+ export declare function loadSessionKey(walletAddress?: string, storage?: EvmSessionStorageInput): Hex | null;
40
+ export declare function loadSessionKey(storage: EvmSessionStorageInput, walletAddress?: string): Hex | null;
41
+ /**
42
+ * Persist the EVM session key in `localStorage` first, mirroring to `sessionStorage`
43
+ * (and falling back to `sessionStorage` when `localStorage` is unavailable).
44
+ */
45
+ export declare function storeEvmSession(storage: EvmSessionStorageInput, privateKey: Hex, walletAddress: string, now?: () => number): void;
46
+ /** Ergonomic helper to persist an EVM session key in `localStorage` + `sessionStorage`. */
47
+ export declare function saveSessionKey(privateKey: Hex, walletAddress: string, options?: EvmSessionStoragePair & {
48
+ now?: () => number;
49
+ }): void;
50
+ /** Remove the EVM session key from both `localStorage` and `sessionStorage`. */
51
+ export declare function clearEvmSession(storage?: EvmSessionStorageInput): void;
52
+ /** A plain native-ETH transfer uses 21,000 gas. */
53
+ export declare const SWEEP_GAS_LIMIT = 21000n;
54
+ /**
55
+ * Compute the native ETH amount to sweep from a session key back to the main wallet:
56
+ * `balance - 1.25 * (21_000 * maxFeePerGas)`, clamped at `0n`.
57
+ */
58
+ export declare function sweepValueWei(balance: bigint, maxFeePerGas: bigint): bigint;
59
+ export interface SweepEvmSessionOptions {
60
+ storage?: EvmSessionStorageInput;
61
+ /** When `true`, deduct exact `21_000 * maxFeePerGas` with `maxPriorityFeePerGas = maxFeePerGas` so EIP-1559 drains to `0n`. */
62
+ exact?: boolean;
63
+ readClient?: {
64
+ getBalance: (args: {
65
+ address: Hex;
66
+ }) => Promise<bigint>;
67
+ estimateFeesPerGas?: () => Promise<{
68
+ maxFeePerGas?: bigint;
69
+ maxPriorityFeePerGas?: bigint;
70
+ }>;
71
+ getGasPrice?: () => Promise<bigint>;
72
+ waitForTransactionReceipt: (args: {
73
+ hash: Hex;
74
+ }) => Promise<{
75
+ status?: string;
76
+ }>;
77
+ };
78
+ walletClient?: {
79
+ account?: Account | Hex;
80
+ sendTransaction: (args: Record<string, unknown>) => Promise<Hex>;
81
+ };
82
+ }
83
+ /**
84
+ * Sweep leftover ETH from an EVM session key back to `mainWallet`, clearing
85
+ * persisted storage **only** once the session address's on-chain balance reaches `0n`.
86
+ * If the sweep fails or non-zero balance remains on-chain, the key is retained in
87
+ * `localStorage` so funded ETH is never orphaned.
88
+ */
89
+ export declare function sweepEvmSession(sessionKey: Hex, mainWallet: Hex, chain: Chain, rpcUrls: string[], options?: SweepEvmSessionOptions): Promise<bigint>;
90
+ /** Persist the committed guess preimage for `gameId` so a reload/reopen can still reveal. */
91
+ export declare function persistEvmGuess(storage: EvmSessionStorageInput, gameId: string, r: Uint8Array): void;
92
+ /** The persisted preimage for `gameId`, or null (missing / different game / unreadable). */
93
+ export declare function loadEvmGuess(storage: EvmSessionStorageInput, gameId: string): Uint8Array | null;
39
94
  /** Drop the persisted guess once the game is done. */
40
- export declare function clearEvmGuess(storage: SessionStorageLike): void;
95
+ export declare function clearEvmGuess(storage?: EvmSessionStorageInput): void;
41
96
  /** 0x address of a session private key. */
42
97
  export declare function evmSessionAddress(privateKey: Hex): Hex;
43
98
  /**
@@ -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,13 @@
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 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
+ export { ADVANCE_ACCOUNT_SPACE, EXTENSION_CREDIT_PROGRAM_ID, advanceAccountDiscriminator, advancePda, decodeExtensionCreditAdvance, type DecodedAdvanceAccount, } from "./shillbot/index.js";
10
11
  export { VALID_TOPICS, isValidTopicId, type TopicId, } from "./inbox/types.js";
11
12
  export { DEFAULT_MAX_VOW_BYTES, fetchVowAttestationJson, validateVowUrl, verifyVow, type FetchVowOptions, type VerifyVowOptions, } from "./vow/verify.js";
12
13
  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,11 +1,12 @@
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
+ export { ADVANCE_ACCOUNT_SPACE, EXTENSION_CREDIT_PROGRAM_ID, advanceAccountDiscriminator, advancePda, decodeExtensionCreditAdvance, } from "./shillbot/index.js";
9
10
  export { VALID_TOPICS, isValidTopicId, } from "./inbox/types.js";
10
11
  export { DEFAULT_MAX_VOW_BYTES, fetchVowAttestationJson, validateVowUrl, verifyVow, } from "./vow/verify.js";
11
12
  export { OPENAPI_SERVERS, OPENAPI_VERSION, } from "./generated/openapi.js";