@partylayer/sdk 0.19.0 → 0.20.1

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