@partylayer/sdk 0.21.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 } };
@@ -1125,6 +684,12 @@ function createSessionProvider(options) {
1125
684
  const provider$1 = {
1126
685
  request: async (args) => {
1127
686
  try {
687
+ if (args === null || typeof args !== "object" || Array.isArray(args) || typeof args.method !== "string") {
688
+ throw new provider.ProviderRpcError("Request must be an object with a string method", provider.JSON_RPC_ERRORS.INVALID_REQUEST);
689
+ }
690
+ if (args.params !== void 0 && (args.params === null || typeof args.params !== "object")) {
691
+ throw new provider.ProviderRpcError("Request params must be an object or array", provider.JSON_RPC_ERRORS.INVALID_PARAMS);
692
+ }
1128
693
  if (disposed) throw new Error("PartyLayer client was destroyed");
1129
694
  if (args.method === "connect" || args.method === "disconnect" || args.method === "signMessage") {
1130
695
  return options.bridge.request(args);
@@ -1214,7 +779,7 @@ function createSessionProvider(options) {
1214
779
  };
1215
780
  }
1216
781
 
1217
- // src/config.ts
782
+ // src/config-base.ts
1218
783
  var DEFAULT_REGISTRY_URL = "https://registry.partylayer.xyz";
1219
784
 
1220
785
  // src/adapters.ts
@@ -1245,54 +810,36 @@ var DefaultCrypto = class {
1245
810
  );
1246
811
  }
1247
812
  async encrypt(data, key) {
1248
- if (typeof crypto === "undefined" || !crypto.subtle) {
1249
- return btoa(data);
1250
- }
1251
- try {
1252
- const cryptoKey = await this.getKey(key);
1253
- const iv = crypto.getRandomValues(new Uint8Array(12));
1254
- const encoder = new TextEncoder();
1255
- const encoded = encoder.encode(data);
1256
- const encrypted = await crypto.subtle.encrypt(
1257
- { name: "AES-GCM", iv },
1258
- cryptoKey,
1259
- encoded
1260
- );
1261
- const combined = new Uint8Array(iv.length + encrypted.byteLength);
1262
- combined.set(iv);
1263
- combined.set(new Uint8Array(encrypted), iv.length);
1264
- return btoa(String.fromCharCode(...combined));
1265
- } catch {
1266
- return btoa(data);
1267
- }
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));
1268
824
  }
1269
825
  async decrypt(encrypted, key) {
1270
- if (typeof crypto === "undefined" || !crypto.subtle) {
1271
- return atob(encrypted);
1272
- }
1273
- try {
1274
- const cryptoKey = await this.getKey(key);
1275
- const combined = Uint8Array.from(atob(encrypted), (c) => c.charCodeAt(0));
1276
- const iv = combined.slice(0, 12);
1277
- const data = combined.slice(12);
1278
- const decrypted = await crypto.subtle.decrypt(
1279
- { name: "AES-GCM", iv },
1280
- cryptoKey,
1281
- data
1282
- );
1283
- const decoder = new TextDecoder();
1284
- return decoder.decode(decrypted);
1285
- } catch {
1286
- return atob(encrypted);
1287
- }
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));
1288
840
  }
1289
841
  async generateKey() {
1290
- if (typeof crypto === "undefined" || !crypto.getRandomValues) {
1291
- return Math.random().toString(36).substring(2, 15);
1292
- }
1293
- const array = new Uint8Array(32);
1294
- crypto.getRandomValues(array);
1295
- 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("");
1296
843
  }
1297
844
  };
1298
845
  var DefaultStorage = class {
@@ -1353,22 +900,6 @@ var DefaultTelemetry = class {
1353
900
  error(_error, _properties) {
1354
901
  }
1355
902
  };
1356
- function getBuiltinAdapters() {
1357
- return [
1358
- new adapterLoop.LoopAdapter(),
1359
- // 5N Loop - QR code / popup
1360
- new adapterCantor8.Cantor8Adapter(),
1361
- // Cantor8 - deep link transport
1362
- new adapterNightly.NightlyAdapter()
1363
- // Nightly - multichain wallet (injected)
1364
- // Console is served via the generic CIP-0103 announce path (registry
1365
- // transport:'announce') — no longer in defaults; ConsoleAdapter stays
1366
- // exported below for opt-in manual/bespoke use.
1367
- // Send is served via the generic CIP-0103 announce path (registry
1368
- // transport:'announce') — no longer in defaults; SendAdapter stays exported
1369
- // below for opt-in manual/bespoke use.
1370
- ];
1371
- }
1372
903
  var SDK_VERSION = "0.3.0";
1373
904
  var MetricsTelemetryAdapter = class {
1374
905
  config;
@@ -1632,6 +1163,23 @@ function eventLogLevel(type) {
1632
1163
  return "info";
1633
1164
  }
1634
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
1635
1183
  var SESSION_STORAGE_KEY = "active_session";
1636
1184
  var WALLETS_CHANGED_DEBOUNCE_MS = 50;
1637
1185
  function deriveAnnounceConfig(entry) {
@@ -1664,7 +1212,55 @@ function matchKnownByIdentity(providerId, base) {
1664
1212
  });
1665
1213
  }
1666
1214
  var DEFAULT_CONNECT_TIMEOUT_MS = 12e4;
1667
- 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
+ }
1668
1264
  config;
1669
1265
  adapters = /* @__PURE__ */ new Map();
1670
1266
  destroyed = false;
@@ -1714,53 +1310,6 @@ var PartyLayerClient = class {
1714
1310
  origin;
1715
1311
  nativeOwner;
1716
1312
  sessionProvider;
1717
- constructor(config) {
1718
- this.config = config;
1719
- if (config.app.origin) {
1720
- this.origin = config.app.origin;
1721
- } else if (typeof window !== "undefined") {
1722
- this.origin = window.location.origin;
1723
- } else {
1724
- this.origin = "unknown";
1725
- }
1726
- this.logger = config.logger || new DefaultLogger();
1727
- this.logLevel = config.logLevel ?? "info";
1728
- this.crypto = config.crypto || new DefaultCrypto();
1729
- this.storage = config.storage || new DefaultStorage();
1730
- if (typeof window !== "undefined") {
1731
- this.nativeOwner = new NativeConnectionOwner((id, identity2) => this.onNativeIdentityChanged(id, identity2));
1732
- }
1733
- const telemetryAdapter = createTelemetryAdapter(config.telemetry);
1734
- this.telemetry = telemetryAdapter || new DefaultTelemetry();
1735
- const defaults = config.adapters ?? getBuiltinAdapters();
1736
- const adaptersToRegister = [...defaults, ...config.additionalAdapters ?? []];
1737
- for (const adapterOrClass of adaptersToRegister) {
1738
- let adapter;
1739
- if (typeof adapterOrClass === "function") {
1740
- adapter = new adapterOrClass();
1741
- } else if (core.isOfficialAdapterFactory(adapterOrClass)) {
1742
- adapter = new GenericDiscoveryAdapter({ factory: adapterOrClass });
1743
- } else if (core.isOfficialProviderAdapter(adapterOrClass)) {
1744
- adapter = new GenericDiscoveryAdapter({ official: adapterOrClass });
1745
- } else {
1746
- adapter = adapterOrClass;
1747
- }
1748
- this.registerAdapter(adapter);
1749
- this.log("debug", "adapter:registered", "Registered wallet adapter", {
1750
- walletId: adapter.walletId,
1751
- name: adapter.name,
1752
- capabilities: adapter.getCapabilities()
1753
- });
1754
- }
1755
- this.registryClient = new registryClient.RegistryClient({
1756
- registryUrl: config.registryUrl || DEFAULT_REGISTRY_URL,
1757
- channel: config.channel || "stable",
1758
- registryPublicKeys: config.registryPublicKeys,
1759
- storage: this.storage
1760
- });
1761
- this.updateRegistryStatus();
1762
- if (!config.deferInitialization) this.initialize();
1763
- }
1764
1313
  /** Start browser discovery/restoration once; safe for framework effect replay. */
1765
1314
  initialize() {
1766
1315
  if (this.initialized || this.destroyed) return;
@@ -1889,7 +1438,7 @@ var PartyLayerClient = class {
1889
1438
  }
1890
1439
  /** Resolve only reviewed default SDKs present in the active registry. */
1891
1440
  async ensureDefaultWallets() {
1892
- if (this.config.adapters !== void 0) return;
1441
+ if (this.config.adapters !== void 0 || !this.runtime.loadDefaultWallet) return;
1893
1442
  let registry;
1894
1443
  try {
1895
1444
  registry = await this.registryClient.getRegistry();
@@ -1903,7 +1452,7 @@ var PartyLayerClient = class {
1903
1452
  if (!pending) {
1904
1453
  pending = (async () => {
1905
1454
  try {
1906
- const entryAdapter = await loadDefaultWallet(entry.id, this.config, this.origin);
1455
+ const entryAdapter = await this.runtime.loadDefaultWallet(entry.id, this.config, this.origin);
1907
1456
  if (!entryAdapter || this.destroyed) return;
1908
1457
  const adapter = core.isOfficialAdapterFactory(entryAdapter) ? new GenericDiscoveryAdapter({
1909
1458
  factory: entryAdapter,
@@ -1950,12 +1499,13 @@ var PartyLayerClient = class {
1950
1499
  * adapters-only) or every non-announce entry is registered.
1951
1500
  */
1952
1501
  async gateUnconnectableEntries(wallets) {
1502
+ if (!this.runtime.browserDiscovery) return wallets.filter((wallet) => this.adapters.has(wallet.walletId));
1953
1503
  let hidden = null;
1954
1504
  const announceCapabilities = /* @__PURE__ */ new Map();
1955
1505
  try {
1956
1506
  const registry = await this.registryClient.getRegistry();
1957
1507
  for (const entry of registry.wallets) {
1958
- if (entry.adapter?.transport === "announce") {
1508
+ if (entry.adapter?.transport === "announce" && this.runtime.browserDiscovery) {
1959
1509
  announceCapabilities.set(entry.id, getAnnounceCapabilities(deriveAnnounceConfig(entry)));
1960
1510
  continue;
1961
1511
  }
@@ -1998,7 +1548,7 @@ var PartyLayerClient = class {
1998
1548
  * ON in the browser and OFF under SSR (no `window`). Canonical: provider.md.
1999
1549
  */
2000
1550
  get announceEnabled() {
2001
- if (typeof window === "undefined") return false;
1551
+ if (typeof window === "undefined" || !this.runtime.browserDiscovery) return false;
2002
1552
  return this.config.discovery?.announce ?? true;
2003
1553
  }
2004
1554
  /**
@@ -2259,7 +1809,7 @@ var PartyLayerClient = class {
2259
1809
  }
2260
1810
  }
2261
1811
  } else if (availableWallets.length === 0) {
2262
- throw new core.WalletNotFoundError("No wallets available");
1812
+ throw new core.WalletNotFoundError(this.runtime.noWalletsMessage ?? "No wallets available");
2263
1813
  } else {
2264
1814
  selectedWallet = availableWallets[0];
2265
1815
  }
@@ -2272,8 +1822,7 @@ var PartyLayerClient = class {
2272
1822
  const walletEntry = await this.registryClient.getWalletEntry(String(selectedWallet.walletId));
2273
1823
  if (walletEntry.originAllowlist && walletEntry.originAllowlist.length > 0) {
2274
1824
  if (!walletEntry.originAllowlist.includes(this.origin)) {
2275
- const { OriginNotAllowedError: OriginNotAllowedError2 } = await import('@partylayer/core');
2276
- throw new OriginNotAllowedError2(
1825
+ throw new core.OriginNotAllowedError(
2277
1826
  this.origin,
2278
1827
  walletEntry.originAllowlist
2279
1828
  );
@@ -2308,8 +1857,8 @@ var PartyLayerClient = class {
2308
1857
  return { selectedWallet, adapter, ctx, isNativeWallet };
2309
1858
  }
2310
1859
  /**
2311
- * Invoke `adapter.connect()` (its FIRST statement — no await precedes it) and
2312
- * 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
2313
1862
  * popup-safe fast-path can call it gesture-synchronously.
2314
1863
  */
2315
1864
  async completeConnect(plan, options, correlationId = newCorrelationId(), attempt) {
@@ -2319,6 +1868,9 @@ var PartyLayerClient = class {
2319
1868
  if (attempt === void 0) ++this.sessionRevision;
2320
1869
  if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
2321
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");
2322
1874
  if (!nativeOwnerBindings.has(adapter) && this.nativeOwner?.getSession()) this.nativeOwner.release();
2323
1875
  const timeoutMs = options?.timeoutMs || DEFAULT_CONNECT_TIMEOUT_MS;
2324
1876
  const abort = new AbortController();
@@ -2344,7 +1896,7 @@ var PartyLayerClient = class {
2344
1896
  }
2345
1897
  if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
2346
1898
  const session = {
2347
- sessionId: core.toSessionId(`session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`),
1899
+ sessionId,
2348
1900
  walletId: selectedWallet.walletId,
2349
1901
  partyId: result.partyId,
2350
1902
  // The wallet's reported network (adapters that read the live wallet —
@@ -2959,107 +2511,580 @@ var PartyLayerClient = class {
2959
2511
  this.emit("session:expired", { type: "session:expired", sessionId: session.sessionId }, correlationId);
2960
2512
  return null;
2961
2513
  }
2962
- this.activeSession = session;
2963
- this.activeSessionNeedsProbe = true;
2964
- return session;
2965
- } catch (err) {
2966
- this.log("warn", "session:restore_failed", "Failed to restore session", {
2967
- error: err instanceof Error ? err.message : String(err)
2968
- }, correlationId);
2969
- return null;
2514
+ this.activeSession = session;
2515
+ this.activeSessionNeedsProbe = true;
2516
+ return session;
2517
+ } catch (err) {
2518
+ if (!current()) return this.activeSession;
2519
+ await this.removeSession();
2520
+ this.log("warn", "session:restore_failed", "Failed to restore session", {
2521
+ error: err instanceof Error ? err.message : String(err)
2522
+ }, correlationId);
2523
+ return null;
2524
+ }
2525
+ }
2526
+ /**
2527
+ * Update registry status and emit event
2528
+ */
2529
+ updateRegistryStatus() {
2530
+ const status = this.registryClient.getStatus();
2531
+ if (status) {
2532
+ if (status.source === "network") {
2533
+ this.telemetry?.increment?.(core.METRICS.REGISTRY_FETCH);
2534
+ } else if (status.source === "cache") {
2535
+ this.telemetry?.increment?.(core.METRICS.REGISTRY_CACHE_HIT);
2536
+ }
2537
+ if (status.stale) {
2538
+ this.telemetry?.increment?.(core.METRICS.REGISTRY_STALE);
2539
+ }
2540
+ this.emit("registry:status", {
2541
+ type: "registry:status",
2542
+ status: {
2543
+ source: status.source,
2544
+ verified: status.verified,
2545
+ channel: status.channel,
2546
+ sequence: status.sequence,
2547
+ stale: status.stale,
2548
+ fetchedAt: status.fetchedAt,
2549
+ etag: status.etag,
2550
+ error: status.error
2551
+ }
2552
+ });
2553
+ }
2554
+ }
2555
+ /**
2556
+ * Get registry status
2557
+ */
2558
+ getRegistryStatus() {
2559
+ return this.registryClient.getStatus();
2560
+ }
2561
+ /**
2562
+ * Emit event to handlers
2563
+ */
2564
+ /**
2565
+ * Central structured log. Filters by the configured level here, before the adapter
2566
+ * is called, so adapters never filter themselves; skips entirely when no real
2567
+ * logger was configured (the no-op default), so a silent client pays only a check.
2568
+ * Every line carries a machine readable payload `{ event, correlationId?, ...fields }`.
2569
+ * Privacy: callers pass only non identifying fields, the same rule as telemetry.
2570
+ */
2571
+ log(level, event, message, fields, correlationId) {
2572
+ if (this.logger instanceof DefaultLogger) return;
2573
+ if (!shouldLog(level, this.logLevel)) return;
2574
+ const payload = {
2575
+ event,
2576
+ ...correlationId ? { correlationId } : {},
2577
+ ...fields ?? {}
2578
+ };
2579
+ switch (level) {
2580
+ case "debug":
2581
+ this.logger.debug(message, payload);
2582
+ break;
2583
+ case "info":
2584
+ this.logger.info(message, payload);
2585
+ break;
2586
+ case "warn":
2587
+ this.logger.warn(message, payload);
2588
+ break;
2589
+ case "error":
2590
+ this.logger.error(message, payload);
2591
+ break;
2592
+ }
2593
+ }
2594
+ emit(event, payload, correlationId) {
2595
+ if (event === "error" && "error" in payload) {
2596
+ const error = payload.error;
2597
+ if (error.code) {
2598
+ this.telemetry?.increment?.(core.errorMetricName(error.code));
2599
+ }
2600
+ }
2601
+ if (this.telemetry && !(this.telemetry instanceof DefaultTelemetry)) {
2602
+ this.telemetry.track(event, eventTelemetryProperties(payload));
2603
+ }
2604
+ this.log(eventLogLevel(event), event, event, eventTelemetryProperties(payload), correlationId);
2605
+ const handlers = this.eventHandlers.get(event);
2606
+ if (handlers) {
2607
+ for (const handler of handlers) {
2608
+ try {
2609
+ handler(payload);
2610
+ } catch (err) {
2611
+ this.log("error", "event:handler_error", "Error in event handler", {
2612
+ error: err instanceof Error ? err.message : String(err)
2613
+ });
2614
+ }
2615
+ }
2616
+ }
2617
+ }
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;
2970
2953
  }
2971
2954
  }
2972
- /**
2973
- * Update registry status and emit event
2974
- */
2975
- updateRegistryStatus() {
2976
- const status = this.registryClient.getStatus();
2977
- if (status) {
2978
- if (status.source === "network") {
2979
- this.telemetry?.increment?.(core.METRICS.REGISTRY_FETCH);
2980
- } else if (status.source === "cache") {
2981
- this.telemetry?.increment?.(core.METRICS.REGISTRY_CACHE_HIT);
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 {
2982
2975
  }
2983
- if (status.stale) {
2984
- this.telemetry?.increment?.(core.METRICS.REGISTRY_STALE);
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
2985
  }
2986
- this.emit("registry:status", {
2987
- type: "registry:status",
2988
- status: {
2989
- source: status.source,
2990
- verified: status.verified,
2991
- channel: status.channel,
2992
- sequence: status.sequence,
2993
- stale: status.stale,
2994
- fetchedAt: status.fetchedAt,
2995
- etag: status.etag,
2996
- error: status.error
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);
2997
2999
  }
2998
- });
3000
+ );
3001
+ };
3002
+ for (const event of ["accountsChanged", "statusChanged"]) {
3003
+ provider.on(event, update);
3004
+ this.unsubscribers.push(() => provider.removeListener(event, update));
2999
3005
  }
3000
3006
  }
3001
- /**
3002
- * Get registry status
3003
- */
3004
- getRegistryStatus() {
3005
- return this.registryClient.getStatus();
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);
3006
3016
  }
3007
- /**
3008
- * Emit event to handlers
3009
- */
3010
- /**
3011
- * Central structured log. Filters by the configured level here, before the adapter
3012
- * is called, so adapters never filter themselves; skips entirely when no real
3013
- * logger was configured (the no-op default), so a silent client pays only a check.
3014
- * Every line carries a machine readable payload `{ event, correlationId?, ...fields }`.
3015
- * Privacy: callers pass only non identifying fields, the same rule as telemetry.
3016
- */
3017
- log(level, event, message, fields, correlationId) {
3018
- if (this.logger instanceof DefaultLogger) return;
3019
- if (!shouldLog(level, this.logLevel)) return;
3020
- const payload = {
3021
- event,
3022
- ...correlationId ? { correlationId } : {},
3023
- ...fields ?? {}
3024
- };
3025
- switch (level) {
3026
- case "debug":
3027
- this.logger.debug(message, payload);
3028
- break;
3029
- case "info":
3030
- this.logger.info(message, payload);
3031
- break;
3032
- case "warn":
3033
- this.logger.warn(message, payload);
3034
- break;
3035
- case "error":
3036
- this.logger.error(message, payload);
3037
- break;
3038
- }
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);
3039
3028
  }
3040
- emit(event, payload, correlationId) {
3041
- if (event === "error" && "error" in payload) {
3042
- const error = payload.error;
3043
- if (error.code) {
3044
- this.telemetry?.increment?.(core.errorMetricName(error.code));
3045
- }
3046
- }
3047
- if (this.telemetry && !(this.telemetry instanceof DefaultTelemetry)) {
3048
- this.telemetry.track(event, eventTelemetryProperties(payload));
3049
- }
3050
- this.log(eventLogLevel(event), event, event, eventTelemetryProperties(payload), correlationId);
3051
- const handlers = this.eventHandlers.get(event);
3052
- if (handlers) {
3053
- for (const handler of handlers) {
3054
- try {
3055
- handler(payload);
3056
- } catch (err) {
3057
- this.log("error", "event:handler_error", "Error in event handler", {
3058
- error: err instanceof Error ? err.message : String(err)
3059
- });
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;
3060
3049
  }
3050
+ this.operation = null;
3051
+ if (id) this.changed(id, null);
3061
3052
  }
3062
- }
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
+ });
3063
3088
  }
3064
3089
  };
3065
3090
  function createPartyLayer(config) {
@@ -3082,8 +3107,14 @@ function createWalletLedgerReader(client, options) {
3082
3107
  function createScopedLedgerReader(client, options, applicationRequest) {
3083
3108
  const networkId = text(options.networkId);
3084
3109
  if (!/^canton:[a-zA-Z0-9_-]+$/.test(networkId)) throw new Error("Expected a Canton CAIP-2 network id");
3085
- const interfaceId = options.holdingInterfaceId === void 0 ? void 0 : text(options.holdingInterfaceId);
3086
- if (interfaceId && !/^[^:#\s]+:[^:\s]+:[^:\s]+$/.test(interfaceId)) throw new Error("Use an exact package-id-qualified holding interface id");
3110
+ function configuredInterface(value) {
3111
+ if (value === void 0) return void 0;
3112
+ const id = text(value);
3113
+ if (!/^[^:#\s]+:[^:\s]+:[^:\s]+$/.test(id)) throw new Error("Use an exact package-id-qualified holding interface id");
3114
+ return id;
3115
+ }
3116
+ const interfaceId = configuredInterface(options.holdingInterfaceId);
3117
+ const v2InterfaceId = configuredInterface(options.holdingV2InterfaceId);
3087
3118
  const timeoutMs = options.timeoutMs ?? 3e4;
3088
3119
  const maxContracts = options.maxContracts ?? 1e3;
3089
3120
  if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 3e5) throw new Error("Invalid ledger read timeout");
@@ -3141,63 +3172,49 @@ function createScopedLedgerReader(client, options, applicationRequest) {
3141
3172
  if (stop) signal?.removeEventListener("abort", stop);
3142
3173
  }
3143
3174
  }
3175
+ function readHoldings(requestedInterface, parse, include, signal) {
3176
+ return read(signal, async (session, request) => {
3177
+ if (!requestedInterface) throw new Error("Configure the version-specific holding interface id before reading holdings");
3178
+ const end = object(await request("/v2/state/ledger-end"));
3179
+ if (!Number.isSafeInteger(end.offset) || end.offset < 0) throw new Error("Unsafe or invalid ledger offset");
3180
+ const rows = await request("/v2/state/active-contracts", {
3181
+ activeAtOffset: end.offset,
3182
+ eventFormat: { filtersByParty: { [String(session.partyId)]: { cumulative: [{
3183
+ identifierFilter: { InterfaceFilter: { value: { interfaceId: requestedInterface, includeInterfaceView: true } } }
3184
+ }] } }, verbose: false }
3185
+ });
3186
+ if (!Array.isArray(rows) || rows.length >= maxContracts) throw new Error("Incomplete or oversized holdings snapshot");
3187
+ const seen = /* @__PURE__ */ new Set();
3188
+ const holdings = [];
3189
+ for (const row of rows) {
3190
+ const entry = object(object(row).contractEntry);
3191
+ if (Object.keys(entry).length !== 1 || !entry.JsActiveContract) throw new Error("Snapshot contains an incomplete reassignment");
3192
+ const created = object(object(entry.JsActiveContract).createdEvent);
3193
+ const cid = text(created.contractId);
3194
+ if (seen.has(cid)) throw new Error("Duplicate holding contract in snapshot");
3195
+ seen.add(cid);
3196
+ if (!Array.isArray(created.interfaceViews)) throw new Error("Missing holding interface view");
3197
+ const views = created.interfaceViews.filter((v) => object(v).interfaceId === requestedInterface);
3198
+ if (views.length !== 1) throw new Error("Missing or ambiguous holding interface view");
3199
+ const view = object(views[0]);
3200
+ if (object(view.viewStatus).code !== 0) throw new Error("Holding interface view failed");
3201
+ const holding = parse(view.viewValue);
3202
+ if (include(holding, String(session.partyId))) holdings.push({ cid, holding });
3203
+ }
3204
+ return { walletId: String(session.walletId), partyId: String(session.partyId), networkId, offset: end.offset, holdings };
3205
+ });
3206
+ }
3144
3207
  return {
3145
3208
  /** A bounded, complete ACS snapshot of the connected party's configured HoldingV1 interface. */
3146
3209
  readHoldings(signal) {
3147
- return read(signal, async (session, request) => {
3148
- if (!interfaceId) throw new Error("Configure holdingInterfaceId before reading holdings");
3149
- const end = object(await request("/v2/state/ledger-end"));
3150
- if (!Number.isSafeInteger(end.offset) || end.offset < 0) throw new Error("Unsafe or invalid ledger offset");
3151
- const rows = await request("/v2/state/active-contracts", {
3152
- activeAtOffset: end.offset,
3153
- eventFormat: { filtersByParty: { [String(session.partyId)]: { cumulative: [{
3154
- identifierFilter: { InterfaceFilter: { value: { interfaceId, includeInterfaceView: true } } }
3155
- }] } }, verbose: false }
3156
- });
3157
- if (!Array.isArray(rows) || rows.length >= maxContracts) throw new Error("Incomplete or oversized holdings snapshot");
3158
- const seen = /* @__PURE__ */ new Set();
3159
- const holdings = rows.map((row) => {
3160
- const entry = object(object(row).contractEntry);
3161
- if (Object.keys(entry).length !== 1 || !entry.JsActiveContract) throw new Error("Snapshot contains an incomplete reassignment");
3162
- const created = object(object(entry.JsActiveContract).createdEvent);
3163
- const cid = text(created.contractId);
3164
- if (seen.has(cid)) throw new Error("Duplicate holding contract in snapshot");
3165
- seen.add(cid);
3166
- if (!Array.isArray(created.interfaceViews)) throw new Error("Missing holding interface view");
3167
- const views = created.interfaceViews.filter((v) => object(v).interfaceId === interfaceId);
3168
- if (views.length !== 1) throw new Error("Missing or ambiguous holding interface view");
3169
- const view = object(views[0]);
3170
- if (object(view.viewStatus).code !== 0) throw new Error("Holding interface view failed");
3171
- const value = object(view.viewValue);
3172
- if (value.owner !== String(session.partyId)) throw new Error("Holding belongs to another party");
3173
- const instrument = object(value.instrumentId);
3174
- if (typeof value.amount !== "string" || !/^(?:0|[1-9]\d{0,27})(?:\.\d{1,10})?$/.test(value.amount)) throw new Error("Invalid token decimal");
3175
- let lock;
3176
- if (value.lock !== null && value.lock !== void 0) {
3177
- const raw = object(value.lock);
3178
- if (!Array.isArray(raw.holders)) throw new Error("Invalid holding lock");
3179
- lock = { holders: raw.holders.map(text) };
3180
- for (const key of ["expiresAt", "expiresAfter", "context"]) {
3181
- if (raw[key] !== void 0 && raw[key] !== null) lock[key] = text(raw[key]);
3182
- }
3183
- }
3184
- let meta;
3185
- if (value.meta !== void 0 && value.meta !== null) {
3186
- const raw = object(value.meta);
3187
- const values = Object.hasOwn(raw, "values") ? object(raw.values) : raw;
3188
- if (Object.values(values).some((v) => typeof v !== "string")) throw new Error("Invalid holding metadata");
3189
- meta = { ...values };
3190
- }
3191
- return { cid, holding: {
3192
- owner: String(session.partyId),
3193
- instrumentId: { admin: text(instrument.admin), id: text(instrument.id) },
3194
- amount: value.amount,
3195
- ...lock ? { lock } : {},
3196
- ...meta ? { meta } : {}
3197
- } };
3198
- });
3199
- return { walletId: String(session.walletId), partyId: String(session.partyId), networkId, offset: end.offset, holdings };
3200
- });
3210
+ return readHoldings(interfaceId, core.parseTokenHoldingV1, (holding, owner) => {
3211
+ if (holding.owner !== owner) throw new Error("Holding belongs to another party");
3212
+ return true;
3213
+ }, signal);
3214
+ },
3215
+ /** Owned V2 accounts only. Provider visibility and ownerless admin accounts do not confer ownership. */
3216
+ readHoldingsV2(signal) {
3217
+ return readHoldings(v2InterfaceId, core.parseTokenHoldingV2, (holding, owner) => holding.account.owner === owner, signal);
3201
3218
  },
3202
3219
  /** One read, never polling or resubmission. Unknown remains unknown if ids cannot be correlated. */
3203
3220
  async confirmTransaction({ transaction, signal }) {
@@ -3269,6 +3286,12 @@ function createApplicationLedgerReader(client, options) {
3269
3286
  });
3270
3287
  }
3271
3288
 
3289
+ // src/bron-authorization.ts
3290
+ async function completeBronAuthorization(redirectUri) {
3291
+ const { completeBronAuthorization: complete } = await import('@partylayer/adapter-bron');
3292
+ complete(redirectUri);
3293
+ }
3294
+
3272
3295
  Object.defineProperty(exports, "AdapterNotRegisteredError", {
3273
3296
  enumerable: true,
3274
3297
  get: function () { return core.AdapterNotRegisteredError; }
@@ -3481,6 +3504,7 @@ exports.GenericDiscoveryAdapter = GenericDiscoveryAdapter;
3481
3504
  exports.MetricsTelemetryAdapter = MetricsTelemetryAdapter;
3482
3505
  exports.PartyLayerClient = PartyLayerClient;
3483
3506
  exports.announcedWalletId = announcedWalletId;
3507
+ exports.completeBronAuthorization = completeBronAuthorization;
3484
3508
  exports.createApplicationLedgerReader = createApplicationLedgerReader;
3485
3509
  exports.createCantonConnect = createPartyLayer;
3486
3510
  exports.createPartyLayer = createPartyLayer;