@arkade-os/sdk 0.4.19 → 0.4.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/cjs/contracts/contractWatcher.js +33 -3
  2. package/dist/cjs/contracts/handlers/default.js +10 -3
  3. package/dist/cjs/contracts/handlers/helpers.js +47 -5
  4. package/dist/cjs/contracts/handlers/vhtlc.js +4 -2
  5. package/dist/cjs/identity/descriptor.js +98 -0
  6. package/dist/cjs/identity/descriptorProvider.js +2 -0
  7. package/dist/cjs/identity/index.js +15 -1
  8. package/dist/cjs/identity/seedIdentity.js +91 -6
  9. package/dist/cjs/identity/serialize.js +166 -0
  10. package/dist/cjs/identity/staticDescriptorProvider.js +65 -0
  11. package/dist/cjs/index.js +6 -3
  12. package/dist/cjs/providers/ark.js +71 -46
  13. package/dist/cjs/providers/electrum.js +663 -0
  14. package/dist/cjs/providers/indexer.js +60 -43
  15. package/dist/cjs/providers/utils.js +62 -12
  16. package/dist/cjs/wallet/ramps.js +1 -1
  17. package/dist/cjs/wallet/serviceWorker/wallet-message-handler.js +10 -0
  18. package/dist/cjs/wallet/serviceWorker/wallet.js +137 -91
  19. package/dist/cjs/wallet/vtxo-manager.js +56 -8
  20. package/dist/cjs/wallet/wallet.js +130 -156
  21. package/dist/cjs/worker/messageBus.js +200 -56
  22. package/dist/esm/contracts/contractWatcher.js +33 -3
  23. package/dist/esm/contracts/handlers/default.js +10 -3
  24. package/dist/esm/contracts/handlers/helpers.js +47 -5
  25. package/dist/esm/contracts/handlers/vhtlc.js +4 -2
  26. package/dist/esm/identity/descriptor.js +92 -0
  27. package/dist/esm/identity/descriptorProvider.js +1 -0
  28. package/dist/esm/identity/index.js +6 -1
  29. package/dist/esm/identity/seedIdentity.js +89 -6
  30. package/dist/esm/identity/serialize.js +159 -0
  31. package/dist/esm/identity/staticDescriptorProvider.js +61 -0
  32. package/dist/esm/index.js +2 -1
  33. package/dist/esm/providers/ark.js +72 -47
  34. package/dist/esm/providers/electrum.js +658 -0
  35. package/dist/esm/providers/indexer.js +61 -44
  36. package/dist/esm/providers/utils.js +61 -12
  37. package/dist/esm/wallet/ramps.js +1 -1
  38. package/dist/esm/wallet/serviceWorker/wallet-message-handler.js +10 -0
  39. package/dist/esm/wallet/serviceWorker/wallet.js +137 -91
  40. package/dist/esm/wallet/vtxo-manager.js +56 -8
  41. package/dist/esm/wallet/wallet.js +130 -156
  42. package/dist/esm/worker/messageBus.js +201 -57
  43. package/dist/types/contracts/contractWatcher.d.ts +3 -0
  44. package/dist/types/contracts/handlers/default.d.ts +1 -1
  45. package/dist/types/contracts/handlers/helpers.d.ts +1 -1
  46. package/dist/types/contracts/types.d.ts +11 -3
  47. package/dist/types/identity/descriptor.d.ts +35 -0
  48. package/dist/types/identity/descriptorProvider.d.ts +28 -0
  49. package/dist/types/identity/index.d.ts +7 -1
  50. package/dist/types/identity/seedIdentity.d.ts +41 -4
  51. package/dist/types/identity/serialize.d.ts +84 -0
  52. package/dist/types/identity/staticDescriptorProvider.d.ts +18 -0
  53. package/dist/types/index.d.ts +4 -2
  54. package/dist/types/providers/electrum.d.ts +212 -0
  55. package/dist/types/providers/utils.d.ts +10 -5
  56. package/dist/types/wallet/serviceWorker/wallet-message-handler.d.ts +11 -2
  57. package/dist/types/wallet/serviceWorker/wallet.d.ts +27 -10
  58. package/dist/types/wallet/vtxo-manager.d.ts +2 -0
  59. package/dist/types/wallet/wallet.d.ts +7 -6
  60. package/dist/types/worker/messageBus.d.ts +68 -8
  61. package/package.json +3 -2
@@ -1,6 +1,6 @@
1
1
  import { hex } from "@scure/base";
2
2
  import { isFetchTimeoutError } from './ark.js';
3
- import { eventSourceIterator } from './utils.js';
3
+ import { eventSourceIterator, isEventSourceError } from './utils.js';
4
4
  import { MetadataList } from '../extension/asset/index.js';
5
5
  export var IndexerTxType;
6
6
  (function (IndexerTxType) {
@@ -153,58 +153,75 @@ export class RestIndexerProvider {
153
153
  }
154
154
  return data;
155
155
  }
156
- async *getSubscription(subscriptionId, abortSignal) {
156
+ getSubscription(subscriptionId, abortSignal) {
157
157
  const url = `${this.serverUrl}/v1/indexer/script/subscription/${subscriptionId}`;
158
- while (!abortSignal?.aborted) {
158
+ let iterator = null;
159
+ const closeIterator = () => iterator?.close();
160
+ const gen = (async function* () {
161
+ const abortHandler = closeIterator;
162
+ abortSignal?.addEventListener("abort", abortHandler);
159
163
  try {
160
- const eventSource = new EventSource(url);
161
- // Set up abort handling
162
- const abortHandler = () => {
163
- eventSource.close();
164
- };
165
- abortSignal?.addEventListener("abort", abortHandler);
166
- try {
167
- for await (const event of eventSourceIterator(eventSource)) {
168
- if (abortSignal?.aborted)
169
- break;
170
- try {
171
- const data = JSON.parse(event.data);
172
- if (data.event) {
173
- yield {
174
- txid: data.event.txid,
175
- scripts: data.event.scripts || [],
176
- newVtxos: (data.event.newVtxos || []).map(convertVtxo),
177
- spentVtxos: (data.event.spentVtxos || []).map(convertVtxo),
178
- sweptVtxos: (data.event.sweptVtxos || []).map(convertVtxo),
179
- tx: data.event.tx,
180
- checkpointTxs: data.event.checkpointTxs,
181
- };
164
+ while (!abortSignal?.aborted) {
165
+ try {
166
+ const currentIterator = eventSourceIterator(new EventSource(url));
167
+ iterator = currentIterator;
168
+ for await (const event of currentIterator) {
169
+ if (abortSignal?.aborted)
170
+ break;
171
+ try {
172
+ const data = JSON.parse(event.data);
173
+ if (data.event) {
174
+ yield {
175
+ txid: data.event.txid,
176
+ scripts: data.event.scripts || [],
177
+ newVtxos: (data.event.newVtxos || []).map(convertVtxo),
178
+ spentVtxos: (data.event.spentVtxos || []).map(convertVtxo),
179
+ sweptVtxos: (data.event.sweptVtxos || []).map(convertVtxo),
180
+ tx: data.event.tx,
181
+ checkpointTxs: data.event.checkpointTxs,
182
+ };
183
+ }
184
+ }
185
+ catch (err) {
186
+ console.error("Failed to parse subscription event:", err);
187
+ throw err;
182
188
  }
183
189
  }
184
- catch (err) {
185
- console.error("Failed to parse subscription event:", err);
186
- throw err;
190
+ }
191
+ catch (error) {
192
+ if (abortSignal?.aborted ||
193
+ (error instanceof Error &&
194
+ error.name === "AbortError")) {
195
+ break;
196
+ }
197
+ // ignore timeout errors, they're expected when the server is not sending anything for 5 min
198
+ if (isFetchTimeoutError(error)) {
199
+ console.debug("Timeout error ignored");
200
+ continue;
201
+ }
202
+ if (isEventSourceError(error)) {
203
+ throw error;
187
204
  }
205
+ console.error("Subscription error:", error);
206
+ throw error;
207
+ }
208
+ finally {
209
+ closeIterator();
210
+ iterator = null;
188
211
  }
189
- }
190
- finally {
191
- abortSignal?.removeEventListener("abort", abortHandler);
192
- eventSource.close();
193
212
  }
194
213
  }
195
- catch (error) {
196
- if (error instanceof Error && error.name === "AbortError") {
197
- break;
198
- }
199
- // ignore timeout errors, they're expected when the server is not sending anything for 5 min
200
- if (isFetchTimeoutError(error)) {
201
- console.debug("Timeout error ignored");
202
- continue;
203
- }
204
- console.error("Subscription error:", error);
205
- throw error;
214
+ finally {
215
+ abortSignal?.removeEventListener("abort", abortHandler);
216
+ closeIterator();
206
217
  }
207
- }
218
+ })();
219
+ const origReturn = gen.return.bind(gen);
220
+ gen.return = (value) => {
221
+ closeIterator();
222
+ return origReturn(value);
223
+ };
224
+ return gen;
208
225
  }
209
226
  async getVirtualTxs(txids, opts) {
210
227
  let url = `${this.serverUrl}/v1/indexer/virtualTx/${txids.join(",")}`;
@@ -1,29 +1,67 @@
1
+ function createAbortError() {
2
+ const error = new Error("EventSource closed");
3
+ error.name = "AbortError";
4
+ return error;
5
+ }
1
6
  /**
2
- * Creates an async iterator over EventSource messages that attaches listeners
3
- * eagerly (at call time) rather than lazily (at first .next() call).
4
- * This ensures events are buffered immediately, preventing race conditions
5
- * where events arrive before iteration begins.
7
+ * Creates a close-aware EventSource async iterator.
8
+ *
9
+ * Listeners attach eagerly so events are buffered before the first next() call.
10
+ * close() closes the EventSource, removes listeners, and wakes any pending
11
+ * next() even when the browser does not emit an error from EventSource.close().
6
12
  */
7
13
  export function eventSourceIterator(eventSource) {
8
14
  const messageQueue = [];
9
15
  const errorQueue = [];
10
16
  let messageResolve = null;
11
17
  let errorResolve = null;
18
+ let closed = false;
19
+ let cleanedUp = false;
20
+ const cleanup = () => {
21
+ if (cleanedUp)
22
+ return;
23
+ cleanedUp = true;
24
+ eventSource.removeEventListener("message", messageHandler);
25
+ eventSource.removeEventListener("error", errorHandler);
26
+ };
27
+ const close = () => {
28
+ if (closed)
29
+ return;
30
+ closed = true;
31
+ messageQueue.length = 0;
32
+ errorQueue.length = 0;
33
+ eventSource.close();
34
+ cleanup();
35
+ if (errorResolve) {
36
+ const reject = errorResolve;
37
+ messageResolve = null;
38
+ errorResolve = null;
39
+ reject(createAbortError());
40
+ }
41
+ };
12
42
  const messageHandler = (event) => {
43
+ if (closed)
44
+ return;
13
45
  if (messageResolve) {
14
- messageResolve(event);
46
+ const resolve = messageResolve;
15
47
  messageResolve = null;
48
+ errorResolve = null;
49
+ resolve(event);
16
50
  }
17
51
  else {
18
52
  messageQueue.push(event);
19
53
  }
20
54
  };
21
55
  const errorHandler = () => {
56
+ if (closed)
57
+ return;
22
58
  const error = new Error("EventSource error");
23
59
  error.name = "EventSourceError";
24
60
  if (errorResolve) {
25
- errorResolve(error);
61
+ const reject = errorResolve;
62
+ messageResolve = null;
26
63
  errorResolve = null;
64
+ reject(error);
27
65
  }
28
66
  else {
29
67
  errorQueue.push(error);
@@ -33,9 +71,9 @@ export function eventSourceIterator(eventSource) {
33
71
  // even before the caller starts iterating
34
72
  eventSource.addEventListener("message", messageHandler);
35
73
  eventSource.addEventListener("error", errorHandler);
36
- return (async function* () {
74
+ const gen = (async function* () {
37
75
  try {
38
- while (true) {
76
+ while (!closed) {
39
77
  // if we have queued messages, yield the first one, remove it from the queue
40
78
  if (messageQueue.length > 0) {
41
79
  yield messageQueue.shift();
@@ -54,15 +92,26 @@ export function eventSourceIterator(eventSource) {
54
92
  messageResolve = null;
55
93
  errorResolve = null;
56
94
  });
57
- if (result) {
95
+ if (!closed && result) {
58
96
  yield result;
59
97
  }
60
98
  }
61
99
  }
62
100
  finally {
63
- // clean up
64
- eventSource.removeEventListener("message", messageHandler);
65
- eventSource.removeEventListener("error", errorHandler);
101
+ closed = true;
102
+ cleanup();
103
+ eventSource.close();
66
104
  }
67
105
  })();
106
+ const origReturn = gen.return.bind(gen);
107
+ const managed = gen;
108
+ managed.close = close;
109
+ managed.return = (value) => {
110
+ close();
111
+ return origReturn(value);
112
+ };
113
+ return managed;
114
+ }
115
+ export function isEventSourceError(error) {
116
+ return error instanceof Error && error.name === "EventSourceError";
68
117
  }
@@ -139,7 +139,7 @@ export class Ramps {
139
139
  weight: 0,
140
140
  birth: vtxo.createdAt,
141
141
  expiry: vtxo.virtualStatus.batchExpiry
142
- ? new Date(vtxo.virtualStatus.batchExpiry * 1000)
142
+ ? new Date(vtxo.virtualStatus.batchExpiry)
143
143
  : undefined,
144
144
  });
145
145
  if (inputFee.satoshis >= vtxo.value) {
@@ -97,6 +97,16 @@ export class WalletMessageHandler {
97
97
  tag: this.messageTag,
98
98
  };
99
99
  }
100
+ // Flows that surrender control to the Ark server and the other participants
101
+ // in a batch round: quiet gaps between protocol events can easily exceed
102
+ // the bus-level messageTimeoutMs. Liveness is covered out-of-band by the
103
+ // page-side PING / MESSAGE_BUS_NOT_INITIALIZED path triggered by concurrent
104
+ // short requests (GET_STATUS, GET_BALANCE, ...).
105
+ isLongRunning(message) {
106
+ return (message.type === "SETTLE" ||
107
+ message.type === "RECOVER_VTXOS" ||
108
+ message.type === "RENEW_VTXOS");
109
+ }
100
110
  async handleMessage(message) {
101
111
  const id = message.id;
102
112
  if (message.type === "INIT_WALLET") {
@@ -1,4 +1,5 @@
1
1
  import { hex } from "@scure/base";
2
+ import { serializeReadonlyIdentity, serializeSigningIdentity, } from '../../identity/index.js';
2
3
  import { setupServiceWorker } from '../../worker/browser/utils.js';
3
4
  import { IndexedDBContractRepository, IndexedDBWalletRepository, } from '../../repositories/index.js';
4
5
  import { DEFAULT_MESSAGE_TAG, } from './wallet-message-handler.js';
@@ -33,7 +34,10 @@ export const DEFAULT_MESSAGE_TIMEOUTS = {
33
34
  GET_EXPIRED_BOARDING_UTXOS: 20000,
34
35
  GET_RECOVERABLE_BALANCE: 20000,
35
36
  RELOAD_WALLET: 20000,
36
- // Transactions — need more headroom
37
+ // Transactions — need more headroom.
38
+ // SETTLE / RECOVER_VTXOS / RENEW_VTXOS go through the streaming path and
39
+ // are treated as long-running on both sides of the bus: the values below
40
+ // are retained only for type completeness and are never enforced.
37
41
  SEND_BITCOIN: 50000,
38
42
  SEND: 50000,
39
43
  SETTLE: 50000,
@@ -78,9 +82,12 @@ function getRequestDedupKey(request) {
78
82
  const { id, tag, ...rest } = request;
79
83
  return JSON.stringify(rest);
80
84
  }
81
- const isPrivateKeyIdentity = (identity) => {
82
- return typeof identity.toHex === "function";
83
- };
85
+ function isSigningCapable(identity) {
86
+ const candidate = identity;
87
+ return (typeof candidate.signMessage === "function" &&
88
+ typeof candidate.sign === "function" &&
89
+ typeof candidate.signerSession === "function");
90
+ }
84
91
  class ServiceWorkerReadonlyAssetManager {
85
92
  constructor(sendMessage, messageTag) {
86
93
  this.sendMessage = sendMessage;
@@ -196,55 +203,54 @@ export class ServiceWorkerReadonlyWallet {
196
203
  const messageTag = options.walletUpdaterTag ?? DEFAULT_MESSAGE_TAG;
197
204
  // Create the wallet instance
198
205
  const wallet = new ServiceWorkerReadonlyWallet(options.serviceWorker, options.identity, walletRepository, contractRepository, messageTag);
206
+ const serializedWallet = await serializeReadonlyIdentity(options.identity);
207
+ // INIT_WALLET retains the legacy `key` payload for wire compatibility
208
+ // with older workers; the current handler does not read it.
199
209
  const publicKey = await options.identity
200
210
  .compressedPublicKey()
201
211
  .then(hex.encode);
202
- const initConfig = {
212
+ const initWalletPayload = {
203
213
  key: { publicKey },
204
214
  arkServerUrl: options.arkServerUrl,
205
215
  arkServerPublicKey: options.arkServerPublicKey,
206
216
  delegatorUrl: options.delegatorUrl,
207
217
  };
208
- // Bootstrap the MessageBus in the service worker
209
- await initializeMessageBus(options.serviceWorker, {
210
- wallet: initConfig.key,
218
+ // Precompute the merged timeout map so page-side waiting and
219
+ // worker-side enforcement are derived from the same source.
220
+ const messageTimeouts = options.messageTimeouts
221
+ ? {
222
+ ...DEFAULT_MESSAGE_TIMEOUTS,
223
+ ...options.messageTimeouts,
224
+ }
225
+ : DEFAULT_MESSAGE_TIMEOUTS;
226
+ const busInitConfig = {
227
+ wallet: serializedWallet,
211
228
  arkServer: {
212
- url: initConfig.arkServerUrl,
213
- publicKey: initConfig.arkServerPublicKey,
229
+ url: options.arkServerUrl,
230
+ publicKey: options.arkServerPublicKey,
214
231
  },
215
- delegatorUrl: initConfig.delegatorUrl,
232
+ delegatorUrl: options.delegatorUrl,
216
233
  indexerUrl: options.indexerUrl,
217
234
  esploraUrl: options.esploraUrl,
218
- timeoutMs: options.messageBusTimeoutMs,
219
235
  watcherConfig: options.watcherConfig,
220
- }, options.messageBusTimeoutMs);
236
+ messageTimeouts,
237
+ };
238
+ // Bootstrap the MessageBus in the service worker
239
+ await initializeMessageBus(options.serviceWorker, { ...busInitConfig, timeoutMs: options.messageBusTimeoutMs }, options.messageBusTimeoutMs);
221
240
  // Initialize the wallet handler
222
241
  const initMessage = {
223
242
  tag: messageTag,
224
243
  type: "INIT_WALLET",
225
244
  id: getRandomId(),
226
- payload: initConfig,
245
+ payload: initWalletPayload,
227
246
  };
228
247
  await wallet.sendMessage(initMessage);
229
- wallet.initConfig = {
230
- wallet: initConfig.key,
231
- arkServer: {
232
- url: initConfig.arkServerUrl,
233
- publicKey: initConfig.arkServerPublicKey,
234
- },
235
- delegatorUrl: initConfig.delegatorUrl,
236
- indexerUrl: options.indexerUrl,
237
- esploraUrl: options.esploraUrl,
238
- watcherConfig: options.watcherConfig,
239
- };
240
- wallet.initWalletPayload = initConfig;
248
+ // Persist the full init config (including messageTimeouts) so
249
+ // reinitialize() re-sends the same map to a restarted worker.
250
+ wallet.initConfig = busInitConfig;
251
+ wallet.initWalletPayload = initWalletPayload;
241
252
  wallet.messageBusTimeoutMs = options.messageBusTimeoutMs;
242
- if (options.messageTimeouts) {
243
- wallet.messageTimeouts = {
244
- ...DEFAULT_MESSAGE_TIMEOUTS,
245
- ...options.messageTimeouts,
246
- };
247
- }
253
+ wallet.messageTimeouts = messageTimeouts;
248
254
  return wallet;
249
255
  }
250
256
  /**
@@ -303,24 +309,16 @@ export class ServiceWorkerReadonlyWallet {
303
309
  }
304
310
  // Like sendMessageDirect but supports streaming responses: intermediate
305
311
  // messages are forwarded via onEvent while the promise resolves on the
306
- // first response for which isComplete returns true. The timeout resets
307
- // on every intermediate event so long-running but progressing operations
308
- // don't time out prematurely.
309
- sendMessageStreaming(request, onEvent, isComplete, timeoutMs) {
312
+ // first response for which isComplete returns true. No inactivity deadline:
313
+ // settlement-class flows surrender control to remote peers and can sit
314
+ // idle for long stretches between protocol events. Service-worker death
315
+ // is detected out-of-band via concurrent short requests that surface
316
+ // MESSAGE_BUS_NOT_INITIALIZED.
317
+ sendMessageStreaming(request, onEvent, isComplete) {
310
318
  return new Promise((resolve, reject) => {
311
- const resetTimeout = () => {
312
- clearTimeout(timeoutId);
313
- timeoutId = setTimeout(() => {
314
- cleanup();
315
- reject(new ServiceWorkerTimeoutError(`Service worker message timed out (${request.type})`));
316
- }, timeoutMs);
317
- };
318
319
  const cleanup = () => {
319
- clearTimeout(timeoutId);
320
320
  navigator.serviceWorker.removeEventListener("message", messageHandler);
321
321
  };
322
- let timeoutId;
323
- resetTimeout();
324
322
  const messageHandler = (event) => {
325
323
  const response = event.data;
326
324
  if (request.id !== response.id)
@@ -335,7 +333,6 @@ export class ServiceWorkerReadonlyWallet {
335
333
  resolve(response);
336
334
  }
337
335
  else {
338
- resetTimeout();
339
336
  onEvent(response);
340
337
  }
341
338
  };
@@ -425,11 +422,10 @@ export class ServiceWorkerReadonlyWallet {
425
422
  await this.reinitialize();
426
423
  }
427
424
  }
428
- const timeoutMs = this.getTimeoutForRequest(request);
429
425
  const maxRetries = 2;
430
426
  for (let attempt = 0;; attempt++) {
431
427
  try {
432
- return await this.sendMessageStreaming(request, onEvent, isComplete, timeoutMs);
428
+ return await this.sendMessageStreaming(request, onEvent, isComplete);
433
429
  }
434
430
  catch (error) {
435
431
  if (!isMessageBusNotInitializedError(error) ||
@@ -440,19 +436,68 @@ export class ServiceWorkerReadonlyWallet {
440
436
  }
441
437
  }
442
438
  }
439
+ /**
440
+ * Produce a serialized envelope for the wallet's identity. The base
441
+ * class always emits a readonly envelope; `ServiceWorkerWallet`
442
+ * overrides to emit a signing envelope.
443
+ */
444
+ async serializeIdentity() {
445
+ return serializeReadonlyIdentity(this.identity);
446
+ }
447
+ /**
448
+ * Return the cached init config, or rebuild one from live instance
449
+ * state when the cache was never populated. Recovery path for
450
+ * SDK-factory-created wallets; manual constructor bypasses do not
451
+ * retain enough state here and will hit the "never initialized" throw.
452
+ */
453
+ async buildInitConfig() {
454
+ if (this.initConfig)
455
+ return this.initConfig;
456
+ if (!this.arkServerUrl) {
457
+ throw new Error("Cannot re-initialize: wallet was not initialized via the SDK factory");
458
+ }
459
+ const wallet = await this.serializeIdentity();
460
+ this.initConfig = {
461
+ wallet,
462
+ arkServer: {
463
+ url: this.arkServerUrl,
464
+ publicKey: this.arkServerPublicKey,
465
+ },
466
+ delegatorUrl: this.delegatorUrl,
467
+ indexerUrl: this.indexerUrl,
468
+ esploraUrl: this.esploraUrl,
469
+ watcherConfig: this.watcherConfig,
470
+ settlementConfig: this.settlementConfig,
471
+ };
472
+ return this.initConfig;
473
+ }
474
+ /** Minimal INIT_WALLET payload used on reinitialize when the cache is gone. */
475
+ buildInitWalletPayload() {
476
+ if (this.initWalletPayload)
477
+ return this.initWalletPayload;
478
+ if (!this.arkServerUrl) {
479
+ throw new Error("Cannot re-initialize: wallet was not initialized via the SDK factory");
480
+ }
481
+ this.initWalletPayload = {
482
+ // `key` is deprecated and ignored by the current handler.
483
+ key: {},
484
+ arkServerUrl: this.arkServerUrl,
485
+ arkServerPublicKey: this.arkServerPublicKey,
486
+ };
487
+ return this.initWalletPayload;
488
+ }
443
489
  async reinitialize() {
444
490
  if (this.reinitPromise)
445
491
  return this.reinitPromise;
446
492
  this.reinitPromise = (async () => {
447
- if (!this.initConfig || !this.initWalletPayload) {
448
- throw new Error("Cannot re-initialize: missing configuration");
449
- }
450
- await initializeMessageBus(this.serviceWorker, this.initConfig, this.messageBusTimeoutMs);
493
+ const config = await this.buildInitConfig();
494
+ const payload = this.buildInitWalletPayload();
495
+ await initializeMessageBus(this.serviceWorker, config, this.messageBusTimeoutMs);
451
496
  const initMessage = {
452
497
  tag: this.messageTag,
453
498
  type: "INIT_WALLET",
454
499
  id: getRandomId(),
455
- payload: this.initWalletPayload,
500
+ payload,
456
501
  };
457
502
  await this.sendMessageDirect(initMessage, this.getTimeoutForRequest(initMessage));
458
503
  })().finally(() => {
@@ -814,71 +859,72 @@ export class ServiceWorkerWallet extends ServiceWorkerReadonlyWallet {
814
859
  get assetManager() {
815
860
  return this._assetManager;
816
861
  }
862
+ async serializeIdentity() {
863
+ return serializeSigningIdentity(this.identity);
864
+ }
817
865
  static async create(options) {
818
866
  const walletRepository = options.storage?.walletRepository ??
819
867
  new IndexedDBWalletRepository();
820
868
  const contractRepository = options.storage?.contractRepository ??
821
869
  new IndexedDBContractRepository();
822
- // Extract identity and check if it can expose private key
823
- const identity = isPrivateKeyIdentity(options.identity)
824
- ? options.identity
825
- : null;
826
- if (!identity) {
827
- throw new Error("ServiceWorkerWallet.create() requires a Identity that can expose a single private key");
870
+ if (!isSigningCapable(options.identity)) {
871
+ throw new Error("ServiceWorkerWallet.create() requires a signing Identity; got a ReadonlyIdentity");
828
872
  }
829
- // Extract private key for service worker initialization
830
- const privateKey = identity.toHex();
873
+ const identity = options.identity;
874
+ const serializedWallet = serializeSigningIdentity(identity);
831
875
  const messageTag = options.walletUpdaterTag ?? DEFAULT_MESSAGE_TAG;
832
876
  // Create the wallet instance
833
877
  const wallet = new ServiceWorkerWallet(options.serviceWorker, identity, walletRepository, contractRepository, messageTag, !!options.delegatorUrl);
834
- const initConfig = {
835
- key: { privateKey },
878
+ // INIT_WALLET retains the legacy `key` payload for wire compatibility
879
+ // with older workers; the current handler does not read it, and only
880
+ // SingleKey-style identities can populate it. Kept optional so seed /
881
+ // mnemonic identities simply omit it.
882
+ const legacyPrivateKey = serializedWallet.type === "single-key"
883
+ ? serializedWallet.privateKey
884
+ : null;
885
+ const initWalletPayload = {
886
+ key: legacyPrivateKey ? { privateKey: legacyPrivateKey } : {},
836
887
  arkServerUrl: options.arkServerUrl,
837
888
  arkServerPublicKey: options.arkServerPublicKey,
838
889
  delegatorUrl: options.delegatorUrl,
839
890
  };
840
- await initializeMessageBus(options.serviceWorker, {
841
- wallet: initConfig.key,
891
+ // Precompute the merged timeout map so page-side waiting and
892
+ // worker-side enforcement are derived from the same source.
893
+ const messageTimeouts = options.messageTimeouts
894
+ ? {
895
+ ...DEFAULT_MESSAGE_TIMEOUTS,
896
+ ...options.messageTimeouts,
897
+ }
898
+ : DEFAULT_MESSAGE_TIMEOUTS;
899
+ const busInitConfig = {
900
+ wallet: serializedWallet,
842
901
  arkServer: {
843
- url: initConfig.arkServerUrl,
844
- publicKey: initConfig.arkServerPublicKey,
902
+ url: options.arkServerUrl,
903
+ publicKey: options.arkServerPublicKey,
845
904
  },
846
- delegatorUrl: initConfig.delegatorUrl,
905
+ delegatorUrl: options.delegatorUrl,
847
906
  indexerUrl: options.indexerUrl,
848
907
  esploraUrl: options.esploraUrl,
849
- timeoutMs: options.messageBusTimeoutMs,
850
908
  settlementConfig: options.settlementConfig,
851
909
  watcherConfig: options.watcherConfig,
852
- }, options.messageBusTimeoutMs);
910
+ messageTimeouts,
911
+ };
912
+ await initializeMessageBus(options.serviceWorker, { ...busInitConfig, timeoutMs: options.messageBusTimeoutMs }, options.messageBusTimeoutMs);
853
913
  // Initialize the service worker with the config
854
914
  const initMessage = {
855
915
  tag: messageTag,
856
916
  type: "INIT_WALLET",
857
917
  id: getRandomId(),
858
- payload: initConfig,
918
+ payload: initWalletPayload,
859
919
  };
860
920
  // Initialize the service worker
861
921
  await wallet.sendMessage(initMessage);
862
- wallet.initConfig = {
863
- wallet: initConfig.key,
864
- arkServer: {
865
- url: initConfig.arkServerUrl,
866
- publicKey: initConfig.arkServerPublicKey,
867
- },
868
- delegatorUrl: initConfig.delegatorUrl,
869
- indexerUrl: options.indexerUrl,
870
- esploraUrl: options.esploraUrl,
871
- settlementConfig: options.settlementConfig,
872
- watcherConfig: options.watcherConfig,
873
- };
874
- wallet.initWalletPayload = initConfig;
922
+ // Persist the full init config (including messageTimeouts) so
923
+ // reinitialize() re-sends the same map to a restarted worker.
924
+ wallet.initConfig = busInitConfig;
925
+ wallet.initWalletPayload = initWalletPayload;
875
926
  wallet.messageBusTimeoutMs = options.messageBusTimeoutMs;
876
- if (options.messageTimeouts) {
877
- wallet.messageTimeouts = {
878
- ...DEFAULT_MESSAGE_TIMEOUTS,
879
- ...options.messageTimeouts,
880
- };
881
- }
927
+ wallet.messageTimeouts = messageTimeouts;
882
928
  return wallet;
883
929
  }
884
930
  /**