@partylayer/sdk 0.22.0 → 0.22.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,50 +10,7 @@ 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/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
- }
13
+ // src/client-base.ts
57
14
  var UNSUPPORTED_METHOD = 4200;
58
15
  var METHOD_NOT_FOUND = -32601;
59
16
  function isUnsupportedMethod(err) {
@@ -174,722 +131,324 @@ function assertConnectionAccepted(result) {
174
131
  function assertPrimaryParty(account) {
175
132
  if (typeof account?.partyId !== "string" || !account.partyId.trim()) throw new core.TransportError("The wallet did not return a primary party");
176
133
  }
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
- }
134
+
135
+ // src/native-owner-bindings.ts
136
+ var nativeOwnerBindings = /* @__PURE__ */ new WeakMap();
137
+ var nativeAdapterCopies = /* @__PURE__ */ new WeakMap();
138
+
139
+ // src/announce-adapter.ts
140
+ function getAnnounceCapabilities(config = {}) {
141
+ const caps = ["connect"];
142
+ if (config.signMessage !== false) caps.push("signMessage");
143
+ caps.push("submitTransaction");
144
+ if (config.restore) caps.push("restore");
145
+ if (config.ledgerApi) caps.push("ledgerApi");
146
+ if (config.events) caps.push("events");
147
+ return caps;
186
148
  }
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
- });
149
+ var ANNOUNCED_WALLET_ID_PREFIX = "browser:ext:";
150
+ function announcedWalletId(announceId) {
151
+ return core.toWalletId(`${ANNOUNCED_WALLET_ID_PREFIX}${announceId}`);
197
152
  }
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;
153
+ function mapTxStatus(status) {
154
+ switch (status) {
155
+ case "pending":
156
+ return "pending";
157
+ case "signed":
158
+ return "submitted";
159
+ case "executed":
160
+ return "committed";
161
+ case "failed":
162
+ default:
163
+ return "failed";
209
164
  }
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
165
  }
220
- var NativeConnectionOwner = class {
221
- constructor(changed = () => {
222
- }) {
223
- this.changed = changed;
166
+ function toBase64Message(message) {
167
+ const bytes = new TextEncoder().encode(message);
168
+ let binary = "";
169
+ for (const b of bytes) binary += String.fromCharCode(b);
170
+ return btoa(binary);
171
+ }
172
+ var GenericAnnounceAdapter = class _GenericAnnounceAdapter {
173
+ walletId;
174
+ name;
175
+ /** Icon surfaced to the picker (announce detail). */
176
+ icon;
177
+ rawProvider;
178
+ metadataEnabled;
179
+ staticMetadata;
180
+ mapError;
181
+ signMessageBase64;
182
+ /**
183
+ * Which execute verb this wallet turned out to support. Resolved on the first
184
+ * submit and reused, so the wallet is asked at most once.
185
+ */
186
+ executeVerb = {};
187
+ // Optional WalletAdapter surface — assigned in the ctor ONLY when configured,
188
+ // so `getCapabilities()` and `'x' in adapter` feature-detection stay honest.
189
+ restore;
190
+ on;
191
+ ledgerApi;
192
+ // signMessage is optional too: assigned in the ctor only when the wallet
193
+ // declares support, so a wallet that cannot sign is not advertised as able to.
194
+ signMessage;
195
+ constructor(args) {
196
+ const configuration = { ...args, config: args.config && {
197
+ ...args.config,
198
+ staticMetadata: args.config.staticMetadata && { ...args.config.staticMetadata }
199
+ } };
200
+ nativeAdapterCopies.set(this, () => new _GenericAnnounceAdapter(configuration));
201
+ this.walletId = args.walletId ?? announcedWalletId(args.announceId);
202
+ this.name = args.name && args.name.length > 0 ? args.name : `Canton Wallet (${args.announceId.slice(0, 6)}\u2026)`;
203
+ this.icon = args.icon;
204
+ this.rawProvider = args.provider;
205
+ const config = args.config;
206
+ this.metadataEnabled = config?.metadata === true;
207
+ this.staticMetadata = config?.staticMetadata;
208
+ this.mapError = config?.mapError;
209
+ this.signMessageBase64 = config?.signMessageBase64 === true;
210
+ if (config?.events) this.on = this.makeOn();
211
+ if (config?.restore) this.restore = this.makeRestore();
212
+ if (config?.ledgerApi) this.ledgerApi = this.makeLedgerApi();
213
+ if (config?.signMessage !== false) this.signMessage = this.signMessageImpl.bind(this);
224
214
  }
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;
215
+ get provider() {
216
+ return nativeOwnerBindings.get(this)?.getProvider(String(this.walletId)) ?? this.rawProvider;
239
217
  }
240
- assertAvailable() {
241
- if (this.disposed) throw disconnected();
242
- if (this.busy) throw new Error("A native wallet operation is already in progress");
218
+ /** @internal Register the discovered transport with the one official owner. */
219
+ async prepareNativeConnection(network) {
220
+ const owner = nativeOwnerBindings.get(this);
221
+ if (!owner) return;
222
+ await owner.prepare(String(this.walletId), {
223
+ providerId: String(this.walletId),
224
+ name: this.name,
225
+ type: "browser",
226
+ icon: this.icon,
227
+ provider: () => this.rawProvider,
228
+ detect: async () => true
229
+ }, network);
243
230
  }
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));
231
+ /**
232
+ * Capabilities derived from actual presence: connect and submitTransaction are
233
+ * always present; signMessage, restore, ledgerApi, and events are each included
234
+ * only when the matching method was assigned, so the set is never advertised
235
+ * beyond what the adapter can do.
236
+ */
237
+ getCapabilities() {
238
+ return getAnnounceCapabilities({
239
+ signMessage: !!this.signMessage,
240
+ restore: !!this.restore,
241
+ ledgerApi: !!this.ledgerApi,
242
+ events: !!this.on
243
+ });
263
244
  }
264
- wrap(registration) {
265
- const source = registration.source;
245
+ /**
246
+ * The adapter is only ever constructed for a wallet that just announced, so
247
+ * its presence is established by the announce handshake itself.
248
+ */
249
+ async detectInstalled() {
266
250
  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
- }
251
+ installed: true,
252
+ // Presence by CONSTRUCTION: this adapter only exists because an announce
253
+ // arrived on the wallet's own target channel. There is no probe to be
254
+ // wrong about, which is why this is the one path that cannot report a
255
+ // wallet that is not there.
256
+ availability: { kind: "installed" },
257
+ reason: "Announced via canton:announceProvider"
337
258
  };
338
- return provider;
339
259
  }
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 () => {
260
+ async connect(ctx, options) {
261
+ return this.guarded(async () => {
262
+ const owner = nativeOwnerBindings.get(this);
263
+ const native = owner ? await owner.connect(String(this.walletId), options?.signal) : void 0;
264
+ if (!owner) assertConnectionAccepted(await this.provider.request({ method: "connect" }));
265
+ const account = native?.account ?? await this.provider.request({
266
+ method: "getPrimaryAccount"
267
+ });
268
+ assertPrimaryParty(account);
269
+ let status;
357
270
  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;
271
+ status = native?.status ?? await this.provider.request({ method: "status" });
272
+ } catch {
373
273
  }
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;
274
+ const reportedNetwork = status?.network?.networkId;
275
+ const partyId = core.toPartyId(account.partyId);
276
+ const network = [reportedNetwork, account.networkId, ctx.network].find(
277
+ (n) => typeof n === "string" && core.isRecognizedNetwork(n)
278
+ ) ?? ctx.network;
279
+ const session = {
280
+ walletId: this.walletId,
281
+ partyId,
282
+ network
283
+ };
284
+ if (this.metadataEnabled) {
285
+ session.metadata = { ...this.staticMetadata ?? {}, ...buildMetadata(status, account) };
382
286
  }
383
- );
384
- return task;
287
+ return { partyId, session, capabilities: this.getCapabilities() };
288
+ });
385
289
  }
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;
290
+ async disconnect() {
291
+ const owner = nativeOwnerBindings.get(this);
292
+ if (owner) {
293
+ await owner.disconnect();
294
+ return;
295
+ }
417
296
  try {
418
- return await task;
419
- } finally {
420
- if (this.pending === task) this.pending = null;
297
+ await this.provider.request({ method: "disconnect" });
298
+ } catch {
421
299
  }
422
300
  }
423
- getSession() {
424
- if (this.disposed || !this.client?.getActiveSession() || !this.projection) return null;
425
- return this.projection;
301
+ // Real signMessage implementation. Exposed as `this.signMessage` from the ctor
302
+ // only when the wallet declares support, so getCapabilities and feature
303
+ // detection stay honest for a wallet that cannot sign.
304
+ async signMessageImpl(_ctx, session, params) {
305
+ return this.guarded(async () => {
306
+ const rpcParams = this.signMessageBase64 ? { message: toBase64Message(params.message) } : { message: params.message };
307
+ const res = await this.provider.request({ method: "signMessage", params: rpcParams });
308
+ return normalizeSignedMessage(res, session, params);
309
+ });
426
310
  }
427
- getProvider(id) {
428
- if (!this.getSession() || id && this.projection?.id !== id) throw disconnected();
429
- return this.client.getProvider();
311
+ async submitTransaction(ctx, _session, params) {
312
+ return this.guarded(
313
+ () => submitViaPrepareExecute(this.provider, params, {
314
+ walletId: String(this.walletId),
315
+ state: this.executeVerb,
316
+ logger: ctx.logger
317
+ })
318
+ );
430
319
  }
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 identity2 = 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: identity2 };
443
- if (identity2.account.partyId !== partyId || core.detectNetworkMismatch(network, identity2.network)) {
444
- this.changed(id, identity2);
445
- throw new Error("Wallet identity changed during message signing");
320
+ // ── Optional-method factories (assigned only when configured) ──────────────
321
+ /** events: bridge the provider's CIP-0103 `txChanged` push event → `txStatus`. */
322
+ makeOn() {
323
+ return (event, handler) => {
324
+ if (event !== "txStatus") return () => {
325
+ };
326
+ const listener = (...args) => {
327
+ const tx = args[0];
328
+ if (!tx) return;
329
+ handler({ status: mapTxStatus(tx.status), commandId: tx.commandId, raw: tx });
330
+ };
331
+ try {
332
+ this.provider.on("txChanged", listener);
333
+ } catch {
334
+ return () => {
335
+ };
446
336
  }
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
- }
337
+ return () => this.provider.removeListener("txChanged", listener);
338
+ };
464
339
  }
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) => {
340
+ /** restore: silent status()/getPrimaryAccount() probe + expiry + party-match. */
341
+ makeRestore() {
342
+ return (_ctx, persisted) => this.guarded(async () => {
343
+ const owner = nativeOwnerBindings.get(this);
344
+ if (owner) {
345
+ await this.prepareNativeConnection(_ctx.network);
346
+ const restored = await owner.restore({ id: String(this.walletId), partyId: persisted.partyId, network: persisted.network });
347
+ return restored?.id === String(this.walletId) ? { ...persisted, capabilitiesSnapshot: this.getCapabilities() } : null;
348
+ }
349
+ if (persisted.expiresAt && Date.now() >= persisted.expiresAt) return null;
350
+ let status;
471
351
  try {
472
- unsubscribe();
352
+ status = await this.provider.request({ method: "status" });
473
353
  } catch {
474
354
  }
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
- (identity2) => {
490
- if (revision !== this.refreshRevision || this.projection?.id !== id || this.disposed)
491
- return;
492
- this.identityRefreshing = false;
493
- this.projection = { id, identity: identity2 };
494
- this.changed(id, identity2);
495
- },
496
- () => {
497
- if (revision === this.refreshRevision) this.invalidate(id);
498
- }
355
+ const connected = status?.isConnected ?? status?.connection?.isConnected;
356
+ if (connected === false) return null;
357
+ const account = await this.provider.request({
358
+ method: "getPrimaryAccount"
359
+ });
360
+ if (account.partyId !== persisted.partyId) return null;
361
+ const network = [status?.network?.networkId, account.networkId].find(
362
+ (value) => typeof value === "string" && core.isRecognizedNetwork(value)
499
363
  );
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);
364
+ if (network && core.detectNetworkMismatch(persisted.network, network)) return null;
365
+ return {
366
+ ...persisted,
367
+ walletId: this.walletId,
368
+ // persisted (lowest) → static config → runtime RPC (wins).
369
+ metadata: {
370
+ ...persisted.metadata ?? {},
371
+ ...this.staticMetadata ?? {},
372
+ ...buildMetadata(status, account)
373
+ }
374
+ };
375
+ });
527
376
  }
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;
377
+ /** ledgerApi: proxy the standard CIP-0103 ledgerApi call; shape to {response:string}. */
378
+ makeLedgerApi() {
379
+ return (_ctx, _session, params) => this.guarded(async () => {
380
+ const result = await this.provider.request({
381
+ method: "ledgerApi",
382
+ params: {
383
+ requestMethod: core.normalizeLedgerMethodLower(params.requestMethod),
384
+ resource: params.resource,
385
+ body: core.ledgerApiBodyToObject(params.body)
548
386
  }
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;
387
+ });
388
+ if (result && typeof result.response === "string") return { response: result.response };
389
+ return { response: JSON.stringify(result ?? null) };
390
+ });
563
391
  }
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;
392
+ /**
393
+ * Run an operation, giving the optional `mapError` hook first crack at any
394
+ * thrown error. With NO hook configured this is a direct pass-through (no
395
+ * try/catch) — byte-identical to the baseline, and the SDK's built-in standard
396
+ * error mapping still applies downstream.
397
+ */
398
+ async guarded(op) {
399
+ if (!this.mapError) return op();
400
+ try {
401
+ return await op();
402
+ } catch (err) {
403
+ const mapped = this.mapError(err);
404
+ throw mapped ?? err;
405
+ }
575
406
  }
576
407
  };
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
- }
590
- var ANNOUNCED_WALLET_ID_PREFIX = "browser:ext:";
591
- function announcedWalletId(announceId) {
592
- return core.toWalletId(`${ANNOUNCED_WALLET_ID_PREFIX}${announceId}`);
593
- }
594
- function mapTxStatus(status) {
595
- switch (status) {
596
- case "pending":
597
- return "pending";
598
- case "signed":
599
- return "submitted";
600
- case "executed":
601
- return "committed";
602
- case "failed":
603
- default:
604
- return "failed";
605
- }
408
+ function buildMetadata(status, account) {
409
+ const meta = {};
410
+ const put = (k, v) => {
411
+ if (typeof v === "string" && v.length > 0) meta[k] = v;
412
+ };
413
+ put("kernelId", status?.kernel?.id);
414
+ put("publicKey", account.publicKey);
415
+ put("namespace", account.namespace);
416
+ put("networkId", account.networkId);
417
+ put("signingProviderId", account.signingProviderId);
418
+ put("hint", account.hint);
419
+ put("ledgerApiBaseUrl", status?.network?.ledgerApi?.baseUrl);
420
+ put("userId", status?.session?.userId);
421
+ return meta;
606
422
  }
607
- function toBase64Message(message) {
608
- const bytes = new TextEncoder().encode(message);
609
- let binary = "";
610
- for (const b of bytes) binary += String.fromCharCode(b);
611
- return btoa(binary);
423
+ function getDiscoveryCapabilities(declared) {
424
+ const capabilities = ["connect", "disconnect"];
425
+ if (declared?.signMessage !== false) capabilities.push("signMessage");
426
+ if (declared?.submitTransaction !== false) capabilities.push("submitTransaction");
427
+ if (declared?.ledgerApi) capabilities.push("ledgerApi");
428
+ return capabilities;
612
429
  }
613
- var GenericAnnounceAdapter = class _GenericAnnounceAdapter {
430
+ var GenericDiscoveryAdapter = class _GenericDiscoveryAdapter {
614
431
  walletId;
615
432
  name;
616
- /** Icon surfaced to the picker (announce detail). */
617
433
  icon;
618
- rawProvider;
619
- metadataEnabled;
620
- staticMetadata;
621
- mapError;
622
- signMessageBase64;
434
+ /**
435
+ * Resolved official adapter. Set at construction for the instance form; for
436
+ * the factory form it stays null until {@link resolveOfficial} constructs it
437
+ * with the network-resolved host.
438
+ */
439
+ official;
440
+ /** Factory form (null for the instance form). */
441
+ factory;
442
+ /** Network→host map for the factory form; injected by the SDK post-registry. */
443
+ networkHosts;
444
+ /** Lazily resolved from `official.provider()` — NOT at construction (SSR-safe). */
445
+ providerInstance = null;
623
446
  /**
624
447
  * Which execute verb this wallet turned out to support. Resolved on the first
625
448
  * submit and reused, so the wallet is asked at most once.
626
449
  */
627
450
  executeVerb = {};
628
- // Optional WalletAdapter surface — assigned in the ctor ONLY when configured,
629
- // so `getCapabilities()` and `'x' in adapter` feature-detection stay honest.
630
- restore;
631
- on;
632
- ledgerApi;
633
- // signMessage is optional too: assigned in the ctor only when the wallet
634
- // declares support, so a wallet that cannot sign is not advertised as able to.
635
- signMessage;
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));
642
- this.walletId = args.walletId ?? announcedWalletId(args.announceId);
643
- this.name = args.name && args.name.length > 0 ? args.name : `Canton Wallet (${args.announceId.slice(0, 6)}\u2026)`;
644
- this.icon = args.icon;
645
- this.rawProvider = args.provider;
646
- const config = args.config;
647
- this.metadataEnabled = config?.metadata === true;
648
- this.staticMetadata = config?.staticMetadata;
649
- this.mapError = config?.mapError;
650
- this.signMessageBase64 = config?.signMessageBase64 === true;
651
- if (config?.events) this.on = this.makeOn();
652
- if (config?.restore) this.restore = this.makeRestore();
653
- if (config?.ledgerApi) this.ledgerApi = this.makeLedgerApi();
654
- if (config?.signMessage !== false) this.signMessage = this.signMessageImpl.bind(this);
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
- }
672
- /**
673
- * Capabilities derived from actual presence: connect and submitTransaction are
674
- * always present; signMessage, restore, ledgerApi, and events are each included
675
- * only when the matching method was assigned, so the set is never advertised
676
- * beyond what the adapter can do.
677
- */
678
- getCapabilities() {
679
- return getAnnounceCapabilities({
680
- signMessage: !!this.signMessage,
681
- restore: !!this.restore,
682
- ledgerApi: !!this.ledgerApi,
683
- events: !!this.on
684
- });
685
- }
686
- /**
687
- * The adapter is only ever constructed for a wallet that just announced, so
688
- * its presence is established by the announce handshake itself.
689
- */
690
- async detectInstalled() {
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
- };
700
- }
701
- async connect(ctx, options) {
702
- return this.guarded(async () => {
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({
707
- method: "getPrimaryAccount"
708
- });
709
- assertPrimaryParty(account);
710
- let status;
711
- try {
712
- status = native?.status ?? await this.provider.request({ method: "status" });
713
- } catch {
714
- }
715
- const reportedNetwork = status?.network?.networkId;
716
- const partyId = core.toPartyId(account.partyId);
717
- const network = [reportedNetwork, account.networkId, ctx.network].find(
718
- (n) => typeof n === "string" && core.isRecognizedNetwork(n)
719
- ) ?? ctx.network;
720
- const session = {
721
- walletId: this.walletId,
722
- partyId,
723
- network
724
- };
725
- if (this.metadataEnabled) {
726
- session.metadata = { ...this.staticMetadata ?? {}, ...buildMetadata(status, account) };
727
- }
728
- return { partyId, session, capabilities: this.getCapabilities() };
729
- });
730
- }
731
- async disconnect() {
732
- const owner = nativeOwnerBindings.get(this);
733
- if (owner) {
734
- await owner.disconnect();
735
- return;
736
- }
737
- try {
738
- await this.provider.request({ method: "disconnect" });
739
- } catch {
740
- }
741
- }
742
- // Real signMessage implementation. Exposed as `this.signMessage` from the ctor
743
- // only when the wallet declares support, so getCapabilities and feature
744
- // detection stay honest for a wallet that cannot sign.
745
- async signMessageImpl(_ctx, session, params) {
746
- return this.guarded(async () => {
747
- const rpcParams = this.signMessageBase64 ? { message: toBase64Message(params.message) } : { message: params.message };
748
- const res = await this.provider.request({ method: "signMessage", params: rpcParams });
749
- return normalizeSignedMessage(res, session, params);
750
- });
751
- }
752
- async submitTransaction(ctx, _session, params) {
753
- return this.guarded(
754
- () => submitViaPrepareExecute(this.provider, params, {
755
- walletId: String(this.walletId),
756
- state: this.executeVerb,
757
- logger: ctx.logger
758
- })
759
- );
760
- }
761
- // ── Optional-method factories (assigned only when configured) ──────────────
762
- /** events: bridge the provider's CIP-0103 `txChanged` push event → `txStatus`. */
763
- makeOn() {
764
- return (event, handler) => {
765
- if (event !== "txStatus") return () => {
766
- };
767
- const listener = (...args) => {
768
- const tx = args[0];
769
- if (!tx) return;
770
- handler({ status: mapTxStatus(tx.status), commandId: tx.commandId, raw: tx });
771
- };
772
- try {
773
- this.provider.on("txChanged", listener);
774
- } catch {
775
- return () => {
776
- };
777
- }
778
- return () => this.provider.removeListener("txChanged", listener);
779
- };
780
- }
781
- /** restore: silent status()/getPrimaryAccount() probe + expiry + party-match. */
782
- makeRestore() {
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
- }
790
- if (persisted.expiresAt && Date.now() >= persisted.expiresAt) return null;
791
- let status;
792
- try {
793
- status = await this.provider.request({ method: "status" });
794
- } catch {
795
- }
796
- const connected = status?.isConnected ?? status?.connection?.isConnected;
797
- if (connected === false) return null;
798
- const account = await this.provider.request({
799
- method: "getPrimaryAccount"
800
- });
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;
806
- return {
807
- ...persisted,
808
- walletId: this.walletId,
809
- // persisted (lowest) → static config → runtime RPC (wins).
810
- metadata: {
811
- ...persisted.metadata ?? {},
812
- ...this.staticMetadata ?? {},
813
- ...buildMetadata(status, account)
814
- }
815
- };
816
- });
817
- }
818
- /** ledgerApi: proxy the standard CIP-0103 ledgerApi call; shape to {response:string}. */
819
- makeLedgerApi() {
820
- return (_ctx, _session, params) => this.guarded(async () => {
821
- const result = await this.provider.request({
822
- method: "ledgerApi",
823
- params: {
824
- requestMethod: core.normalizeLedgerMethodLower(params.requestMethod),
825
- resource: params.resource,
826
- body: core.ledgerApiBodyToObject(params.body)
827
- }
828
- });
829
- if (result && typeof result.response === "string") return { response: result.response };
830
- return { response: JSON.stringify(result ?? null) };
831
- });
832
- }
833
- /**
834
- * Run an operation, giving the optional `mapError` hook first crack at any
835
- * thrown error. With NO hook configured this is a direct pass-through (no
836
- * try/catch) — byte-identical to the baseline, and the SDK's built-in standard
837
- * error mapping still applies downstream.
838
- */
839
- async guarded(op) {
840
- if (!this.mapError) return op();
841
- try {
842
- return await op();
843
- } catch (err) {
844
- const mapped = this.mapError(err);
845
- throw mapped ?? err;
846
- }
847
- }
848
- };
849
- function buildMetadata(status, account) {
850
- const meta = {};
851
- const put = (k, v) => {
852
- if (typeof v === "string" && v.length > 0) meta[k] = v;
853
- };
854
- put("kernelId", status?.kernel?.id);
855
- put("publicKey", account.publicKey);
856
- put("namespace", account.namespace);
857
- put("networkId", account.networkId);
858
- put("signingProviderId", account.signingProviderId);
859
- put("hint", account.hint);
860
- put("ledgerApiBaseUrl", status?.network?.ledgerApi?.baseUrl);
861
- put("userId", status?.session?.userId);
862
- return meta;
863
- }
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 {
872
- walletId;
873
- name;
874
- icon;
875
- /**
876
- * Resolved official adapter. Set at construction for the instance form; for
877
- * the factory form it stays null until {@link resolveOfficial} constructs it
878
- * with the network-resolved host.
879
- */
880
- official;
881
- /** Factory form (null for the instance form). */
882
- factory;
883
- /** Network→host map for the factory form; injected by the SDK post-registry. */
884
- networkHosts;
885
- /** Lazily resolved from `official.provider()` — NOT at construction (SSR-safe). */
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;
451
+ capabilities;
893
452
  ledgerApi;
894
453
  constructor(args) {
895
454
  const configuration = { ...args, capabilities: args.capabilities && { ...args.capabilities } };
@@ -1220,7 +779,7 @@ function createSessionProvider(options) {
1220
779
  };
1221
780
  }
1222
781
 
1223
- // src/config.ts
782
+ // src/config-base.ts
1224
783
  var DEFAULT_REGISTRY_URL = "https://registry.partylayer.xyz";
1225
784
 
1226
785
  // src/adapters.ts
@@ -1251,54 +810,36 @@ var DefaultCrypto = class {
1251
810
  );
1252
811
  }
1253
812
  async encrypt(data, key) {
1254
- if (typeof crypto === "undefined" || !crypto.subtle) {
1255
- return btoa(data);
1256
- }
1257
- try {
1258
- const cryptoKey = await this.getKey(key);
1259
- const iv = crypto.getRandomValues(new Uint8Array(12));
1260
- const encoder = new TextEncoder();
1261
- const encoded = encoder.encode(data);
1262
- const encrypted = await crypto.subtle.encrypt(
1263
- { name: "AES-GCM", iv },
1264
- cryptoKey,
1265
- encoded
1266
- );
1267
- const combined = new Uint8Array(iv.length + encrypted.byteLength);
1268
- combined.set(iv);
1269
- combined.set(new Uint8Array(encrypted), iv.length);
1270
- return btoa(String.fromCharCode(...combined));
1271
- } catch {
1272
- return btoa(data);
1273
- }
813
+ const iv = new Uint8Array(this.randomBytes(12));
814
+ const cryptoKey = await this.getKey(key);
815
+ const encrypted = await globalThis.crypto.subtle.encrypt(
816
+ { name: "AES-GCM", iv },
817
+ cryptoKey,
818
+ new TextEncoder().encode(data)
819
+ );
820
+ const combined = new Uint8Array(iv.length + encrypted.byteLength);
821
+ combined.set(iv);
822
+ combined.set(new Uint8Array(encrypted), iv.length);
823
+ return btoa(String.fromCharCode(...combined));
1274
824
  }
1275
825
  async decrypt(encrypted, key) {
1276
- if (typeof crypto === "undefined" || !crypto.subtle) {
1277
- return atob(encrypted);
1278
- }
1279
- try {
1280
- const cryptoKey = await this.getKey(key);
1281
- const combined = Uint8Array.from(atob(encrypted), (c) => c.charCodeAt(0));
1282
- const iv = combined.slice(0, 12);
1283
- const data = combined.slice(12);
1284
- const decrypted = await crypto.subtle.decrypt(
1285
- { name: "AES-GCM", iv },
1286
- cryptoKey,
1287
- data
1288
- );
1289
- const decoder = new TextDecoder();
1290
- return decoder.decode(decrypted);
1291
- } catch {
1292
- return atob(encrypted);
1293
- }
826
+ const cryptoKey = await this.getKey(key);
827
+ const combined = Uint8Array.from(atob(encrypted), (character) => character.charCodeAt(0));
828
+ if (combined.length < 28) throw new Error("Invalid AES-GCM session ciphertext");
829
+ const decrypted = await globalThis.crypto.subtle.decrypt(
830
+ { name: "AES-GCM", iv: combined.slice(0, 12) },
831
+ cryptoKey,
832
+ combined.slice(12)
833
+ );
834
+ return new TextDecoder("utf-8", { fatal: true }).decode(decrypted);
835
+ }
836
+ randomBytes(byteLength) {
837
+ if (!globalThis.crypto?.getRandomValues) throw new Error("Secure random entropy is unavailable");
838
+ if (!Number.isInteger(byteLength) || byteLength < 1 || byteLength > 65536) throw new Error("Invalid secure byte length");
839
+ return globalThis.crypto.getRandomValues(new Uint8Array(byteLength));
1294
840
  }
1295
841
  async generateKey() {
1296
- if (typeof crypto === "undefined" || !crypto.getRandomValues) {
1297
- return Math.random().toString(36).substring(2, 15);
1298
- }
1299
- const array = new Uint8Array(32);
1300
- crypto.getRandomValues(array);
1301
- return Array.from(array, (b) => b.toString(16).padStart(2, "0")).join("");
842
+ return Array.from(this.randomBytes(32), (byte) => byte.toString(16).padStart(2, "0")).join("");
1302
843
  }
1303
844
  };
1304
845
  var DefaultStorage = class {
@@ -1359,22 +900,6 @@ var DefaultTelemetry = class {
1359
900
  error(_error, _properties) {
1360
901
  }
1361
902
  };
1362
- function getBuiltinAdapters() {
1363
- return [
1364
- new adapterLoop.LoopAdapter(),
1365
- // 5N Loop - QR code / popup
1366
- new adapterCantor8.Cantor8Adapter(),
1367
- // Cantor8 - deep link transport
1368
- new adapterNightly.NightlyAdapter()
1369
- // Nightly - multichain wallet (injected)
1370
- // Console is served via the generic CIP-0103 announce path (registry
1371
- // transport:'announce') — no longer in defaults; ConsoleAdapter stays
1372
- // exported below for opt-in manual/bespoke use.
1373
- // Send is served via the generic CIP-0103 announce path (registry
1374
- // transport:'announce') — no longer in defaults; SendAdapter stays exported
1375
- // below for opt-in manual/bespoke use.
1376
- ];
1377
- }
1378
903
  var SDK_VERSION = "0.3.0";
1379
904
  var MetricsTelemetryAdapter = class {
1380
905
  config;
@@ -1638,6 +1163,23 @@ function eventLogLevel(type) {
1638
1163
  return "info";
1639
1164
  }
1640
1165
  }
1166
+ var SESSION_ENTROPY_BYTES = 32;
1167
+ function createSecureSessionId(crypto2) {
1168
+ if (typeof globalThis.crypto?.getRandomValues === "function") return core.generateSessionId();
1169
+ if (!crypto2.randomBytes) throw new Error("Secure session entropy requires platform getRandomValues or CryptoAdapter.randomBytes");
1170
+ const encode = (bytes2) => {
1171
+ if (!(bytes2 instanceof Uint8Array) || bytes2.byteLength !== SESSION_ENTROPY_BYTES) {
1172
+ throw new Error("Session entropy must be a Uint8Array of exactly 32 bytes");
1173
+ }
1174
+ return core.toSessionId(`session_${Date.now()}_${Array.from(bytes2, (byte) => byte.toString(16).padStart(2, "0")).join("")}`);
1175
+ };
1176
+ const bytes = crypto2.randomBytes(SESSION_ENTROPY_BYTES);
1177
+ if (bytes instanceof Uint8Array) return encode(bytes);
1178
+ if (bytes && typeof bytes.then === "function") return Promise.resolve(bytes).then(encode);
1179
+ throw new Error("Session entropy must be a Uint8Array of exactly 32 bytes");
1180
+ }
1181
+
1182
+ // src/client-base.ts
1641
1183
  var SESSION_STORAGE_KEY = "active_session";
1642
1184
  var WALLETS_CHANGED_DEBOUNCE_MS = 50;
1643
1185
  function deriveAnnounceConfig(entry) {
@@ -1670,7 +1212,55 @@ function matchKnownByIdentity(providerId, base) {
1670
1212
  });
1671
1213
  }
1672
1214
  var DEFAULT_CONNECT_TIMEOUT_MS = 12e4;
1673
- var PartyLayerClient = class {
1215
+ var PartyLayerClientBase = class {
1216
+ constructor(config, runtime = {}) {
1217
+ this.runtime = runtime;
1218
+ this.config = config;
1219
+ if (config.app.origin) {
1220
+ this.origin = config.app.origin;
1221
+ } else if (typeof window !== "undefined") {
1222
+ this.origin = window.location.origin;
1223
+ } else {
1224
+ this.origin = "unknown";
1225
+ }
1226
+ this.logger = config.logger || new DefaultLogger();
1227
+ this.logLevel = config.logLevel ?? "info";
1228
+ this.crypto = config.crypto || new DefaultCrypto();
1229
+ this.storage = config.storage || new DefaultStorage();
1230
+ if (typeof window !== "undefined" && runtime.createOwner) {
1231
+ this.nativeOwner = runtime.createOwner((id, identity2) => this.onNativeIdentityChanged(id, identity2));
1232
+ }
1233
+ const telemetryAdapter = createTelemetryAdapter(config.telemetry);
1234
+ this.telemetry = telemetryAdapter || new DefaultTelemetry();
1235
+ const defaults = config.adapters ?? runtime.getBuiltinAdapters?.() ?? [];
1236
+ const adaptersToRegister = [...defaults, ...config.additionalAdapters ?? []];
1237
+ for (const adapterOrClass of adaptersToRegister) {
1238
+ let adapter;
1239
+ if (typeof adapterOrClass === "function") {
1240
+ adapter = new adapterOrClass();
1241
+ } else if (core.isOfficialAdapterFactory(adapterOrClass)) {
1242
+ adapter = new GenericDiscoveryAdapter({ factory: adapterOrClass });
1243
+ } else if (core.isOfficialProviderAdapter(adapterOrClass)) {
1244
+ adapter = new GenericDiscoveryAdapter({ official: adapterOrClass });
1245
+ } else {
1246
+ adapter = adapterOrClass;
1247
+ }
1248
+ this.registerAdapter(adapter);
1249
+ this.log("debug", "adapter:registered", "Registered wallet adapter", {
1250
+ walletId: adapter.walletId,
1251
+ name: adapter.name,
1252
+ capabilities: adapter.getCapabilities()
1253
+ });
1254
+ }
1255
+ this.registryClient = new registryClient.RegistryClient({
1256
+ registryUrl: config.registryUrl || DEFAULT_REGISTRY_URL,
1257
+ channel: config.channel || "stable",
1258
+ registryPublicKeys: config.registryPublicKeys,
1259
+ storage: this.storage
1260
+ });
1261
+ this.updateRegistryStatus();
1262
+ if (!config.deferInitialization) this.initialize();
1263
+ }
1674
1264
  config;
1675
1265
  adapters = /* @__PURE__ */ new Map();
1676
1266
  destroyed = false;
@@ -1720,53 +1310,6 @@ var PartyLayerClient = class {
1720
1310
  origin;
1721
1311
  nativeOwner;
1722
1312
  sessionProvider;
1723
- constructor(config) {
1724
- this.config = config;
1725
- if (config.app.origin) {
1726
- this.origin = config.app.origin;
1727
- } else if (typeof window !== "undefined") {
1728
- this.origin = window.location.origin;
1729
- } else {
1730
- this.origin = "unknown";
1731
- }
1732
- this.logger = config.logger || new DefaultLogger();
1733
- this.logLevel = config.logLevel ?? "info";
1734
- this.crypto = config.crypto || new DefaultCrypto();
1735
- this.storage = config.storage || new DefaultStorage();
1736
- if (typeof window !== "undefined") {
1737
- this.nativeOwner = new NativeConnectionOwner((id, identity2) => this.onNativeIdentityChanged(id, identity2));
1738
- }
1739
- const telemetryAdapter = createTelemetryAdapter(config.telemetry);
1740
- this.telemetry = telemetryAdapter || new DefaultTelemetry();
1741
- const defaults = config.adapters ?? getBuiltinAdapters();
1742
- const adaptersToRegister = [...defaults, ...config.additionalAdapters ?? []];
1743
- for (const adapterOrClass of adaptersToRegister) {
1744
- let adapter;
1745
- if (typeof adapterOrClass === "function") {
1746
- adapter = new adapterOrClass();
1747
- } else if (core.isOfficialAdapterFactory(adapterOrClass)) {
1748
- adapter = new GenericDiscoveryAdapter({ factory: adapterOrClass });
1749
- } else if (core.isOfficialProviderAdapter(adapterOrClass)) {
1750
- adapter = new GenericDiscoveryAdapter({ official: adapterOrClass });
1751
- } else {
1752
- adapter = adapterOrClass;
1753
- }
1754
- this.registerAdapter(adapter);
1755
- this.log("debug", "adapter:registered", "Registered wallet adapter", {
1756
- walletId: adapter.walletId,
1757
- name: adapter.name,
1758
- capabilities: adapter.getCapabilities()
1759
- });
1760
- }
1761
- this.registryClient = new registryClient.RegistryClient({
1762
- registryUrl: config.registryUrl || DEFAULT_REGISTRY_URL,
1763
- channel: config.channel || "stable",
1764
- registryPublicKeys: config.registryPublicKeys,
1765
- storage: this.storage
1766
- });
1767
- this.updateRegistryStatus();
1768
- if (!config.deferInitialization) this.initialize();
1769
- }
1770
1313
  /** Start browser discovery/restoration once; safe for framework effect replay. */
1771
1314
  initialize() {
1772
1315
  if (this.initialized || this.destroyed) return;
@@ -1895,7 +1438,7 @@ var PartyLayerClient = class {
1895
1438
  }
1896
1439
  /** Resolve only reviewed default SDKs present in the active registry. */
1897
1440
  async ensureDefaultWallets() {
1898
- if (this.config.adapters !== void 0) return;
1441
+ if (this.config.adapters !== void 0 || !this.runtime.loadDefaultWallet) return;
1899
1442
  let registry;
1900
1443
  try {
1901
1444
  registry = await this.registryClient.getRegistry();
@@ -1909,7 +1452,7 @@ var PartyLayerClient = class {
1909
1452
  if (!pending) {
1910
1453
  pending = (async () => {
1911
1454
  try {
1912
- const entryAdapter = await loadDefaultWallet(entry.id, this.config, this.origin);
1455
+ const entryAdapter = await this.runtime.loadDefaultWallet(entry.id, this.config, this.origin);
1913
1456
  if (!entryAdapter || this.destroyed) return;
1914
1457
  const adapter = core.isOfficialAdapterFactory(entryAdapter) ? new GenericDiscoveryAdapter({
1915
1458
  factory: entryAdapter,
@@ -1956,12 +1499,13 @@ var PartyLayerClient = class {
1956
1499
  * adapters-only) or every non-announce entry is registered.
1957
1500
  */
1958
1501
  async gateUnconnectableEntries(wallets) {
1502
+ if (!this.runtime.browserDiscovery) return wallets.filter((wallet) => this.adapters.has(wallet.walletId));
1959
1503
  let hidden = null;
1960
1504
  const announceCapabilities = /* @__PURE__ */ new Map();
1961
1505
  try {
1962
1506
  const registry = await this.registryClient.getRegistry();
1963
1507
  for (const entry of registry.wallets) {
1964
- if (entry.adapter?.transport === "announce") {
1508
+ if (entry.adapter?.transport === "announce" && this.runtime.browserDiscovery) {
1965
1509
  announceCapabilities.set(entry.id, getAnnounceCapabilities(deriveAnnounceConfig(entry)));
1966
1510
  continue;
1967
1511
  }
@@ -2004,7 +1548,7 @@ var PartyLayerClient = class {
2004
1548
  * ON in the browser and OFF under SSR (no `window`). Canonical: provider.md.
2005
1549
  */
2006
1550
  get announceEnabled() {
2007
- if (typeof window === "undefined") return false;
1551
+ if (typeof window === "undefined" || !this.runtime.browserDiscovery) return false;
2008
1552
  return this.config.discovery?.announce ?? true;
2009
1553
  }
2010
1554
  /**
@@ -2265,7 +1809,7 @@ var PartyLayerClient = class {
2265
1809
  }
2266
1810
  }
2267
1811
  } else if (availableWallets.length === 0) {
2268
- throw new core.WalletNotFoundError("No wallets available");
1812
+ throw new core.WalletNotFoundError(this.runtime.noWalletsMessage ?? "No wallets available");
2269
1813
  } else {
2270
1814
  selectedWallet = availableWallets[0];
2271
1815
  }
@@ -2313,8 +1857,8 @@ var PartyLayerClient = class {
2313
1857
  return { selectedWallet, adapter, ctx, isNativeWallet };
2314
1858
  }
2315
1859
  /**
2316
- * Invoke `adapter.connect()` (its FIRST statement — no await precedes it) and
2317
- * build / persist / emit the session. Separated from plan resolution so the
1860
+ * Generate secure entropy, invoke `adapter.connect()` without awaiting the
1861
+ * platform RNG path, then build / persist / emit the session. Separated from plan resolution so the
2318
1862
  * popup-safe fast-path can call it gesture-synchronously.
2319
1863
  */
2320
1864
  async completeConnect(plan, options, correlationId = newCorrelationId(), attempt) {
@@ -2324,6 +1868,9 @@ var PartyLayerClient = class {
2324
1868
  if (attempt === void 0) ++this.sessionRevision;
2325
1869
  if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
2326
1870
  const { selectedWallet, adapter, ctx } = plan;
1871
+ const entropy = createSecureSessionId(this.crypto);
1872
+ const sessionId = typeof entropy === "string" ? entropy : await entropy;
1873
+ if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
2327
1874
  if (!nativeOwnerBindings.has(adapter) && this.nativeOwner?.getSession()) this.nativeOwner.release();
2328
1875
  const timeoutMs = options?.timeoutMs || DEFAULT_CONNECT_TIMEOUT_MS;
2329
1876
  const abort = new AbortController();
@@ -2349,7 +1896,7 @@ var PartyLayerClient = class {
2349
1896
  }
2350
1897
  if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
2351
1898
  const session = {
2352
- sessionId: core.toSessionId(`session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`),
1899
+ sessionId,
2353
1900
  walletId: selectedWallet.walletId,
2354
1901
  partyId: result.partyId,
2355
1902
  // The wallet's reported network (adapters that read the live wallet —
@@ -2968,6 +2515,8 @@ var PartyLayerClient = class {
2968
2515
  this.activeSessionNeedsProbe = true;
2969
2516
  return session;
2970
2517
  } catch (err) {
2518
+ if (!current()) return this.activeSession;
2519
+ await this.removeSession();
2971
2520
  this.log("warn", "session:restore_failed", "Failed to restore session", {
2972
2521
  error: err instanceof Error ? err.message : String(err)
2973
2522
  }, correlationId);
@@ -3067,6 +2616,477 @@ var PartyLayerClient = class {
3067
2616
  }
3068
2617
  }
3069
2618
  };
2619
+ function getBuiltinAdapters() {
2620
+ return [
2621
+ new adapterLoop.LoopAdapter(),
2622
+ // 5N Loop - QR code / popup
2623
+ new adapterCantor8.Cantor8Adapter(),
2624
+ // Cantor8 - deep link transport
2625
+ new adapterNightly.NightlyAdapter()
2626
+ // Nightly - multichain wallet (injected)
2627
+ // Console is served via the generic CIP-0103 announce path (registry
2628
+ // transport:'announce') — no longer in defaults; ConsoleAdapter stays
2629
+ // exported below for opt-in manual/bespoke use.
2630
+ // Send is served via the generic CIP-0103 announce path (registry
2631
+ // transport:'announce') — no longer in defaults; SendAdapter stays exported
2632
+ // below for opt-in manual/bespoke use.
2633
+ ];
2634
+ }
2635
+ var loaders = {
2636
+ walley: async () => {
2637
+ const { WalleyAdapter } = await import('@k2flabs/walley-dapp-sdk');
2638
+ return { providerId: "walley", create: (host) => new WalleyAdapter({ host }) };
2639
+ },
2640
+ cauri: async () => {
2641
+ const { cauriAdapterFactory } = await import('@lithiumdigital/cauri-dapp-sdk');
2642
+ return cauriAdapterFactory;
2643
+ },
2644
+ oneswap: async (network) => {
2645
+ const { createOneSwapHostedAdapter } = await import('#partylayer-hosted-wallet-profiles');
2646
+ return {
2647
+ providerId: "oneswap",
2648
+ create: (host) => createOneSwapHostedAdapter({
2649
+ walletUrl: host,
2650
+ networkId: core.toCAIP2Network(network).networkId
2651
+ })
2652
+ };
2653
+ },
2654
+ vala: async () => {
2655
+ const { valaAdapterFactory } = await import('@vala-wallet/dapp-sdk');
2656
+ return valaAdapterFactory;
2657
+ }
2658
+ };
2659
+ async function loadDefaultWallet(id, config, origin) {
2660
+ if (id === "walletconnect" && config.walletConnect?.projectId.trim()) {
2661
+ const { WalletConnectAdapter } = await import('@partylayer/adapter-walletconnect');
2662
+ return new WalletConnectAdapter({
2663
+ ...config.walletConnect,
2664
+ metadata: config.walletConnect.metadata ?? {
2665
+ name: config.app.name,
2666
+ description: config.app.name,
2667
+ url: origin === "unknown" ? "" : origin,
2668
+ icons: []
2669
+ }
2670
+ });
2671
+ }
2672
+ if (id === "bron" && config.bron) {
2673
+ const { BronAdapter: BronAdapter2 } = await import('@partylayer/adapter-bron');
2674
+ return new BronAdapter2(config.bron);
2675
+ }
2676
+ return Object.prototype.hasOwnProperty.call(loaders, id) ? loaders[id](config.network) : void 0;
2677
+ }
2678
+ var SILENT_PROBE_TIMEOUT_MS = 1e4;
2679
+ function disconnected() {
2680
+ return new Error("Native wallet connection is no longer active");
2681
+ }
2682
+ function teardown(source) {
2683
+ try {
2684
+ source?.teardown?.();
2685
+ } catch {
2686
+ }
2687
+ }
2688
+ function abortable(promise, signal) {
2689
+ return new Promise((resolve, reject) => {
2690
+ const abort = () => reject(disconnected());
2691
+ if (signal.aborted) {
2692
+ reject(disconnected());
2693
+ return;
2694
+ }
2695
+ signal.addEventListener("abort", abort, { once: true });
2696
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
2697
+ });
2698
+ }
2699
+ async function readIdentity(provider, registration, signal) {
2700
+ const account = await abortable(
2701
+ provider.request({ method: "getPrimaryAccount" }),
2702
+ signal
2703
+ );
2704
+ assertPrimaryParty(account);
2705
+ let status;
2706
+ try {
2707
+ status = await abortable(provider.request({ method: "status" }), signal);
2708
+ } catch (error) {
2709
+ if (signal.aborted) throw error;
2710
+ }
2711
+ if (status?.isConnected === false || status?.connection?.isConnected === false)
2712
+ throw disconnected();
2713
+ const network = [status?.network?.networkId, account.networkId, registration.network].find(
2714
+ (value) => typeof value === "string" && core.isRecognizedNetwork(value)
2715
+ ) ?? registration.network;
2716
+ if (registration.expected && (account.partyId !== registration.expected.partyId || core.detectNetworkMismatch(registration.expected.network, network)))
2717
+ throw disconnected();
2718
+ if (signal.aborted) throw disconnected();
2719
+ return { account, network, status };
2720
+ }
2721
+ var NativeConnectionOwner = class {
2722
+ constructor(changed = () => {
2723
+ }) {
2724
+ this.changed = changed;
2725
+ }
2726
+ client = null;
2727
+ initialization = null;
2728
+ registrations = /* @__PURE__ */ new Map();
2729
+ operation = null;
2730
+ pending = null;
2731
+ closing = null;
2732
+ projection = null;
2733
+ unsubscribers = [];
2734
+ disposed = false;
2735
+ refreshRevision = 0;
2736
+ identityRefreshing = false;
2737
+ probes = /* @__PURE__ */ new Set();
2738
+ get busy() {
2739
+ return this.operation !== null || this.closing !== null;
2740
+ }
2741
+ assertAvailable() {
2742
+ if (this.disposed) throw disconnected();
2743
+ if (this.busy) throw new Error("A native wallet operation is already in progress");
2744
+ }
2745
+ /** Run during picker preparation, never between a click and provider.connect. */
2746
+ async prepare(id, source, network) {
2747
+ if (this.disposed) throw disconnected();
2748
+ this.registrations.set(id, { id, source, network });
2749
+ if (!this.initialization) {
2750
+ this.initialization = (async () => {
2751
+ const { DiscoveryClient } = await import('@canton-network/core-wallet-discovery');
2752
+ const client = await DiscoveryClient.create({ adapters: [] });
2753
+ if (this.disposed) {
2754
+ client.destroy();
2755
+ return;
2756
+ }
2757
+ this.client = client;
2758
+ })();
2759
+ }
2760
+ await this.initialization;
2761
+ if (this.disposed || !this.client) throw disconnected();
2762
+ for (const registration of this.registrations.values())
2763
+ this.client.registerAdapter(this.wrap(registration));
2764
+ }
2765
+ wrap(registration) {
2766
+ const source = registration.source;
2767
+ return {
2768
+ providerId: registration.id,
2769
+ name: source.name,
2770
+ type: source.type === "desktop" || source.type === "mobile" || source.type === "remote" ? source.type : "browser",
2771
+ icon: source.icon,
2772
+ getInfo: () => ({
2773
+ providerId: registration.id,
2774
+ name: source.name,
2775
+ type: "browser",
2776
+ icon: source.icon
2777
+ }),
2778
+ detect: () => source.detect(),
2779
+ provider: () => this.guard(source.provider(), registration),
2780
+ teardown: () => teardown(source),
2781
+ restore: async () => {
2782
+ const operation = this.operation;
2783
+ if (!operation) throw disconnected();
2784
+ try {
2785
+ const raw = source.restore ? await abortable(source.restore(), operation.abort.signal) : source.provider();
2786
+ if (!raw) return null;
2787
+ const provider = raw;
2788
+ operation.identity = await readIdentity(provider, registration, operation.abort.signal);
2789
+ return this.guard(provider, registration);
2790
+ } catch (error) {
2791
+ teardown(source);
2792
+ throw error;
2793
+ }
2794
+ }
2795
+ };
2796
+ }
2797
+ guard(raw, registration) {
2798
+ const provider = {
2799
+ request: async (args) => {
2800
+ if (this.disposed) throw disconnected();
2801
+ if (args.method !== "connect") {
2802
+ if (this.client?.getActiveSession()?.provider !== provider) throw disconnected();
2803
+ if (!this.projection && args.method !== "disconnect") throw disconnected();
2804
+ if (this.identityRefreshing && ![
2805
+ "status",
2806
+ "getPrimaryAccount",
2807
+ "listAccounts",
2808
+ "getActiveNetwork",
2809
+ "isConnected"
2810
+ ].includes(args.method)) {
2811
+ throw new Error("Native wallet identity is being refreshed");
2812
+ }
2813
+ const result = await (args.method === "disconnect" && this.operation ? abortable(raw.request(args), this.operation.abort.signal) : raw.request(args));
2814
+ if (args.method === "status") {
2815
+ const status = result;
2816
+ if (status?.isConnected === false || status?.connection?.isConnected === false) {
2817
+ this.invalidate(registration.id);
2818
+ }
2819
+ }
2820
+ return result;
2821
+ }
2822
+ const operation = this.operation;
2823
+ if (!operation || operation.abort.signal.aborted) throw disconnected();
2824
+ const response = await abortable(raw.request(args), operation.abort.signal);
2825
+ assertConnectionAccepted(response);
2826
+ operation.identity = await readIdentity(raw, registration, operation.abort.signal);
2827
+ return response;
2828
+ },
2829
+ on: (event, listener) => {
2830
+ raw.on(event, listener);
2831
+ return provider;
2832
+ },
2833
+ emit: (event, ...args) => raw.emit(event, ...args),
2834
+ removeListener: (event, listener) => {
2835
+ raw.removeListener(event, listener);
2836
+ return provider;
2837
+ }
2838
+ };
2839
+ return provider;
2840
+ }
2841
+ /** No await precedes the official client's connect call. */
2842
+ connect(id, signal) {
2843
+ this.assertAvailable();
2844
+ if (!this.client || !this.registrations.has(id))
2845
+ return Promise.reject(new Error("Native wallet was not prepared"));
2846
+ const operation = { abort: new AbortController(), id };
2847
+ this.operation = operation;
2848
+ this.detach();
2849
+ const previous = this.client.getActiveSession();
2850
+ teardown(previous?.adapter);
2851
+ const previousId = this.projection?.id;
2852
+ this.projection = null;
2853
+ if (previousId) this.changed(previousId, null);
2854
+ const abort = () => operation.abort.abort();
2855
+ if (signal?.aborted) abort();
2856
+ signal?.addEventListener("abort", abort, { once: true });
2857
+ const task = (async () => {
2858
+ try {
2859
+ await this.client.connect(id);
2860
+ if (operation.abort.signal.aborted || this.disposed || !operation.identity)
2861
+ throw disconnected();
2862
+ this.projection = { id, identity: operation.identity };
2863
+ this.attach(id);
2864
+ return operation.identity;
2865
+ } catch (error) {
2866
+ this.client?.destroy();
2867
+ this.client = null;
2868
+ this.initialization = null;
2869
+ teardown(this.registrations.get(id)?.source);
2870
+ throw error;
2871
+ } finally {
2872
+ signal?.removeEventListener("abort", abort);
2873
+ if (this.operation === operation) this.operation = null;
2874
+ }
2875
+ })();
2876
+ this.pending = task;
2877
+ void task.then(
2878
+ () => {
2879
+ if (this.pending === task) this.pending = null;
2880
+ },
2881
+ () => {
2882
+ if (this.pending === task) this.pending = null;
2883
+ }
2884
+ );
2885
+ return task;
2886
+ }
2887
+ async restore(expected) {
2888
+ if (!this.client || this.projection || this.busy || this.disposed) return this.getSession();
2889
+ const registration = expected && this.registrations.get(expected.id);
2890
+ if (registration) registration.expected = expected;
2891
+ const operation = { abort: new AbortController() };
2892
+ this.operation = operation;
2893
+ const timeout = setTimeout(() => operation.abort.abort(), SILENT_PROBE_TIMEOUT_MS);
2894
+ const task = (async () => {
2895
+ try {
2896
+ await this.client.restorePersistedSessionIfNeeded();
2897
+ const active = this.client?.getActiveSession();
2898
+ if (!active || !operation.identity || operation.abort.signal.aborted || this.disposed)
2899
+ return null;
2900
+ if (expected && active.providerId !== expected.id) {
2901
+ teardown(active.adapter);
2902
+ this.client.destroy();
2903
+ this.client = null;
2904
+ this.initialization = null;
2905
+ return null;
2906
+ }
2907
+ const id = String(active.providerId);
2908
+ this.projection = { id, identity: operation.identity };
2909
+ this.attach(id);
2910
+ return this.getSession();
2911
+ } finally {
2912
+ clearTimeout(timeout);
2913
+ if (registration) delete registration.expected;
2914
+ if (this.operation === operation) this.operation = null;
2915
+ }
2916
+ })();
2917
+ this.pending = task;
2918
+ try {
2919
+ return await task;
2920
+ } finally {
2921
+ if (this.pending === task) this.pending = null;
2922
+ }
2923
+ }
2924
+ getSession() {
2925
+ if (this.disposed || !this.client?.getActiveSession() || !this.projection) return null;
2926
+ return this.projection;
2927
+ }
2928
+ getProvider(id) {
2929
+ if (!this.getSession() || id && this.projection?.id !== id) throw disconnected();
2930
+ return this.client.getProvider();
2931
+ }
2932
+ /** A bare signature must not be attributed to an old, eventless primary party. */
2933
+ async validateIdentity(id, partyId, network) {
2934
+ const provider = this.getProvider(id);
2935
+ const revision = ++this.refreshRevision;
2936
+ this.identityRefreshing = true;
2937
+ let verified = false;
2938
+ try {
2939
+ const identity2 = await this.probe(provider, this.registrations.get(id));
2940
+ if (revision !== this.refreshRevision || this.getProvider(id) !== provider)
2941
+ throw disconnected();
2942
+ verified = true;
2943
+ this.projection = { id, identity: identity2 };
2944
+ if (identity2.account.partyId !== partyId || core.detectNetworkMismatch(network, identity2.network)) {
2945
+ this.changed(id, identity2);
2946
+ throw new Error("Wallet identity changed during message signing");
2947
+ }
2948
+ } catch (error) {
2949
+ if (!verified && revision === this.refreshRevision) this.invalidate(id);
2950
+ throw error;
2951
+ } finally {
2952
+ if (revision === this.refreshRevision) this.identityRefreshing = false;
2953
+ }
2954
+ }
2955
+ async probe(provider, registration) {
2956
+ const abort = new AbortController();
2957
+ this.probes.add(abort);
2958
+ const timeout = setTimeout(() => abort.abort(), SILENT_PROBE_TIMEOUT_MS);
2959
+ try {
2960
+ return await readIdentity(provider, registration, abort.signal);
2961
+ } finally {
2962
+ clearTimeout(timeout);
2963
+ this.probes.delete(abort);
2964
+ }
2965
+ }
2966
+ detach() {
2967
+ ++this.refreshRevision;
2968
+ this.identityRefreshing = false;
2969
+ for (const probe of this.probes) probe.abort();
2970
+ this.probes.clear();
2971
+ this.unsubscribers.splice(0).forEach((unsubscribe) => {
2972
+ try {
2973
+ unsubscribe();
2974
+ } catch {
2975
+ }
2976
+ });
2977
+ }
2978
+ attach(id) {
2979
+ const provider = this.getProvider(id);
2980
+ const update = (payload) => {
2981
+ const status = payload;
2982
+ if (status?.connection?.isConnected === false || status?.isConnected === false || Array.isArray(payload) && payload.length === 0) {
2983
+ this.invalidate(id);
2984
+ return;
2985
+ }
2986
+ const revision = ++this.refreshRevision;
2987
+ this.identityRefreshing = true;
2988
+ const registration = this.registrations.get(id);
2989
+ void this.probe(provider, registration).then(
2990
+ (identity2) => {
2991
+ if (revision !== this.refreshRevision || this.projection?.id !== id || this.disposed)
2992
+ return;
2993
+ this.identityRefreshing = false;
2994
+ this.projection = { id, identity: identity2 };
2995
+ this.changed(id, identity2);
2996
+ },
2997
+ () => {
2998
+ if (revision === this.refreshRevision) this.invalidate(id);
2999
+ }
3000
+ );
3001
+ };
3002
+ for (const event of ["accountsChanged", "statusChanged"]) {
3003
+ provider.on(event, update);
3004
+ this.unsubscribers.push(() => provider.removeListener(event, update));
3005
+ }
3006
+ }
3007
+ invalidate(id) {
3008
+ if (this.projection?.id !== id) return;
3009
+ this.detach();
3010
+ this.projection = null;
3011
+ teardown(this.client?.getActiveSession()?.adapter);
3012
+ this.client?.destroy();
3013
+ this.client = null;
3014
+ this.initialization = null;
3015
+ this.changed(id, null);
3016
+ }
3017
+ /** Local transport cleanup when switching to a proprietary integration. */
3018
+ release() {
3019
+ this.assertAvailable();
3020
+ const id = this.projection?.id;
3021
+ this.detach();
3022
+ this.projection = null;
3023
+ teardown(this.client?.getActiveSession()?.adapter);
3024
+ this.client?.destroy();
3025
+ this.client = null;
3026
+ this.initialization = null;
3027
+ if (id) this.changed(id, null);
3028
+ }
3029
+ disconnect() {
3030
+ if (this.closing) return this.closing;
3031
+ this.operation?.abort.abort();
3032
+ const task = (async () => {
3033
+ await this.pending?.catch(() => {
3034
+ });
3035
+ this.detach();
3036
+ const id = this.projection?.id;
3037
+ this.projection = null;
3038
+ const operation = { abort: new AbortController() };
3039
+ this.operation = operation;
3040
+ const timeout = setTimeout(() => operation.abort.abort(), SILENT_PROBE_TIMEOUT_MS);
3041
+ try {
3042
+ await this.client?.disconnect();
3043
+ } finally {
3044
+ clearTimeout(timeout);
3045
+ if (this.client?.getActiveSession()) {
3046
+ this.client.destroy();
3047
+ this.client = null;
3048
+ this.initialization = null;
3049
+ }
3050
+ this.operation = null;
3051
+ if (id) this.changed(id, null);
3052
+ }
3053
+ })();
3054
+ this.closing = task;
3055
+ void task.then(
3056
+ () => {
3057
+ if (this.closing === task) this.closing = null;
3058
+ },
3059
+ () => {
3060
+ if (this.closing === task) this.closing = null;
3061
+ }
3062
+ );
3063
+ return task;
3064
+ }
3065
+ destroy() {
3066
+ if (this.disposed) return;
3067
+ this.disposed = true;
3068
+ this.operation?.abort.abort();
3069
+ this.detach();
3070
+ this.projection = null;
3071
+ teardown(this.client?.getActiveSession()?.adapter);
3072
+ if (!this.client?.getActiveSession() && this.operation?.id)
3073
+ teardown(this.registrations.get(this.operation.id)?.source);
3074
+ this.client?.destroy();
3075
+ this.client = null;
3076
+ }
3077
+ };
3078
+
3079
+ // src/client.ts
3080
+ var PartyLayerClient = class extends PartyLayerClientBase {
3081
+ constructor(config) {
3082
+ super(config, {
3083
+ getBuiltinAdapters,
3084
+ loadDefaultWallet: (id, _sharedConfig, origin) => loadDefaultWallet(id, config, origin),
3085
+ createOwner: (onIdentityChanged) => new NativeConnectionOwner(onIdentityChanged),
3086
+ browserDiscovery: true
3087
+ });
3088
+ }
3089
+ };
3070
3090
  function createPartyLayer(config) {
3071
3091
  return new PartyLayerClient(config);
3072
3092
  }