@partylayer/sdk 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- import { toWalletId, toPartyId, isRecognizedNetwork, toSignature, ledgerApiBodyToObject, normalizeLedgerMethodLower, hashForPrivacy, createMetricsPayload, isOfficialAdapterFactory, isOfficialProviderAdapter, mapUnknownErrorToPartyLayerError, findMatchingWalletInfo, detectNetworkMismatch, NetworkMismatchError, METRICS, AdapterNotRegisteredError, WalletNotFoundError, capabilityGuard, installGuard, toSessionId, CapabilityNotSupportedError, toTransferIntent, errorMetricName, toTransactionHash } from '@partylayer/core';
1
+ import { toWalletId, toPartyId, isRecognizedNetwork, detectNetworkMismatch, ledgerApiBodyToObject, normalizeLedgerMethodLower, hashForPrivacy, createMetricsPayload, isOfficialAdapterFactory, isOfficialProviderAdapter, mapUnknownErrorToPartyLayerError, findMatchingWalletInfo, NetworkMismatchError, METRICS, WalletNotFoundError, AdapterNotRegisteredError, capabilityGuard, installGuard, toSessionId, CapabilityNotSupportedError, toTransferIntent, errorMetricName, TransportError, toSignature, toTransactionHash, toCAIP2Network } from '@partylayer/core';
2
2
  export { AdapterNotRegisteredError, PartyLayerError as CantonConnectError, CapabilityNotSupportedError, ENABLEMENT_METRICS, ERROR_METRICS, InternalError, METRICS, OriginNotAllowedError, PartyLayerError, REGISTRY_METRICS, RegistryFetchFailedError, RegistrySchemaInvalidError, RegistryVerificationFailedError, SessionExpiredError, TRANSFER_INTENT_FIELDS, TimeoutError, TransportError, UserRejectedError, WalletNotFoundError, WalletNotInstalledError, errorMetricName, isOfficialAdapterFactory, isOfficialProviderAdapter, toTransferIntent } from '@partylayer/core';
3
3
  import { RegistryClient } from '@partylayer/registry-client';
4
4
  export { deriveGenericWalletName, findMatchingWallet, findMatchingWalletInfo, isCip0103Native, matchesProviderDetection } from '@partylayer/registry-client';
5
- import { subscribeAnnouncedProviders, createExtensionChannelProvider, discoverProviders, createProviderBridge } from '@partylayer/provider';
5
+ import { subscribeAnnouncedProviders, createExtensionChannelProvider, discoverProviders, createProviderBridge, CIP0103EventBus, toProviderRpcError } from '@partylayer/provider';
6
6
  export { CANTON_NETWORKS, CIP0103EventBus, CIP0103_EVENTS, CIP0103_MANDATORY_METHODS, CIP0103_METHODS, JSON_RPC_ERRORS, PartyLayerProvider, ProviderRpcError, RPC_ERRORS, createProviderBridge, discoverInjectedProviders, fromCAIP2Network, isCIP0103Provider, isValidCAIP2, toCAIP2Network, waitForProvider } from '@partylayer/provider';
7
7
  export { ConsoleAdapter } from '@partylayer/adapter-console';
8
8
  import { LoopAdapter } from '@partylayer/adapter-loop';
@@ -14,13 +14,66 @@ export { NightlyAdapter } from '@partylayer/adapter-nightly';
14
14
  export { SendAdapter } from '@partylayer/adapter-send';
15
15
  export { BronAdapter } from '@partylayer/adapter-bron';
16
16
 
17
- // src/client.ts
17
+ // src/default-wallets.ts
18
+ var loaders = {
19
+ walley: async () => {
20
+ const { WalleyAdapter } = await import('@k2flabs/walley-dapp-sdk');
21
+ return { providerId: "walley", create: (host) => new WalleyAdapter({ host }) };
22
+ },
23
+ cauri: async () => {
24
+ const { cauriAdapterFactory } = await import('@lithiumdigital/cauri-dapp-sdk');
25
+ return cauriAdapterFactory;
26
+ },
27
+ oneswap: async (network) => {
28
+ const { createOneSwapProviderAdapter } = await import('@oneswap/wallet-cip0103-adapter');
29
+ return {
30
+ providerId: "oneswap",
31
+ create: (host) => createOneSwapProviderAdapter({
32
+ walletUrl: host,
33
+ networkId: toCAIP2Network(network).networkId
34
+ })
35
+ };
36
+ },
37
+ vala: async () => {
38
+ const { valaAdapterFactory } = await import('@vala-wallet/dapp-sdk');
39
+ return valaAdapterFactory;
40
+ }
41
+ };
42
+ async function loadDefaultWallet(id, config, origin) {
43
+ if (id === "walletconnect" && config.walletConnect?.projectId.trim()) {
44
+ const { WalletConnectAdapter } = await import('@partylayer/adapter-walletconnect');
45
+ return new WalletConnectAdapter({
46
+ ...config.walletConnect,
47
+ metadata: config.walletConnect.metadata ?? {
48
+ name: config.app.name,
49
+ description: config.app.name,
50
+ url: origin === "unknown" ? "" : origin,
51
+ icons: []
52
+ }
53
+ });
54
+ }
55
+ if (id === "bron" && config.bron) {
56
+ const { BronAdapter: BronAdapter2 } = await import('@partylayer/adapter-bron');
57
+ return new BronAdapter2(config.bron);
58
+ }
59
+ return Object.prototype.hasOwnProperty.call(loaders, id) ? loaders[id](config.network) : void 0;
60
+ }
18
61
  var UNSUPPORTED_METHOD = 4200;
19
62
  var METHOD_NOT_FOUND = -32601;
20
63
  function isUnsupportedMethod(err) {
21
64
  const code = err?.code;
22
65
  return code === UNSUPPORTED_METHOD || code === METHOD_NOT_FOUND;
23
66
  }
67
+ function assertExecuteCorrelation(result, request) {
68
+ const expected = request?.commandId;
69
+ if (typeof expected !== "string" || !expected) return;
70
+ const value = result;
71
+ for (const actual of [value?.commandId, value?.tx?.commandId]) {
72
+ if (typeof actual === "string" && actual && actual !== expected) {
73
+ throw new TransportError("Wallet returned a different commandId; transaction outcome is unknown. Reconcile before retrying.");
74
+ }
75
+ }
76
+ }
24
77
  function receiptFromExecutedTx(result) {
25
78
  const tx = result?.tx;
26
79
  const updateId = tx?.payload?.updateId;
@@ -29,35 +82,59 @@ function receiptFromExecutedTx(result) {
29
82
  transactionHash: toTransactionHash(updateId),
30
83
  submittedAt: Date.now(),
31
84
  commandId: typeof tx?.commandId === "string" ? tx.commandId : void 0,
32
- updateId
85
+ updateId,
86
+ ...validOffset(tx?.payload?.completionOffset) ? { completionOffset: tx.payload.completionOffset } : {}
87
+ };
88
+ }
89
+ function normalizeReceipt(result, request) {
90
+ assertExecuteCorrelation(result, request);
91
+ const executed = receiptFromExecutedTx(result);
92
+ if (executed) return executed;
93
+ const value = result && typeof result === "object" ? result : {};
94
+ const timestamp = typeof value.submittedAt === "number" ? value.submittedAt : typeof value.submittedAt === "string" ? Date.parse(value.submittedAt) : NaN;
95
+ const tx = value.tx && typeof value.tx === "object" ? value.tx : {};
96
+ const commandId = typeof value.commandId === "string" ? value.commandId : typeof tx.commandId === "string" ? tx.commandId : typeof request.commandId === "string" ? request.commandId : void 0;
97
+ return {
98
+ submittedAt: Number.isFinite(timestamp) ? timestamp : Date.now(),
99
+ ...typeof value.transactionHash === "string" && value.transactionHash.length > 0 ? { transactionHash: toTransactionHash(value.transactionHash) } : {},
100
+ ...typeof value.updateId === "string" && value.updateId.length > 0 ? { updateId: value.updateId } : {},
101
+ ...validOffset(value.completionOffset) ? { completionOffset: value.completionOffset } : {},
102
+ ...commandId ? { commandId } : {}
33
103
  };
34
104
  }
105
+ function validOffset(value) {
106
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
107
+ }
35
108
  function reportOnce(state, walletId, detail, logger) {
36
109
  if (state.logged) return;
37
110
  state.logged = true;
38
111
  logger?.warn(
39
- `[PartyLayer] ${walletId}: ${detail} Receipts from it carry no real updateId.`
112
+ `[PartyLayer] ${walletId}: ${detail} Confirm ledger completion only when the receipt contains a real updateId.`
40
113
  );
41
114
  }
42
115
  async function submitViaPrepareExecute(provider, params, opts) {
43
- const rpcParams = params;
116
+ const payload = Object.prototype.hasOwnProperty.call(params, "signedTx") ? params.signedTx : params;
117
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
118
+ throw new TransportError("CIP-0103 submission requires a command payload object as signedTx");
119
+ }
120
+ const rpcParams = payload;
44
121
  const { walletId, state, logger } = opts;
45
122
  if (state.verb !== "plain") {
46
123
  try {
47
- const result = await provider.request({
124
+ const result2 = await provider.request({
48
125
  method: "prepareExecuteAndWait",
49
126
  params: rpcParams
50
127
  });
51
128
  state.verb = "awaited";
52
- const receipt = receiptFromExecutedTx(result);
53
- if (receipt) return receipt;
129
+ const receipt = normalizeReceipt(result2, rpcParams);
130
+ if (receipt.updateId) return receipt;
54
131
  reportOnce(
55
132
  state,
56
133
  walletId,
57
134
  "prepareExecuteAndWait returned no updateId.",
58
135
  logger
59
136
  );
60
- return result;
137
+ return receipt;
61
138
  } catch (err) {
62
139
  if (!isUnsupportedMethod(err)) throw err;
63
140
  state.verb = "plain";
@@ -69,10 +146,451 @@ async function submitViaPrepareExecute(provider, params, opts) {
69
146
  );
70
147
  }
71
148
  }
72
- return provider.request({ method: "prepareExecute", params: rpcParams });
149
+ const result = await provider.request({ method: "prepareExecute", params: rpcParams });
150
+ return normalizeReceipt(result, rpcParams);
151
+ }
152
+ function normalizeSignedMessage(response, session, params) {
153
+ const signature = typeof response === "string" ? response : response?.signature;
154
+ if (typeof signature !== "string" || signature.trim().length === 0) {
155
+ throw new TransportError("The wallet returned an invalid message signature");
156
+ }
157
+ const reportedParty = response && typeof response === "object" ? response.partyId : void 0;
158
+ if (reportedParty !== void 0 && reportedParty !== session.partyId) {
159
+ throw new TransportError("The wallet account changed while signing; reconnect before retrying");
160
+ }
161
+ const reportedMessage = response && typeof response === "object" ? response.message : void 0;
162
+ if (reportedMessage !== void 0 && reportedMessage !== params.message) {
163
+ throw new TransportError("Wallet signed an unexpected message");
164
+ }
165
+ return {
166
+ signature: toSignature(signature),
167
+ partyId: session.partyId,
168
+ message: params.message,
169
+ nonce: params.nonce,
170
+ domain: params.domain
171
+ };
172
+ }
173
+ function assertConnectionAccepted(result) {
174
+ if (result === false || result && typeof result === "object" && result.isConnected === false) {
175
+ throw new TransportError("The wallet did not establish a connection");
176
+ }
177
+ }
178
+ function assertPrimaryParty(account) {
179
+ if (typeof account?.partyId !== "string" || !account.partyId.trim()) throw new TransportError("The wallet did not return a primary party");
180
+ }
181
+ var SILENT_PROBE_TIMEOUT_MS = 1e4;
182
+ function disconnected() {
183
+ return new Error("Native wallet connection is no longer active");
184
+ }
185
+ function teardown(source) {
186
+ try {
187
+ source?.teardown?.();
188
+ } catch {
189
+ }
73
190
  }
191
+ function abortable(promise, signal) {
192
+ return new Promise((resolve, reject) => {
193
+ const abort = () => reject(disconnected());
194
+ if (signal.aborted) {
195
+ reject(disconnected());
196
+ return;
197
+ }
198
+ signal.addEventListener("abort", abort, { once: true });
199
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
200
+ });
201
+ }
202
+ async function readIdentity(provider, registration, signal) {
203
+ const account = await abortable(
204
+ provider.request({ method: "getPrimaryAccount" }),
205
+ signal
206
+ );
207
+ assertPrimaryParty(account);
208
+ let status;
209
+ try {
210
+ status = await abortable(provider.request({ method: "status" }), signal);
211
+ } catch (error) {
212
+ if (signal.aborted) throw error;
213
+ }
214
+ if (status?.isConnected === false || status?.connection?.isConnected === false)
215
+ throw disconnected();
216
+ const network = [status?.network?.networkId, account.networkId, registration.network].find(
217
+ (value) => typeof value === "string" && isRecognizedNetwork(value)
218
+ ) ?? registration.network;
219
+ if (registration.expected && (account.partyId !== registration.expected.partyId || detectNetworkMismatch(registration.expected.network, network)))
220
+ throw disconnected();
221
+ if (signal.aborted) throw disconnected();
222
+ return { account, network, status };
223
+ }
224
+ var NativeConnectionOwner = class {
225
+ constructor(changed = () => {
226
+ }) {
227
+ this.changed = changed;
228
+ }
229
+ client = null;
230
+ initialization = null;
231
+ registrations = /* @__PURE__ */ new Map();
232
+ operation = null;
233
+ pending = null;
234
+ closing = null;
235
+ projection = null;
236
+ unsubscribers = [];
237
+ disposed = false;
238
+ refreshRevision = 0;
239
+ identityRefreshing = false;
240
+ probes = /* @__PURE__ */ new Set();
241
+ get busy() {
242
+ return this.operation !== null || this.closing !== null;
243
+ }
244
+ assertAvailable() {
245
+ if (this.disposed) throw disconnected();
246
+ if (this.busy) throw new Error("A native wallet operation is already in progress");
247
+ }
248
+ /** Run during picker preparation, never between a click and provider.connect. */
249
+ async prepare(id, source, network) {
250
+ if (this.disposed) throw disconnected();
251
+ this.registrations.set(id, { id, source, network });
252
+ if (!this.initialization) {
253
+ this.initialization = (async () => {
254
+ const { DiscoveryClient } = await import('@canton-network/core-wallet-discovery');
255
+ const client = await DiscoveryClient.create({ adapters: [] });
256
+ if (this.disposed) {
257
+ client.destroy();
258
+ return;
259
+ }
260
+ this.client = client;
261
+ })();
262
+ }
263
+ await this.initialization;
264
+ if (this.disposed || !this.client) throw disconnected();
265
+ for (const registration of this.registrations.values())
266
+ this.client.registerAdapter(this.wrap(registration));
267
+ }
268
+ wrap(registration) {
269
+ const source = registration.source;
270
+ return {
271
+ providerId: registration.id,
272
+ name: source.name,
273
+ type: source.type === "desktop" || source.type === "mobile" || source.type === "remote" ? source.type : "browser",
274
+ icon: source.icon,
275
+ getInfo: () => ({
276
+ providerId: registration.id,
277
+ name: source.name,
278
+ type: "browser",
279
+ icon: source.icon
280
+ }),
281
+ detect: () => source.detect(),
282
+ provider: () => this.guard(source.provider(), registration),
283
+ teardown: () => teardown(source),
284
+ restore: async () => {
285
+ const operation = this.operation;
286
+ if (!operation) throw disconnected();
287
+ try {
288
+ const raw = source.restore ? await abortable(source.restore(), operation.abort.signal) : source.provider();
289
+ if (!raw) return null;
290
+ const provider = raw;
291
+ operation.identity = await readIdentity(provider, registration, operation.abort.signal);
292
+ return this.guard(provider, registration);
293
+ } catch (error) {
294
+ teardown(source);
295
+ throw error;
296
+ }
297
+ }
298
+ };
299
+ }
300
+ guard(raw, registration) {
301
+ const provider = {
302
+ request: async (args) => {
303
+ if (this.disposed) throw disconnected();
304
+ if (args.method !== "connect") {
305
+ if (this.client?.getActiveSession()?.provider !== provider) throw disconnected();
306
+ if (!this.projection && args.method !== "disconnect") throw disconnected();
307
+ if (this.identityRefreshing && ![
308
+ "status",
309
+ "getPrimaryAccount",
310
+ "listAccounts",
311
+ "getActiveNetwork",
312
+ "isConnected"
313
+ ].includes(args.method)) {
314
+ throw new Error("Native wallet identity is being refreshed");
315
+ }
316
+ const result = await (args.method === "disconnect" && this.operation ? abortable(raw.request(args), this.operation.abort.signal) : raw.request(args));
317
+ if (args.method === "status") {
318
+ const status = result;
319
+ if (status?.isConnected === false || status?.connection?.isConnected === false) {
320
+ this.invalidate(registration.id);
321
+ }
322
+ }
323
+ return result;
324
+ }
325
+ const operation = this.operation;
326
+ if (!operation || operation.abort.signal.aborted) throw disconnected();
327
+ const response = await abortable(raw.request(args), operation.abort.signal);
328
+ assertConnectionAccepted(response);
329
+ operation.identity = await readIdentity(raw, registration, operation.abort.signal);
330
+ return response;
331
+ },
332
+ on: (event, listener) => {
333
+ raw.on(event, listener);
334
+ return provider;
335
+ },
336
+ emit: (event, ...args) => raw.emit(event, ...args),
337
+ removeListener: (event, listener) => {
338
+ raw.removeListener(event, listener);
339
+ return provider;
340
+ }
341
+ };
342
+ return provider;
343
+ }
344
+ /** No await precedes the official client's connect call. */
345
+ connect(id, signal) {
346
+ this.assertAvailable();
347
+ if (!this.client || !this.registrations.has(id))
348
+ return Promise.reject(new Error("Native wallet was not prepared"));
349
+ const operation = { abort: new AbortController(), id };
350
+ this.operation = operation;
351
+ this.detach();
352
+ const previous = this.client.getActiveSession();
353
+ teardown(previous?.adapter);
354
+ const previousId = this.projection?.id;
355
+ this.projection = null;
356
+ if (previousId) this.changed(previousId, null);
357
+ const abort = () => operation.abort.abort();
358
+ if (signal?.aborted) abort();
359
+ signal?.addEventListener("abort", abort, { once: true });
360
+ const task = (async () => {
361
+ try {
362
+ await this.client.connect(id);
363
+ if (operation.abort.signal.aborted || this.disposed || !operation.identity)
364
+ throw disconnected();
365
+ this.projection = { id, identity: operation.identity };
366
+ this.attach(id);
367
+ return operation.identity;
368
+ } catch (error) {
369
+ this.client?.destroy();
370
+ this.client = null;
371
+ this.initialization = null;
372
+ teardown(this.registrations.get(id)?.source);
373
+ throw error;
374
+ } finally {
375
+ signal?.removeEventListener("abort", abort);
376
+ if (this.operation === operation) this.operation = null;
377
+ }
378
+ })();
379
+ this.pending = task;
380
+ void task.then(
381
+ () => {
382
+ if (this.pending === task) this.pending = null;
383
+ },
384
+ () => {
385
+ if (this.pending === task) this.pending = null;
386
+ }
387
+ );
388
+ return task;
389
+ }
390
+ async restore(expected) {
391
+ if (!this.client || this.projection || this.busy || this.disposed) return this.getSession();
392
+ const registration = expected && this.registrations.get(expected.id);
393
+ if (registration) registration.expected = expected;
394
+ const operation = { abort: new AbortController() };
395
+ this.operation = operation;
396
+ const timeout = setTimeout(() => operation.abort.abort(), SILENT_PROBE_TIMEOUT_MS);
397
+ const task = (async () => {
398
+ try {
399
+ await this.client.restorePersistedSessionIfNeeded();
400
+ const active = this.client?.getActiveSession();
401
+ if (!active || !operation.identity || operation.abort.signal.aborted || this.disposed)
402
+ return null;
403
+ if (expected && active.providerId !== expected.id) {
404
+ teardown(active.adapter);
405
+ this.client.destroy();
406
+ this.client = null;
407
+ this.initialization = null;
408
+ return null;
409
+ }
410
+ const id = String(active.providerId);
411
+ this.projection = { id, identity: operation.identity };
412
+ this.attach(id);
413
+ return this.getSession();
414
+ } finally {
415
+ clearTimeout(timeout);
416
+ if (registration) delete registration.expected;
417
+ if (this.operation === operation) this.operation = null;
418
+ }
419
+ })();
420
+ this.pending = task;
421
+ try {
422
+ return await task;
423
+ } finally {
424
+ if (this.pending === task) this.pending = null;
425
+ }
426
+ }
427
+ getSession() {
428
+ if (this.disposed || !this.client?.getActiveSession() || !this.projection) return null;
429
+ return this.projection;
430
+ }
431
+ getProvider(id) {
432
+ if (!this.getSession() || id && this.projection?.id !== id) throw disconnected();
433
+ return this.client.getProvider();
434
+ }
435
+ /** A bare signature must not be attributed to an old, eventless primary party. */
436
+ async validateIdentity(id, partyId, network) {
437
+ const provider = this.getProvider(id);
438
+ const revision = ++this.refreshRevision;
439
+ this.identityRefreshing = true;
440
+ let verified = false;
441
+ try {
442
+ const identity = await this.probe(provider, this.registrations.get(id));
443
+ if (revision !== this.refreshRevision || this.getProvider(id) !== provider)
444
+ throw disconnected();
445
+ verified = true;
446
+ this.projection = { id, identity };
447
+ if (identity.account.partyId !== partyId || detectNetworkMismatch(network, identity.network)) {
448
+ this.changed(id, identity);
449
+ throw new Error("Wallet identity changed during message signing");
450
+ }
451
+ } catch (error) {
452
+ if (!verified && revision === this.refreshRevision) this.invalidate(id);
453
+ throw error;
454
+ } finally {
455
+ if (revision === this.refreshRevision) this.identityRefreshing = false;
456
+ }
457
+ }
458
+ async probe(provider, registration) {
459
+ const abort = new AbortController();
460
+ this.probes.add(abort);
461
+ const timeout = setTimeout(() => abort.abort(), SILENT_PROBE_TIMEOUT_MS);
462
+ try {
463
+ return await readIdentity(provider, registration, abort.signal);
464
+ } finally {
465
+ clearTimeout(timeout);
466
+ this.probes.delete(abort);
467
+ }
468
+ }
469
+ detach() {
470
+ ++this.refreshRevision;
471
+ this.identityRefreshing = false;
472
+ for (const probe of this.probes) probe.abort();
473
+ this.probes.clear();
474
+ this.unsubscribers.splice(0).forEach((unsubscribe) => {
475
+ try {
476
+ unsubscribe();
477
+ } catch {
478
+ }
479
+ });
480
+ }
481
+ attach(id) {
482
+ const provider = this.getProvider(id);
483
+ const update = (payload) => {
484
+ const status = payload;
485
+ if (status?.connection?.isConnected === false || status?.isConnected === false || Array.isArray(payload) && payload.length === 0) {
486
+ this.invalidate(id);
487
+ return;
488
+ }
489
+ const revision = ++this.refreshRevision;
490
+ this.identityRefreshing = true;
491
+ const registration = this.registrations.get(id);
492
+ void this.probe(provider, registration).then(
493
+ (identity) => {
494
+ if (revision !== this.refreshRevision || this.projection?.id !== id || this.disposed)
495
+ return;
496
+ this.identityRefreshing = false;
497
+ this.projection = { id, identity };
498
+ this.changed(id, identity);
499
+ },
500
+ () => {
501
+ if (revision === this.refreshRevision) this.invalidate(id);
502
+ }
503
+ );
504
+ };
505
+ for (const event of ["accountsChanged", "statusChanged"]) {
506
+ provider.on(event, update);
507
+ this.unsubscribers.push(() => provider.removeListener(event, update));
508
+ }
509
+ }
510
+ invalidate(id) {
511
+ if (this.projection?.id !== id) return;
512
+ this.detach();
513
+ this.projection = null;
514
+ teardown(this.client?.getActiveSession()?.adapter);
515
+ this.client?.destroy();
516
+ this.client = null;
517
+ this.initialization = null;
518
+ this.changed(id, null);
519
+ }
520
+ /** Local transport cleanup when switching to a proprietary integration. */
521
+ release() {
522
+ this.assertAvailable();
523
+ const id = this.projection?.id;
524
+ this.detach();
525
+ this.projection = null;
526
+ teardown(this.client?.getActiveSession()?.adapter);
527
+ this.client?.destroy();
528
+ this.client = null;
529
+ this.initialization = null;
530
+ if (id) this.changed(id, null);
531
+ }
532
+ disconnect() {
533
+ if (this.closing) return this.closing;
534
+ this.operation?.abort.abort();
535
+ const task = (async () => {
536
+ await this.pending?.catch(() => {
537
+ });
538
+ this.detach();
539
+ const id = this.projection?.id;
540
+ this.projection = null;
541
+ const operation = { abort: new AbortController() };
542
+ this.operation = operation;
543
+ const timeout = setTimeout(() => operation.abort.abort(), SILENT_PROBE_TIMEOUT_MS);
544
+ try {
545
+ await this.client?.disconnect();
546
+ } finally {
547
+ clearTimeout(timeout);
548
+ if (this.client?.getActiveSession()) {
549
+ this.client.destroy();
550
+ this.client = null;
551
+ this.initialization = null;
552
+ }
553
+ this.operation = null;
554
+ if (id) this.changed(id, null);
555
+ }
556
+ })();
557
+ this.closing = task;
558
+ void task.then(
559
+ () => {
560
+ if (this.closing === task) this.closing = null;
561
+ },
562
+ () => {
563
+ if (this.closing === task) this.closing = null;
564
+ }
565
+ );
566
+ return task;
567
+ }
568
+ destroy() {
569
+ if (this.disposed) return;
570
+ this.disposed = true;
571
+ this.operation?.abort.abort();
572
+ this.detach();
573
+ this.projection = null;
574
+ teardown(this.client?.getActiveSession()?.adapter);
575
+ if (!this.client?.getActiveSession() && this.operation?.id)
576
+ teardown(this.registrations.get(this.operation.id)?.source);
577
+ this.client?.destroy();
578
+ this.client = null;
579
+ }
580
+ };
581
+ var nativeOwnerBindings = /* @__PURE__ */ new WeakMap();
582
+ var nativeAdapterCopies = /* @__PURE__ */ new WeakMap();
74
583
 
75
584
  // src/announce-adapter.ts
585
+ function getAnnounceCapabilities(config = {}) {
586
+ const caps = ["connect"];
587
+ if (config.signMessage !== false) caps.push("signMessage");
588
+ caps.push("submitTransaction");
589
+ if (config.restore) caps.push("restore");
590
+ if (config.ledgerApi) caps.push("ledgerApi");
591
+ if (config.events) caps.push("events");
592
+ return caps;
593
+ }
76
594
  var ANNOUNCED_WALLET_ID_PREFIX = "browser:ext:";
77
595
  function announcedWalletId(announceId) {
78
596
  return toWalletId(`${ANNOUNCED_WALLET_ID_PREFIX}${announceId}`);
@@ -96,12 +614,12 @@ function toBase64Message(message) {
96
614
  for (const b of bytes) binary += String.fromCharCode(b);
97
615
  return btoa(binary);
98
616
  }
99
- var GenericAnnounceAdapter = class {
617
+ var GenericAnnounceAdapter = class _GenericAnnounceAdapter {
100
618
  walletId;
101
619
  name;
102
620
  /** Icon surfaced to the picker (announce detail). */
103
621
  icon;
104
- provider;
622
+ rawProvider;
105
623
  metadataEnabled;
106
624
  staticMetadata;
107
625
  mapError;
@@ -120,10 +638,15 @@ var GenericAnnounceAdapter = class {
120
638
  // declares support, so a wallet that cannot sign is not advertised as able to.
121
639
  signMessage;
122
640
  constructor(args) {
641
+ const configuration = { ...args, config: args.config && {
642
+ ...args.config,
643
+ staticMetadata: args.config.staticMetadata && { ...args.config.staticMetadata }
644
+ } };
645
+ nativeAdapterCopies.set(this, () => new _GenericAnnounceAdapter(configuration));
123
646
  this.walletId = args.walletId ?? announcedWalletId(args.announceId);
124
647
  this.name = args.name && args.name.length > 0 ? args.name : `Canton Wallet (${args.announceId.slice(0, 6)}\u2026)`;
125
648
  this.icon = args.icon;
126
- this.provider = args.provider;
649
+ this.rawProvider = args.provider;
127
650
  const config = args.config;
128
651
  this.metadataEnabled = config?.metadata === true;
129
652
  this.staticMetadata = config?.staticMetadata;
@@ -134,6 +657,22 @@ var GenericAnnounceAdapter = class {
134
657
  if (config?.ledgerApi) this.ledgerApi = this.makeLedgerApi();
135
658
  if (config?.signMessage !== false) this.signMessage = this.signMessageImpl.bind(this);
136
659
  }
660
+ get provider() {
661
+ return nativeOwnerBindings.get(this)?.getProvider(String(this.walletId)) ?? this.rawProvider;
662
+ }
663
+ /** @internal Register the discovered transport with the one official owner. */
664
+ async prepareNativeConnection(network) {
665
+ const owner = nativeOwnerBindings.get(this);
666
+ if (!owner) return;
667
+ await owner.prepare(String(this.walletId), {
668
+ providerId: String(this.walletId),
669
+ name: this.name,
670
+ type: "browser",
671
+ icon: this.icon,
672
+ provider: () => this.rawProvider,
673
+ detect: async () => true
674
+ }, network);
675
+ }
137
676
  /**
138
677
  * Capabilities derived from actual presence: connect and submitTransaction are
139
678
  * always present; signMessage, restore, ledgerApi, and events are each included
@@ -141,30 +680,40 @@ var GenericAnnounceAdapter = class {
141
680
  * beyond what the adapter can do.
142
681
  */
143
682
  getCapabilities() {
144
- const caps = ["connect"];
145
- if (this.signMessage) caps.push("signMessage");
146
- caps.push("submitTransaction");
147
- if (this.restore) caps.push("restore");
148
- if (this.ledgerApi) caps.push("ledgerApi");
149
- if (this.on) caps.push("events");
150
- return caps;
683
+ return getAnnounceCapabilities({
684
+ signMessage: !!this.signMessage,
685
+ restore: !!this.restore,
686
+ ledgerApi: !!this.ledgerApi,
687
+ events: !!this.on
688
+ });
151
689
  }
152
690
  /**
153
691
  * The adapter is only ever constructed for a wallet that just announced, so
154
692
  * its presence is established by the announce handshake itself.
155
693
  */
156
694
  async detectInstalled() {
157
- return { installed: true, reason: "Announced via canton:announceProvider" };
695
+ return {
696
+ installed: true,
697
+ // Presence by CONSTRUCTION: this adapter only exists because an announce
698
+ // arrived on the wallet's own target channel. There is no probe to be
699
+ // wrong about, which is why this is the one path that cannot report a
700
+ // wallet that is not there.
701
+ availability: { kind: "installed" },
702
+ reason: "Announced via canton:announceProvider"
703
+ };
158
704
  }
159
- async connect(ctx) {
705
+ async connect(ctx, options) {
160
706
  return this.guarded(async () => {
161
- await this.provider.request({ method: "connect" });
162
- const account = await this.provider.request({
707
+ const owner = nativeOwnerBindings.get(this);
708
+ const native = owner ? await owner.connect(String(this.walletId), options?.signal) : void 0;
709
+ if (!owner) assertConnectionAccepted(await this.provider.request({ method: "connect" }));
710
+ const account = native?.account ?? await this.provider.request({
163
711
  method: "getPrimaryAccount"
164
712
  });
713
+ assertPrimaryParty(account);
165
714
  let status;
166
715
  try {
167
- status = await this.provider.request({ method: "status" });
716
+ status = native?.status ?? await this.provider.request({ method: "status" });
168
717
  } catch {
169
718
  }
170
719
  const reportedNetwork = status?.network?.networkId;
@@ -184,6 +733,11 @@ var GenericAnnounceAdapter = class {
184
733
  });
185
734
  }
186
735
  async disconnect() {
736
+ const owner = nativeOwnerBindings.get(this);
737
+ if (owner) {
738
+ await owner.disconnect();
739
+ return;
740
+ }
187
741
  try {
188
742
  await this.provider.request({ method: "disconnect" });
189
743
  } catch {
@@ -196,14 +750,7 @@ var GenericAnnounceAdapter = class {
196
750
  return this.guarded(async () => {
197
751
  const rpcParams = this.signMessageBase64 ? { message: toBase64Message(params.message) } : { message: params.message };
198
752
  const res = await this.provider.request({ method: "signMessage", params: rpcParams });
199
- const sig = typeof res === "string" ? res : res?.signature ?? "";
200
- return {
201
- signature: toSignature(String(sig)),
202
- partyId: session.partyId,
203
- message: params.message,
204
- nonce: params.nonce,
205
- domain: params.domain
206
- };
753
+ return normalizeSignedMessage(res, session, params);
207
754
  });
208
755
  }
209
756
  async submitTransaction(ctx, _session, params) {
@@ -238,6 +785,12 @@ var GenericAnnounceAdapter = class {
238
785
  /** restore: silent status()/getPrimaryAccount() probe + expiry + party-match. */
239
786
  makeRestore() {
240
787
  return (_ctx, persisted) => this.guarded(async () => {
788
+ const owner = nativeOwnerBindings.get(this);
789
+ if (owner) {
790
+ await this.prepareNativeConnection(_ctx.network);
791
+ const restored = await owner.restore({ id: String(this.walletId), partyId: persisted.partyId, network: persisted.network });
792
+ return restored?.id === String(this.walletId) ? { ...persisted, capabilitiesSnapshot: this.getCapabilities() } : null;
793
+ }
241
794
  if (persisted.expiresAt && Date.now() >= persisted.expiresAt) return null;
242
795
  let status;
243
796
  try {
@@ -250,6 +803,10 @@ var GenericAnnounceAdapter = class {
250
803
  method: "getPrimaryAccount"
251
804
  });
252
805
  if (account.partyId !== persisted.partyId) return null;
806
+ const network = [status?.network?.networkId, account.networkId].find(
807
+ (value) => typeof value === "string" && isRecognizedNetwork(value)
808
+ );
809
+ if (network && detectNetworkMismatch(persisted.network, network)) return null;
253
810
  return {
254
811
  ...persisted,
255
812
  walletId: this.walletId,
@@ -308,7 +865,14 @@ function buildMetadata(status, account) {
308
865
  put("userId", status?.session?.userId);
309
866
  return meta;
310
867
  }
311
- var GenericDiscoveryAdapter = class {
868
+ function getDiscoveryCapabilities(declared) {
869
+ const capabilities = ["connect", "disconnect"];
870
+ if (declared?.signMessage !== false) capabilities.push("signMessage");
871
+ if (declared?.submitTransaction !== false) capabilities.push("submitTransaction");
872
+ if (declared?.ledgerApi) capabilities.push("ledgerApi");
873
+ return capabilities;
874
+ }
875
+ var GenericDiscoveryAdapter = class _GenericDiscoveryAdapter {
312
876
  walletId;
313
877
  name;
314
878
  icon;
@@ -329,7 +893,28 @@ var GenericDiscoveryAdapter = class {
329
893
  * submit and reused, so the wallet is asked at most once.
330
894
  */
331
895
  executeVerb = {};
896
+ capabilities;
897
+ ledgerApi;
332
898
  constructor(args) {
899
+ const configuration = { ...args, capabilities: args.capabilities && { ...args.capabilities } };
900
+ nativeAdapterCopies.set(this, () => new _GenericDiscoveryAdapter({
901
+ ...configuration,
902
+ networkHosts: { ...this.networkHosts }
903
+ }));
904
+ this.capabilities = getDiscoveryCapabilities(args.capabilities);
905
+ if (args.capabilities?.ledgerApi) {
906
+ this.ledgerApi = async (_ctx, _session, params) => {
907
+ const result = await this.provider.request({
908
+ method: "ledgerApi",
909
+ params: {
910
+ requestMethod: normalizeLedgerMethodLower(params.requestMethod),
911
+ resource: params.resource,
912
+ body: ledgerApiBodyToObject(params.body)
913
+ }
914
+ });
915
+ return { response: typeof result?.response === "string" ? result.response : JSON.stringify(result ?? null) };
916
+ };
917
+ }
333
918
  if (args.official) {
334
919
  this.official = args.official;
335
920
  this.factory = null;
@@ -382,11 +967,20 @@ var GenericDiscoveryAdapter = class {
382
967
  }
383
968
  this.official = this.factory.create(host);
384
969
  }
970
+ /** @internal Prepare the official owner before a popup-opening click. */
971
+ async prepareNativeConnection(network) {
972
+ const owner = nativeOwnerBindings.get(this);
973
+ if (!owner) return;
974
+ this.resolveOfficial(network);
975
+ await owner.prepare(String(this.walletId), this.official, network);
976
+ }
385
977
  /** Lazily obtain (and cache) the official provider — deferred off the init/SSR path.
386
978
  * `official.provider()` is typed `OfficialProvider` (loose `request` so real
387
979
  * official adapters are assignable); it is call-compatible with CIP0103Provider
388
980
  * (the bridge only ever calls `request({ method, params })`). */
389
981
  get provider() {
982
+ const owner = nativeOwnerBindings.get(this);
983
+ if (owner) return owner.getProvider(String(this.walletId));
390
984
  if (this.providerInstance === null) {
391
985
  if (!this.official) {
392
986
  throw new Error(
@@ -397,37 +991,55 @@ var GenericDiscoveryAdapter = class {
397
991
  }
398
992
  return this.providerInstance;
399
993
  }
400
- /**
401
- * Baseline CIP-0103 capabilities. NEVER includes `'events'`: popup/remote
402
- * wallets expose the event surface but do not emit (truthfulness doctrine).
403
- */
994
+ /** Implemented, registry-declared capabilities; popup event listeners are never claimed. */
404
995
  getCapabilities() {
405
- return ["connect", "disconnect", "signMessage", "submitTransaction"];
996
+ return [...this.capabilities];
406
997
  }
407
- /** Install/availability probe — delegated to the official adapter (popup-free). */
998
+ /**
999
+ * THE SINGLE PLACE THE discovery-adapter RULE IS APPLIED.
1000
+ *
1001
+ * **A `discovery-adapter` transport implies there is no local install.** Every
1002
+ * wallet on that transport is a hosted popup or remote gateway reached with
1003
+ * `window.open` — Walley, Cauri and OneSwap today. There is no extension, no
1004
+ * injected global, nothing on the machine to probe. The honest answer is
1005
+ * `no-local-install`, and it follows from the registry entry alone.
1006
+ *
1007
+ * SO THE VENDOR'S `detect()` IS NOT CALLED, and reinstating that call would be
1008
+ * a regression however much it looks like rigour. Read from their shipped
1009
+ * source, all three are constants:
1010
+ *
1011
+ * walley: typeof window < "u" && typeof window.open == "function"
1012
+ * cauri: Promise.resolve(true)
1013
+ * oneswap: typeof window !== 'undefined'
1014
+ *
1015
+ * Each returns true in any browser. Awaiting them bought a value carrying no
1016
+ * information, at the cost of an async hop on the picker's render path and a
1017
+ * dependency on three third parties independently choosing to answer
1018
+ * honestly. The registry already knows, it is signed, and it cannot drift.
1019
+ *
1020
+ * `installed: false` is deliberate and is NOT "not available": there is no
1021
+ * local install, so the only truthful value for a field that asks about one
1022
+ * is false. A picker must read `availability`, which says why.
1023
+ */
408
1024
  async detectInstalled() {
409
- if (!this.official) {
410
- return { installed: true, reason: "Popup/remote wallet (resolved at connect)" };
411
- }
412
- try {
413
- const installed = await this.official.detect();
414
- return {
415
- installed,
416
- reason: installed ? void 0 : "Wallet reported not available"
417
- };
418
- } catch {
419
- return { installed: false, reason: "Detection failed" };
420
- }
1025
+ return {
1026
+ installed: false,
1027
+ availability: { kind: "no-local-install" },
1028
+ reason: "Hosted popup wallet \u2014 opens in a window; nothing is installed locally"
1029
+ };
421
1030
  }
422
- async connect(ctx) {
1031
+ async connect(ctx, options) {
423
1032
  this.resolveOfficial(ctx.network);
424
- await this.provider.request({ method: "connect" });
425
- const account = await this.provider.request({
1033
+ const owner = nativeOwnerBindings.get(this);
1034
+ const native = owner ? await owner.connect(String(this.walletId), options?.signal) : void 0;
1035
+ if (!owner) assertConnectionAccepted(await this.provider.request({ method: "connect" }));
1036
+ const account = native?.account ?? await this.provider.request({
426
1037
  method: "getPrimaryAccount"
427
1038
  });
1039
+ assertPrimaryParty(account);
428
1040
  let reportedNetwork;
429
1041
  try {
430
- const status = await this.provider.request({
1042
+ const status = native?.status ?? await this.provider.request({
431
1043
  method: "status"
432
1044
  });
433
1045
  reportedNetwork = status?.network?.networkId;
@@ -444,57 +1056,60 @@ var GenericDiscoveryAdapter = class {
444
1056
  };
445
1057
  return { partyId, session, capabilities: this.getCapabilities() };
446
1058
  }
447
- /**
448
- * Restore a persisted session by delegating to the official adapter's own `restore`.
449
- *
450
- * The official `ProviderAdapter` shape carries an optional `restore()` that reinstates a
451
- * session (for example from the wallet's own storage) and returns a LIVE provider.
452
- * Without this method the SDK revived the persisted record as-is and then built a fresh,
453
- * SESSION-LESS provider from `provider()`, so a wallet that restores in `restore` looked
454
- * connected after a reload but its first real request threw. This forwards to the
455
- * official `restore` and, when it yields a provider, adopts it as the cached provider so
456
- * the very next request uses the restored session.
457
- *
458
- * Popup-safe: this runs on the SDK's init/restore path, never inside a user gesture, so a
459
- * popup could not open here even if an adapter tried (the browser would block it). Per
460
- * the official contract `restore` is storage-based and gesture-free. If the official
461
- * adapter has no `restore`, it returns null, or host resolution is not ready, this falls
462
- * through to the previous behavior: the persisted session is returned and the provider is
463
- * built lazily on first use, exactly as before.
464
- */
1059
+ /** Restore silently and validate the live party before exposing a connected session. */
465
1060
  async restore(ctx, persisted) {
466
- const asIs = { ...persisted, walletId: this.walletId };
467
1061
  try {
1062
+ if (persisted.expiresAt && Date.now() >= persisted.expiresAt) return null;
468
1063
  this.resolveOfficial(ctx.network);
469
- } catch {
470
- return asIs;
471
- }
472
- const restore = this.official?.restore;
473
- if (this.official && restore) {
474
- let restored = null;
475
- try {
476
- restored = await restore.call(this.official);
477
- } catch {
478
- restored = null;
1064
+ const owner = nativeOwnerBindings.get(this);
1065
+ if (owner) {
1066
+ await this.prepareNativeConnection(ctx.network);
1067
+ const restored = await owner.restore({
1068
+ id: String(this.walletId),
1069
+ partyId: persisted.partyId,
1070
+ network: persisted.network
1071
+ });
1072
+ return restored?.id === String(this.walletId) ? { ...persisted, walletId: this.walletId, capabilitiesSnapshot: this.getCapabilities() } : null;
479
1073
  }
480
- if (restored) {
1074
+ if (this.official?.restore) {
1075
+ const restored = await this.official.restore();
1076
+ if (!restored) return null;
481
1077
  this.providerInstance = restored;
482
- return asIs;
483
1078
  }
1079
+ const account = await this.provider.request({ method: "getPrimaryAccount" });
1080
+ if (account.partyId !== persisted.partyId) return null;
1081
+ let status;
1082
+ try {
1083
+ status = await this.provider.request({ method: "status" });
1084
+ } catch {
1085
+ }
1086
+ if (status?.connection?.isConnected === false) return null;
1087
+ const network = [status?.network?.networkId, account.networkId].find(
1088
+ (value) => typeof value === "string" && isRecognizedNetwork(value)
1089
+ );
1090
+ if (network && detectNetworkMismatch(persisted.network, network)) return null;
1091
+ return { ...persisted, walletId: this.walletId, capabilitiesSnapshot: this.getCapabilities() };
1092
+ } catch {
1093
+ return null;
484
1094
  }
485
- return asIs;
486
1095
  }
487
1096
  async disconnect() {
1097
+ const owner = nativeOwnerBindings.get(this);
1098
+ if (owner) {
1099
+ await owner.disconnect();
1100
+ return;
1101
+ }
488
1102
  try {
489
1103
  await this.provider.request({ method: "disconnect" });
490
1104
  } catch {
491
1105
  }
492
1106
  }
493
- async signMessage(_ctx, _session, params) {
494
- return this.provider.request({
1107
+ async signMessage(_ctx, session, params) {
1108
+ const response = await this.provider.request({
495
1109
  method: "signMessage",
496
1110
  params: { message: params.message }
497
1111
  });
1112
+ return normalizeSignedMessage(response, session, params);
498
1113
  }
499
1114
  async submitTransaction(ctx, _session, params) {
500
1115
  return submitViaPrepareExecute(this.provider, params, {
@@ -504,6 +1119,104 @@ var GenericDiscoveryAdapter = class {
504
1119
  });
505
1120
  }
506
1121
  };
1122
+ function createSessionProvider(options) {
1123
+ const events = new CIP0103EventBus();
1124
+ let current = null;
1125
+ let disposed = false;
1126
+ let revision = 0;
1127
+ const nativeSubscriptions = [];
1128
+ const bridgeSubscriptions = [];
1129
+ const provider = {
1130
+ request: async (args) => {
1131
+ try {
1132
+ if (disposed) throw new Error("PartyLayer client was destroyed");
1133
+ if (args.method === "connect" || args.method === "disconnect" || args.method === "signMessage") {
1134
+ return options.bridge.request(args);
1135
+ }
1136
+ await options.ensureSession();
1137
+ const native = options.native();
1138
+ if (!native) return options.bridge.request(args);
1139
+ if ([
1140
+ "prepareExecute",
1141
+ "prepareExecuteAndWait",
1142
+ "prepareTransaction",
1143
+ "executeTransaction",
1144
+ "signTransaction",
1145
+ "ledgerApi"
1146
+ ].includes(args.method))
1147
+ options.guardNetwork();
1148
+ const result = await native.request(args);
1149
+ if (args.method === "prepareExecute" || args.method === "prepareExecuteAndWait")
1150
+ assertExecuteCorrelation(result, args.params);
1151
+ return result;
1152
+ } catch (error) {
1153
+ throw toProviderRpcError(error);
1154
+ }
1155
+ },
1156
+ on: (event, listener) => {
1157
+ events.on(event, listener);
1158
+ return provider;
1159
+ },
1160
+ emit: (event, ...args) => events.emit(event, ...args),
1161
+ removeListener: (event, listener) => {
1162
+ events.removeListener(event, listener);
1163
+ return provider;
1164
+ }
1165
+ };
1166
+ events.setOwner(provider);
1167
+ const refresh = () => {
1168
+ const next = options.native();
1169
+ if (next === current) return;
1170
+ ++revision;
1171
+ nativeSubscriptions.splice(0).forEach((unsubscribe2) => unsubscribe2());
1172
+ current = next;
1173
+ if (!next || disposed) return;
1174
+ const captured = revision;
1175
+ for (const name of ["statusChanged", "accountsChanged", "txChanged", "connected"]) {
1176
+ const listener = (...args) => {
1177
+ if (!disposed && next === options.native()) events.emit(name, ...args);
1178
+ };
1179
+ next.on(name, listener);
1180
+ nativeSubscriptions.push(() => next.removeListener(name, listener));
1181
+ }
1182
+ for (const [method, event] of [
1183
+ ["status", "statusChanged"],
1184
+ ["listAccounts", "accountsChanged"]
1185
+ ]) {
1186
+ void next.request({ method }).then(
1187
+ (value) => {
1188
+ if (!disposed && captured === revision && next === options.native())
1189
+ events.emit(event, value);
1190
+ },
1191
+ () => {
1192
+ }
1193
+ );
1194
+ }
1195
+ events.emit("connected", { isConnected: true });
1196
+ };
1197
+ for (const name of ["statusChanged", "accountsChanged", "txChanged", "connected"]) {
1198
+ const listener = (...args) => {
1199
+ if (!options.native() && !disposed) events.emit(name, ...args);
1200
+ };
1201
+ options.bridge.on(name, listener);
1202
+ bridgeSubscriptions.push(() => options.bridge.removeListener(name, listener));
1203
+ }
1204
+ const unsubscribe = options.subscribe(refresh);
1205
+ refresh();
1206
+ return {
1207
+ provider,
1208
+ destroy: () => {
1209
+ if (disposed) return;
1210
+ disposed = true;
1211
+ ++revision;
1212
+ unsubscribe();
1213
+ nativeSubscriptions.splice(0).forEach((remove) => remove());
1214
+ bridgeSubscriptions.splice(0).forEach((remove) => remove());
1215
+ current = null;
1216
+ events.removeAllListeners();
1217
+ }
1218
+ };
1219
+ }
507
1220
 
508
1221
  // src/config.ts
509
1222
  var DEFAULT_REGISTRY_URL = "https://registry.partylayer.xyz";
@@ -948,9 +1661,20 @@ function deriveAnnounceConfig(entry) {
948
1661
  }
949
1662
  return config;
950
1663
  }
1664
+ function matchKnownByIdentity(providerId, base) {
1665
+ return base.find((w) => {
1666
+ const k = w.installHints?.injectedKey;
1667
+ return providerId === String(w.walletId) || !!k && (providerId === k || providerId.startsWith(`${k}.`));
1668
+ });
1669
+ }
1670
+ var DEFAULT_CONNECT_TIMEOUT_MS = 12e4;
951
1671
  var PartyLayerClient = class {
952
1672
  config;
953
1673
  adapters = /* @__PURE__ */ new Map();
1674
+ destroyed = false;
1675
+ initialized = false;
1676
+ defaultLoads = /* @__PURE__ */ new Map();
1677
+ registryDefaultIds = /* @__PURE__ */ new Set();
954
1678
  /**
955
1679
  * Pre-resolved connect plans for popup/remote (GenericDiscoveryAdapter)
956
1680
  * wallets, warmed on `listWallets()` (which the modal calls on open) so a
@@ -960,6 +1684,11 @@ var PartyLayerClient = class {
960
1684
  warmPlans = /* @__PURE__ */ new Map();
961
1685
  eventHandlers = /* @__PURE__ */ new Map();
962
1686
  activeSession = null;
1687
+ sessionRevision = 0;
1688
+ connectionAttempt = 0;
1689
+ restoreTask = null;
1690
+ restorationBlocked = false;
1691
+ sessionStorageQueue = Promise.resolve();
963
1692
  /**
964
1693
  * True when `activeSession` was revived AS-IS (no live `status()` probe) because
965
1694
  * its adapter wasn't registered yet at restore time (the lazy configured-announce
@@ -982,10 +1711,13 @@ var PartyLayerClient = class {
982
1711
  // captured (not just a one-shot window). Read by aggregateAnnouncedWallets;
983
1712
  // torn down in destroy(). Empty → listWallets() output is byte-identical.
984
1713
  announceRegistry = /* @__PURE__ */ new Map();
1714
+ announceChannels = /* @__PURE__ */ new Map();
985
1715
  announceUnsubscribe = null;
986
1716
  /** Pending debounced `wallets:changed` emit (coalesces an announce burst). */
987
1717
  walletsChangedTimer = null;
988
1718
  origin;
1719
+ nativeOwner;
1720
+ sessionProvider;
989
1721
  constructor(config) {
990
1722
  this.config = config;
991
1723
  if (config.app.origin) {
@@ -999,9 +1731,13 @@ var PartyLayerClient = class {
999
1731
  this.logLevel = config.logLevel ?? "info";
1000
1732
  this.crypto = config.crypto || new DefaultCrypto();
1001
1733
  this.storage = config.storage || new DefaultStorage();
1734
+ if (typeof window !== "undefined") {
1735
+ this.nativeOwner = new NativeConnectionOwner((id, identity) => this.onNativeIdentityChanged(id, identity));
1736
+ }
1002
1737
  const telemetryAdapter = createTelemetryAdapter(config.telemetry);
1003
1738
  this.telemetry = telemetryAdapter || new DefaultTelemetry();
1004
- const adaptersToRegister = config.adapters ?? getBuiltinAdapters();
1739
+ const defaults = config.adapters ?? getBuiltinAdapters();
1740
+ const adaptersToRegister = [...defaults, ...config.additionalAdapters ?? []];
1005
1741
  for (const adapterOrClass of adaptersToRegister) {
1006
1742
  let adapter;
1007
1743
  if (typeof adapterOrClass === "function") {
@@ -1013,7 +1749,7 @@ var PartyLayerClient = class {
1013
1749
  } else {
1014
1750
  adapter = adapterOrClass;
1015
1751
  }
1016
- this.adapters.set(adapter.walletId, adapter);
1752
+ this.registerAdapter(adapter);
1017
1753
  this.log("debug", "adapter:registered", "Registered wallet adapter", {
1018
1754
  walletId: adapter.walletId,
1019
1755
  name: adapter.name,
@@ -1027,10 +1763,16 @@ var PartyLayerClient = class {
1027
1763
  storage: this.storage
1028
1764
  });
1029
1765
  this.updateRegistryStatus();
1766
+ if (!config.deferInitialization) this.initialize();
1767
+ }
1768
+ /** Start browser discovery/restoration once; safe for framework effect replay. */
1769
+ initialize() {
1770
+ if (this.initialized || this.destroyed) return;
1771
+ this.initialized = true;
1030
1772
  if (this.announceEnabled) {
1031
1773
  this.announceUnsubscribe = subscribeAnnouncedProviders(
1032
1774
  (p) => this.onAnnounceAccumulated(p),
1033
- { createProvider: (a) => createExtensionChannelProvider({ target: a.target ?? a.id }) }
1775
+ { createProvider: (a) => this.announceChannel(a.target ?? a.id) }
1034
1776
  );
1035
1777
  }
1036
1778
  this.restoreSession().catch((err) => {
@@ -1042,6 +1784,15 @@ var PartyLayerClient = class {
1042
1784
  });
1043
1785
  });
1044
1786
  }
1787
+ announceChannel(target) {
1788
+ if (this.destroyed) throw new Error("PartyLayer client was destroyed");
1789
+ let provider = this.announceChannels.get(target);
1790
+ if (!provider) {
1791
+ provider = createExtensionChannelProvider({ target });
1792
+ this.announceChannels.set(target, provider);
1793
+ }
1794
+ return provider;
1795
+ }
1045
1796
  /**
1046
1797
  * Register a wallet adapter
1047
1798
  *
@@ -1050,7 +1801,34 @@ var PartyLayerClient = class {
1050
1801
  * In production, adapters would be auto-registered via registry.
1051
1802
  */
1052
1803
  registerAdapter(adapter) {
1804
+ const boundOwner = nativeOwnerBindings.get(adapter);
1805
+ if (this.nativeOwner && boundOwner && boundOwner !== this.nativeOwner) {
1806
+ adapter = nativeAdapterCopies.get(adapter)();
1807
+ }
1053
1808
  this.adapters.set(adapter.walletId, adapter);
1809
+ if (this.nativeOwner && (adapter instanceof GenericDiscoveryAdapter || adapter instanceof GenericAnnounceAdapter)) {
1810
+ nativeOwnerBindings.set(adapter, this.nativeOwner);
1811
+ }
1812
+ }
1813
+ onNativeIdentityChanged(id, identity) {
1814
+ const active = this.activeSession;
1815
+ if (this.destroyed || !active || String(active.walletId) !== id) return;
1816
+ ++this.sessionRevision;
1817
+ if (!identity) {
1818
+ this.restorationBlocked = true;
1819
+ this.warmPlans.clear();
1820
+ this.activeSession = null;
1821
+ void this.removeSession(active.sessionId);
1822
+ this.emit("session:disconnected", { type: "session:disconnected", sessionId: active.sessionId });
1823
+ return;
1824
+ }
1825
+ const session = { ...active, partyId: identity.account.partyId, network: identity.network };
1826
+ const mismatch = this.networkMismatch(session);
1827
+ if (mismatch) session.networkMismatch = mismatch;
1828
+ else delete session.networkMismatch;
1829
+ this.activeSession = session;
1830
+ void this.persistSession(session);
1831
+ this.emit("session:connected", { type: "session:connected", session });
1054
1832
  }
1055
1833
  /**
1056
1834
  * Look up a registered adapter by wallet id.
@@ -1074,6 +1852,7 @@ var PartyLayerClient = class {
1074
1852
  * List available wallets
1075
1853
  */
1076
1854
  async listWallets(filter) {
1855
+ this.initialize();
1077
1856
  let registryWallets;
1078
1857
  try {
1079
1858
  registryWallets = await this.registryClient.getWallets();
@@ -1085,9 +1864,10 @@ var PartyLayerClient = class {
1085
1864
  });
1086
1865
  registryWallets = [];
1087
1866
  }
1867
+ await this.ensureDefaultWallets();
1088
1868
  const registryIds = new Set(registryWallets.map((w) => String(w.walletId)));
1089
1869
  for (const [, adapter] of this.adapters) {
1090
- if (registryIds.has(String(adapter.walletId))) continue;
1870
+ if (registryIds.has(String(adapter.walletId)) || this.registryDefaultIds.has(adapter.walletId)) continue;
1091
1871
  registryWallets.push({
1092
1872
  walletId: adapter.walletId,
1093
1873
  name: adapter.name,
@@ -1097,25 +1877,62 @@ var PartyLayerClient = class {
1097
1877
  adapter: { packageName: "builtin", versionRange: "*" },
1098
1878
  docs: [],
1099
1879
  networks: [this.config.network || "devnet"],
1100
- channel: "stable"
1880
+ channel: this.config.channel || "stable"
1101
1881
  });
1102
1882
  }
1103
1883
  registryWallets = await this.gateUnconnectableEntries(registryWallets);
1104
1884
  registryWallets = await this.aggregateAnnouncedWallets(registryWallets);
1105
- void this.warmDiscoveryPlans(registryWallets);
1106
- if (filter?.requiredCapabilities) {
1107
- return registryWallets.filter(
1108
- (walletInfo) => filter.requiredCapabilities.every(
1109
- (cap) => walletInfo.capabilities.includes(cap)
1110
- )
1111
- );
1112
- }
1113
- if (!filter?.includeExperimental) {
1114
- const channel = this.config.channel || "stable";
1115
- return registryWallets.filter((walletInfo) => walletInfo.channel === channel);
1116
- }
1885
+ registryWallets = registryWallets.map((wallet) => {
1886
+ const adapter = this.adapters.get(wallet.walletId);
1887
+ return adapter ? { ...wallet, capabilities: adapter.getCapabilities() } : wallet;
1888
+ }).filter(
1889
+ (wallet) => wallet.networks.includes(this.config.network) && (filter?.includeExperimental || wallet.channel === (this.config.channel || "stable")) && (!filter?.requiredCapabilities || filter.requiredCapabilities.every((cap) => wallet.capabilities.includes(cap)))
1890
+ );
1891
+ await this.warmDiscoveryPlans(registryWallets);
1117
1892
  return registryWallets;
1118
1893
  }
1894
+ /** Resolve only reviewed default SDKs present in the active registry. */
1895
+ async ensureDefaultWallets() {
1896
+ if (this.config.adapters !== void 0) return;
1897
+ let registry;
1898
+ try {
1899
+ registry = await this.registryClient.getRegistry();
1900
+ } catch {
1901
+ return;
1902
+ }
1903
+ await Promise.all(registry.wallets.map(async (entry) => {
1904
+ const id = toWalletId(entry.id);
1905
+ if (this.adapters.has(id) || !entry.supportedNetworks.includes(this.config.network) || entry.adapter?.transport === "discovery-adapter" && !entry.adapter.networkHosts?.[this.config.network]) return;
1906
+ let pending = this.defaultLoads.get(entry.id);
1907
+ if (!pending) {
1908
+ pending = (async () => {
1909
+ try {
1910
+ const entryAdapter = await loadDefaultWallet(entry.id, this.config, this.origin);
1911
+ if (!entryAdapter || this.destroyed) return;
1912
+ const adapter = isOfficialAdapterFactory(entryAdapter) ? new GenericDiscoveryAdapter({
1913
+ factory: entryAdapter,
1914
+ name: entry.name,
1915
+ networkHosts: entry.adapter?.networkHosts,
1916
+ capabilities: entry.capabilities
1917
+ }) : entryAdapter;
1918
+ if (typeof window !== "undefined" && adapter instanceof GenericDiscoveryAdapter) {
1919
+ adapter.resolveOfficial(this.config.network);
1920
+ }
1921
+ this.registerAdapter(adapter);
1922
+ this.registryDefaultIds.add(id);
1923
+ } catch (error) {
1924
+ this.defaultLoads.delete(entry.id);
1925
+ this.log("warn", "wallet:load_failed", "Official wallet SDK could not load", {
1926
+ walletId: entry.id,
1927
+ error: String(error)
1928
+ });
1929
+ }
1930
+ })();
1931
+ this.defaultLoads.set(entry.id, pending);
1932
+ }
1933
+ await pending;
1934
+ }));
1935
+ }
1119
1936
  /**
1120
1937
  * Hide registry entries whose wallet needs an app-registered adapter that is
1121
1938
  * NOT registered. This is the library default (RainbowKit-style): never show a
@@ -1138,10 +1955,14 @@ var PartyLayerClient = class {
1138
1955
  */
1139
1956
  async gateUnconnectableEntries(wallets) {
1140
1957
  let hidden = null;
1958
+ const announceCapabilities = /* @__PURE__ */ new Map();
1141
1959
  try {
1142
1960
  const registry = await this.registryClient.getRegistry();
1143
1961
  for (const entry of registry.wallets) {
1144
- if (entry.adapter?.transport === "announce") continue;
1962
+ if (entry.adapter?.transport === "announce") {
1963
+ announceCapabilities.set(entry.id, getAnnounceCapabilities(deriveAnnounceConfig(entry)));
1964
+ continue;
1965
+ }
1145
1966
  const walletId = toWalletId(entry.id);
1146
1967
  if (!this.adapters.has(walletId)) {
1147
1968
  (hidden ??= /* @__PURE__ */ new Set()).add(String(walletId));
@@ -1150,8 +1971,10 @@ var PartyLayerClient = class {
1150
1971
  } catch {
1151
1972
  return wallets;
1152
1973
  }
1153
- if (!hidden || hidden.size === 0) return wallets;
1154
- return wallets.filter((w) => !hidden.has(String(w.walletId)));
1974
+ return wallets.filter((w) => !hidden?.has(String(w.walletId))).map((w) => {
1975
+ const capabilities = announceCapabilities.get(String(w.walletId));
1976
+ return capabilities ? { ...w, capabilities } : w;
1977
+ });
1155
1978
  }
1156
1979
  /**
1157
1980
  * If `walletId` maps to a registry entry with `transport: 'discovery-adapter'`,
@@ -1242,7 +2065,7 @@ var PartyLayerClient = class {
1242
2065
  injectionPaths,
1243
2066
  // Working provider over the announce target channel; G4 (provider.md):
1244
2067
  // target defaults to id when omitted — never a shared slot.
1245
- createProvider: (a) => createExtensionChannelProvider({ target: a.target ?? a.id })
2068
+ createProvider: (a) => this.announceChannel(a.target ?? a.id)
1246
2069
  });
1247
2070
  const byId = /* @__PURE__ */ new Map();
1248
2071
  for (const d of snapshot) byId.set(d.id, d);
@@ -1255,7 +2078,7 @@ var PartyLayerClient = class {
1255
2078
  const known = findMatchingWalletInfo(
1256
2079
  { provider: { id: d.id } },
1257
2080
  base
1258
- );
2081
+ ) ?? matchKnownByIdentity(d.id, base);
1259
2082
  if (known) {
1260
2083
  if (this.adapters.has(known.walletId)) continue;
1261
2084
  try {
@@ -1269,21 +2092,25 @@ var PartyLayerClient = class {
1269
2092
  provider: d.provider,
1270
2093
  config: deriveAnnounceConfig(entry)
1271
2094
  });
1272
- this.adapters.set(configured.walletId, configured);
2095
+ this.registerAdapter(configured);
1273
2096
  const active = this.activeSession;
1274
2097
  if (active && this.activeSessionNeedsProbe && active.walletId === configured.walletId && configured.restore) {
2098
+ const revision = this.sessionRevision;
1275
2099
  try {
1276
2100
  const reprobed = await configured.restore(this.createAdapterContext(), {
1277
2101
  ...active,
1278
2102
  encrypted: ""
1279
2103
  });
2104
+ if (this.destroyed || revision !== this.sessionRevision || this.activeSession !== active) continue;
1280
2105
  if (reprobed) {
1281
2106
  this.activeSession = reprobed;
1282
2107
  this.activeSessionNeedsProbe = false;
1283
2108
  await this.persistSession(reprobed);
2109
+ if (this.destroyed || revision !== this.sessionRevision || this.activeSession !== reprobed) continue;
1284
2110
  this.emit("session:connected", { type: "session:connected", session: reprobed });
1285
2111
  } else {
1286
2112
  await this.removeSession(active.sessionId);
2113
+ if (this.destroyed || revision !== this.sessionRevision || this.activeSession !== active) continue;
1287
2114
  this.activeSession = null;
1288
2115
  this.activeSessionNeedsProbe = false;
1289
2116
  this.emit("session:expired", { type: "session:expired", sessionId: active.sessionId });
@@ -1305,7 +2132,7 @@ var PartyLayerClient = class {
1305
2132
  icon: d.icon,
1306
2133
  provider: d.provider
1307
2134
  });
1308
- this.adapters.set(adapter.walletId, adapter);
2135
+ this.registerAdapter(adapter);
1309
2136
  entries.push({
1310
2137
  walletId: adapter.walletId,
1311
2138
  name: adapter.name,
@@ -1357,16 +2184,22 @@ var PartyLayerClient = class {
1357
2184
  * Connect to a wallet
1358
2185
  */
1359
2186
  async connect(options) {
2187
+ this.initialize();
2188
+ this.nativeOwner?.assertAvailable();
2189
+ this.restorationBlocked = true;
2190
+ const attempt = ++this.connectionAttempt;
2191
+ ++this.sessionRevision;
1360
2192
  this.telemetry?.increment?.(METRICS.WALLET_CONNECT_ATTEMPTS);
1361
2193
  const correlationId = newCorrelationId();
1362
2194
  this.log("debug", "connect:start", "connect", {}, correlationId);
1363
2195
  try {
1364
- const fast = this.tryFastConnect(options, correlationId);
2196
+ const fast = this.tryFastConnect(options, correlationId, attempt);
1365
2197
  if (fast) return await fast;
1366
2198
  const plan = await this.resolveConnectPlan(options);
1367
- return await this.completeConnect(plan, options, correlationId);
2199
+ return await this.completeConnect(plan, options, correlationId, attempt);
1368
2200
  } catch (err) {
1369
- const timeoutMs = options?.timeoutMs || 3e4;
2201
+ this.warmPlans.clear();
2202
+ const timeoutMs = options?.timeoutMs || DEFAULT_CONNECT_TIMEOUT_MS;
1370
2203
  const error = mapUnknownErrorToPartyLayerError(err, {
1371
2204
  phase: "connect",
1372
2205
  walletId: options?.walletId ? String(options.walletId) : void 0,
@@ -1404,6 +2237,10 @@ var PartyLayerClient = class {
1404
2237
  } else {
1405
2238
  const nativeAdapter = this.adapters.get(options.walletId);
1406
2239
  if (nativeAdapter) {
2240
+ const entry = await this.registryClient.getWalletEntry(String(options.walletId)).catch(() => null);
2241
+ if (entry?.supportedNetworks?.length && !entry.supportedNetworks.includes(this.config.network)) {
2242
+ throw new WalletNotFoundError(`${String(options.walletId)} is unavailable on ${this.config.network}`);
2243
+ }
1407
2244
  isNativeWallet = true;
1408
2245
  selectedWallet = {
1409
2246
  walletId: options.walletId,
@@ -1469,6 +2306,9 @@ var PartyLayerClient = class {
1469
2306
  adapter.setNetworkHosts(networkHosts);
1470
2307
  adapter.resolveOfficial(ctx.network);
1471
2308
  }
2309
+ if (adapter instanceof GenericDiscoveryAdapter || adapter instanceof GenericAnnounceAdapter) {
2310
+ await adapter.prepareNativeConnection(ctx.network);
2311
+ }
1472
2312
  return { selectedWallet, adapter, ctx, isNativeWallet };
1473
2313
  }
1474
2314
  /**
@@ -1476,21 +2316,37 @@ var PartyLayerClient = class {
1476
2316
  * build / persist / emit the session. Separated from plan resolution so the
1477
2317
  * popup-safe fast-path can call it gesture-synchronously.
1478
2318
  */
1479
- async completeConnect(plan, options, correlationId = newCorrelationId()) {
2319
+ async completeConnect(plan, options, correlationId = newCorrelationId(), attempt) {
2320
+ this.nativeOwner?.assertAvailable();
2321
+ this.restorationBlocked = true;
2322
+ const currentAttempt = attempt ?? ++this.connectionAttempt;
2323
+ if (attempt === void 0) ++this.sessionRevision;
2324
+ if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
1480
2325
  const { selectedWallet, adapter, ctx } = plan;
1481
- const timeoutMs = options?.timeoutMs || 12e4;
2326
+ if (!nativeOwnerBindings.has(adapter) && this.nativeOwner?.getSession()) this.nativeOwner.release();
2327
+ const timeoutMs = options?.timeoutMs || DEFAULT_CONNECT_TIMEOUT_MS;
2328
+ const abort = new AbortController();
1482
2329
  const connectPromise = adapter.connect(ctx, {
1483
2330
  timeoutMs,
2331
+ signal: abort.signal,
1484
2332
  partyId: void 0,
1485
2333
  preferInstalled: options?.preferInstalled,
1486
2334
  onDisplayUri: options?.onDisplayUri
1487
2335
  });
2336
+ let timeoutHandle;
1488
2337
  const timeoutPromise = new Promise((_, reject) => {
1489
- setTimeout(() => {
2338
+ timeoutHandle = setTimeout(() => {
2339
+ abort.abort();
1490
2340
  reject(new Error(`Connection timed out after ${timeoutMs}ms - user did not complete wallet connection`));
1491
2341
  }, timeoutMs);
1492
2342
  });
1493
- const result = await Promise.race([connectPromise, timeoutPromise]);
2343
+ let result;
2344
+ try {
2345
+ result = await Promise.race([connectPromise, timeoutPromise]);
2346
+ } finally {
2347
+ if (timeoutHandle !== void 0) clearTimeout(timeoutHandle);
2348
+ }
2349
+ if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
1494
2350
  const session = {
1495
2351
  sessionId: toSessionId(`session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`),
1496
2352
  walletId: selectedWallet.walletId,
@@ -1521,12 +2377,18 @@ var PartyLayerClient = class {
1521
2377
  enforced: this.enforcement !== "off"
1522
2378
  }, correlationId);
1523
2379
  if (this.enforcement === "strict") {
2380
+ if (nativeOwnerBindings.has(adapter)) await this.nativeOwner?.disconnect();
1524
2381
  throw new NetworkMismatchError(mismatch.expected, mismatch.actual);
1525
2382
  }
1526
2383
  }
1527
- await this.persistSession(session);
2384
+ ++this.sessionRevision;
1528
2385
  this.activeSession = session;
2386
+ this.restorationBlocked = false;
1529
2387
  this.activeSessionNeedsProbe = false;
2388
+ await this.persistSession(session);
2389
+ if (this.destroyed || currentAttempt !== this.connectionAttempt || this.activeSession !== session) {
2390
+ throw new Error("Wallet connection was superseded");
2391
+ }
1530
2392
  this.updateRegistryStatus();
1531
2393
  this.telemetry?.increment?.(METRICS.WALLET_CONNECT_SUCCESS);
1532
2394
  this.telemetry?.increment?.(METRICS.SESSIONS_CREATED);
@@ -1557,7 +2419,7 @@ var PartyLayerClient = class {
1557
2419
  */
1558
2420
  async warmDiscoveryPlans(wallets) {
1559
2421
  for (const [walletId, adapter] of this.adapters) {
1560
- if (!(adapter instanceof GenericDiscoveryAdapter)) continue;
2422
+ if (!(adapter instanceof GenericDiscoveryAdapter || adapter instanceof GenericAnnounceAdapter)) continue;
1561
2423
  if (this.warmPlans.has(walletId)) continue;
1562
2424
  try {
1563
2425
  const plan = await this.resolveConnectPlan({ walletId }, wallets);
@@ -1573,30 +2435,39 @@ var PartyLayerClient = class {
1573
2435
  * Returns the in-flight Session promise, or null to fall back to the normal
1574
2436
  * path (e.g. cold cache, or a non-discovery wallet).
1575
2437
  */
1576
- tryFastConnect(options, correlationId) {
2438
+ tryFastConnect(options, correlationId, attempt) {
1577
2439
  const walletId = options?.walletId;
1578
2440
  if (!walletId) return null;
1579
2441
  if (options?.requiredCapabilities || options?.allowWallets) return null;
1580
2442
  const plan = this.warmPlans.get(walletId);
1581
2443
  if (!plan) return null;
1582
2444
  this.warmPlans.delete(walletId);
1583
- return this.completeConnect(plan, options, correlationId);
2445
+ return this.completeConnect(plan, options, correlationId, attempt);
1584
2446
  }
1585
2447
  /**
1586
2448
  * Disconnect from wallet
1587
2449
  */
1588
2450
  async disconnect() {
1589
- if (!this.activeSession) {
2451
+ this.restorationBlocked = true;
2452
+ this.warmPlans.clear();
2453
+ const revision = ++this.sessionRevision;
2454
+ ++this.connectionAttempt;
2455
+ const session = this.activeSession;
2456
+ if (!session) {
2457
+ if (this.nativeOwner?.busy) await this.nativeOwner.disconnect();
2458
+ await this.removeSession();
1590
2459
  return;
1591
2460
  }
1592
2461
  try {
1593
- const adapter = this.adapters.get(this.activeSession.walletId);
2462
+ const adapter = this.adapters.get(session.walletId);
1594
2463
  if (adapter) {
1595
2464
  const ctx = this.createAdapterContext();
1596
- await adapter.disconnect(ctx, this.activeSession);
2465
+ await adapter.disconnect(ctx, session);
1597
2466
  }
1598
- const sessionId = this.activeSession.sessionId;
2467
+ if (revision !== this.sessionRevision || this.activeSession !== session) return;
2468
+ const sessionId = session.sessionId;
1599
2469
  await this.removeSession(sessionId);
2470
+ if (revision !== this.sessionRevision || this.activeSession !== session) return;
1600
2471
  this.activeSession = null;
1601
2472
  this.warmPlans.clear();
1602
2473
  this.emit("session:disconnected", {
@@ -1616,12 +2487,20 @@ var PartyLayerClient = class {
1616
2487
  * Get active session
1617
2488
  */
1618
2489
  async getActiveSession() {
2490
+ if (this.destroyed) return null;
2491
+ this.initialize();
1619
2492
  if (this.activeSession) {
2493
+ const adapter = this.adapters.get(this.activeSession.walletId);
2494
+ if (adapter && nativeOwnerBindings.has(adapter) && this.nativeOwner?.getSession()?.id !== String(this.activeSession.walletId)) {
2495
+ this.onNativeIdentityChanged(String(this.activeSession.walletId), null);
2496
+ return null;
2497
+ }
1620
2498
  if (this.activeSession.expiresAt && Date.now() >= this.activeSession.expiresAt) {
2499
+ const sessionId = this.activeSession.sessionId;
1621
2500
  await this.disconnect();
1622
2501
  this.emit("session:expired", {
1623
2502
  type: "session:expired",
1624
- sessionId: this.activeSession.sessionId
2503
+ sessionId
1625
2504
  });
1626
2505
  return null;
1627
2506
  }
@@ -1647,7 +2526,11 @@ var PartyLayerClient = class {
1647
2526
  try {
1648
2527
  this.assertNetworkOk(session);
1649
2528
  const ctx = this.createAdapterContext();
1650
- return await adapter.signMessage(ctx, session, params);
2529
+ const result = await adapter.signMessage(ctx, session, params);
2530
+ if (nativeOwnerBindings.has(adapter)) {
2531
+ await this.nativeOwner.validateIdentity(String(session.walletId), session.partyId, session.network);
2532
+ }
2533
+ return normalizeSignedMessage(result, session, params);
1651
2534
  } catch (err) {
1652
2535
  const error = mapUnknownErrorToPartyLayerError(err, {
1653
2536
  phase: "signMessage",
@@ -1832,28 +2715,55 @@ var PartyLayerClient = class {
1832
2715
  }
1833
2716
  }
1834
2717
  /**
1835
- * Get a CIP-0103 Provider backed by this client.
2718
+ * Get the stable provider facade for this client.
1836
2719
  *
1837
- * This bridge routes all request() calls through the existing
1838
- * PartyLayerClient methods and maps events to CIP-0103 format.
2720
+ * Browser-native connections expose the official owner's actual accounts,
2721
+ * network, execution/events and raw Ledger API response, including standard
2722
+ * path/query/header request fields. Signing keeps the reviewed encoding policy.
2723
+ * Existing proprietary/custom integrations retain their compatibility bridge.
2724
+ * `createProviderBridge(client)` remains available explicitly for legacy callers.
2725
+ * Full async server user-URL orchestration needs a verified direct provider path.
1839
2726
  *
1840
- * The bridge implements the full CIP-0103 specification:
1841
- * - All 10 mandatory methods including `ledgerApi` (when adapter supports it)
1842
- * - Full transaction lifecycle: pending -> signed -> executed/failed
1843
- * - All CIP-0103 events: statusChanged, accountsChanged, txChanged, connected
1844
- *
1845
- * **Note:** Async wallets (userUrl pattern) are not supported through the
1846
- * bridge. For async wallet support, use `PartyLayerProvider` directly.
1847
- *
1848
- * @returns CIP-0103 compliant Provider
2727
+ * @returns Stable CIP-0103 provider facade
1849
2728
  */
1850
2729
  asProvider() {
1851
- return createProviderBridge(this);
2730
+ if (!this.sessionProvider) {
2731
+ this.sessionProvider = createSessionProvider({
2732
+ bridge: createProviderBridge(this),
2733
+ native: () => {
2734
+ const session = this.activeSession;
2735
+ const adapter = session && this.adapters.get(session.walletId);
2736
+ if (!adapter || !nativeOwnerBindings.has(adapter) || !this.nativeOwner?.getSession()) return null;
2737
+ return this.nativeOwner.getProvider(String(session.walletId));
2738
+ },
2739
+ ensureSession: () => this.getActiveSession(),
2740
+ guardNetwork: () => {
2741
+ if (this.activeSession) this.assertNetworkOk(this.activeSession);
2742
+ },
2743
+ subscribe: (changed) => {
2744
+ const connected = this.on("session:connected", changed);
2745
+ const disconnected2 = this.on("session:disconnected", changed);
2746
+ const expired = this.on("session:expired", changed);
2747
+ return () => {
2748
+ connected();
2749
+ disconnected2();
2750
+ expired();
2751
+ };
2752
+ }
2753
+ });
2754
+ }
2755
+ return this.sessionProvider.provider;
1852
2756
  }
1853
2757
  /**
1854
2758
  * Destroy client and cleanup
1855
2759
  */
1856
2760
  destroy() {
2761
+ if (this.destroyed) return;
2762
+ ++this.sessionRevision;
2763
+ ++this.connectionAttempt;
2764
+ this.destroyed = true;
2765
+ this.sessionProvider?.destroy();
2766
+ this.nativeOwner?.destroy();
1857
2767
  if (this.telemetry && "destroy" in this.telemetry && typeof this.telemetry.destroy === "function") {
1858
2768
  this.telemetry.destroy();
1859
2769
  } else if (this.telemetry?.flush) {
@@ -1863,6 +2773,8 @@ var PartyLayerClient = class {
1863
2773
  this.announceUnsubscribe?.();
1864
2774
  this.announceUnsubscribe = null;
1865
2775
  this.announceRegistry.clear();
2776
+ for (const channel of this.announceChannels.values()) channel.destroy();
2777
+ this.announceChannels.clear();
1866
2778
  if (this.walletsChangedTimer !== null) {
1867
2779
  clearTimeout(this.walletsChangedTimer);
1868
2780
  this.walletsChangedTimer = null;
@@ -1898,10 +2810,16 @@ var PartyLayerClient = class {
1898
2810
  * Persist session to storage
1899
2811
  */
1900
2812
  async persistSession(session) {
2813
+ const revision = this.sessionRevision;
1901
2814
  try {
1902
2815
  const data = JSON.stringify(session);
1903
2816
  const encrypted = await this.crypto.encrypt(data, this.origin);
1904
- await this.storage.set(SESSION_STORAGE_KEY, encrypted);
2817
+ const write = this.sessionStorageQueue.then(async () => {
2818
+ if (!this.destroyed && revision === this.sessionRevision) await this.storage.set(SESSION_STORAGE_KEY, encrypted);
2819
+ });
2820
+ this.sessionStorageQueue = write.catch(() => {
2821
+ });
2822
+ await write;
1905
2823
  } catch (err) {
1906
2824
  this.log("warn", "session:persist_failed", "Failed to persist session", {
1907
2825
  error: err instanceof Error ? err.message : String(err)
@@ -1915,8 +2833,14 @@ var PartyLayerClient = class {
1915
2833
  * active session we always remove the single SESSION_STORAGE_KEY.
1916
2834
  */
1917
2835
  async removeSession(_sessionId) {
2836
+ const revision = this.sessionRevision;
1918
2837
  try {
1919
- await this.storage.remove(SESSION_STORAGE_KEY);
2838
+ const remove = this.sessionStorageQueue.then(async () => {
2839
+ if (!this.destroyed && revision === this.sessionRevision) await this.storage.remove(SESSION_STORAGE_KEY);
2840
+ });
2841
+ this.sessionStorageQueue = remove.catch(() => {
2842
+ });
2843
+ await remove;
1920
2844
  } catch (err) {
1921
2845
  this.log("warn", "session:remove_failed", "Failed to remove session", {
1922
2846
  error: err instanceof Error ? err.message : String(err)
@@ -1926,16 +2850,31 @@ var PartyLayerClient = class {
1926
2850
  /**
1927
2851
  * Restore session from storage
1928
2852
  */
1929
- async restoreSession() {
2853
+ restoreSession() {
2854
+ if (this.destroyed || this.restorationBlocked) return Promise.resolve(null);
2855
+ if (this.restoreTask) return this.restoreTask;
2856
+ const task = this.restoreSessionOnce();
2857
+ this.restoreTask = task;
2858
+ const clear = () => {
2859
+ if (this.restoreTask === task) this.restoreTask = null;
2860
+ };
2861
+ void task.then(clear, clear);
2862
+ return task;
2863
+ }
2864
+ async restoreSessionOnce() {
2865
+ const revision = this.sessionRevision;
2866
+ const current = () => !this.destroyed && !this.restorationBlocked && revision === this.sessionRevision;
1930
2867
  this.telemetry?.increment?.(METRICS.RESTORE_ATTEMPTS);
1931
2868
  const correlationId = newCorrelationId();
1932
2869
  this.log("debug", "session:restore_start", "restoreSession", {}, correlationId);
1933
2870
  try {
1934
2871
  const encrypted = await this.storage.get(SESSION_STORAGE_KEY);
2872
+ if (!current()) return this.activeSession;
1935
2873
  if (!encrypted) {
1936
2874
  return null;
1937
2875
  }
1938
2876
  const decrypted = await this.crypto.decrypt(encrypted, this.origin);
2877
+ if (!current()) return this.activeSession;
1939
2878
  const session = JSON.parse(decrypted);
1940
2879
  if (session.expiresAt && Date.now() >= session.expiresAt) {
1941
2880
  await this.removeSession(session.sessionId);
@@ -1967,7 +2906,17 @@ var PartyLayerClient = class {
1967
2906
  }
1968
2907
  session.networkMismatch = mismatch;
1969
2908
  }
1970
- const adapter = this.adapters.get(session.walletId);
2909
+ await this.ensureDefaultWallets();
2910
+ if (!current()) return this.activeSession;
2911
+ let adapter = this.adapters.get(session.walletId);
2912
+ if (this.nativeOwner && !adapter) {
2913
+ try {
2914
+ await this.aggregateAnnouncedWallets(await this.registryClient.getWallets());
2915
+ } catch {
2916
+ }
2917
+ if (!current()) return this.activeSession;
2918
+ adapter = this.adapters.get(session.walletId);
2919
+ }
1971
2920
  if (adapter?.restore) {
1972
2921
  const ctx = this.createAdapterContext();
1973
2922
  if (adapter instanceof GenericDiscoveryAdapter && adapter.usesFactory()) {
@@ -1987,10 +2936,12 @@ var PartyLayerClient = class {
1987
2936
  ...session,
1988
2937
  encrypted
1989
2938
  });
1990
- if (restored) {
2939
+ if (!current()) return this.activeSession;
2940
+ if (restored && restored.partyId === session.partyId && !detectNetworkMismatch(session.network, restored.network)) {
1991
2941
  this.activeSession = restored;
1992
2942
  this.activeSessionNeedsProbe = false;
1993
2943
  await this.persistSession(restored);
2944
+ if (!current()) return this.activeSession;
1994
2945
  this.telemetry?.increment?.(METRICS.SESSIONS_RESTORED);
1995
2946
  this.telemetry?.increment?.(METRICS.WALLET_CONNECT_SUCCESS);
1996
2947
  this.emit("session:connected", {
@@ -2007,6 +2958,11 @@ var PartyLayerClient = class {
2007
2958
  return null;
2008
2959
  }
2009
2960
  }
2961
+ if (this.nativeOwner && (!adapter || nativeOwnerBindings.has(adapter))) {
2962
+ await this.removeSession(session.sessionId);
2963
+ this.emit("session:expired", { type: "session:expired", sessionId: session.sessionId }, correlationId);
2964
+ return null;
2965
+ }
2010
2966
  this.activeSession = session;
2011
2967
  this.activeSessionNeedsProbe = true;
2012
2968
  return session;
@@ -2114,6 +3070,6 @@ function createPartyLayer(config) {
2114
3070
  return new PartyLayerClient(config);
2115
3071
  }
2116
3072
 
2117
- export { ANNOUNCED_WALLET_ID_PREFIX, PartyLayerClient as CantonConnectClient, DEFAULT_REGISTRY_URL, GenericAnnounceAdapter, GenericDiscoveryAdapter, MetricsTelemetryAdapter, PartyLayerClient, announcedWalletId, createPartyLayer as createCantonConnect, createPartyLayer, createTelemetryAdapter, getBuiltinAdapters, isTelemetryConfig };
3073
+ export { ANNOUNCED_WALLET_ID_PREFIX, PartyLayerClient as CantonConnectClient, DEFAULT_REGISTRY_URL, GenericAnnounceAdapter, GenericDiscoveryAdapter, MetricsTelemetryAdapter, PartyLayerClient, announcedWalletId, createPartyLayer as createCantonConnect, createPartyLayer, createTelemetryAdapter, getBuiltinAdapters, getDiscoveryCapabilities, isTelemetryConfig };
2118
3074
  //# sourceMappingURL=index.mjs.map
2119
3075
  //# sourceMappingURL=index.mjs.map