@partylayer/sdk 0.22.0 → 0.22.2

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) {
@@ -1669,8 +1211,62 @@ function matchKnownByIdentity(providerId, base) {
1669
1211
  return providerId === String(w.walletId) || !!k && (providerId === k || providerId.startsWith(`${k}.`));
1670
1212
  });
1671
1213
  }
1214
+ function matchDiscoveredWallet(id, wallets) {
1215
+ return core.findMatchingWalletInfo(
1216
+ { provider: { id } },
1217
+ wallets
1218
+ ) ?? matchKnownByIdentity(id, wallets);
1219
+ }
1672
1220
  var DEFAULT_CONNECT_TIMEOUT_MS = 12e4;
1673
- var PartyLayerClient = class {
1221
+ var PartyLayerClientBase = class {
1222
+ constructor(config, runtime = {}) {
1223
+ this.runtime = runtime;
1224
+ this.config = config;
1225
+ if (config.app.origin) {
1226
+ this.origin = config.app.origin;
1227
+ } else if (typeof window !== "undefined") {
1228
+ this.origin = window.location.origin;
1229
+ } else {
1230
+ this.origin = "unknown";
1231
+ }
1232
+ this.logger = config.logger || new DefaultLogger();
1233
+ this.logLevel = config.logLevel ?? "info";
1234
+ this.crypto = config.crypto || new DefaultCrypto();
1235
+ this.storage = config.storage || new DefaultStorage();
1236
+ if (typeof window !== "undefined" && runtime.createOwner) {
1237
+ this.nativeOwner = runtime.createOwner((id, identity2) => this.onNativeIdentityChanged(id, identity2));
1238
+ }
1239
+ const telemetryAdapter = createTelemetryAdapter(config.telemetry);
1240
+ this.telemetry = telemetryAdapter || new DefaultTelemetry();
1241
+ const defaults = config.adapters ?? runtime.getBuiltinAdapters?.() ?? [];
1242
+ const adaptersToRegister = [...defaults, ...config.additionalAdapters ?? []];
1243
+ for (const adapterOrClass of adaptersToRegister) {
1244
+ let adapter;
1245
+ if (typeof adapterOrClass === "function") {
1246
+ adapter = new adapterOrClass();
1247
+ } else if (core.isOfficialAdapterFactory(adapterOrClass)) {
1248
+ adapter = new GenericDiscoveryAdapter({ factory: adapterOrClass });
1249
+ } else if (core.isOfficialProviderAdapter(adapterOrClass)) {
1250
+ adapter = new GenericDiscoveryAdapter({ official: adapterOrClass });
1251
+ } else {
1252
+ adapter = adapterOrClass;
1253
+ }
1254
+ this.registerAdapter(adapter);
1255
+ this.log("debug", "adapter:registered", "Registered wallet adapter", {
1256
+ walletId: adapter.walletId,
1257
+ name: adapter.name,
1258
+ capabilities: adapter.getCapabilities()
1259
+ });
1260
+ }
1261
+ this.registryClient = new registryClient.RegistryClient({
1262
+ registryUrl: config.registryUrl || DEFAULT_REGISTRY_URL,
1263
+ channel: config.channel || "stable",
1264
+ registryPublicKeys: config.registryPublicKeys,
1265
+ storage: this.storage
1266
+ });
1267
+ this.updateRegistryStatus();
1268
+ if (!config.deferInitialization) this.initialize();
1269
+ }
1674
1270
  config;
1675
1271
  adapters = /* @__PURE__ */ new Map();
1676
1272
  destroyed = false;
@@ -1720,53 +1316,6 @@ var PartyLayerClient = class {
1720
1316
  origin;
1721
1317
  nativeOwner;
1722
1318
  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
1319
  /** Start browser discovery/restoration once; safe for framework effect replay. */
1771
1320
  initialize() {
1772
1321
  if (this.initialized || this.destroyed) return;
@@ -1895,7 +1444,7 @@ var PartyLayerClient = class {
1895
1444
  }
1896
1445
  /** Resolve only reviewed default SDKs present in the active registry. */
1897
1446
  async ensureDefaultWallets() {
1898
- if (this.config.adapters !== void 0) return;
1447
+ if (this.config.adapters !== void 0 || !this.runtime.loadDefaultWallet) return;
1899
1448
  let registry;
1900
1449
  try {
1901
1450
  registry = await this.registryClient.getRegistry();
@@ -1904,12 +1453,13 @@ var PartyLayerClient = class {
1904
1453
  }
1905
1454
  await Promise.all(registry.wallets.map(async (entry) => {
1906
1455
  const id = core.toWalletId(entry.id);
1907
- if (this.adapters.has(id) || !entry.supportedNetworks.includes(this.config.network) || entry.adapter?.transport === "discovery-adapter" && !entry.adapter.networkHosts?.[this.config.network]) return;
1456
+ const network = this.config.network;
1457
+ if (this.adapters.has(id) || !entry.supportedNetworks.includes(network) && !entry.additionalNetworks?.includes(network) || entry.adapter?.transport === "discovery-adapter" && !entry.adapter.networkHosts?.[network]) return;
1908
1458
  let pending = this.defaultLoads.get(entry.id);
1909
1459
  if (!pending) {
1910
1460
  pending = (async () => {
1911
1461
  try {
1912
- const entryAdapter = await loadDefaultWallet(entry.id, this.config, this.origin);
1462
+ const entryAdapter = await this.runtime.loadDefaultWallet(entry.id, this.config, this.origin);
1913
1463
  if (!entryAdapter || this.destroyed) return;
1914
1464
  const adapter = core.isOfficialAdapterFactory(entryAdapter) ? new GenericDiscoveryAdapter({
1915
1465
  factory: entryAdapter,
@@ -1917,8 +1467,9 @@ var PartyLayerClient = class {
1917
1467
  networkHosts: entry.adapter?.networkHosts,
1918
1468
  capabilities: entry.capabilities
1919
1469
  }) : entryAdapter;
1470
+ if (!this.registryNetworkSupported(entry, adapter)) return;
1920
1471
  if (typeof window !== "undefined" && adapter instanceof GenericDiscoveryAdapter) {
1921
- adapter.resolveOfficial(this.config.network);
1472
+ adapter.resolveOfficial(network);
1922
1473
  }
1923
1474
  this.registerAdapter(adapter);
1924
1475
  this.registryDefaultIds.add(id);
@@ -1935,6 +1486,10 @@ var PartyLayerClient = class {
1935
1486
  await pending;
1936
1487
  }));
1937
1488
  }
1489
+ registryNetworkSupported(entry, adapter) {
1490
+ const network = this.config.network;
1491
+ return entry.supportedNetworks.includes(network) || entry.additionalNetworks?.includes(network) === true && adapter?.supportsNetwork?.(network) === true;
1492
+ }
1938
1493
  /**
1939
1494
  * Hide registry entries whose wallet needs an app-registered adapter that is
1940
1495
  * NOT registered. This is the library default (RainbowKit-style): never show a
@@ -1956,18 +1511,23 @@ var PartyLayerClient = class {
1956
1511
  * adapters-only) or every non-announce entry is registered.
1957
1512
  */
1958
1513
  async gateUnconnectableEntries(wallets) {
1514
+ if (!this.runtime.browserDiscovery) wallets = wallets.filter((wallet) => this.adapters.has(wallet.walletId));
1959
1515
  let hidden = null;
1960
1516
  const announceCapabilities = /* @__PURE__ */ new Map();
1517
+ const additionalNetworks = /* @__PURE__ */ new Map();
1961
1518
  try {
1962
1519
  const registry = await this.registryClient.getRegistry();
1963
1520
  for (const entry of registry.wallets) {
1964
- if (entry.adapter?.transport === "announce") {
1521
+ const adapter = this.adapters.get(core.toWalletId(entry.id));
1522
+ if (entry.additionalNetworks && adapter) {
1523
+ additionalNetworks.set(entry.id, entry.additionalNetworks.filter((network) => adapter.supportsNetwork?.(network) === true));
1524
+ }
1525
+ if (entry.adapter?.transport === "announce" && this.runtime.browserDiscovery) {
1965
1526
  announceCapabilities.set(entry.id, getAnnounceCapabilities(deriveAnnounceConfig(entry)));
1966
1527
  continue;
1967
1528
  }
1968
- const walletId = core.toWalletId(entry.id);
1969
- if (!this.adapters.has(walletId)) {
1970
- (hidden ??= /* @__PURE__ */ new Set()).add(String(walletId));
1529
+ if (!adapter) {
1530
+ (hidden ??= /* @__PURE__ */ new Set()).add(entry.id);
1971
1531
  }
1972
1532
  }
1973
1533
  } catch {
@@ -1975,7 +1535,13 @@ var PartyLayerClient = class {
1975
1535
  }
1976
1536
  return wallets.filter((w) => !hidden?.has(String(w.walletId))).map((w) => {
1977
1537
  const capabilities = announceCapabilities.get(String(w.walletId));
1978
- return capabilities ? { ...w, capabilities } : w;
1538
+ const networks = additionalNetworks.get(String(w.walletId));
1539
+ if (!capabilities && !networks?.length) return w;
1540
+ return {
1541
+ ...w,
1542
+ capabilities: capabilities ?? w.capabilities,
1543
+ networks: networks?.length ? [.../* @__PURE__ */ new Set([...w.networks, ...networks])] : w.networks
1544
+ };
1979
1545
  });
1980
1546
  }
1981
1547
  /**
@@ -2004,7 +1570,7 @@ var PartyLayerClient = class {
2004
1570
  * ON in the browser and OFF under SSR (no `window`). Canonical: provider.md.
2005
1571
  */
2006
1572
  get announceEnabled() {
2007
- if (typeof window === "undefined") return false;
1573
+ if (typeof window === "undefined" || !this.runtime.browserDiscovery) return false;
2008
1574
  return this.config.discovery?.announce ?? true;
2009
1575
  }
2010
1576
  /**
@@ -2070,17 +1636,26 @@ var PartyLayerClient = class {
2070
1636
  createProvider: (a) => this.announceChannel(a.target ?? a.id)
2071
1637
  });
2072
1638
  const byId = /* @__PURE__ */ new Map();
2073
- for (const d of snapshot) byId.set(d.id, d);
2074
- for (const d of this.announceRegistry.values())
2075
- if (!byId.has(d.id)) byId.set(d.id, d);
1639
+ const matchedAnnouncements = /* @__PURE__ */ new Set();
1640
+ for (const d of snapshot) {
1641
+ const announced = this.announceRegistry.get(d.id);
1642
+ if (d.announcementId) matchedAnnouncements.add(d.announcementId);
1643
+ byId.set(d.id, {
1644
+ ...d,
1645
+ name: d.name ?? announced?.name,
1646
+ icon: d.icon ?? announced?.icon
1647
+ });
1648
+ }
1649
+ for (const announced of this.announceRegistry.values()) {
1650
+ if (!byId.has(announced.id) && !matchedAnnouncements.has(announced.id)) {
1651
+ byId.set(announced.id, announced);
1652
+ }
1653
+ }
2076
1654
  const discovered = [...byId.values()];
2077
1655
  const entries = [];
2078
1656
  for (const d of discovered) {
2079
1657
  if (d.identityResolved === false) continue;
2080
- const known = core.findMatchingWalletInfo(
2081
- { provider: { id: d.id } },
2082
- base
2083
- ) ?? matchKnownByIdentity(d.id, base);
1658
+ const known = matchDiscoveredWallet(d.id, base) ?? (d.announcementId ? matchDiscoveredWallet(d.announcementId, base) : void 0);
2084
1659
  if (known) {
2085
1660
  if (this.adapters.has(known.walletId)) continue;
2086
1661
  try {
@@ -2144,7 +1719,7 @@ var PartyLayerClient = class {
2144
1719
  adapter: { packageName: "announced", versionRange: "*" },
2145
1720
  docs: [],
2146
1721
  networks: [this.config.network || "devnet"],
2147
- channel: "stable"
1722
+ channel: this.config.channel ?? "stable"
2148
1723
  });
2149
1724
  }
2150
1725
  this.announceEntriesCache = entries;
@@ -2240,7 +1815,7 @@ var PartyLayerClient = class {
2240
1815
  const nativeAdapter = this.adapters.get(options.walletId);
2241
1816
  if (nativeAdapter) {
2242
1817
  const entry = await this.registryClient.getWalletEntry(String(options.walletId)).catch(() => null);
2243
- if (entry?.supportedNetworks?.length && !entry.supportedNetworks.includes(this.config.network)) {
1818
+ if (entry?.supportedNetworks?.length && !this.registryNetworkSupported(entry, nativeAdapter)) {
2244
1819
  throw new core.WalletNotFoundError(`${String(options.walletId)} is unavailable on ${this.config.network}`);
2245
1820
  }
2246
1821
  isNativeWallet = true;
@@ -2265,13 +1840,20 @@ var PartyLayerClient = class {
2265
1840
  }
2266
1841
  }
2267
1842
  } else if (availableWallets.length === 0) {
2268
- throw new core.WalletNotFoundError("No wallets available");
1843
+ throw new core.WalletNotFoundError(this.runtime.noWalletsMessage ?? "No wallets available");
2269
1844
  } else {
2270
1845
  selectedWallet = availableWallets[0];
2271
1846
  }
2272
1847
  const adapter = this.adapters.get(selectedWallet.walletId);
2273
1848
  if (!adapter) {
2274
- throw new core.WalletNotFoundError(String(selectedWallet.walletId));
1849
+ const walletId = String(selectedWallet.walletId);
1850
+ if (this.announceEnabled) {
1851
+ const entry = await this.registryClient.getWalletEntry(walletId).catch(() => null);
1852
+ if (entry?.adapter?.transport === "announce") {
1853
+ throw new core.WalletNotInstalledError(walletId);
1854
+ }
1855
+ }
1856
+ throw new core.WalletNotFoundError(walletId);
2275
1857
  }
2276
1858
  if (!isNativeWallet) {
2277
1859
  try {
@@ -2313,8 +1895,8 @@ var PartyLayerClient = class {
2313
1895
  return { selectedWallet, adapter, ctx, isNativeWallet };
2314
1896
  }
2315
1897
  /**
2316
- * Invoke `adapter.connect()` (its FIRST statement — no await precedes it) and
2317
- * build / persist / emit the session. Separated from plan resolution so the
1898
+ * Generate secure entropy, invoke `adapter.connect()` without awaiting the
1899
+ * platform RNG path, then build / persist / emit the session. Separated from plan resolution so the
2318
1900
  * popup-safe fast-path can call it gesture-synchronously.
2319
1901
  */
2320
1902
  async completeConnect(plan, options, correlationId = newCorrelationId(), attempt) {
@@ -2324,6 +1906,9 @@ var PartyLayerClient = class {
2324
1906
  if (attempt === void 0) ++this.sessionRevision;
2325
1907
  if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
2326
1908
  const { selectedWallet, adapter, ctx } = plan;
1909
+ const entropy = createSecureSessionId(this.crypto);
1910
+ const sessionId = typeof entropy === "string" ? entropy : await entropy;
1911
+ if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
2327
1912
  if (!nativeOwnerBindings.has(adapter) && this.nativeOwner?.getSession()) this.nativeOwner.release();
2328
1913
  const timeoutMs = options?.timeoutMs || DEFAULT_CONNECT_TIMEOUT_MS;
2329
1914
  const abort = new AbortController();
@@ -2349,7 +1934,7 @@ var PartyLayerClient = class {
2349
1934
  }
2350
1935
  if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
2351
1936
  const session = {
2352
- sessionId: core.toSessionId(`session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`),
1937
+ sessionId,
2353
1938
  walletId: selectedWallet.walletId,
2354
1939
  partyId: result.partyId,
2355
1940
  // The wallet's reported network (adapters that read the live wallet —
@@ -2968,6 +2553,8 @@ var PartyLayerClient = class {
2968
2553
  this.activeSessionNeedsProbe = true;
2969
2554
  return session;
2970
2555
  } catch (err) {
2556
+ if (!current()) return this.activeSession;
2557
+ await this.removeSession();
2971
2558
  this.log("warn", "session:restore_failed", "Failed to restore session", {
2972
2559
  error: err instanceof Error ? err.message : String(err)
2973
2560
  }, correlationId);
@@ -3067,6 +2654,477 @@ var PartyLayerClient = class {
3067
2654
  }
3068
2655
  }
3069
2656
  };
2657
+ function getBuiltinAdapters() {
2658
+ return [
2659
+ new adapterLoop.LoopAdapter(),
2660
+ // 5N Loop - QR code / popup
2661
+ new adapterCantor8.Cantor8Adapter(),
2662
+ // Cantor8 - deep link transport
2663
+ new adapterNightly.NightlyAdapter()
2664
+ // Nightly - multichain wallet (injected)
2665
+ // Console is served via the generic CIP-0103 announce path (registry
2666
+ // transport:'announce') — no longer in defaults; ConsoleAdapter stays
2667
+ // exported below for opt-in manual/bespoke use.
2668
+ // Send is served via the generic CIP-0103 announce path (registry
2669
+ // transport:'announce') — no longer in defaults; SendAdapter stays exported
2670
+ // below for opt-in manual/bespoke use.
2671
+ ];
2672
+ }
2673
+ var loaders = {
2674
+ walley: async () => {
2675
+ const { WalleyAdapter } = await import('@k2flabs/walley-dapp-sdk');
2676
+ return { providerId: "walley", create: (host) => new WalleyAdapter({ host }) };
2677
+ },
2678
+ cauri: async () => {
2679
+ const { cauriAdapterFactory } = await import('@lithiumdigital/cauri-dapp-sdk');
2680
+ return cauriAdapterFactory;
2681
+ },
2682
+ oneswap: async (network) => {
2683
+ const { createOneSwapHostedAdapter } = await import('#partylayer-hosted-wallet-profiles');
2684
+ return {
2685
+ providerId: "oneswap",
2686
+ create: (host) => createOneSwapHostedAdapter({
2687
+ walletUrl: host,
2688
+ networkId: core.toCAIP2Network(network).networkId
2689
+ })
2690
+ };
2691
+ },
2692
+ vala: async () => {
2693
+ const { valaAdapterFactory } = await import('@vala-wallet/dapp-sdk');
2694
+ return valaAdapterFactory;
2695
+ }
2696
+ };
2697
+ async function loadDefaultWallet(id, config, origin) {
2698
+ if (id === "walletconnect" && config.walletConnect?.projectId.trim()) {
2699
+ const { WalletConnectAdapter } = await import('@partylayer/adapter-walletconnect');
2700
+ return new WalletConnectAdapter({
2701
+ ...config.walletConnect,
2702
+ metadata: config.walletConnect.metadata ?? {
2703
+ name: config.app.name,
2704
+ description: config.app.name,
2705
+ url: origin === "unknown" ? "" : origin,
2706
+ icons: []
2707
+ }
2708
+ });
2709
+ }
2710
+ if (id === "bron" && config.bron) {
2711
+ const { BronAdapter: BronAdapter2 } = await import('@partylayer/adapter-bron');
2712
+ return new BronAdapter2(config.bron);
2713
+ }
2714
+ return Object.prototype.hasOwnProperty.call(loaders, id) ? loaders[id](config.network) : void 0;
2715
+ }
2716
+ var SILENT_PROBE_TIMEOUT_MS = 1e4;
2717
+ function disconnected() {
2718
+ return new Error("Native wallet connection is no longer active");
2719
+ }
2720
+ function teardown(source) {
2721
+ try {
2722
+ source?.teardown?.();
2723
+ } catch {
2724
+ }
2725
+ }
2726
+ function abortable(promise, signal) {
2727
+ return new Promise((resolve, reject) => {
2728
+ const abort = () => reject(disconnected());
2729
+ if (signal.aborted) {
2730
+ reject(disconnected());
2731
+ return;
2732
+ }
2733
+ signal.addEventListener("abort", abort, { once: true });
2734
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
2735
+ });
2736
+ }
2737
+ async function readIdentity(provider, registration, signal) {
2738
+ const account = await abortable(
2739
+ provider.request({ method: "getPrimaryAccount" }),
2740
+ signal
2741
+ );
2742
+ assertPrimaryParty(account);
2743
+ let status;
2744
+ try {
2745
+ status = await abortable(provider.request({ method: "status" }), signal);
2746
+ } catch (error) {
2747
+ if (signal.aborted) throw error;
2748
+ }
2749
+ if (status?.isConnected === false || status?.connection?.isConnected === false)
2750
+ throw disconnected();
2751
+ const network = [status?.network?.networkId, account.networkId, registration.network].find(
2752
+ (value) => typeof value === "string" && core.isRecognizedNetwork(value)
2753
+ ) ?? registration.network;
2754
+ if (registration.expected && (account.partyId !== registration.expected.partyId || core.detectNetworkMismatch(registration.expected.network, network)))
2755
+ throw disconnected();
2756
+ if (signal.aborted) throw disconnected();
2757
+ return { account, network, status };
2758
+ }
2759
+ var NativeConnectionOwner = class {
2760
+ constructor(changed = () => {
2761
+ }) {
2762
+ this.changed = changed;
2763
+ }
2764
+ client = null;
2765
+ initialization = null;
2766
+ registrations = /* @__PURE__ */ new Map();
2767
+ operation = null;
2768
+ pending = null;
2769
+ closing = null;
2770
+ projection = null;
2771
+ unsubscribers = [];
2772
+ disposed = false;
2773
+ refreshRevision = 0;
2774
+ identityRefreshing = false;
2775
+ probes = /* @__PURE__ */ new Set();
2776
+ get busy() {
2777
+ return this.operation !== null || this.closing !== null;
2778
+ }
2779
+ assertAvailable() {
2780
+ if (this.disposed) throw disconnected();
2781
+ if (this.busy) throw new Error("A native wallet operation is already in progress");
2782
+ }
2783
+ /** Run during picker preparation, never between a click and provider.connect. */
2784
+ async prepare(id, source, network) {
2785
+ if (this.disposed) throw disconnected();
2786
+ this.registrations.set(id, { id, source, network });
2787
+ if (!this.initialization) {
2788
+ this.initialization = (async () => {
2789
+ const { DiscoveryClient } = await import('@canton-network/core-wallet-discovery');
2790
+ const client = await DiscoveryClient.create({ adapters: [] });
2791
+ if (this.disposed) {
2792
+ client.destroy();
2793
+ return;
2794
+ }
2795
+ this.client = client;
2796
+ })();
2797
+ }
2798
+ await this.initialization;
2799
+ if (this.disposed || !this.client) throw disconnected();
2800
+ for (const registration of this.registrations.values())
2801
+ this.client.registerAdapter(this.wrap(registration));
2802
+ }
2803
+ wrap(registration) {
2804
+ const source = registration.source;
2805
+ return {
2806
+ providerId: registration.id,
2807
+ name: source.name,
2808
+ type: source.type === "desktop" || source.type === "mobile" || source.type === "remote" ? source.type : "browser",
2809
+ icon: source.icon,
2810
+ getInfo: () => ({
2811
+ providerId: registration.id,
2812
+ name: source.name,
2813
+ type: "browser",
2814
+ icon: source.icon
2815
+ }),
2816
+ detect: () => source.detect(),
2817
+ provider: () => this.guard(source.provider(), registration),
2818
+ teardown: () => teardown(source),
2819
+ restore: async () => {
2820
+ const operation = this.operation;
2821
+ if (!operation) throw disconnected();
2822
+ try {
2823
+ const raw = source.restore ? await abortable(source.restore(), operation.abort.signal) : source.provider();
2824
+ if (!raw) return null;
2825
+ const provider = raw;
2826
+ operation.identity = await readIdentity(provider, registration, operation.abort.signal);
2827
+ return this.guard(provider, registration);
2828
+ } catch (error) {
2829
+ teardown(source);
2830
+ throw error;
2831
+ }
2832
+ }
2833
+ };
2834
+ }
2835
+ guard(raw, registration) {
2836
+ const provider = {
2837
+ request: async (args) => {
2838
+ if (this.disposed) throw disconnected();
2839
+ if (args.method !== "connect") {
2840
+ if (this.client?.getActiveSession()?.provider !== provider) throw disconnected();
2841
+ if (!this.projection && args.method !== "disconnect") throw disconnected();
2842
+ if (this.identityRefreshing && ![
2843
+ "status",
2844
+ "getPrimaryAccount",
2845
+ "listAccounts",
2846
+ "getActiveNetwork",
2847
+ "isConnected"
2848
+ ].includes(args.method)) {
2849
+ throw new Error("Native wallet identity is being refreshed");
2850
+ }
2851
+ const result = await (args.method === "disconnect" && this.operation ? abortable(raw.request(args), this.operation.abort.signal) : raw.request(args));
2852
+ if (args.method === "status") {
2853
+ const status = result;
2854
+ if (status?.isConnected === false || status?.connection?.isConnected === false) {
2855
+ this.invalidate(registration.id);
2856
+ }
2857
+ }
2858
+ return result;
2859
+ }
2860
+ const operation = this.operation;
2861
+ if (!operation || operation.abort.signal.aborted) throw disconnected();
2862
+ const response = await abortable(raw.request(args), operation.abort.signal);
2863
+ assertConnectionAccepted(response);
2864
+ operation.identity = await readIdentity(raw, registration, operation.abort.signal);
2865
+ return response;
2866
+ },
2867
+ on: (event, listener) => {
2868
+ raw.on(event, listener);
2869
+ return provider;
2870
+ },
2871
+ emit: (event, ...args) => raw.emit(event, ...args),
2872
+ removeListener: (event, listener) => {
2873
+ raw.removeListener(event, listener);
2874
+ return provider;
2875
+ }
2876
+ };
2877
+ return provider;
2878
+ }
2879
+ /** No await precedes the official client's connect call. */
2880
+ connect(id, signal) {
2881
+ this.assertAvailable();
2882
+ if (!this.client || !this.registrations.has(id))
2883
+ return Promise.reject(new Error("Native wallet was not prepared"));
2884
+ const operation = { abort: new AbortController(), id };
2885
+ this.operation = operation;
2886
+ this.detach();
2887
+ const previous = this.client.getActiveSession();
2888
+ teardown(previous?.adapter);
2889
+ const previousId = this.projection?.id;
2890
+ this.projection = null;
2891
+ if (previousId) this.changed(previousId, null);
2892
+ const abort = () => operation.abort.abort();
2893
+ if (signal?.aborted) abort();
2894
+ signal?.addEventListener("abort", abort, { once: true });
2895
+ const task = (async () => {
2896
+ try {
2897
+ await this.client.connect(id);
2898
+ if (operation.abort.signal.aborted || this.disposed || !operation.identity)
2899
+ throw disconnected();
2900
+ this.projection = { id, identity: operation.identity };
2901
+ this.attach(id);
2902
+ return operation.identity;
2903
+ } catch (error) {
2904
+ this.client?.destroy();
2905
+ this.client = null;
2906
+ this.initialization = null;
2907
+ teardown(this.registrations.get(id)?.source);
2908
+ throw error;
2909
+ } finally {
2910
+ signal?.removeEventListener("abort", abort);
2911
+ if (this.operation === operation) this.operation = null;
2912
+ }
2913
+ })();
2914
+ this.pending = task;
2915
+ void task.then(
2916
+ () => {
2917
+ if (this.pending === task) this.pending = null;
2918
+ },
2919
+ () => {
2920
+ if (this.pending === task) this.pending = null;
2921
+ }
2922
+ );
2923
+ return task;
2924
+ }
2925
+ async restore(expected) {
2926
+ if (!this.client || this.projection || this.busy || this.disposed) return this.getSession();
2927
+ const registration = expected && this.registrations.get(expected.id);
2928
+ if (registration) registration.expected = expected;
2929
+ const operation = { abort: new AbortController() };
2930
+ this.operation = operation;
2931
+ const timeout = setTimeout(() => operation.abort.abort(), SILENT_PROBE_TIMEOUT_MS);
2932
+ const task = (async () => {
2933
+ try {
2934
+ await this.client.restorePersistedSessionIfNeeded();
2935
+ const active = this.client?.getActiveSession();
2936
+ if (!active || !operation.identity || operation.abort.signal.aborted || this.disposed)
2937
+ return null;
2938
+ if (expected && active.providerId !== expected.id) {
2939
+ teardown(active.adapter);
2940
+ this.client.destroy();
2941
+ this.client = null;
2942
+ this.initialization = null;
2943
+ return null;
2944
+ }
2945
+ const id = String(active.providerId);
2946
+ this.projection = { id, identity: operation.identity };
2947
+ this.attach(id);
2948
+ return this.getSession();
2949
+ } finally {
2950
+ clearTimeout(timeout);
2951
+ if (registration) delete registration.expected;
2952
+ if (this.operation === operation) this.operation = null;
2953
+ }
2954
+ })();
2955
+ this.pending = task;
2956
+ try {
2957
+ return await task;
2958
+ } finally {
2959
+ if (this.pending === task) this.pending = null;
2960
+ }
2961
+ }
2962
+ getSession() {
2963
+ if (this.disposed || !this.client?.getActiveSession() || !this.projection) return null;
2964
+ return this.projection;
2965
+ }
2966
+ getProvider(id) {
2967
+ if (!this.getSession() || id && this.projection?.id !== id) throw disconnected();
2968
+ return this.client.getProvider();
2969
+ }
2970
+ /** A bare signature must not be attributed to an old, eventless primary party. */
2971
+ async validateIdentity(id, partyId, network) {
2972
+ const provider = this.getProvider(id);
2973
+ const revision = ++this.refreshRevision;
2974
+ this.identityRefreshing = true;
2975
+ let verified = false;
2976
+ try {
2977
+ const identity2 = await this.probe(provider, this.registrations.get(id));
2978
+ if (revision !== this.refreshRevision || this.getProvider(id) !== provider)
2979
+ throw disconnected();
2980
+ verified = true;
2981
+ this.projection = { id, identity: identity2 };
2982
+ if (identity2.account.partyId !== partyId || core.detectNetworkMismatch(network, identity2.network)) {
2983
+ this.changed(id, identity2);
2984
+ throw new Error("Wallet identity changed during message signing");
2985
+ }
2986
+ } catch (error) {
2987
+ if (!verified && revision === this.refreshRevision) this.invalidate(id);
2988
+ throw error;
2989
+ } finally {
2990
+ if (revision === this.refreshRevision) this.identityRefreshing = false;
2991
+ }
2992
+ }
2993
+ async probe(provider, registration) {
2994
+ const abort = new AbortController();
2995
+ this.probes.add(abort);
2996
+ const timeout = setTimeout(() => abort.abort(), SILENT_PROBE_TIMEOUT_MS);
2997
+ try {
2998
+ return await readIdentity(provider, registration, abort.signal);
2999
+ } finally {
3000
+ clearTimeout(timeout);
3001
+ this.probes.delete(abort);
3002
+ }
3003
+ }
3004
+ detach() {
3005
+ ++this.refreshRevision;
3006
+ this.identityRefreshing = false;
3007
+ for (const probe of this.probes) probe.abort();
3008
+ this.probes.clear();
3009
+ this.unsubscribers.splice(0).forEach((unsubscribe) => {
3010
+ try {
3011
+ unsubscribe();
3012
+ } catch {
3013
+ }
3014
+ });
3015
+ }
3016
+ attach(id) {
3017
+ const provider = this.getProvider(id);
3018
+ const update = (payload) => {
3019
+ const status = payload;
3020
+ if (status?.connection?.isConnected === false || status?.isConnected === false || Array.isArray(payload) && payload.length === 0) {
3021
+ this.invalidate(id);
3022
+ return;
3023
+ }
3024
+ const revision = ++this.refreshRevision;
3025
+ this.identityRefreshing = true;
3026
+ const registration = this.registrations.get(id);
3027
+ void this.probe(provider, registration).then(
3028
+ (identity2) => {
3029
+ if (revision !== this.refreshRevision || this.projection?.id !== id || this.disposed)
3030
+ return;
3031
+ this.identityRefreshing = false;
3032
+ this.projection = { id, identity: identity2 };
3033
+ this.changed(id, identity2);
3034
+ },
3035
+ () => {
3036
+ if (revision === this.refreshRevision) this.invalidate(id);
3037
+ }
3038
+ );
3039
+ };
3040
+ for (const event of ["accountsChanged", "statusChanged"]) {
3041
+ provider.on(event, update);
3042
+ this.unsubscribers.push(() => provider.removeListener(event, update));
3043
+ }
3044
+ }
3045
+ invalidate(id) {
3046
+ if (this.projection?.id !== id) return;
3047
+ this.detach();
3048
+ this.projection = null;
3049
+ teardown(this.client?.getActiveSession()?.adapter);
3050
+ this.client?.destroy();
3051
+ this.client = null;
3052
+ this.initialization = null;
3053
+ this.changed(id, null);
3054
+ }
3055
+ /** Local transport cleanup when switching to a proprietary integration. */
3056
+ release() {
3057
+ this.assertAvailable();
3058
+ const id = this.projection?.id;
3059
+ this.detach();
3060
+ this.projection = null;
3061
+ teardown(this.client?.getActiveSession()?.adapter);
3062
+ this.client?.destroy();
3063
+ this.client = null;
3064
+ this.initialization = null;
3065
+ if (id) this.changed(id, null);
3066
+ }
3067
+ disconnect() {
3068
+ if (this.closing) return this.closing;
3069
+ this.operation?.abort.abort();
3070
+ const task = (async () => {
3071
+ await this.pending?.catch(() => {
3072
+ });
3073
+ this.detach();
3074
+ const id = this.projection?.id;
3075
+ this.projection = null;
3076
+ const operation = { abort: new AbortController() };
3077
+ this.operation = operation;
3078
+ const timeout = setTimeout(() => operation.abort.abort(), SILENT_PROBE_TIMEOUT_MS);
3079
+ try {
3080
+ await this.client?.disconnect();
3081
+ } finally {
3082
+ clearTimeout(timeout);
3083
+ if (this.client?.getActiveSession()) {
3084
+ this.client.destroy();
3085
+ this.client = null;
3086
+ this.initialization = null;
3087
+ }
3088
+ this.operation = null;
3089
+ if (id) this.changed(id, null);
3090
+ }
3091
+ })();
3092
+ this.closing = task;
3093
+ void task.then(
3094
+ () => {
3095
+ if (this.closing === task) this.closing = null;
3096
+ },
3097
+ () => {
3098
+ if (this.closing === task) this.closing = null;
3099
+ }
3100
+ );
3101
+ return task;
3102
+ }
3103
+ destroy() {
3104
+ if (this.disposed) return;
3105
+ this.disposed = true;
3106
+ this.operation?.abort.abort();
3107
+ this.detach();
3108
+ this.projection = null;
3109
+ teardown(this.client?.getActiveSession()?.adapter);
3110
+ if (!this.client?.getActiveSession() && this.operation?.id)
3111
+ teardown(this.registrations.get(this.operation.id)?.source);
3112
+ this.client?.destroy();
3113
+ this.client = null;
3114
+ }
3115
+ };
3116
+
3117
+ // src/client.ts
3118
+ var PartyLayerClient = class extends PartyLayerClientBase {
3119
+ constructor(config) {
3120
+ super(config, {
3121
+ getBuiltinAdapters,
3122
+ loadDefaultWallet: (id, _sharedConfig, origin) => loadDefaultWallet(id, config, origin),
3123
+ createOwner: (onIdentityChanged) => new NativeConnectionOwner(onIdentityChanged),
3124
+ browserDiscovery: true
3125
+ });
3126
+ }
3127
+ };
3070
3128
  function createPartyLayer(config) {
3071
3129
  return new PartyLayerClient(config);
3072
3130
  }