@partylayer/sdk 0.18.2 → 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.js CHANGED
@@ -10,7 +10,583 @@ 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
+ }
57
+ var UNSUPPORTED_METHOD = 4200;
58
+ var METHOD_NOT_FOUND = -32601;
59
+ function isUnsupportedMethod(err) {
60
+ const code = err?.code;
61
+ return code === UNSUPPORTED_METHOD || code === METHOD_NOT_FOUND;
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
+ }
73
+ function receiptFromExecutedTx(result) {
74
+ const tx = result?.tx;
75
+ const updateId = tx?.payload?.updateId;
76
+ if (typeof updateId !== "string" || updateId.length === 0) return null;
77
+ return {
78
+ transactionHash: core.toTransactionHash(updateId),
79
+ submittedAt: Date.now(),
80
+ commandId: typeof tx?.commandId === "string" ? tx.commandId : void 0,
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 } : {}
99
+ };
100
+ }
101
+ function validOffset(value) {
102
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
103
+ }
104
+ function reportOnce(state, walletId, detail, logger) {
105
+ if (state.logged) return;
106
+ state.logged = true;
107
+ logger?.warn(
108
+ `[PartyLayer] ${walletId}: ${detail} Confirm ledger completion only when the receipt contains a real updateId.`
109
+ );
110
+ }
111
+ async function submitViaPrepareExecute(provider, params, opts) {
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;
117
+ const { walletId, state, logger } = opts;
118
+ if (state.verb !== "plain") {
119
+ try {
120
+ const result2 = await provider.request({
121
+ method: "prepareExecuteAndWait",
122
+ params: rpcParams
123
+ });
124
+ state.verb = "awaited";
125
+ const receipt = normalizeReceipt(result2, rpcParams);
126
+ if (receipt.updateId) return receipt;
127
+ reportOnce(
128
+ state,
129
+ walletId,
130
+ "prepareExecuteAndWait returned no updateId.",
131
+ logger
132
+ );
133
+ return receipt;
134
+ } catch (err) {
135
+ if (!isUnsupportedMethod(err)) throw err;
136
+ state.verb = "plain";
137
+ reportOnce(
138
+ state,
139
+ walletId,
140
+ "has no prepareExecuteAndWait; using prepareExecute, which the CIP-0103 types return as null.",
141
+ logger
142
+ );
143
+ }
144
+ }
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
+ }
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();
579
+
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
+ }
14
590
  var ANNOUNCED_WALLET_ID_PREFIX = "browser:ext:";
15
591
  function announcedWalletId(announceId) {
16
592
  return core.toWalletId(`${ANNOUNCED_WALLET_ID_PREFIX}${announceId}`);
@@ -34,16 +610,21 @@ function toBase64Message(message) {
34
610
  for (const b of bytes) binary += String.fromCharCode(b);
35
611
  return btoa(binary);
36
612
  }
37
- var GenericAnnounceAdapter = class {
613
+ var GenericAnnounceAdapter = class _GenericAnnounceAdapter {
38
614
  walletId;
39
615
  name;
40
616
  /** Icon surfaced to the picker (announce detail). */
41
617
  icon;
42
- provider;
618
+ rawProvider;
43
619
  metadataEnabled;
44
620
  staticMetadata;
45
621
  mapError;
46
622
  signMessageBase64;
623
+ /**
624
+ * Which execute verb this wallet turned out to support. Resolved on the first
625
+ * submit and reused, so the wallet is asked at most once.
626
+ */
627
+ executeVerb = {};
47
628
  // Optional WalletAdapter surface — assigned in the ctor ONLY when configured,
48
629
  // so `getCapabilities()` and `'x' in adapter` feature-detection stay honest.
49
630
  restore;
@@ -53,10 +634,15 @@ var GenericAnnounceAdapter = class {
53
634
  // declares support, so a wallet that cannot sign is not advertised as able to.
54
635
  signMessage;
55
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));
56
642
  this.walletId = args.walletId ?? announcedWalletId(args.announceId);
57
643
  this.name = args.name && args.name.length > 0 ? args.name : `Canton Wallet (${args.announceId.slice(0, 6)}\u2026)`;
58
644
  this.icon = args.icon;
59
- this.provider = args.provider;
645
+ this.rawProvider = args.provider;
60
646
  const config = args.config;
61
647
  this.metadataEnabled = config?.metadata === true;
62
648
  this.staticMetadata = config?.staticMetadata;
@@ -67,6 +653,22 @@ var GenericAnnounceAdapter = class {
67
653
  if (config?.ledgerApi) this.ledgerApi = this.makeLedgerApi();
68
654
  if (config?.signMessage !== false) this.signMessage = this.signMessageImpl.bind(this);
69
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
+ }
70
672
  /**
71
673
  * Capabilities derived from actual presence: connect and submitTransaction are
72
674
  * always present; signMessage, restore, ledgerApi, and events are each included
@@ -74,30 +676,40 @@ var GenericAnnounceAdapter = class {
74
676
  * beyond what the adapter can do.
75
677
  */
76
678
  getCapabilities() {
77
- const caps = ["connect"];
78
- if (this.signMessage) caps.push("signMessage");
79
- caps.push("submitTransaction");
80
- if (this.restore) caps.push("restore");
81
- if (this.ledgerApi) caps.push("ledgerApi");
82
- if (this.on) caps.push("events");
83
- return caps;
679
+ return getAnnounceCapabilities({
680
+ signMessage: !!this.signMessage,
681
+ restore: !!this.restore,
682
+ ledgerApi: !!this.ledgerApi,
683
+ events: !!this.on
684
+ });
84
685
  }
85
686
  /**
86
687
  * The adapter is only ever constructed for a wallet that just announced, so
87
688
  * its presence is established by the announce handshake itself.
88
689
  */
89
690
  async detectInstalled() {
90
- 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
+ };
91
700
  }
92
- async connect(ctx) {
701
+ async connect(ctx, options) {
93
702
  return this.guarded(async () => {
94
- await this.provider.request({ method: "connect" });
95
- 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({
96
707
  method: "getPrimaryAccount"
97
708
  });
709
+ assertPrimaryParty(account);
98
710
  let status;
99
711
  try {
100
- status = await this.provider.request({ method: "status" });
712
+ status = native?.status ?? await this.provider.request({ method: "status" });
101
713
  } catch {
102
714
  }
103
715
  const reportedNetwork = status?.network?.networkId;
@@ -117,6 +729,11 @@ var GenericAnnounceAdapter = class {
117
729
  });
118
730
  }
119
731
  async disconnect() {
732
+ const owner = nativeOwnerBindings.get(this);
733
+ if (owner) {
734
+ await owner.disconnect();
735
+ return;
736
+ }
120
737
  try {
121
738
  await this.provider.request({ method: "disconnect" });
122
739
  } catch {
@@ -129,21 +746,15 @@ var GenericAnnounceAdapter = class {
129
746
  return this.guarded(async () => {
130
747
  const rpcParams = this.signMessageBase64 ? { message: toBase64Message(params.message) } : { message: params.message };
131
748
  const res = await this.provider.request({ method: "signMessage", params: rpcParams });
132
- const sig = typeof res === "string" ? res : res?.signature ?? "";
133
- return {
134
- signature: core.toSignature(String(sig)),
135
- partyId: session.partyId,
136
- message: params.message,
137
- nonce: params.nonce,
138
- domain: params.domain
139
- };
749
+ return normalizeSignedMessage(res, session, params);
140
750
  });
141
751
  }
142
- async submitTransaction(_ctx, _session, params) {
752
+ async submitTransaction(ctx, _session, params) {
143
753
  return this.guarded(
144
- () => this.provider.request({
145
- method: "prepareExecute",
146
- params
754
+ () => submitViaPrepareExecute(this.provider, params, {
755
+ walletId: String(this.walletId),
756
+ state: this.executeVerb,
757
+ logger: ctx.logger
147
758
  })
148
759
  );
149
760
  }
@@ -170,6 +781,12 @@ var GenericAnnounceAdapter = class {
170
781
  /** restore: silent status()/getPrimaryAccount() probe + expiry + party-match. */
171
782
  makeRestore() {
172
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
+ }
173
790
  if (persisted.expiresAt && Date.now() >= persisted.expiresAt) return null;
174
791
  let status;
175
792
  try {
@@ -182,6 +799,10 @@ var GenericAnnounceAdapter = class {
182
799
  method: "getPrimaryAccount"
183
800
  });
184
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;
185
806
  return {
186
807
  ...persisted,
187
808
  walletId: this.walletId,
@@ -240,7 +861,14 @@ function buildMetadata(status, account) {
240
861
  put("userId", status?.session?.userId);
241
862
  return meta;
242
863
  }
243
- 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 {
244
872
  walletId;
245
873
  name;
246
874
  icon;
@@ -256,7 +884,33 @@ var GenericDiscoveryAdapter = class {
256
884
  networkHosts;
257
885
  /** Lazily resolved from `official.provider()` — NOT at construction (SSR-safe). */
258
886
  providerInstance = null;
887
+ /**
888
+ * Which execute verb this wallet turned out to support. Resolved on the first
889
+ * submit and reused, so the wallet is asked at most once.
890
+ */
891
+ executeVerb = {};
892
+ capabilities;
893
+ ledgerApi;
259
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
+ }
260
914
  if (args.official) {
261
915
  this.official = args.official;
262
916
  this.factory = null;
@@ -309,11 +963,20 @@ var GenericDiscoveryAdapter = class {
309
963
  }
310
964
  this.official = this.factory.create(host);
311
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
+ }
312
973
  /** Lazily obtain (and cache) the official provider — deferred off the init/SSR path.
313
974
  * `official.provider()` is typed `OfficialProvider` (loose `request` so real
314
975
  * official adapters are assignable); it is call-compatible with CIP0103Provider
315
976
  * (the bridge only ever calls `request({ method, params })`). */
316
977
  get provider() {
978
+ const owner = nativeOwnerBindings.get(this);
979
+ if (owner) return owner.getProvider(String(this.walletId));
317
980
  if (this.providerInstance === null) {
318
981
  if (!this.official) {
319
982
  throw new Error(
@@ -324,37 +987,55 @@ var GenericDiscoveryAdapter = class {
324
987
  }
325
988
  return this.providerInstance;
326
989
  }
327
- /**
328
- * Baseline CIP-0103 capabilities. NEVER includes `'events'`: popup/remote
329
- * wallets expose the event surface but do not emit (truthfulness doctrine).
330
- */
990
+ /** Implemented, registry-declared capabilities; popup event listeners are never claimed. */
331
991
  getCapabilities() {
332
- return ["connect", "disconnect", "signMessage", "submitTransaction"];
992
+ return [...this.capabilities];
333
993
  }
334
- /** 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
+ */
335
1020
  async detectInstalled() {
336
- if (!this.official) {
337
- return { installed: true, reason: "Popup/remote wallet (resolved at connect)" };
338
- }
339
- try {
340
- const installed = await this.official.detect();
341
- return {
342
- installed,
343
- reason: installed ? void 0 : "Wallet reported not available"
344
- };
345
- } catch {
346
- return { installed: false, reason: "Detection failed" };
347
- }
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
+ };
348
1026
  }
349
- async connect(ctx) {
1027
+ async connect(ctx, options) {
350
1028
  this.resolveOfficial(ctx.network);
351
- await this.provider.request({ method: "connect" });
352
- 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({
353
1033
  method: "getPrimaryAccount"
354
1034
  });
1035
+ assertPrimaryParty(account);
355
1036
  let reportedNetwork;
356
1037
  try {
357
- const status = await this.provider.request({
1038
+ const status = native?.status ?? await this.provider.request({
358
1039
  method: "status"
359
1040
  });
360
1041
  reportedNetwork = status?.network?.networkId;
@@ -371,65 +1052,167 @@ var GenericDiscoveryAdapter = class {
371
1052
  };
372
1053
  return { partyId, session, capabilities: this.getCapabilities() };
373
1054
  }
374
- /**
375
- * Restore a persisted session by delegating to the official adapter's own `restore`.
376
- *
377
- * The official `ProviderAdapter` shape carries an optional `restore()` that reinstates a
378
- * session (for example from the wallet's own storage) and returns a LIVE provider.
379
- * Without this method the SDK revived the persisted record as-is and then built a fresh,
380
- * SESSION-LESS provider from `provider()`, so a wallet that restores in `restore` looked
381
- * connected after a reload but its first real request threw. This forwards to the
382
- * official `restore` and, when it yields a provider, adopts it as the cached provider so
383
- * the very next request uses the restored session.
384
- *
385
- * Popup-safe: this runs on the SDK's init/restore path, never inside a user gesture, so a
386
- * popup could not open here even if an adapter tried (the browser would block it). Per
387
- * the official contract `restore` is storage-based and gesture-free. If the official
388
- * adapter has no `restore`, it returns null, or host resolution is not ready, this falls
389
- * through to the previous behavior: the persisted session is returned and the provider is
390
- * built lazily on first use, exactly as before.
391
- */
1055
+ /** Restore silently and validate the live party before exposing a connected session. */
392
1056
  async restore(ctx, persisted) {
393
- const asIs = { ...persisted, walletId: this.walletId };
394
1057
  try {
1058
+ if (persisted.expiresAt && Date.now() >= persisted.expiresAt) return null;
395
1059
  this.resolveOfficial(ctx.network);
396
- } catch {
397
- return asIs;
398
- }
399
- const restore = this.official?.restore;
400
- if (this.official && restore) {
401
- let restored = null;
402
- try {
403
- restored = await restore.call(this.official);
404
- } catch {
405
- 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;
406
1069
  }
407
- if (restored) {
1070
+ if (this.official?.restore) {
1071
+ const restored = await this.official.restore();
1072
+ if (!restored) return null;
408
1073
  this.providerInstance = restored;
409
- return asIs;
410
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;
411
1090
  }
412
- return asIs;
413
1091
  }
414
1092
  async disconnect() {
1093
+ const owner = nativeOwnerBindings.get(this);
1094
+ if (owner) {
1095
+ await owner.disconnect();
1096
+ return;
1097
+ }
415
1098
  try {
416
1099
  await this.provider.request({ method: "disconnect" });
417
1100
  } catch {
418
1101
  }
419
1102
  }
420
- async signMessage(_ctx, _session, params) {
421
- return this.provider.request({
1103
+ async signMessage(_ctx, session, params) {
1104
+ const response = await this.provider.request({
422
1105
  method: "signMessage",
423
1106
  params: { message: params.message }
424
1107
  });
1108
+ return normalizeSignedMessage(response, session, params);
425
1109
  }
426
- async submitTransaction(_ctx, _session, params) {
427
- return this.provider.request({
428
- method: "prepareExecute",
429
- params
1110
+ async submitTransaction(ctx, _session, params) {
1111
+ return submitViaPrepareExecute(this.provider, params, {
1112
+ walletId: String(this.walletId),
1113
+ state: this.executeVerb,
1114
+ logger: ctx.logger
430
1115
  });
431
1116
  }
432
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
+ }
433
1216
 
434
1217
  // src/config.ts
435
1218
  var DEFAULT_REGISTRY_URL = "https://registry.partylayer.xyz";
@@ -874,9 +1657,20 @@ function deriveAnnounceConfig(entry) {
874
1657
  }
875
1658
  return config;
876
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;
877
1667
  var PartyLayerClient = class {
878
1668
  config;
879
1669
  adapters = /* @__PURE__ */ new Map();
1670
+ destroyed = false;
1671
+ initialized = false;
1672
+ defaultLoads = /* @__PURE__ */ new Map();
1673
+ registryDefaultIds = /* @__PURE__ */ new Set();
880
1674
  /**
881
1675
  * Pre-resolved connect plans for popup/remote (GenericDiscoveryAdapter)
882
1676
  * wallets, warmed on `listWallets()` (which the modal calls on open) so a
@@ -886,6 +1680,11 @@ var PartyLayerClient = class {
886
1680
  warmPlans = /* @__PURE__ */ new Map();
887
1681
  eventHandlers = /* @__PURE__ */ new Map();
888
1682
  activeSession = null;
1683
+ sessionRevision = 0;
1684
+ connectionAttempt = 0;
1685
+ restoreTask = null;
1686
+ restorationBlocked = false;
1687
+ sessionStorageQueue = Promise.resolve();
889
1688
  /**
890
1689
  * True when `activeSession` was revived AS-IS (no live `status()` probe) because
891
1690
  * its adapter wasn't registered yet at restore time (the lazy configured-announce
@@ -908,10 +1707,13 @@ var PartyLayerClient = class {
908
1707
  // captured (not just a one-shot window). Read by aggregateAnnouncedWallets;
909
1708
  // torn down in destroy(). Empty → listWallets() output is byte-identical.
910
1709
  announceRegistry = /* @__PURE__ */ new Map();
1710
+ announceChannels = /* @__PURE__ */ new Map();
911
1711
  announceUnsubscribe = null;
912
1712
  /** Pending debounced `wallets:changed` emit (coalesces an announce burst). */
913
1713
  walletsChangedTimer = null;
914
1714
  origin;
1715
+ nativeOwner;
1716
+ sessionProvider;
915
1717
  constructor(config) {
916
1718
  this.config = config;
917
1719
  if (config.app.origin) {
@@ -925,9 +1727,13 @@ var PartyLayerClient = class {
925
1727
  this.logLevel = config.logLevel ?? "info";
926
1728
  this.crypto = config.crypto || new DefaultCrypto();
927
1729
  this.storage = config.storage || new DefaultStorage();
1730
+ if (typeof window !== "undefined") {
1731
+ this.nativeOwner = new NativeConnectionOwner((id, identity) => this.onNativeIdentityChanged(id, identity));
1732
+ }
928
1733
  const telemetryAdapter = createTelemetryAdapter(config.telemetry);
929
1734
  this.telemetry = telemetryAdapter || new DefaultTelemetry();
930
- const adaptersToRegister = config.adapters ?? getBuiltinAdapters();
1735
+ const defaults = config.adapters ?? getBuiltinAdapters();
1736
+ const adaptersToRegister = [...defaults, ...config.additionalAdapters ?? []];
931
1737
  for (const adapterOrClass of adaptersToRegister) {
932
1738
  let adapter;
933
1739
  if (typeof adapterOrClass === "function") {
@@ -939,7 +1745,7 @@ var PartyLayerClient = class {
939
1745
  } else {
940
1746
  adapter = adapterOrClass;
941
1747
  }
942
- this.adapters.set(adapter.walletId, adapter);
1748
+ this.registerAdapter(adapter);
943
1749
  this.log("debug", "adapter:registered", "Registered wallet adapter", {
944
1750
  walletId: adapter.walletId,
945
1751
  name: adapter.name,
@@ -953,10 +1759,16 @@ var PartyLayerClient = class {
953
1759
  storage: this.storage
954
1760
  });
955
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;
956
1768
  if (this.announceEnabled) {
957
1769
  this.announceUnsubscribe = provider.subscribeAnnouncedProviders(
958
1770
  (p) => this.onAnnounceAccumulated(p),
959
- { createProvider: (a) => provider.createExtensionChannelProvider({ target: a.target ?? a.id }) }
1771
+ { createProvider: (a) => this.announceChannel(a.target ?? a.id) }
960
1772
  );
961
1773
  }
962
1774
  this.restoreSession().catch((err) => {
@@ -968,6 +1780,15 @@ var PartyLayerClient = class {
968
1780
  });
969
1781
  });
970
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
+ }
971
1792
  /**
972
1793
  * Register a wallet adapter
973
1794
  *
@@ -976,7 +1797,34 @@ var PartyLayerClient = class {
976
1797
  * In production, adapters would be auto-registered via registry.
977
1798
  */
978
1799
  registerAdapter(adapter) {
1800
+ const boundOwner = nativeOwnerBindings.get(adapter);
1801
+ if (this.nativeOwner && boundOwner && boundOwner !== this.nativeOwner) {
1802
+ adapter = nativeAdapterCopies.get(adapter)();
1803
+ }
979
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 });
980
1828
  }
981
1829
  /**
982
1830
  * Look up a registered adapter by wallet id.
@@ -1000,6 +1848,7 @@ var PartyLayerClient = class {
1000
1848
  * List available wallets
1001
1849
  */
1002
1850
  async listWallets(filter) {
1851
+ this.initialize();
1003
1852
  let registryWallets;
1004
1853
  try {
1005
1854
  registryWallets = await this.registryClient.getWallets();
@@ -1011,9 +1860,10 @@ var PartyLayerClient = class {
1011
1860
  });
1012
1861
  registryWallets = [];
1013
1862
  }
1863
+ await this.ensureDefaultWallets();
1014
1864
  const registryIds = new Set(registryWallets.map((w) => String(w.walletId)));
1015
1865
  for (const [, adapter] of this.adapters) {
1016
- if (registryIds.has(String(adapter.walletId))) continue;
1866
+ if (registryIds.has(String(adapter.walletId)) || this.registryDefaultIds.has(adapter.walletId)) continue;
1017
1867
  registryWallets.push({
1018
1868
  walletId: adapter.walletId,
1019
1869
  name: adapter.name,
@@ -1023,24 +1873,62 @@ var PartyLayerClient = class {
1023
1873
  adapter: { packageName: "builtin", versionRange: "*" },
1024
1874
  docs: [],
1025
1875
  networks: [this.config.network || "devnet"],
1026
- channel: "stable"
1876
+ channel: this.config.channel || "stable"
1027
1877
  });
1028
1878
  }
1029
1879
  registryWallets = await this.gateUnconnectableEntries(registryWallets);
1030
1880
  registryWallets = await this.aggregateAnnouncedWallets(registryWallets);
1031
- void this.warmDiscoveryPlans(registryWallets);
1032
- if (filter?.requiredCapabilities) {
1033
- return registryWallets.filter(
1034
- (walletInfo) => filter.requiredCapabilities.every(
1035
- (cap) => walletInfo.capabilities.includes(cap)
1036
- )
1037
- );
1038
- }
1039
- if (!filter?.includeExperimental) {
1040
- return registryWallets.filter((walletInfo) => walletInfo.channel === "stable");
1041
- }
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);
1042
1888
  return registryWallets;
1043
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
+ }
1044
1932
  /**
1045
1933
  * Hide registry entries whose wallet needs an app-registered adapter that is
1046
1934
  * NOT registered. This is the library default (RainbowKit-style): never show a
@@ -1063,10 +1951,14 @@ var PartyLayerClient = class {
1063
1951
  */
1064
1952
  async gateUnconnectableEntries(wallets) {
1065
1953
  let hidden = null;
1954
+ const announceCapabilities = /* @__PURE__ */ new Map();
1066
1955
  try {
1067
1956
  const registry = await this.registryClient.getRegistry();
1068
1957
  for (const entry of registry.wallets) {
1069
- if (entry.adapter?.transport === "announce") continue;
1958
+ if (entry.adapter?.transport === "announce") {
1959
+ announceCapabilities.set(entry.id, getAnnounceCapabilities(deriveAnnounceConfig(entry)));
1960
+ continue;
1961
+ }
1070
1962
  const walletId = core.toWalletId(entry.id);
1071
1963
  if (!this.adapters.has(walletId)) {
1072
1964
  (hidden ??= /* @__PURE__ */ new Set()).add(String(walletId));
@@ -1075,8 +1967,10 @@ var PartyLayerClient = class {
1075
1967
  } catch {
1076
1968
  return wallets;
1077
1969
  }
1078
- if (!hidden || hidden.size === 0) return wallets;
1079
- 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
+ });
1080
1974
  }
1081
1975
  /**
1082
1976
  * If `walletId` maps to a registry entry with `transport: 'discovery-adapter'`,
@@ -1167,7 +2061,7 @@ var PartyLayerClient = class {
1167
2061
  injectionPaths,
1168
2062
  // Working provider over the announce target channel; G4 (provider.md):
1169
2063
  // target defaults to id when omitted — never a shared slot.
1170
- createProvider: (a) => provider.createExtensionChannelProvider({ target: a.target ?? a.id })
2064
+ createProvider: (a) => this.announceChannel(a.target ?? a.id)
1171
2065
  });
1172
2066
  const byId = /* @__PURE__ */ new Map();
1173
2067
  for (const d of snapshot) byId.set(d.id, d);
@@ -1180,7 +2074,7 @@ var PartyLayerClient = class {
1180
2074
  const known = core.findMatchingWalletInfo(
1181
2075
  { provider: { id: d.id } },
1182
2076
  base
1183
- );
2077
+ ) ?? matchKnownByIdentity(d.id, base);
1184
2078
  if (known) {
1185
2079
  if (this.adapters.has(known.walletId)) continue;
1186
2080
  try {
@@ -1194,21 +2088,25 @@ var PartyLayerClient = class {
1194
2088
  provider: d.provider,
1195
2089
  config: deriveAnnounceConfig(entry)
1196
2090
  });
1197
- this.adapters.set(configured.walletId, configured);
2091
+ this.registerAdapter(configured);
1198
2092
  const active = this.activeSession;
1199
2093
  if (active && this.activeSessionNeedsProbe && active.walletId === configured.walletId && configured.restore) {
2094
+ const revision = this.sessionRevision;
1200
2095
  try {
1201
2096
  const reprobed = await configured.restore(this.createAdapterContext(), {
1202
2097
  ...active,
1203
2098
  encrypted: ""
1204
2099
  });
2100
+ if (this.destroyed || revision !== this.sessionRevision || this.activeSession !== active) continue;
1205
2101
  if (reprobed) {
1206
2102
  this.activeSession = reprobed;
1207
2103
  this.activeSessionNeedsProbe = false;
1208
2104
  await this.persistSession(reprobed);
2105
+ if (this.destroyed || revision !== this.sessionRevision || this.activeSession !== reprobed) continue;
1209
2106
  this.emit("session:connected", { type: "session:connected", session: reprobed });
1210
2107
  } else {
1211
2108
  await this.removeSession(active.sessionId);
2109
+ if (this.destroyed || revision !== this.sessionRevision || this.activeSession !== active) continue;
1212
2110
  this.activeSession = null;
1213
2111
  this.activeSessionNeedsProbe = false;
1214
2112
  this.emit("session:expired", { type: "session:expired", sessionId: active.sessionId });
@@ -1230,7 +2128,7 @@ var PartyLayerClient = class {
1230
2128
  icon: d.icon,
1231
2129
  provider: d.provider
1232
2130
  });
1233
- this.adapters.set(adapter.walletId, adapter);
2131
+ this.registerAdapter(adapter);
1234
2132
  entries.push({
1235
2133
  walletId: adapter.walletId,
1236
2134
  name: adapter.name,
@@ -1282,16 +2180,22 @@ var PartyLayerClient = class {
1282
2180
  * Connect to a wallet
1283
2181
  */
1284
2182
  async connect(options) {
2183
+ this.initialize();
2184
+ this.nativeOwner?.assertAvailable();
2185
+ this.restorationBlocked = true;
2186
+ const attempt = ++this.connectionAttempt;
2187
+ ++this.sessionRevision;
1285
2188
  this.telemetry?.increment?.(core.METRICS.WALLET_CONNECT_ATTEMPTS);
1286
2189
  const correlationId = newCorrelationId();
1287
2190
  this.log("debug", "connect:start", "connect", {}, correlationId);
1288
2191
  try {
1289
- const fast = this.tryFastConnect(options, correlationId);
2192
+ const fast = this.tryFastConnect(options, correlationId, attempt);
1290
2193
  if (fast) return await fast;
1291
2194
  const plan = await this.resolveConnectPlan(options);
1292
- return await this.completeConnect(plan, options, correlationId);
2195
+ return await this.completeConnect(plan, options, correlationId, attempt);
1293
2196
  } catch (err) {
1294
- const timeoutMs = options?.timeoutMs || 3e4;
2197
+ this.warmPlans.clear();
2198
+ const timeoutMs = options?.timeoutMs || DEFAULT_CONNECT_TIMEOUT_MS;
1295
2199
  const error = core.mapUnknownErrorToPartyLayerError(err, {
1296
2200
  phase: "connect",
1297
2201
  walletId: options?.walletId ? String(options.walletId) : void 0,
@@ -1329,6 +2233,10 @@ var PartyLayerClient = class {
1329
2233
  } else {
1330
2234
  const nativeAdapter = this.adapters.get(options.walletId);
1331
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
+ }
1332
2240
  isNativeWallet = true;
1333
2241
  selectedWallet = {
1334
2242
  walletId: options.walletId,
@@ -1394,6 +2302,9 @@ var PartyLayerClient = class {
1394
2302
  adapter.setNetworkHosts(networkHosts);
1395
2303
  adapter.resolveOfficial(ctx.network);
1396
2304
  }
2305
+ if (adapter instanceof GenericDiscoveryAdapter || adapter instanceof GenericAnnounceAdapter) {
2306
+ await adapter.prepareNativeConnection(ctx.network);
2307
+ }
1397
2308
  return { selectedWallet, adapter, ctx, isNativeWallet };
1398
2309
  }
1399
2310
  /**
@@ -1401,21 +2312,37 @@ var PartyLayerClient = class {
1401
2312
  * build / persist / emit the session. Separated from plan resolution so the
1402
2313
  * popup-safe fast-path can call it gesture-synchronously.
1403
2314
  */
1404
- 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");
1405
2321
  const { selectedWallet, adapter, ctx } = plan;
1406
- 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();
1407
2325
  const connectPromise = adapter.connect(ctx, {
1408
2326
  timeoutMs,
2327
+ signal: abort.signal,
1409
2328
  partyId: void 0,
1410
2329
  preferInstalled: options?.preferInstalled,
1411
2330
  onDisplayUri: options?.onDisplayUri
1412
2331
  });
2332
+ let timeoutHandle;
1413
2333
  const timeoutPromise = new Promise((_, reject) => {
1414
- setTimeout(() => {
2334
+ timeoutHandle = setTimeout(() => {
2335
+ abort.abort();
1415
2336
  reject(new Error(`Connection timed out after ${timeoutMs}ms - user did not complete wallet connection`));
1416
2337
  }, timeoutMs);
1417
2338
  });
1418
- 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");
1419
2346
  const session = {
1420
2347
  sessionId: core.toSessionId(`session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`),
1421
2348
  walletId: selectedWallet.walletId,
@@ -1446,12 +2373,18 @@ var PartyLayerClient = class {
1446
2373
  enforced: this.enforcement !== "off"
1447
2374
  }, correlationId);
1448
2375
  if (this.enforcement === "strict") {
2376
+ if (nativeOwnerBindings.has(adapter)) await this.nativeOwner?.disconnect();
1449
2377
  throw new core.NetworkMismatchError(mismatch.expected, mismatch.actual);
1450
2378
  }
1451
2379
  }
1452
- await this.persistSession(session);
2380
+ ++this.sessionRevision;
1453
2381
  this.activeSession = session;
2382
+ this.restorationBlocked = false;
1454
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
+ }
1455
2388
  this.updateRegistryStatus();
1456
2389
  this.telemetry?.increment?.(core.METRICS.WALLET_CONNECT_SUCCESS);
1457
2390
  this.telemetry?.increment?.(core.METRICS.SESSIONS_CREATED);
@@ -1482,7 +2415,7 @@ var PartyLayerClient = class {
1482
2415
  */
1483
2416
  async warmDiscoveryPlans(wallets) {
1484
2417
  for (const [walletId, adapter] of this.adapters) {
1485
- if (!(adapter instanceof GenericDiscoveryAdapter)) continue;
2418
+ if (!(adapter instanceof GenericDiscoveryAdapter || adapter instanceof GenericAnnounceAdapter)) continue;
1486
2419
  if (this.warmPlans.has(walletId)) continue;
1487
2420
  try {
1488
2421
  const plan = await this.resolveConnectPlan({ walletId }, wallets);
@@ -1498,30 +2431,39 @@ var PartyLayerClient = class {
1498
2431
  * Returns the in-flight Session promise, or null to fall back to the normal
1499
2432
  * path (e.g. cold cache, or a non-discovery wallet).
1500
2433
  */
1501
- tryFastConnect(options, correlationId) {
2434
+ tryFastConnect(options, correlationId, attempt) {
1502
2435
  const walletId = options?.walletId;
1503
2436
  if (!walletId) return null;
1504
2437
  if (options?.requiredCapabilities || options?.allowWallets) return null;
1505
2438
  const plan = this.warmPlans.get(walletId);
1506
2439
  if (!plan) return null;
1507
2440
  this.warmPlans.delete(walletId);
1508
- return this.completeConnect(plan, options, correlationId);
2441
+ return this.completeConnect(plan, options, correlationId, attempt);
1509
2442
  }
1510
2443
  /**
1511
2444
  * Disconnect from wallet
1512
2445
  */
1513
2446
  async disconnect() {
1514
- 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();
1515
2455
  return;
1516
2456
  }
1517
2457
  try {
1518
- const adapter = this.adapters.get(this.activeSession.walletId);
2458
+ const adapter = this.adapters.get(session.walletId);
1519
2459
  if (adapter) {
1520
2460
  const ctx = this.createAdapterContext();
1521
- await adapter.disconnect(ctx, this.activeSession);
2461
+ await adapter.disconnect(ctx, session);
1522
2462
  }
1523
- const sessionId = this.activeSession.sessionId;
2463
+ if (revision !== this.sessionRevision || this.activeSession !== session) return;
2464
+ const sessionId = session.sessionId;
1524
2465
  await this.removeSession(sessionId);
2466
+ if (revision !== this.sessionRevision || this.activeSession !== session) return;
1525
2467
  this.activeSession = null;
1526
2468
  this.warmPlans.clear();
1527
2469
  this.emit("session:disconnected", {
@@ -1541,12 +2483,20 @@ var PartyLayerClient = class {
1541
2483
  * Get active session
1542
2484
  */
1543
2485
  async getActiveSession() {
2486
+ if (this.destroyed) return null;
2487
+ this.initialize();
1544
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
+ }
1545
2494
  if (this.activeSession.expiresAt && Date.now() >= this.activeSession.expiresAt) {
2495
+ const sessionId = this.activeSession.sessionId;
1546
2496
  await this.disconnect();
1547
2497
  this.emit("session:expired", {
1548
2498
  type: "session:expired",
1549
- sessionId: this.activeSession.sessionId
2499
+ sessionId
1550
2500
  });
1551
2501
  return null;
1552
2502
  }
@@ -1572,7 +2522,11 @@ var PartyLayerClient = class {
1572
2522
  try {
1573
2523
  this.assertNetworkOk(session);
1574
2524
  const ctx = this.createAdapterContext();
1575
- 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);
1576
2530
  } catch (err) {
1577
2531
  const error = core.mapUnknownErrorToPartyLayerError(err, {
1578
2532
  phase: "signMessage",
@@ -1686,6 +2640,55 @@ var PartyLayerClient = class {
1686
2640
  throw error;
1687
2641
  }
1688
2642
  }
2643
+ /**
2644
+ * Request a typed transfer. The application says what it wants; the wallet
2645
+ * builds the command, shows the user what they are authorising, obtains their
2646
+ * approval, signs, executes, and returns the real update id.
2647
+ *
2648
+ * The acting party comes from the active session, never from the caller, and
2649
+ * the intent is narrowed to the allowlisted fields before any adapter sees it,
2650
+ * so no caller-supplied option can reach the wallet.
2651
+ *
2652
+ * Throws `CapabilityNotSupportedError` when the active wallet does not
2653
+ * implement it. Ask first with `session.capabilitiesSnapshot.includes('transfer')`,
2654
+ * or require it at connect with `connect({ requiredCapabilities: ['transfer'] })`.
2655
+ */
2656
+ async requestTransfer(intent) {
2657
+ const session = await this.getActiveSession();
2658
+ if (!session) {
2659
+ throw new Error("No active session");
2660
+ }
2661
+ const adapter = this.adapters.get(session.walletId);
2662
+ if (!adapter || !adapter.requestTransfer) {
2663
+ throw new core.CapabilityNotSupportedError(
2664
+ session.walletId,
2665
+ "transfer"
2666
+ );
2667
+ }
2668
+ const safeIntent = core.toTransferIntent(intent);
2669
+ const correlationId = newCorrelationId();
2670
+ this.log("debug", "requestTransfer:start", "requestTransfer", {}, correlationId);
2671
+ try {
2672
+ this.assertNetworkOk(session);
2673
+ const ctx = this.createAdapterContext();
2674
+ const result = await adapter.requestTransfer(ctx, session, safeIntent);
2675
+ this.emit("tx:status", {
2676
+ type: "tx:status",
2677
+ sessionId: session.sessionId,
2678
+ txId: result.updateId,
2679
+ status: "committed",
2680
+ raw: result
2681
+ }, correlationId);
2682
+ return result;
2683
+ } catch (err) {
2684
+ const error = core.mapUnknownErrorToPartyLayerError(err, {
2685
+ phase: "requestTransfer",
2686
+ walletId: String(session.walletId)
2687
+ });
2688
+ this.emit("error", { type: "error", error }, correlationId);
2689
+ throw error;
2690
+ }
2691
+ }
1689
2692
  /**
1690
2693
  * Subscribe to events
1691
2694
  */
@@ -1708,28 +2711,55 @@ var PartyLayerClient = class {
1708
2711
  }
1709
2712
  }
1710
2713
  /**
1711
- * Get a CIP-0103 Provider backed by this client.
2714
+ * Get the stable provider facade for this client.
1712
2715
  *
1713
- * This bridge routes all request() calls through the existing
1714
- * 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.
1715
2722
  *
1716
- * The bridge implements the full CIP-0103 specification:
1717
- * - All 10 mandatory methods including `ledgerApi` (when adapter supports it)
1718
- * - Full transaction lifecycle: pending -> signed -> executed/failed
1719
- * - All CIP-0103 events: statusChanged, accountsChanged, txChanged, connected
1720
- *
1721
- * **Note:** Async wallets (userUrl pattern) are not supported through the
1722
- * bridge. For async wallet support, use `PartyLayerProvider` directly.
1723
- *
1724
- * @returns CIP-0103 compliant Provider
2723
+ * @returns Stable CIP-0103 provider facade
1725
2724
  */
1726
2725
  asProvider() {
1727
- 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;
1728
2752
  }
1729
2753
  /**
1730
2754
  * Destroy client and cleanup
1731
2755
  */
1732
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();
1733
2763
  if (this.telemetry && "destroy" in this.telemetry && typeof this.telemetry.destroy === "function") {
1734
2764
  this.telemetry.destroy();
1735
2765
  } else if (this.telemetry?.flush) {
@@ -1739,6 +2769,8 @@ var PartyLayerClient = class {
1739
2769
  this.announceUnsubscribe?.();
1740
2770
  this.announceUnsubscribe = null;
1741
2771
  this.announceRegistry.clear();
2772
+ for (const channel of this.announceChannels.values()) channel.destroy();
2773
+ this.announceChannels.clear();
1742
2774
  if (this.walletsChangedTimer !== null) {
1743
2775
  clearTimeout(this.walletsChangedTimer);
1744
2776
  this.walletsChangedTimer = null;
@@ -1774,10 +2806,16 @@ var PartyLayerClient = class {
1774
2806
  * Persist session to storage
1775
2807
  */
1776
2808
  async persistSession(session) {
2809
+ const revision = this.sessionRevision;
1777
2810
  try {
1778
2811
  const data = JSON.stringify(session);
1779
2812
  const encrypted = await this.crypto.encrypt(data, this.origin);
1780
- 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;
1781
2819
  } catch (err) {
1782
2820
  this.log("warn", "session:persist_failed", "Failed to persist session", {
1783
2821
  error: err instanceof Error ? err.message : String(err)
@@ -1791,8 +2829,14 @@ var PartyLayerClient = class {
1791
2829
  * active session we always remove the single SESSION_STORAGE_KEY.
1792
2830
  */
1793
2831
  async removeSession(_sessionId) {
2832
+ const revision = this.sessionRevision;
1794
2833
  try {
1795
- 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;
1796
2840
  } catch (err) {
1797
2841
  this.log("warn", "session:remove_failed", "Failed to remove session", {
1798
2842
  error: err instanceof Error ? err.message : String(err)
@@ -1802,16 +2846,31 @@ var PartyLayerClient = class {
1802
2846
  /**
1803
2847
  * Restore session from storage
1804
2848
  */
1805
- 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;
1806
2863
  this.telemetry?.increment?.(core.METRICS.RESTORE_ATTEMPTS);
1807
2864
  const correlationId = newCorrelationId();
1808
2865
  this.log("debug", "session:restore_start", "restoreSession", {}, correlationId);
1809
2866
  try {
1810
2867
  const encrypted = await this.storage.get(SESSION_STORAGE_KEY);
2868
+ if (!current()) return this.activeSession;
1811
2869
  if (!encrypted) {
1812
2870
  return null;
1813
2871
  }
1814
2872
  const decrypted = await this.crypto.decrypt(encrypted, this.origin);
2873
+ if (!current()) return this.activeSession;
1815
2874
  const session = JSON.parse(decrypted);
1816
2875
  if (session.expiresAt && Date.now() >= session.expiresAt) {
1817
2876
  await this.removeSession(session.sessionId);
@@ -1843,7 +2902,17 @@ var PartyLayerClient = class {
1843
2902
  }
1844
2903
  session.networkMismatch = mismatch;
1845
2904
  }
1846
- 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
+ }
1847
2916
  if (adapter?.restore) {
1848
2917
  const ctx = this.createAdapterContext();
1849
2918
  if (adapter instanceof GenericDiscoveryAdapter && adapter.usesFactory()) {
@@ -1863,10 +2932,12 @@ var PartyLayerClient = class {
1863
2932
  ...session,
1864
2933
  encrypted
1865
2934
  });
1866
- if (restored) {
2935
+ if (!current()) return this.activeSession;
2936
+ if (restored && restored.partyId === session.partyId && !core.detectNetworkMismatch(session.network, restored.network)) {
1867
2937
  this.activeSession = restored;
1868
2938
  this.activeSessionNeedsProbe = false;
1869
2939
  await this.persistSession(restored);
2940
+ if (!current()) return this.activeSession;
1870
2941
  this.telemetry?.increment?.(core.METRICS.SESSIONS_RESTORED);
1871
2942
  this.telemetry?.increment?.(core.METRICS.WALLET_CONNECT_SUCCESS);
1872
2943
  this.emit("session:connected", {
@@ -1883,6 +2954,11 @@ var PartyLayerClient = class {
1883
2954
  return null;
1884
2955
  }
1885
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
+ }
1886
2962
  this.activeSession = session;
1887
2963
  this.activeSessionNeedsProbe = true;
1888
2964
  return session;
@@ -2046,6 +3122,10 @@ Object.defineProperty(exports, "SessionExpiredError", {
2046
3122
  enumerable: true,
2047
3123
  get: function () { return core.SessionExpiredError; }
2048
3124
  });
3125
+ Object.defineProperty(exports, "TRANSFER_INTENT_FIELDS", {
3126
+ enumerable: true,
3127
+ get: function () { return core.TRANSFER_INTENT_FIELDS; }
3128
+ });
2049
3129
  Object.defineProperty(exports, "TimeoutError", {
2050
3130
  enumerable: true,
2051
3131
  get: function () { return core.TimeoutError; }
@@ -2078,6 +3158,10 @@ Object.defineProperty(exports, "isOfficialProviderAdapter", {
2078
3158
  enumerable: true,
2079
3159
  get: function () { return core.isOfficialProviderAdapter; }
2080
3160
  });
3161
+ Object.defineProperty(exports, "toTransferIntent", {
3162
+ enumerable: true,
3163
+ get: function () { return core.toTransferIntent; }
3164
+ });
2081
3165
  Object.defineProperty(exports, "deriveGenericWalletName", {
2082
3166
  enumerable: true,
2083
3167
  get: function () { return registryClient.deriveGenericWalletName; }
@@ -2198,6 +3282,7 @@ exports.createCantonConnect = createPartyLayer;
2198
3282
  exports.createPartyLayer = createPartyLayer;
2199
3283
  exports.createTelemetryAdapter = createTelemetryAdapter;
2200
3284
  exports.getBuiltinAdapters = getBuiltinAdapters;
3285
+ exports.getDiscoveryCapabilities = getDiscoveryCapabilities;
2201
3286
  exports.isTelemetryConfig = isTelemetryConfig;
2202
3287
  //# sourceMappingURL=index.js.map
2203
3288
  //# sourceMappingURL=index.js.map