@partylayer/sdk 0.22.0 → 0.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { toWalletId, toPartyId, isRecognizedNetwork, detectNetworkMismatch, ledgerApiBodyToObject, normalizeLedgerMethodLower, hashForPrivacy, createMetricsPayload, isOfficialAdapterFactory, isOfficialProviderAdapter, mapUnknownErrorToPartyLayerError, findMatchingWalletInfo, NetworkMismatchError, METRICS, WalletNotFoundError, AdapterNotRegisteredError, OriginNotAllowedError, capabilityGuard, installGuard, toSessionId, CapabilityNotSupportedError, toTransferIntent, errorMetricName, TransportError, toSignature, parseTokenHoldingV2, parseTokenHoldingV1, toCAIP2Network, toTransactionHash } from '@partylayer/core';
1
+ import { toWalletId, toPartyId, isRecognizedNetwork, detectNetworkMismatch, ledgerApiBodyToObject, normalizeLedgerMethodLower, hashForPrivacy, createMetricsPayload, TransportError, toSignature, isOfficialAdapterFactory, isOfficialProviderAdapter, mapUnknownErrorToPartyLayerError, NetworkMismatchError, METRICS, WalletNotFoundError, AdapterNotRegisteredError, WalletNotInstalledError, OriginNotAllowedError, capabilityGuard, installGuard, CapabilityNotSupportedError, toTransferIntent, errorMetricName, parseTokenHoldingV2, parseTokenHoldingV1, toCAIP2Network, toTransactionHash, findMatchingWalletInfo, generateSessionId, toSessionId } from '@partylayer/core';
2
2
  export { AdapterNotRegisteredError, PartyLayerError as CantonConnectError, CapabilityNotSupportedError, ENABLEMENT_METRICS, ERROR_METRICS, InternalError, METRICS, OriginNotAllowedError, PartyLayerError, REGISTRY_METRICS, RegistryFetchFailedError, RegistrySchemaInvalidError, RegistryVerificationFailedError, SessionExpiredError, TRANSFER_INTENT_FIELDS, TimeoutError, TransportError, UserRejectedError, WalletNotFoundError, WalletNotInstalledError, errorMetricName, isOfficialAdapterFactory, isOfficialProviderAdapter, toTransferIntent } from '@partylayer/core';
3
3
  import { RegistryClient } from '@partylayer/registry-client';
4
4
  export { deriveGenericWalletName, findMatchingWallet, findMatchingWalletInfo, isCip0103Native, matchesProviderDetection } from '@partylayer/registry-client';
@@ -14,50 +14,7 @@ export { NightlyAdapter } from '@partylayer/adapter-nightly';
14
14
  export { SendAdapter } from '@partylayer/adapter-send';
15
15
  export { BronAdapter } from '@partylayer/adapter-bron';
16
16
 
17
- // src/default-wallets.ts
18
- var loaders = {
19
- walley: async () => {
20
- const { WalleyAdapter } = await import('@k2flabs/walley-dapp-sdk');
21
- return { providerId: "walley", create: (host) => new WalleyAdapter({ host }) };
22
- },
23
- cauri: async () => {
24
- const { cauriAdapterFactory } = await import('@lithiumdigital/cauri-dapp-sdk');
25
- return cauriAdapterFactory;
26
- },
27
- oneswap: async (network) => {
28
- const { createOneSwapProviderAdapter } = await import('@oneswap/wallet-cip0103-adapter');
29
- return {
30
- providerId: "oneswap",
31
- create: (host) => createOneSwapProviderAdapter({
32
- walletUrl: host,
33
- networkId: toCAIP2Network(network).networkId
34
- })
35
- };
36
- },
37
- vala: async () => {
38
- const { valaAdapterFactory } = await import('@vala-wallet/dapp-sdk');
39
- return valaAdapterFactory;
40
- }
41
- };
42
- async function loadDefaultWallet(id, config, origin) {
43
- if (id === "walletconnect" && config.walletConnect?.projectId.trim()) {
44
- const { WalletConnectAdapter } = await import('@partylayer/adapter-walletconnect');
45
- return new WalletConnectAdapter({
46
- ...config.walletConnect,
47
- metadata: config.walletConnect.metadata ?? {
48
- name: config.app.name,
49
- description: config.app.name,
50
- url: origin === "unknown" ? "" : origin,
51
- icons: []
52
- }
53
- });
54
- }
55
- if (id === "bron" && config.bron) {
56
- const { BronAdapter: BronAdapter2 } = await import('@partylayer/adapter-bron');
57
- return new BronAdapter2(config.bron);
58
- }
59
- return Object.prototype.hasOwnProperty.call(loaders, id) ? loaders[id](config.network) : void 0;
60
- }
17
+ // src/client-base.ts
61
18
  var UNSUPPORTED_METHOD = 4200;
62
19
  var METHOD_NOT_FOUND = -32601;
63
20
  function isUnsupportedMethod(err) {
@@ -178,722 +135,324 @@ function assertConnectionAccepted(result) {
178
135
  function assertPrimaryParty(account) {
179
136
  if (typeof account?.partyId !== "string" || !account.partyId.trim()) throw new TransportError("The wallet did not return a primary party");
180
137
  }
181
- var SILENT_PROBE_TIMEOUT_MS = 1e4;
182
- function disconnected() {
183
- return new Error("Native wallet connection is no longer active");
184
- }
185
- function teardown(source) {
186
- try {
187
- source?.teardown?.();
188
- } catch {
189
- }
138
+
139
+ // src/native-owner-bindings.ts
140
+ var nativeOwnerBindings = /* @__PURE__ */ new WeakMap();
141
+ var nativeAdapterCopies = /* @__PURE__ */ new WeakMap();
142
+
143
+ // src/announce-adapter.ts
144
+ function getAnnounceCapabilities(config = {}) {
145
+ const caps = ["connect"];
146
+ if (config.signMessage !== false) caps.push("signMessage");
147
+ caps.push("submitTransaction");
148
+ if (config.restore) caps.push("restore");
149
+ if (config.ledgerApi) caps.push("ledgerApi");
150
+ if (config.events) caps.push("events");
151
+ return caps;
190
152
  }
191
- function abortable(promise, signal) {
192
- return new Promise((resolve, reject) => {
193
- const abort = () => reject(disconnected());
194
- if (signal.aborted) {
195
- reject(disconnected());
196
- return;
197
- }
198
- signal.addEventListener("abort", abort, { once: true });
199
- promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
200
- });
153
+ var ANNOUNCED_WALLET_ID_PREFIX = "browser:ext:";
154
+ function announcedWalletId(announceId) {
155
+ return toWalletId(`${ANNOUNCED_WALLET_ID_PREFIX}${announceId}`);
201
156
  }
202
- async function readIdentity(provider, registration, signal) {
203
- const account = await abortable(
204
- provider.request({ method: "getPrimaryAccount" }),
205
- signal
206
- );
207
- assertPrimaryParty(account);
208
- let status;
209
- try {
210
- status = await abortable(provider.request({ method: "status" }), signal);
211
- } catch (error) {
212
- if (signal.aborted) throw error;
157
+ function mapTxStatus(status) {
158
+ switch (status) {
159
+ case "pending":
160
+ return "pending";
161
+ case "signed":
162
+ return "submitted";
163
+ case "executed":
164
+ return "committed";
165
+ case "failed":
166
+ default:
167
+ return "failed";
213
168
  }
214
- if (status?.isConnected === false || status?.connection?.isConnected === false)
215
- throw disconnected();
216
- const network = [status?.network?.networkId, account.networkId, registration.network].find(
217
- (value) => typeof value === "string" && isRecognizedNetwork(value)
218
- ) ?? registration.network;
219
- if (registration.expected && (account.partyId !== registration.expected.partyId || detectNetworkMismatch(registration.expected.network, network)))
220
- throw disconnected();
221
- if (signal.aborted) throw disconnected();
222
- return { account, network, status };
223
169
  }
224
- var NativeConnectionOwner = class {
225
- constructor(changed = () => {
226
- }) {
227
- this.changed = changed;
170
+ function toBase64Message(message) {
171
+ const bytes = new TextEncoder().encode(message);
172
+ let binary = "";
173
+ for (const b of bytes) binary += String.fromCharCode(b);
174
+ return btoa(binary);
175
+ }
176
+ var GenericAnnounceAdapter = class _GenericAnnounceAdapter {
177
+ walletId;
178
+ name;
179
+ /** Icon surfaced to the picker (announce detail). */
180
+ icon;
181
+ rawProvider;
182
+ metadataEnabled;
183
+ staticMetadata;
184
+ mapError;
185
+ signMessageBase64;
186
+ /**
187
+ * Which execute verb this wallet turned out to support. Resolved on the first
188
+ * submit and reused, so the wallet is asked at most once.
189
+ */
190
+ executeVerb = {};
191
+ // Optional WalletAdapter surface — assigned in the ctor ONLY when configured,
192
+ // so `getCapabilities()` and `'x' in adapter` feature-detection stay honest.
193
+ restore;
194
+ on;
195
+ ledgerApi;
196
+ // signMessage is optional too: assigned in the ctor only when the wallet
197
+ // declares support, so a wallet that cannot sign is not advertised as able to.
198
+ signMessage;
199
+ constructor(args) {
200
+ const configuration = { ...args, config: args.config && {
201
+ ...args.config,
202
+ staticMetadata: args.config.staticMetadata && { ...args.config.staticMetadata }
203
+ } };
204
+ nativeAdapterCopies.set(this, () => new _GenericAnnounceAdapter(configuration));
205
+ this.walletId = args.walletId ?? announcedWalletId(args.announceId);
206
+ this.name = args.name && args.name.length > 0 ? args.name : `Canton Wallet (${args.announceId.slice(0, 6)}\u2026)`;
207
+ this.icon = args.icon;
208
+ this.rawProvider = args.provider;
209
+ const config = args.config;
210
+ this.metadataEnabled = config?.metadata === true;
211
+ this.staticMetadata = config?.staticMetadata;
212
+ this.mapError = config?.mapError;
213
+ this.signMessageBase64 = config?.signMessageBase64 === true;
214
+ if (config?.events) this.on = this.makeOn();
215
+ if (config?.restore) this.restore = this.makeRestore();
216
+ if (config?.ledgerApi) this.ledgerApi = this.makeLedgerApi();
217
+ if (config?.signMessage !== false) this.signMessage = this.signMessageImpl.bind(this);
228
218
  }
229
- client = null;
230
- initialization = null;
231
- registrations = /* @__PURE__ */ new Map();
232
- operation = null;
233
- pending = null;
234
- closing = null;
235
- projection = null;
236
- unsubscribers = [];
237
- disposed = false;
238
- refreshRevision = 0;
239
- identityRefreshing = false;
240
- probes = /* @__PURE__ */ new Set();
241
- get busy() {
242
- return this.operation !== null || this.closing !== null;
219
+ get provider() {
220
+ return nativeOwnerBindings.get(this)?.getProvider(String(this.walletId)) ?? this.rawProvider;
243
221
  }
244
- assertAvailable() {
245
- if (this.disposed) throw disconnected();
246
- if (this.busy) throw new Error("A native wallet operation is already in progress");
222
+ /** @internal Register the discovered transport with the one official owner. */
223
+ async prepareNativeConnection(network) {
224
+ const owner = nativeOwnerBindings.get(this);
225
+ if (!owner) return;
226
+ await owner.prepare(String(this.walletId), {
227
+ providerId: String(this.walletId),
228
+ name: this.name,
229
+ type: "browser",
230
+ icon: this.icon,
231
+ provider: () => this.rawProvider,
232
+ detect: async () => true
233
+ }, network);
247
234
  }
248
- /** Run during picker preparation, never between a click and provider.connect. */
249
- async prepare(id, source, network) {
250
- if (this.disposed) throw disconnected();
251
- this.registrations.set(id, { id, source, network });
252
- if (!this.initialization) {
253
- this.initialization = (async () => {
254
- const { DiscoveryClient } = await import('@canton-network/core-wallet-discovery');
255
- const client = await DiscoveryClient.create({ adapters: [] });
256
- if (this.disposed) {
257
- client.destroy();
258
- return;
259
- }
260
- this.client = client;
261
- })();
262
- }
263
- await this.initialization;
264
- if (this.disposed || !this.client) throw disconnected();
265
- for (const registration of this.registrations.values())
266
- this.client.registerAdapter(this.wrap(registration));
235
+ /**
236
+ * Capabilities derived from actual presence: connect and submitTransaction are
237
+ * always present; signMessage, restore, ledgerApi, and events are each included
238
+ * only when the matching method was assigned, so the set is never advertised
239
+ * beyond what the adapter can do.
240
+ */
241
+ getCapabilities() {
242
+ return getAnnounceCapabilities({
243
+ signMessage: !!this.signMessage,
244
+ restore: !!this.restore,
245
+ ledgerApi: !!this.ledgerApi,
246
+ events: !!this.on
247
+ });
267
248
  }
268
- wrap(registration) {
269
- const source = registration.source;
249
+ /**
250
+ * The adapter is only ever constructed for a wallet that just announced, so
251
+ * its presence is established by the announce handshake itself.
252
+ */
253
+ async detectInstalled() {
270
254
  return {
271
- providerId: registration.id,
272
- name: source.name,
273
- type: source.type === "desktop" || source.type === "mobile" || source.type === "remote" ? source.type : "browser",
274
- icon: source.icon,
275
- getInfo: () => ({
276
- providerId: registration.id,
277
- name: source.name,
278
- type: "browser",
279
- icon: source.icon
280
- }),
281
- detect: () => source.detect(),
282
- provider: () => this.guard(source.provider(), registration),
283
- teardown: () => teardown(source),
284
- restore: async () => {
285
- const operation = this.operation;
286
- if (!operation) throw disconnected();
287
- try {
288
- const raw = source.restore ? await abortable(source.restore(), operation.abort.signal) : source.provider();
289
- if (!raw) return null;
290
- const provider = raw;
291
- operation.identity = await readIdentity(provider, registration, operation.abort.signal);
292
- return this.guard(provider, registration);
293
- } catch (error) {
294
- teardown(source);
295
- throw error;
296
- }
297
- }
298
- };
299
- }
300
- guard(raw, registration) {
301
- const provider = {
302
- request: async (args) => {
303
- if (this.disposed) throw disconnected();
304
- if (args.method !== "connect") {
305
- if (this.client?.getActiveSession()?.provider !== provider) throw disconnected();
306
- if (!this.projection && args.method !== "disconnect") throw disconnected();
307
- if (this.identityRefreshing && ![
308
- "status",
309
- "getPrimaryAccount",
310
- "listAccounts",
311
- "getActiveNetwork",
312
- "isConnected"
313
- ].includes(args.method)) {
314
- throw new Error("Native wallet identity is being refreshed");
315
- }
316
- const result = await (args.method === "disconnect" && this.operation ? abortable(raw.request(args), this.operation.abort.signal) : raw.request(args));
317
- if (args.method === "status") {
318
- const status = result;
319
- if (status?.isConnected === false || status?.connection?.isConnected === false) {
320
- this.invalidate(registration.id);
321
- }
322
- }
323
- return result;
324
- }
325
- const operation = this.operation;
326
- if (!operation || operation.abort.signal.aborted) throw disconnected();
327
- const response = await abortable(raw.request(args), operation.abort.signal);
328
- assertConnectionAccepted(response);
329
- operation.identity = await readIdentity(raw, registration, operation.abort.signal);
330
- return response;
331
- },
332
- on: (event, listener) => {
333
- raw.on(event, listener);
334
- return provider;
335
- },
336
- emit: (event, ...args) => raw.emit(event, ...args),
337
- removeListener: (event, listener) => {
338
- raw.removeListener(event, listener);
339
- return provider;
340
- }
255
+ installed: true,
256
+ // Presence by CONSTRUCTION: this adapter only exists because an announce
257
+ // arrived on the wallet's own target channel. There is no probe to be
258
+ // wrong about, which is why this is the one path that cannot report a
259
+ // wallet that is not there.
260
+ availability: { kind: "installed" },
261
+ reason: "Announced via canton:announceProvider"
341
262
  };
342
- return provider;
343
263
  }
344
- /** No await precedes the official client's connect call. */
345
- connect(id, signal) {
346
- this.assertAvailable();
347
- if (!this.client || !this.registrations.has(id))
348
- return Promise.reject(new Error("Native wallet was not prepared"));
349
- const operation = { abort: new AbortController(), id };
350
- this.operation = operation;
351
- this.detach();
352
- const previous = this.client.getActiveSession();
353
- teardown(previous?.adapter);
354
- const previousId = this.projection?.id;
355
- this.projection = null;
356
- if (previousId) this.changed(previousId, null);
357
- const abort = () => operation.abort.abort();
358
- if (signal?.aborted) abort();
359
- signal?.addEventListener("abort", abort, { once: true });
360
- const task = (async () => {
264
+ async connect(ctx, options) {
265
+ return this.guarded(async () => {
266
+ const owner = nativeOwnerBindings.get(this);
267
+ const native = owner ? await owner.connect(String(this.walletId), options?.signal) : void 0;
268
+ if (!owner) assertConnectionAccepted(await this.provider.request({ method: "connect" }));
269
+ const account = native?.account ?? await this.provider.request({
270
+ method: "getPrimaryAccount"
271
+ });
272
+ assertPrimaryParty(account);
273
+ let status;
361
274
  try {
362
- await this.client.connect(id);
363
- if (operation.abort.signal.aborted || this.disposed || !operation.identity)
364
- throw disconnected();
365
- this.projection = { id, identity: operation.identity };
366
- this.attach(id);
367
- return operation.identity;
368
- } catch (error) {
369
- this.client?.destroy();
370
- this.client = null;
371
- this.initialization = null;
372
- teardown(this.registrations.get(id)?.source);
373
- throw error;
374
- } finally {
375
- signal?.removeEventListener("abort", abort);
376
- if (this.operation === operation) this.operation = null;
275
+ status = native?.status ?? await this.provider.request({ method: "status" });
276
+ } catch {
377
277
  }
378
- })();
379
- this.pending = task;
380
- void task.then(
381
- () => {
382
- if (this.pending === task) this.pending = null;
383
- },
384
- () => {
385
- if (this.pending === task) this.pending = null;
278
+ const reportedNetwork = status?.network?.networkId;
279
+ const partyId = toPartyId(account.partyId);
280
+ const network = [reportedNetwork, account.networkId, ctx.network].find(
281
+ (n) => typeof n === "string" && isRecognizedNetwork(n)
282
+ ) ?? ctx.network;
283
+ const session = {
284
+ walletId: this.walletId,
285
+ partyId,
286
+ network
287
+ };
288
+ if (this.metadataEnabled) {
289
+ session.metadata = { ...this.staticMetadata ?? {}, ...buildMetadata(status, account) };
386
290
  }
387
- );
388
- return task;
291
+ return { partyId, session, capabilities: this.getCapabilities() };
292
+ });
389
293
  }
390
- async restore(expected) {
391
- if (!this.client || this.projection || this.busy || this.disposed) return this.getSession();
392
- const registration = expected && this.registrations.get(expected.id);
393
- if (registration) registration.expected = expected;
394
- const operation = { abort: new AbortController() };
395
- this.operation = operation;
396
- const timeout = setTimeout(() => operation.abort.abort(), SILENT_PROBE_TIMEOUT_MS);
397
- const task = (async () => {
398
- try {
399
- await this.client.restorePersistedSessionIfNeeded();
400
- const active = this.client?.getActiveSession();
401
- if (!active || !operation.identity || operation.abort.signal.aborted || this.disposed)
402
- return null;
403
- if (expected && active.providerId !== expected.id) {
404
- teardown(active.adapter);
405
- this.client.destroy();
406
- this.client = null;
407
- this.initialization = null;
408
- return null;
409
- }
410
- const id = String(active.providerId);
411
- this.projection = { id, identity: operation.identity };
412
- this.attach(id);
413
- return this.getSession();
414
- } finally {
415
- clearTimeout(timeout);
416
- if (registration) delete registration.expected;
417
- if (this.operation === operation) this.operation = null;
418
- }
419
- })();
420
- this.pending = task;
294
+ async disconnect() {
295
+ const owner = nativeOwnerBindings.get(this);
296
+ if (owner) {
297
+ await owner.disconnect();
298
+ return;
299
+ }
421
300
  try {
422
- return await task;
423
- } finally {
424
- if (this.pending === task) this.pending = null;
301
+ await this.provider.request({ method: "disconnect" });
302
+ } catch {
425
303
  }
426
304
  }
427
- getSession() {
428
- if (this.disposed || !this.client?.getActiveSession() || !this.projection) return null;
429
- return this.projection;
305
+ // Real signMessage implementation. Exposed as `this.signMessage` from the ctor
306
+ // only when the wallet declares support, so getCapabilities and feature
307
+ // detection stay honest for a wallet that cannot sign.
308
+ async signMessageImpl(_ctx, session, params) {
309
+ return this.guarded(async () => {
310
+ const rpcParams = this.signMessageBase64 ? { message: toBase64Message(params.message) } : { message: params.message };
311
+ const res = await this.provider.request({ method: "signMessage", params: rpcParams });
312
+ return normalizeSignedMessage(res, session, params);
313
+ });
430
314
  }
431
- getProvider(id) {
432
- if (!this.getSession() || id && this.projection?.id !== id) throw disconnected();
433
- return this.client.getProvider();
315
+ async submitTransaction(ctx, _session, params) {
316
+ return this.guarded(
317
+ () => submitViaPrepareExecute(this.provider, params, {
318
+ walletId: String(this.walletId),
319
+ state: this.executeVerb,
320
+ logger: ctx.logger
321
+ })
322
+ );
434
323
  }
435
- /** A bare signature must not be attributed to an old, eventless primary party. */
436
- async validateIdentity(id, partyId, network) {
437
- const provider = this.getProvider(id);
438
- const revision = ++this.refreshRevision;
439
- this.identityRefreshing = true;
440
- let verified = false;
441
- try {
442
- const identity2 = await this.probe(provider, this.registrations.get(id));
443
- if (revision !== this.refreshRevision || this.getProvider(id) !== provider)
444
- throw disconnected();
445
- verified = true;
446
- this.projection = { id, identity: identity2 };
447
- if (identity2.account.partyId !== partyId || detectNetworkMismatch(network, identity2.network)) {
448
- this.changed(id, identity2);
449
- throw new Error("Wallet identity changed during message signing");
324
+ // ── Optional-method factories (assigned only when configured) ──────────────
325
+ /** events: bridge the provider's CIP-0103 `txChanged` push event → `txStatus`. */
326
+ makeOn() {
327
+ return (event, handler) => {
328
+ if (event !== "txStatus") return () => {
329
+ };
330
+ const listener = (...args) => {
331
+ const tx = args[0];
332
+ if (!tx) return;
333
+ handler({ status: mapTxStatus(tx.status), commandId: tx.commandId, raw: tx });
334
+ };
335
+ try {
336
+ this.provider.on("txChanged", listener);
337
+ } catch {
338
+ return () => {
339
+ };
450
340
  }
451
- } catch (error) {
452
- if (!verified && revision === this.refreshRevision) this.invalidate(id);
453
- throw error;
454
- } finally {
455
- if (revision === this.refreshRevision) this.identityRefreshing = false;
456
- }
457
- }
458
- async probe(provider, registration) {
459
- const abort = new AbortController();
460
- this.probes.add(abort);
461
- const timeout = setTimeout(() => abort.abort(), SILENT_PROBE_TIMEOUT_MS);
462
- try {
463
- return await readIdentity(provider, registration, abort.signal);
464
- } finally {
465
- clearTimeout(timeout);
466
- this.probes.delete(abort);
467
- }
341
+ return () => this.provider.removeListener("txChanged", listener);
342
+ };
468
343
  }
469
- detach() {
470
- ++this.refreshRevision;
471
- this.identityRefreshing = false;
472
- for (const probe of this.probes) probe.abort();
473
- this.probes.clear();
474
- this.unsubscribers.splice(0).forEach((unsubscribe) => {
344
+ /** restore: silent status()/getPrimaryAccount() probe + expiry + party-match. */
345
+ makeRestore() {
346
+ return (_ctx, persisted) => this.guarded(async () => {
347
+ const owner = nativeOwnerBindings.get(this);
348
+ if (owner) {
349
+ await this.prepareNativeConnection(_ctx.network);
350
+ const restored = await owner.restore({ id: String(this.walletId), partyId: persisted.partyId, network: persisted.network });
351
+ return restored?.id === String(this.walletId) ? { ...persisted, capabilitiesSnapshot: this.getCapabilities() } : null;
352
+ }
353
+ if (persisted.expiresAt && Date.now() >= persisted.expiresAt) return null;
354
+ let status;
475
355
  try {
476
- unsubscribe();
356
+ status = await this.provider.request({ method: "status" });
477
357
  } catch {
478
358
  }
479
- });
480
- }
481
- attach(id) {
482
- const provider = this.getProvider(id);
483
- const update = (payload) => {
484
- const status = payload;
485
- if (status?.connection?.isConnected === false || status?.isConnected === false || Array.isArray(payload) && payload.length === 0) {
486
- this.invalidate(id);
487
- return;
488
- }
489
- const revision = ++this.refreshRevision;
490
- this.identityRefreshing = true;
491
- const registration = this.registrations.get(id);
492
- void this.probe(provider, registration).then(
493
- (identity2) => {
494
- if (revision !== this.refreshRevision || this.projection?.id !== id || this.disposed)
495
- return;
496
- this.identityRefreshing = false;
497
- this.projection = { id, identity: identity2 };
498
- this.changed(id, identity2);
499
- },
500
- () => {
501
- if (revision === this.refreshRevision) this.invalidate(id);
502
- }
359
+ const connected = status?.isConnected ?? status?.connection?.isConnected;
360
+ if (connected === false) return null;
361
+ const account = await this.provider.request({
362
+ method: "getPrimaryAccount"
363
+ });
364
+ if (account.partyId !== persisted.partyId) return null;
365
+ const network = [status?.network?.networkId, account.networkId].find(
366
+ (value) => typeof value === "string" && isRecognizedNetwork(value)
503
367
  );
504
- };
505
- for (const event of ["accountsChanged", "statusChanged"]) {
506
- provider.on(event, update);
507
- this.unsubscribers.push(() => provider.removeListener(event, update));
508
- }
509
- }
510
- invalidate(id) {
511
- if (this.projection?.id !== id) return;
512
- this.detach();
513
- this.projection = null;
514
- teardown(this.client?.getActiveSession()?.adapter);
515
- this.client?.destroy();
516
- this.client = null;
517
- this.initialization = null;
518
- this.changed(id, null);
519
- }
520
- /** Local transport cleanup when switching to a proprietary integration. */
521
- release() {
522
- this.assertAvailable();
523
- const id = this.projection?.id;
524
- this.detach();
525
- this.projection = null;
526
- teardown(this.client?.getActiveSession()?.adapter);
527
- this.client?.destroy();
528
- this.client = null;
529
- this.initialization = null;
530
- if (id) this.changed(id, null);
368
+ if (network && detectNetworkMismatch(persisted.network, network)) return null;
369
+ return {
370
+ ...persisted,
371
+ walletId: this.walletId,
372
+ // persisted (lowest) → static config → runtime RPC (wins).
373
+ metadata: {
374
+ ...persisted.metadata ?? {},
375
+ ...this.staticMetadata ?? {},
376
+ ...buildMetadata(status, account)
377
+ }
378
+ };
379
+ });
531
380
  }
532
- disconnect() {
533
- if (this.closing) return this.closing;
534
- this.operation?.abort.abort();
535
- const task = (async () => {
536
- await this.pending?.catch(() => {
537
- });
538
- this.detach();
539
- const id = this.projection?.id;
540
- this.projection = null;
541
- const operation = { abort: new AbortController() };
542
- this.operation = operation;
543
- const timeout = setTimeout(() => operation.abort.abort(), SILENT_PROBE_TIMEOUT_MS);
544
- try {
545
- await this.client?.disconnect();
546
- } finally {
547
- clearTimeout(timeout);
548
- if (this.client?.getActiveSession()) {
549
- this.client.destroy();
550
- this.client = null;
551
- this.initialization = null;
381
+ /** ledgerApi: proxy the standard CIP-0103 ledgerApi call; shape to {response:string}. */
382
+ makeLedgerApi() {
383
+ return (_ctx, _session, params) => this.guarded(async () => {
384
+ const result = await this.provider.request({
385
+ method: "ledgerApi",
386
+ params: {
387
+ requestMethod: normalizeLedgerMethodLower(params.requestMethod),
388
+ resource: params.resource,
389
+ body: ledgerApiBodyToObject(params.body)
552
390
  }
553
- this.operation = null;
554
- if (id) this.changed(id, null);
555
- }
556
- })();
557
- this.closing = task;
558
- void task.then(
559
- () => {
560
- if (this.closing === task) this.closing = null;
561
- },
562
- () => {
563
- if (this.closing === task) this.closing = null;
564
- }
565
- );
566
- return task;
391
+ });
392
+ if (result && typeof result.response === "string") return { response: result.response };
393
+ return { response: JSON.stringify(result ?? null) };
394
+ });
567
395
  }
568
- destroy() {
569
- if (this.disposed) return;
570
- this.disposed = true;
571
- this.operation?.abort.abort();
572
- this.detach();
573
- this.projection = null;
574
- teardown(this.client?.getActiveSession()?.adapter);
575
- if (!this.client?.getActiveSession() && this.operation?.id)
576
- teardown(this.registrations.get(this.operation.id)?.source);
577
- this.client?.destroy();
578
- this.client = null;
396
+ /**
397
+ * Run an operation, giving the optional `mapError` hook first crack at any
398
+ * thrown error. With NO hook configured this is a direct pass-through (no
399
+ * try/catch) — byte-identical to the baseline, and the SDK's built-in standard
400
+ * error mapping still applies downstream.
401
+ */
402
+ async guarded(op) {
403
+ if (!this.mapError) return op();
404
+ try {
405
+ return await op();
406
+ } catch (err) {
407
+ const mapped = this.mapError(err);
408
+ throw mapped ?? err;
409
+ }
579
410
  }
580
411
  };
581
- var nativeOwnerBindings = /* @__PURE__ */ new WeakMap();
582
- var nativeAdapterCopies = /* @__PURE__ */ new WeakMap();
583
-
584
- // src/announce-adapter.ts
585
- function getAnnounceCapabilities(config = {}) {
586
- const caps = ["connect"];
587
- if (config.signMessage !== false) caps.push("signMessage");
588
- caps.push("submitTransaction");
589
- if (config.restore) caps.push("restore");
590
- if (config.ledgerApi) caps.push("ledgerApi");
591
- if (config.events) caps.push("events");
592
- return caps;
593
- }
594
- var ANNOUNCED_WALLET_ID_PREFIX = "browser:ext:";
595
- function announcedWalletId(announceId) {
596
- return toWalletId(`${ANNOUNCED_WALLET_ID_PREFIX}${announceId}`);
597
- }
598
- function mapTxStatus(status) {
599
- switch (status) {
600
- case "pending":
601
- return "pending";
602
- case "signed":
603
- return "submitted";
604
- case "executed":
605
- return "committed";
606
- case "failed":
607
- default:
608
- return "failed";
609
- }
412
+ function buildMetadata(status, account) {
413
+ const meta = {};
414
+ const put = (k, v) => {
415
+ if (typeof v === "string" && v.length > 0) meta[k] = v;
416
+ };
417
+ put("kernelId", status?.kernel?.id);
418
+ put("publicKey", account.publicKey);
419
+ put("namespace", account.namespace);
420
+ put("networkId", account.networkId);
421
+ put("signingProviderId", account.signingProviderId);
422
+ put("hint", account.hint);
423
+ put("ledgerApiBaseUrl", status?.network?.ledgerApi?.baseUrl);
424
+ put("userId", status?.session?.userId);
425
+ return meta;
610
426
  }
611
- function toBase64Message(message) {
612
- const bytes = new TextEncoder().encode(message);
613
- let binary = "";
614
- for (const b of bytes) binary += String.fromCharCode(b);
615
- return btoa(binary);
427
+ function getDiscoveryCapabilities(declared) {
428
+ const capabilities = ["connect", "disconnect"];
429
+ if (declared?.signMessage !== false) capabilities.push("signMessage");
430
+ if (declared?.submitTransaction !== false) capabilities.push("submitTransaction");
431
+ if (declared?.ledgerApi) capabilities.push("ledgerApi");
432
+ return capabilities;
616
433
  }
617
- var GenericAnnounceAdapter = class _GenericAnnounceAdapter {
434
+ var GenericDiscoveryAdapter = class _GenericDiscoveryAdapter {
618
435
  walletId;
619
436
  name;
620
- /** Icon surfaced to the picker (announce detail). */
621
437
  icon;
622
- rawProvider;
623
- metadataEnabled;
624
- staticMetadata;
625
- mapError;
626
- signMessageBase64;
438
+ /**
439
+ * Resolved official adapter. Set at construction for the instance form; for
440
+ * the factory form it stays null until {@link resolveOfficial} constructs it
441
+ * with the network-resolved host.
442
+ */
443
+ official;
444
+ /** Factory form (null for the instance form). */
445
+ factory;
446
+ /** Network→host map for the factory form; injected by the SDK post-registry. */
447
+ networkHosts;
448
+ /** Lazily resolved from `official.provider()` — NOT at construction (SSR-safe). */
449
+ providerInstance = null;
627
450
  /**
628
451
  * Which execute verb this wallet turned out to support. Resolved on the first
629
452
  * submit and reused, so the wallet is asked at most once.
630
453
  */
631
454
  executeVerb = {};
632
- // Optional WalletAdapter surface — assigned in the ctor ONLY when configured,
633
- // so `getCapabilities()` and `'x' in adapter` feature-detection stay honest.
634
- restore;
635
- on;
636
- ledgerApi;
637
- // signMessage is optional too: assigned in the ctor only when the wallet
638
- // declares support, so a wallet that cannot sign is not advertised as able to.
639
- signMessage;
640
- constructor(args) {
641
- const configuration = { ...args, config: args.config && {
642
- ...args.config,
643
- staticMetadata: args.config.staticMetadata && { ...args.config.staticMetadata }
644
- } };
645
- nativeAdapterCopies.set(this, () => new _GenericAnnounceAdapter(configuration));
646
- this.walletId = args.walletId ?? announcedWalletId(args.announceId);
647
- this.name = args.name && args.name.length > 0 ? args.name : `Canton Wallet (${args.announceId.slice(0, 6)}\u2026)`;
648
- this.icon = args.icon;
649
- this.rawProvider = args.provider;
650
- const config = args.config;
651
- this.metadataEnabled = config?.metadata === true;
652
- this.staticMetadata = config?.staticMetadata;
653
- this.mapError = config?.mapError;
654
- this.signMessageBase64 = config?.signMessageBase64 === true;
655
- if (config?.events) this.on = this.makeOn();
656
- if (config?.restore) this.restore = this.makeRestore();
657
- if (config?.ledgerApi) this.ledgerApi = this.makeLedgerApi();
658
- if (config?.signMessage !== false) this.signMessage = this.signMessageImpl.bind(this);
659
- }
660
- get provider() {
661
- return nativeOwnerBindings.get(this)?.getProvider(String(this.walletId)) ?? this.rawProvider;
662
- }
663
- /** @internal Register the discovered transport with the one official owner. */
664
- async prepareNativeConnection(network) {
665
- const owner = nativeOwnerBindings.get(this);
666
- if (!owner) return;
667
- await owner.prepare(String(this.walletId), {
668
- providerId: String(this.walletId),
669
- name: this.name,
670
- type: "browser",
671
- icon: this.icon,
672
- provider: () => this.rawProvider,
673
- detect: async () => true
674
- }, network);
675
- }
676
- /**
677
- * Capabilities derived from actual presence: connect and submitTransaction are
678
- * always present; signMessage, restore, ledgerApi, and events are each included
679
- * only when the matching method was assigned, so the set is never advertised
680
- * beyond what the adapter can do.
681
- */
682
- getCapabilities() {
683
- return getAnnounceCapabilities({
684
- signMessage: !!this.signMessage,
685
- restore: !!this.restore,
686
- ledgerApi: !!this.ledgerApi,
687
- events: !!this.on
688
- });
689
- }
690
- /**
691
- * The adapter is only ever constructed for a wallet that just announced, so
692
- * its presence is established by the announce handshake itself.
693
- */
694
- async detectInstalled() {
695
- return {
696
- installed: true,
697
- // Presence by CONSTRUCTION: this adapter only exists because an announce
698
- // arrived on the wallet's own target channel. There is no probe to be
699
- // wrong about, which is why this is the one path that cannot report a
700
- // wallet that is not there.
701
- availability: { kind: "installed" },
702
- reason: "Announced via canton:announceProvider"
703
- };
704
- }
705
- async connect(ctx, options) {
706
- return this.guarded(async () => {
707
- const owner = nativeOwnerBindings.get(this);
708
- const native = owner ? await owner.connect(String(this.walletId), options?.signal) : void 0;
709
- if (!owner) assertConnectionAccepted(await this.provider.request({ method: "connect" }));
710
- const account = native?.account ?? await this.provider.request({
711
- method: "getPrimaryAccount"
712
- });
713
- assertPrimaryParty(account);
714
- let status;
715
- try {
716
- status = native?.status ?? await this.provider.request({ method: "status" });
717
- } catch {
718
- }
719
- const reportedNetwork = status?.network?.networkId;
720
- const partyId = toPartyId(account.partyId);
721
- const network = [reportedNetwork, account.networkId, ctx.network].find(
722
- (n) => typeof n === "string" && isRecognizedNetwork(n)
723
- ) ?? ctx.network;
724
- const session = {
725
- walletId: this.walletId,
726
- partyId,
727
- network
728
- };
729
- if (this.metadataEnabled) {
730
- session.metadata = { ...this.staticMetadata ?? {}, ...buildMetadata(status, account) };
731
- }
732
- return { partyId, session, capabilities: this.getCapabilities() };
733
- });
734
- }
735
- async disconnect() {
736
- const owner = nativeOwnerBindings.get(this);
737
- if (owner) {
738
- await owner.disconnect();
739
- return;
740
- }
741
- try {
742
- await this.provider.request({ method: "disconnect" });
743
- } catch {
744
- }
745
- }
746
- // Real signMessage implementation. Exposed as `this.signMessage` from the ctor
747
- // only when the wallet declares support, so getCapabilities and feature
748
- // detection stay honest for a wallet that cannot sign.
749
- async signMessageImpl(_ctx, session, params) {
750
- return this.guarded(async () => {
751
- const rpcParams = this.signMessageBase64 ? { message: toBase64Message(params.message) } : { message: params.message };
752
- const res = await this.provider.request({ method: "signMessage", params: rpcParams });
753
- return normalizeSignedMessage(res, session, params);
754
- });
755
- }
756
- async submitTransaction(ctx, _session, params) {
757
- return this.guarded(
758
- () => submitViaPrepareExecute(this.provider, params, {
759
- walletId: String(this.walletId),
760
- state: this.executeVerb,
761
- logger: ctx.logger
762
- })
763
- );
764
- }
765
- // ── Optional-method factories (assigned only when configured) ──────────────
766
- /** events: bridge the provider's CIP-0103 `txChanged` push event → `txStatus`. */
767
- makeOn() {
768
- return (event, handler) => {
769
- if (event !== "txStatus") return () => {
770
- };
771
- const listener = (...args) => {
772
- const tx = args[0];
773
- if (!tx) return;
774
- handler({ status: mapTxStatus(tx.status), commandId: tx.commandId, raw: tx });
775
- };
776
- try {
777
- this.provider.on("txChanged", listener);
778
- } catch {
779
- return () => {
780
- };
781
- }
782
- return () => this.provider.removeListener("txChanged", listener);
783
- };
784
- }
785
- /** restore: silent status()/getPrimaryAccount() probe + expiry + party-match. */
786
- makeRestore() {
787
- return (_ctx, persisted) => this.guarded(async () => {
788
- const owner = nativeOwnerBindings.get(this);
789
- if (owner) {
790
- await this.prepareNativeConnection(_ctx.network);
791
- const restored = await owner.restore({ id: String(this.walletId), partyId: persisted.partyId, network: persisted.network });
792
- return restored?.id === String(this.walletId) ? { ...persisted, capabilitiesSnapshot: this.getCapabilities() } : null;
793
- }
794
- if (persisted.expiresAt && Date.now() >= persisted.expiresAt) return null;
795
- let status;
796
- try {
797
- status = await this.provider.request({ method: "status" });
798
- } catch {
799
- }
800
- const connected = status?.isConnected ?? status?.connection?.isConnected;
801
- if (connected === false) return null;
802
- const account = await this.provider.request({
803
- method: "getPrimaryAccount"
804
- });
805
- if (account.partyId !== persisted.partyId) return null;
806
- const network = [status?.network?.networkId, account.networkId].find(
807
- (value) => typeof value === "string" && isRecognizedNetwork(value)
808
- );
809
- if (network && detectNetworkMismatch(persisted.network, network)) return null;
810
- return {
811
- ...persisted,
812
- walletId: this.walletId,
813
- // persisted (lowest) → static config → runtime RPC (wins).
814
- metadata: {
815
- ...persisted.metadata ?? {},
816
- ...this.staticMetadata ?? {},
817
- ...buildMetadata(status, account)
818
- }
819
- };
820
- });
821
- }
822
- /** ledgerApi: proxy the standard CIP-0103 ledgerApi call; shape to {response:string}. */
823
- makeLedgerApi() {
824
- return (_ctx, _session, params) => this.guarded(async () => {
825
- const result = await this.provider.request({
826
- method: "ledgerApi",
827
- params: {
828
- requestMethod: normalizeLedgerMethodLower(params.requestMethod),
829
- resource: params.resource,
830
- body: ledgerApiBodyToObject(params.body)
831
- }
832
- });
833
- if (result && typeof result.response === "string") return { response: result.response };
834
- return { response: JSON.stringify(result ?? null) };
835
- });
836
- }
837
- /**
838
- * Run an operation, giving the optional `mapError` hook first crack at any
839
- * thrown error. With NO hook configured this is a direct pass-through (no
840
- * try/catch) — byte-identical to the baseline, and the SDK's built-in standard
841
- * error mapping still applies downstream.
842
- */
843
- async guarded(op) {
844
- if (!this.mapError) return op();
845
- try {
846
- return await op();
847
- } catch (err) {
848
- const mapped = this.mapError(err);
849
- throw mapped ?? err;
850
- }
851
- }
852
- };
853
- function buildMetadata(status, account) {
854
- const meta = {};
855
- const put = (k, v) => {
856
- if (typeof v === "string" && v.length > 0) meta[k] = v;
857
- };
858
- put("kernelId", status?.kernel?.id);
859
- put("publicKey", account.publicKey);
860
- put("namespace", account.namespace);
861
- put("networkId", account.networkId);
862
- put("signingProviderId", account.signingProviderId);
863
- put("hint", account.hint);
864
- put("ledgerApiBaseUrl", status?.network?.ledgerApi?.baseUrl);
865
- put("userId", status?.session?.userId);
866
- return meta;
867
- }
868
- function getDiscoveryCapabilities(declared) {
869
- const capabilities = ["connect", "disconnect"];
870
- if (declared?.signMessage !== false) capabilities.push("signMessage");
871
- if (declared?.submitTransaction !== false) capabilities.push("submitTransaction");
872
- if (declared?.ledgerApi) capabilities.push("ledgerApi");
873
- return capabilities;
874
- }
875
- var GenericDiscoveryAdapter = class _GenericDiscoveryAdapter {
876
- walletId;
877
- name;
878
- icon;
879
- /**
880
- * Resolved official adapter. Set at construction for the instance form; for
881
- * the factory form it stays null until {@link resolveOfficial} constructs it
882
- * with the network-resolved host.
883
- */
884
- official;
885
- /** Factory form (null for the instance form). */
886
- factory;
887
- /** Network→host map for the factory form; injected by the SDK post-registry. */
888
- networkHosts;
889
- /** Lazily resolved from `official.provider()` — NOT at construction (SSR-safe). */
890
- providerInstance = null;
891
- /**
892
- * Which execute verb this wallet turned out to support. Resolved on the first
893
- * submit and reused, so the wallet is asked at most once.
894
- */
895
- executeVerb = {};
896
- capabilities;
455
+ capabilities;
897
456
  ledgerApi;
898
457
  constructor(args) {
899
458
  const configuration = { ...args, capabilities: args.capabilities && { ...args.capabilities } };
@@ -1224,7 +783,7 @@ function createSessionProvider(options) {
1224
783
  };
1225
784
  }
1226
785
 
1227
- // src/config.ts
786
+ // src/config-base.ts
1228
787
  var DEFAULT_REGISTRY_URL = "https://registry.partylayer.xyz";
1229
788
 
1230
789
  // src/adapters.ts
@@ -1255,54 +814,36 @@ var DefaultCrypto = class {
1255
814
  );
1256
815
  }
1257
816
  async encrypt(data, key) {
1258
- if (typeof crypto === "undefined" || !crypto.subtle) {
1259
- return btoa(data);
1260
- }
1261
- try {
1262
- const cryptoKey = await this.getKey(key);
1263
- const iv = crypto.getRandomValues(new Uint8Array(12));
1264
- const encoder = new TextEncoder();
1265
- const encoded = encoder.encode(data);
1266
- const encrypted = await crypto.subtle.encrypt(
1267
- { name: "AES-GCM", iv },
1268
- cryptoKey,
1269
- encoded
1270
- );
1271
- const combined = new Uint8Array(iv.length + encrypted.byteLength);
1272
- combined.set(iv);
1273
- combined.set(new Uint8Array(encrypted), iv.length);
1274
- return btoa(String.fromCharCode(...combined));
1275
- } catch {
1276
- return btoa(data);
1277
- }
817
+ const iv = new Uint8Array(this.randomBytes(12));
818
+ const cryptoKey = await this.getKey(key);
819
+ const encrypted = await globalThis.crypto.subtle.encrypt(
820
+ { name: "AES-GCM", iv },
821
+ cryptoKey,
822
+ new TextEncoder().encode(data)
823
+ );
824
+ const combined = new Uint8Array(iv.length + encrypted.byteLength);
825
+ combined.set(iv);
826
+ combined.set(new Uint8Array(encrypted), iv.length);
827
+ return btoa(String.fromCharCode(...combined));
1278
828
  }
1279
829
  async decrypt(encrypted, key) {
1280
- if (typeof crypto === "undefined" || !crypto.subtle) {
1281
- return atob(encrypted);
1282
- }
1283
- try {
1284
- const cryptoKey = await this.getKey(key);
1285
- const combined = Uint8Array.from(atob(encrypted), (c) => c.charCodeAt(0));
1286
- const iv = combined.slice(0, 12);
1287
- const data = combined.slice(12);
1288
- const decrypted = await crypto.subtle.decrypt(
1289
- { name: "AES-GCM", iv },
1290
- cryptoKey,
1291
- data
1292
- );
1293
- const decoder = new TextDecoder();
1294
- return decoder.decode(decrypted);
1295
- } catch {
1296
- return atob(encrypted);
1297
- }
830
+ const cryptoKey = await this.getKey(key);
831
+ const combined = Uint8Array.from(atob(encrypted), (character) => character.charCodeAt(0));
832
+ if (combined.length < 28) throw new Error("Invalid AES-GCM session ciphertext");
833
+ const decrypted = await globalThis.crypto.subtle.decrypt(
834
+ { name: "AES-GCM", iv: combined.slice(0, 12) },
835
+ cryptoKey,
836
+ combined.slice(12)
837
+ );
838
+ return new TextDecoder("utf-8", { fatal: true }).decode(decrypted);
839
+ }
840
+ randomBytes(byteLength) {
841
+ if (!globalThis.crypto?.getRandomValues) throw new Error("Secure random entropy is unavailable");
842
+ if (!Number.isInteger(byteLength) || byteLength < 1 || byteLength > 65536) throw new Error("Invalid secure byte length");
843
+ return globalThis.crypto.getRandomValues(new Uint8Array(byteLength));
1298
844
  }
1299
845
  async generateKey() {
1300
- if (typeof crypto === "undefined" || !crypto.getRandomValues) {
1301
- return Math.random().toString(36).substring(2, 15);
1302
- }
1303
- const array = new Uint8Array(32);
1304
- crypto.getRandomValues(array);
1305
- return Array.from(array, (b) => b.toString(16).padStart(2, "0")).join("");
846
+ return Array.from(this.randomBytes(32), (byte) => byte.toString(16).padStart(2, "0")).join("");
1306
847
  }
1307
848
  };
1308
849
  var DefaultStorage = class {
@@ -1363,22 +904,6 @@ var DefaultTelemetry = class {
1363
904
  error(_error, _properties) {
1364
905
  }
1365
906
  };
1366
- function getBuiltinAdapters() {
1367
- return [
1368
- new LoopAdapter(),
1369
- // 5N Loop - QR code / popup
1370
- new Cantor8Adapter(),
1371
- // Cantor8 - deep link transport
1372
- new NightlyAdapter()
1373
- // Nightly - multichain wallet (injected)
1374
- // Console is served via the generic CIP-0103 announce path (registry
1375
- // transport:'announce') — no longer in defaults; ConsoleAdapter stays
1376
- // exported below for opt-in manual/bespoke use.
1377
- // Send is served via the generic CIP-0103 announce path (registry
1378
- // transport:'announce') — no longer in defaults; SendAdapter stays exported
1379
- // below for opt-in manual/bespoke use.
1380
- ];
1381
- }
1382
907
  var SDK_VERSION = "0.3.0";
1383
908
  var MetricsTelemetryAdapter = class {
1384
909
  config;
@@ -1642,6 +1167,23 @@ function eventLogLevel(type) {
1642
1167
  return "info";
1643
1168
  }
1644
1169
  }
1170
+ var SESSION_ENTROPY_BYTES = 32;
1171
+ function createSecureSessionId(crypto2) {
1172
+ if (typeof globalThis.crypto?.getRandomValues === "function") return generateSessionId();
1173
+ if (!crypto2.randomBytes) throw new Error("Secure session entropy requires platform getRandomValues or CryptoAdapter.randomBytes");
1174
+ const encode = (bytes2) => {
1175
+ if (!(bytes2 instanceof Uint8Array) || bytes2.byteLength !== SESSION_ENTROPY_BYTES) {
1176
+ throw new Error("Session entropy must be a Uint8Array of exactly 32 bytes");
1177
+ }
1178
+ return toSessionId(`session_${Date.now()}_${Array.from(bytes2, (byte) => byte.toString(16).padStart(2, "0")).join("")}`);
1179
+ };
1180
+ const bytes = crypto2.randomBytes(SESSION_ENTROPY_BYTES);
1181
+ if (bytes instanceof Uint8Array) return encode(bytes);
1182
+ if (bytes && typeof bytes.then === "function") return Promise.resolve(bytes).then(encode);
1183
+ throw new Error("Session entropy must be a Uint8Array of exactly 32 bytes");
1184
+ }
1185
+
1186
+ // src/client-base.ts
1645
1187
  var SESSION_STORAGE_KEY = "active_session";
1646
1188
  var WALLETS_CHANGED_DEBOUNCE_MS = 50;
1647
1189
  function deriveAnnounceConfig(entry) {
@@ -1673,8 +1215,62 @@ function matchKnownByIdentity(providerId, base) {
1673
1215
  return providerId === String(w.walletId) || !!k && (providerId === k || providerId.startsWith(`${k}.`));
1674
1216
  });
1675
1217
  }
1218
+ function matchDiscoveredWallet(id, wallets) {
1219
+ return findMatchingWalletInfo(
1220
+ { provider: { id } },
1221
+ wallets
1222
+ ) ?? matchKnownByIdentity(id, wallets);
1223
+ }
1676
1224
  var DEFAULT_CONNECT_TIMEOUT_MS = 12e4;
1677
- var PartyLayerClient = class {
1225
+ var PartyLayerClientBase = class {
1226
+ constructor(config, runtime = {}) {
1227
+ this.runtime = runtime;
1228
+ this.config = config;
1229
+ if (config.app.origin) {
1230
+ this.origin = config.app.origin;
1231
+ } else if (typeof window !== "undefined") {
1232
+ this.origin = window.location.origin;
1233
+ } else {
1234
+ this.origin = "unknown";
1235
+ }
1236
+ this.logger = config.logger || new DefaultLogger();
1237
+ this.logLevel = config.logLevel ?? "info";
1238
+ this.crypto = config.crypto || new DefaultCrypto();
1239
+ this.storage = config.storage || new DefaultStorage();
1240
+ if (typeof window !== "undefined" && runtime.createOwner) {
1241
+ this.nativeOwner = runtime.createOwner((id, identity2) => this.onNativeIdentityChanged(id, identity2));
1242
+ }
1243
+ const telemetryAdapter = createTelemetryAdapter(config.telemetry);
1244
+ this.telemetry = telemetryAdapter || new DefaultTelemetry();
1245
+ const defaults = config.adapters ?? runtime.getBuiltinAdapters?.() ?? [];
1246
+ const adaptersToRegister = [...defaults, ...config.additionalAdapters ?? []];
1247
+ for (const adapterOrClass of adaptersToRegister) {
1248
+ let adapter;
1249
+ if (typeof adapterOrClass === "function") {
1250
+ adapter = new adapterOrClass();
1251
+ } else if (isOfficialAdapterFactory(adapterOrClass)) {
1252
+ adapter = new GenericDiscoveryAdapter({ factory: adapterOrClass });
1253
+ } else if (isOfficialProviderAdapter(adapterOrClass)) {
1254
+ adapter = new GenericDiscoveryAdapter({ official: adapterOrClass });
1255
+ } else {
1256
+ adapter = adapterOrClass;
1257
+ }
1258
+ this.registerAdapter(adapter);
1259
+ this.log("debug", "adapter:registered", "Registered wallet adapter", {
1260
+ walletId: adapter.walletId,
1261
+ name: adapter.name,
1262
+ capabilities: adapter.getCapabilities()
1263
+ });
1264
+ }
1265
+ this.registryClient = new RegistryClient({
1266
+ registryUrl: config.registryUrl || DEFAULT_REGISTRY_URL,
1267
+ channel: config.channel || "stable",
1268
+ registryPublicKeys: config.registryPublicKeys,
1269
+ storage: this.storage
1270
+ });
1271
+ this.updateRegistryStatus();
1272
+ if (!config.deferInitialization) this.initialize();
1273
+ }
1678
1274
  config;
1679
1275
  adapters = /* @__PURE__ */ new Map();
1680
1276
  destroyed = false;
@@ -1724,53 +1320,6 @@ var PartyLayerClient = class {
1724
1320
  origin;
1725
1321
  nativeOwner;
1726
1322
  sessionProvider;
1727
- constructor(config) {
1728
- this.config = config;
1729
- if (config.app.origin) {
1730
- this.origin = config.app.origin;
1731
- } else if (typeof window !== "undefined") {
1732
- this.origin = window.location.origin;
1733
- } else {
1734
- this.origin = "unknown";
1735
- }
1736
- this.logger = config.logger || new DefaultLogger();
1737
- this.logLevel = config.logLevel ?? "info";
1738
- this.crypto = config.crypto || new DefaultCrypto();
1739
- this.storage = config.storage || new DefaultStorage();
1740
- if (typeof window !== "undefined") {
1741
- this.nativeOwner = new NativeConnectionOwner((id, identity2) => this.onNativeIdentityChanged(id, identity2));
1742
- }
1743
- const telemetryAdapter = createTelemetryAdapter(config.telemetry);
1744
- this.telemetry = telemetryAdapter || new DefaultTelemetry();
1745
- const defaults = config.adapters ?? getBuiltinAdapters();
1746
- const adaptersToRegister = [...defaults, ...config.additionalAdapters ?? []];
1747
- for (const adapterOrClass of adaptersToRegister) {
1748
- let adapter;
1749
- if (typeof adapterOrClass === "function") {
1750
- adapter = new adapterOrClass();
1751
- } else if (isOfficialAdapterFactory(adapterOrClass)) {
1752
- adapter = new GenericDiscoveryAdapter({ factory: adapterOrClass });
1753
- } else if (isOfficialProviderAdapter(adapterOrClass)) {
1754
- adapter = new GenericDiscoveryAdapter({ official: adapterOrClass });
1755
- } else {
1756
- adapter = adapterOrClass;
1757
- }
1758
- this.registerAdapter(adapter);
1759
- this.log("debug", "adapter:registered", "Registered wallet adapter", {
1760
- walletId: adapter.walletId,
1761
- name: adapter.name,
1762
- capabilities: adapter.getCapabilities()
1763
- });
1764
- }
1765
- this.registryClient = new RegistryClient({
1766
- registryUrl: config.registryUrl || DEFAULT_REGISTRY_URL,
1767
- channel: config.channel || "stable",
1768
- registryPublicKeys: config.registryPublicKeys,
1769
- storage: this.storage
1770
- });
1771
- this.updateRegistryStatus();
1772
- if (!config.deferInitialization) this.initialize();
1773
- }
1774
1323
  /** Start browser discovery/restoration once; safe for framework effect replay. */
1775
1324
  initialize() {
1776
1325
  if (this.initialized || this.destroyed) return;
@@ -1899,7 +1448,7 @@ var PartyLayerClient = class {
1899
1448
  }
1900
1449
  /** Resolve only reviewed default SDKs present in the active registry. */
1901
1450
  async ensureDefaultWallets() {
1902
- if (this.config.adapters !== void 0) return;
1451
+ if (this.config.adapters !== void 0 || !this.runtime.loadDefaultWallet) return;
1903
1452
  let registry;
1904
1453
  try {
1905
1454
  registry = await this.registryClient.getRegistry();
@@ -1908,12 +1457,13 @@ var PartyLayerClient = class {
1908
1457
  }
1909
1458
  await Promise.all(registry.wallets.map(async (entry) => {
1910
1459
  const id = toWalletId(entry.id);
1911
- if (this.adapters.has(id) || !entry.supportedNetworks.includes(this.config.network) || entry.adapter?.transport === "discovery-adapter" && !entry.adapter.networkHosts?.[this.config.network]) return;
1460
+ const network = this.config.network;
1461
+ if (this.adapters.has(id) || !entry.supportedNetworks.includes(network) && !entry.additionalNetworks?.includes(network) || entry.adapter?.transport === "discovery-adapter" && !entry.adapter.networkHosts?.[network]) return;
1912
1462
  let pending = this.defaultLoads.get(entry.id);
1913
1463
  if (!pending) {
1914
1464
  pending = (async () => {
1915
1465
  try {
1916
- const entryAdapter = await loadDefaultWallet(entry.id, this.config, this.origin);
1466
+ const entryAdapter = await this.runtime.loadDefaultWallet(entry.id, this.config, this.origin);
1917
1467
  if (!entryAdapter || this.destroyed) return;
1918
1468
  const adapter = isOfficialAdapterFactory(entryAdapter) ? new GenericDiscoveryAdapter({
1919
1469
  factory: entryAdapter,
@@ -1921,8 +1471,9 @@ var PartyLayerClient = class {
1921
1471
  networkHosts: entry.adapter?.networkHosts,
1922
1472
  capabilities: entry.capabilities
1923
1473
  }) : entryAdapter;
1474
+ if (!this.registryNetworkSupported(entry, adapter)) return;
1924
1475
  if (typeof window !== "undefined" && adapter instanceof GenericDiscoveryAdapter) {
1925
- adapter.resolveOfficial(this.config.network);
1476
+ adapter.resolveOfficial(network);
1926
1477
  }
1927
1478
  this.registerAdapter(adapter);
1928
1479
  this.registryDefaultIds.add(id);
@@ -1939,6 +1490,10 @@ var PartyLayerClient = class {
1939
1490
  await pending;
1940
1491
  }));
1941
1492
  }
1493
+ registryNetworkSupported(entry, adapter) {
1494
+ const network = this.config.network;
1495
+ return entry.supportedNetworks.includes(network) || entry.additionalNetworks?.includes(network) === true && adapter?.supportsNetwork?.(network) === true;
1496
+ }
1942
1497
  /**
1943
1498
  * Hide registry entries whose wallet needs an app-registered adapter that is
1944
1499
  * NOT registered. This is the library default (RainbowKit-style): never show a
@@ -1960,18 +1515,23 @@ var PartyLayerClient = class {
1960
1515
  * adapters-only) or every non-announce entry is registered.
1961
1516
  */
1962
1517
  async gateUnconnectableEntries(wallets) {
1518
+ if (!this.runtime.browserDiscovery) wallets = wallets.filter((wallet) => this.adapters.has(wallet.walletId));
1963
1519
  let hidden = null;
1964
1520
  const announceCapabilities = /* @__PURE__ */ new Map();
1521
+ const additionalNetworks = /* @__PURE__ */ new Map();
1965
1522
  try {
1966
1523
  const registry = await this.registryClient.getRegistry();
1967
1524
  for (const entry of registry.wallets) {
1968
- if (entry.adapter?.transport === "announce") {
1525
+ const adapter = this.adapters.get(toWalletId(entry.id));
1526
+ if (entry.additionalNetworks && adapter) {
1527
+ additionalNetworks.set(entry.id, entry.additionalNetworks.filter((network) => adapter.supportsNetwork?.(network) === true));
1528
+ }
1529
+ if (entry.adapter?.transport === "announce" && this.runtime.browserDiscovery) {
1969
1530
  announceCapabilities.set(entry.id, getAnnounceCapabilities(deriveAnnounceConfig(entry)));
1970
1531
  continue;
1971
1532
  }
1972
- const walletId = toWalletId(entry.id);
1973
- if (!this.adapters.has(walletId)) {
1974
- (hidden ??= /* @__PURE__ */ new Set()).add(String(walletId));
1533
+ if (!adapter) {
1534
+ (hidden ??= /* @__PURE__ */ new Set()).add(entry.id);
1975
1535
  }
1976
1536
  }
1977
1537
  } catch {
@@ -1979,7 +1539,13 @@ var PartyLayerClient = class {
1979
1539
  }
1980
1540
  return wallets.filter((w) => !hidden?.has(String(w.walletId))).map((w) => {
1981
1541
  const capabilities = announceCapabilities.get(String(w.walletId));
1982
- return capabilities ? { ...w, capabilities } : w;
1542
+ const networks = additionalNetworks.get(String(w.walletId));
1543
+ if (!capabilities && !networks?.length) return w;
1544
+ return {
1545
+ ...w,
1546
+ capabilities: capabilities ?? w.capabilities,
1547
+ networks: networks?.length ? [.../* @__PURE__ */ new Set([...w.networks, ...networks])] : w.networks
1548
+ };
1983
1549
  });
1984
1550
  }
1985
1551
  /**
@@ -2008,7 +1574,7 @@ var PartyLayerClient = class {
2008
1574
  * ON in the browser and OFF under SSR (no `window`). Canonical: provider.md.
2009
1575
  */
2010
1576
  get announceEnabled() {
2011
- if (typeof window === "undefined") return false;
1577
+ if (typeof window === "undefined" || !this.runtime.browserDiscovery) return false;
2012
1578
  return this.config.discovery?.announce ?? true;
2013
1579
  }
2014
1580
  /**
@@ -2074,17 +1640,26 @@ var PartyLayerClient = class {
2074
1640
  createProvider: (a) => this.announceChannel(a.target ?? a.id)
2075
1641
  });
2076
1642
  const byId = /* @__PURE__ */ new Map();
2077
- for (const d of snapshot) byId.set(d.id, d);
2078
- for (const d of this.announceRegistry.values())
2079
- if (!byId.has(d.id)) byId.set(d.id, d);
1643
+ const matchedAnnouncements = /* @__PURE__ */ new Set();
1644
+ for (const d of snapshot) {
1645
+ const announced = this.announceRegistry.get(d.id);
1646
+ if (d.announcementId) matchedAnnouncements.add(d.announcementId);
1647
+ byId.set(d.id, {
1648
+ ...d,
1649
+ name: d.name ?? announced?.name,
1650
+ icon: d.icon ?? announced?.icon
1651
+ });
1652
+ }
1653
+ for (const announced of this.announceRegistry.values()) {
1654
+ if (!byId.has(announced.id) && !matchedAnnouncements.has(announced.id)) {
1655
+ byId.set(announced.id, announced);
1656
+ }
1657
+ }
2080
1658
  const discovered = [...byId.values()];
2081
1659
  const entries = [];
2082
1660
  for (const d of discovered) {
2083
1661
  if (d.identityResolved === false) continue;
2084
- const known = findMatchingWalletInfo(
2085
- { provider: { id: d.id } },
2086
- base
2087
- ) ?? matchKnownByIdentity(d.id, base);
1662
+ const known = matchDiscoveredWallet(d.id, base) ?? (d.announcementId ? matchDiscoveredWallet(d.announcementId, base) : void 0);
2088
1663
  if (known) {
2089
1664
  if (this.adapters.has(known.walletId)) continue;
2090
1665
  try {
@@ -2148,7 +1723,7 @@ var PartyLayerClient = class {
2148
1723
  adapter: { packageName: "announced", versionRange: "*" },
2149
1724
  docs: [],
2150
1725
  networks: [this.config.network || "devnet"],
2151
- channel: "stable"
1726
+ channel: this.config.channel ?? "stable"
2152
1727
  });
2153
1728
  }
2154
1729
  this.announceEntriesCache = entries;
@@ -2244,7 +1819,7 @@ var PartyLayerClient = class {
2244
1819
  const nativeAdapter = this.adapters.get(options.walletId);
2245
1820
  if (nativeAdapter) {
2246
1821
  const entry = await this.registryClient.getWalletEntry(String(options.walletId)).catch(() => null);
2247
- if (entry?.supportedNetworks?.length && !entry.supportedNetworks.includes(this.config.network)) {
1822
+ if (entry?.supportedNetworks?.length && !this.registryNetworkSupported(entry, nativeAdapter)) {
2248
1823
  throw new WalletNotFoundError(`${String(options.walletId)} is unavailable on ${this.config.network}`);
2249
1824
  }
2250
1825
  isNativeWallet = true;
@@ -2269,13 +1844,20 @@ var PartyLayerClient = class {
2269
1844
  }
2270
1845
  }
2271
1846
  } else if (availableWallets.length === 0) {
2272
- throw new WalletNotFoundError("No wallets available");
1847
+ throw new WalletNotFoundError(this.runtime.noWalletsMessage ?? "No wallets available");
2273
1848
  } else {
2274
1849
  selectedWallet = availableWallets[0];
2275
1850
  }
2276
1851
  const adapter = this.adapters.get(selectedWallet.walletId);
2277
1852
  if (!adapter) {
2278
- throw new WalletNotFoundError(String(selectedWallet.walletId));
1853
+ const walletId = String(selectedWallet.walletId);
1854
+ if (this.announceEnabled) {
1855
+ const entry = await this.registryClient.getWalletEntry(walletId).catch(() => null);
1856
+ if (entry?.adapter?.transport === "announce") {
1857
+ throw new WalletNotInstalledError(walletId);
1858
+ }
1859
+ }
1860
+ throw new WalletNotFoundError(walletId);
2279
1861
  }
2280
1862
  if (!isNativeWallet) {
2281
1863
  try {
@@ -2317,8 +1899,8 @@ var PartyLayerClient = class {
2317
1899
  return { selectedWallet, adapter, ctx, isNativeWallet };
2318
1900
  }
2319
1901
  /**
2320
- * Invoke `adapter.connect()` (its FIRST statement — no await precedes it) and
2321
- * build / persist / emit the session. Separated from plan resolution so the
1902
+ * Generate secure entropy, invoke `adapter.connect()` without awaiting the
1903
+ * platform RNG path, then build / persist / emit the session. Separated from plan resolution so the
2322
1904
  * popup-safe fast-path can call it gesture-synchronously.
2323
1905
  */
2324
1906
  async completeConnect(plan, options, correlationId = newCorrelationId(), attempt) {
@@ -2328,6 +1910,9 @@ var PartyLayerClient = class {
2328
1910
  if (attempt === void 0) ++this.sessionRevision;
2329
1911
  if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
2330
1912
  const { selectedWallet, adapter, ctx } = plan;
1913
+ const entropy = createSecureSessionId(this.crypto);
1914
+ const sessionId = typeof entropy === "string" ? entropy : await entropy;
1915
+ if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
2331
1916
  if (!nativeOwnerBindings.has(adapter) && this.nativeOwner?.getSession()) this.nativeOwner.release();
2332
1917
  const timeoutMs = options?.timeoutMs || DEFAULT_CONNECT_TIMEOUT_MS;
2333
1918
  const abort = new AbortController();
@@ -2353,7 +1938,7 @@ var PartyLayerClient = class {
2353
1938
  }
2354
1939
  if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
2355
1940
  const session = {
2356
- sessionId: toSessionId(`session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`),
1941
+ sessionId,
2357
1942
  walletId: selectedWallet.walletId,
2358
1943
  partyId: result.partyId,
2359
1944
  // The wallet's reported network (adapters that read the live wallet —
@@ -2972,6 +2557,8 @@ var PartyLayerClient = class {
2972
2557
  this.activeSessionNeedsProbe = true;
2973
2558
  return session;
2974
2559
  } catch (err) {
2560
+ if (!current()) return this.activeSession;
2561
+ await this.removeSession();
2975
2562
  this.log("warn", "session:restore_failed", "Failed to restore session", {
2976
2563
  error: err instanceof Error ? err.message : String(err)
2977
2564
  }, correlationId);
@@ -3071,6 +2658,477 @@ var PartyLayerClient = class {
3071
2658
  }
3072
2659
  }
3073
2660
  };
2661
+ function getBuiltinAdapters() {
2662
+ return [
2663
+ new LoopAdapter(),
2664
+ // 5N Loop - QR code / popup
2665
+ new Cantor8Adapter(),
2666
+ // Cantor8 - deep link transport
2667
+ new NightlyAdapter()
2668
+ // Nightly - multichain wallet (injected)
2669
+ // Console is served via the generic CIP-0103 announce path (registry
2670
+ // transport:'announce') — no longer in defaults; ConsoleAdapter stays
2671
+ // exported below for opt-in manual/bespoke use.
2672
+ // Send is served via the generic CIP-0103 announce path (registry
2673
+ // transport:'announce') — no longer in defaults; SendAdapter stays exported
2674
+ // below for opt-in manual/bespoke use.
2675
+ ];
2676
+ }
2677
+ var loaders = {
2678
+ walley: async () => {
2679
+ const { WalleyAdapter } = await import('@k2flabs/walley-dapp-sdk');
2680
+ return { providerId: "walley", create: (host) => new WalleyAdapter({ host }) };
2681
+ },
2682
+ cauri: async () => {
2683
+ const { cauriAdapterFactory } = await import('@lithiumdigital/cauri-dapp-sdk');
2684
+ return cauriAdapterFactory;
2685
+ },
2686
+ oneswap: async (network) => {
2687
+ const { createOneSwapHostedAdapter } = await import('#partylayer-hosted-wallet-profiles');
2688
+ return {
2689
+ providerId: "oneswap",
2690
+ create: (host) => createOneSwapHostedAdapter({
2691
+ walletUrl: host,
2692
+ networkId: toCAIP2Network(network).networkId
2693
+ })
2694
+ };
2695
+ },
2696
+ vala: async () => {
2697
+ const { valaAdapterFactory } = await import('@vala-wallet/dapp-sdk');
2698
+ return valaAdapterFactory;
2699
+ }
2700
+ };
2701
+ async function loadDefaultWallet(id, config, origin) {
2702
+ if (id === "walletconnect" && config.walletConnect?.projectId.trim()) {
2703
+ const { WalletConnectAdapter } = await import('@partylayer/adapter-walletconnect');
2704
+ return new WalletConnectAdapter({
2705
+ ...config.walletConnect,
2706
+ metadata: config.walletConnect.metadata ?? {
2707
+ name: config.app.name,
2708
+ description: config.app.name,
2709
+ url: origin === "unknown" ? "" : origin,
2710
+ icons: []
2711
+ }
2712
+ });
2713
+ }
2714
+ if (id === "bron" && config.bron) {
2715
+ const { BronAdapter: BronAdapter2 } = await import('@partylayer/adapter-bron');
2716
+ return new BronAdapter2(config.bron);
2717
+ }
2718
+ return Object.prototype.hasOwnProperty.call(loaders, id) ? loaders[id](config.network) : void 0;
2719
+ }
2720
+ var SILENT_PROBE_TIMEOUT_MS = 1e4;
2721
+ function disconnected() {
2722
+ return new Error("Native wallet connection is no longer active");
2723
+ }
2724
+ function teardown(source) {
2725
+ try {
2726
+ source?.teardown?.();
2727
+ } catch {
2728
+ }
2729
+ }
2730
+ function abortable(promise, signal) {
2731
+ return new Promise((resolve, reject) => {
2732
+ const abort = () => reject(disconnected());
2733
+ if (signal.aborted) {
2734
+ reject(disconnected());
2735
+ return;
2736
+ }
2737
+ signal.addEventListener("abort", abort, { once: true });
2738
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
2739
+ });
2740
+ }
2741
+ async function readIdentity(provider, registration, signal) {
2742
+ const account = await abortable(
2743
+ provider.request({ method: "getPrimaryAccount" }),
2744
+ signal
2745
+ );
2746
+ assertPrimaryParty(account);
2747
+ let status;
2748
+ try {
2749
+ status = await abortable(provider.request({ method: "status" }), signal);
2750
+ } catch (error) {
2751
+ if (signal.aborted) throw error;
2752
+ }
2753
+ if (status?.isConnected === false || status?.connection?.isConnected === false)
2754
+ throw disconnected();
2755
+ const network = [status?.network?.networkId, account.networkId, registration.network].find(
2756
+ (value) => typeof value === "string" && isRecognizedNetwork(value)
2757
+ ) ?? registration.network;
2758
+ if (registration.expected && (account.partyId !== registration.expected.partyId || detectNetworkMismatch(registration.expected.network, network)))
2759
+ throw disconnected();
2760
+ if (signal.aborted) throw disconnected();
2761
+ return { account, network, status };
2762
+ }
2763
+ var NativeConnectionOwner = class {
2764
+ constructor(changed = () => {
2765
+ }) {
2766
+ this.changed = changed;
2767
+ }
2768
+ client = null;
2769
+ initialization = null;
2770
+ registrations = /* @__PURE__ */ new Map();
2771
+ operation = null;
2772
+ pending = null;
2773
+ closing = null;
2774
+ projection = null;
2775
+ unsubscribers = [];
2776
+ disposed = false;
2777
+ refreshRevision = 0;
2778
+ identityRefreshing = false;
2779
+ probes = /* @__PURE__ */ new Set();
2780
+ get busy() {
2781
+ return this.operation !== null || this.closing !== null;
2782
+ }
2783
+ assertAvailable() {
2784
+ if (this.disposed) throw disconnected();
2785
+ if (this.busy) throw new Error("A native wallet operation is already in progress");
2786
+ }
2787
+ /** Run during picker preparation, never between a click and provider.connect. */
2788
+ async prepare(id, source, network) {
2789
+ if (this.disposed) throw disconnected();
2790
+ this.registrations.set(id, { id, source, network });
2791
+ if (!this.initialization) {
2792
+ this.initialization = (async () => {
2793
+ const { DiscoveryClient } = await import('@canton-network/core-wallet-discovery');
2794
+ const client = await DiscoveryClient.create({ adapters: [] });
2795
+ if (this.disposed) {
2796
+ client.destroy();
2797
+ return;
2798
+ }
2799
+ this.client = client;
2800
+ })();
2801
+ }
2802
+ await this.initialization;
2803
+ if (this.disposed || !this.client) throw disconnected();
2804
+ for (const registration of this.registrations.values())
2805
+ this.client.registerAdapter(this.wrap(registration));
2806
+ }
2807
+ wrap(registration) {
2808
+ const source = registration.source;
2809
+ return {
2810
+ providerId: registration.id,
2811
+ name: source.name,
2812
+ type: source.type === "desktop" || source.type === "mobile" || source.type === "remote" ? source.type : "browser",
2813
+ icon: source.icon,
2814
+ getInfo: () => ({
2815
+ providerId: registration.id,
2816
+ name: source.name,
2817
+ type: "browser",
2818
+ icon: source.icon
2819
+ }),
2820
+ detect: () => source.detect(),
2821
+ provider: () => this.guard(source.provider(), registration),
2822
+ teardown: () => teardown(source),
2823
+ restore: async () => {
2824
+ const operation = this.operation;
2825
+ if (!operation) throw disconnected();
2826
+ try {
2827
+ const raw = source.restore ? await abortable(source.restore(), operation.abort.signal) : source.provider();
2828
+ if (!raw) return null;
2829
+ const provider = raw;
2830
+ operation.identity = await readIdentity(provider, registration, operation.abort.signal);
2831
+ return this.guard(provider, registration);
2832
+ } catch (error) {
2833
+ teardown(source);
2834
+ throw error;
2835
+ }
2836
+ }
2837
+ };
2838
+ }
2839
+ guard(raw, registration) {
2840
+ const provider = {
2841
+ request: async (args) => {
2842
+ if (this.disposed) throw disconnected();
2843
+ if (args.method !== "connect") {
2844
+ if (this.client?.getActiveSession()?.provider !== provider) throw disconnected();
2845
+ if (!this.projection && args.method !== "disconnect") throw disconnected();
2846
+ if (this.identityRefreshing && ![
2847
+ "status",
2848
+ "getPrimaryAccount",
2849
+ "listAccounts",
2850
+ "getActiveNetwork",
2851
+ "isConnected"
2852
+ ].includes(args.method)) {
2853
+ throw new Error("Native wallet identity is being refreshed");
2854
+ }
2855
+ const result = await (args.method === "disconnect" && this.operation ? abortable(raw.request(args), this.operation.abort.signal) : raw.request(args));
2856
+ if (args.method === "status") {
2857
+ const status = result;
2858
+ if (status?.isConnected === false || status?.connection?.isConnected === false) {
2859
+ this.invalidate(registration.id);
2860
+ }
2861
+ }
2862
+ return result;
2863
+ }
2864
+ const operation = this.operation;
2865
+ if (!operation || operation.abort.signal.aborted) throw disconnected();
2866
+ const response = await abortable(raw.request(args), operation.abort.signal);
2867
+ assertConnectionAccepted(response);
2868
+ operation.identity = await readIdentity(raw, registration, operation.abort.signal);
2869
+ return response;
2870
+ },
2871
+ on: (event, listener) => {
2872
+ raw.on(event, listener);
2873
+ return provider;
2874
+ },
2875
+ emit: (event, ...args) => raw.emit(event, ...args),
2876
+ removeListener: (event, listener) => {
2877
+ raw.removeListener(event, listener);
2878
+ return provider;
2879
+ }
2880
+ };
2881
+ return provider;
2882
+ }
2883
+ /** No await precedes the official client's connect call. */
2884
+ connect(id, signal) {
2885
+ this.assertAvailable();
2886
+ if (!this.client || !this.registrations.has(id))
2887
+ return Promise.reject(new Error("Native wallet was not prepared"));
2888
+ const operation = { abort: new AbortController(), id };
2889
+ this.operation = operation;
2890
+ this.detach();
2891
+ const previous = this.client.getActiveSession();
2892
+ teardown(previous?.adapter);
2893
+ const previousId = this.projection?.id;
2894
+ this.projection = null;
2895
+ if (previousId) this.changed(previousId, null);
2896
+ const abort = () => operation.abort.abort();
2897
+ if (signal?.aborted) abort();
2898
+ signal?.addEventListener("abort", abort, { once: true });
2899
+ const task = (async () => {
2900
+ try {
2901
+ await this.client.connect(id);
2902
+ if (operation.abort.signal.aborted || this.disposed || !operation.identity)
2903
+ throw disconnected();
2904
+ this.projection = { id, identity: operation.identity };
2905
+ this.attach(id);
2906
+ return operation.identity;
2907
+ } catch (error) {
2908
+ this.client?.destroy();
2909
+ this.client = null;
2910
+ this.initialization = null;
2911
+ teardown(this.registrations.get(id)?.source);
2912
+ throw error;
2913
+ } finally {
2914
+ signal?.removeEventListener("abort", abort);
2915
+ if (this.operation === operation) this.operation = null;
2916
+ }
2917
+ })();
2918
+ this.pending = task;
2919
+ void task.then(
2920
+ () => {
2921
+ if (this.pending === task) this.pending = null;
2922
+ },
2923
+ () => {
2924
+ if (this.pending === task) this.pending = null;
2925
+ }
2926
+ );
2927
+ return task;
2928
+ }
2929
+ async restore(expected) {
2930
+ if (!this.client || this.projection || this.busy || this.disposed) return this.getSession();
2931
+ const registration = expected && this.registrations.get(expected.id);
2932
+ if (registration) registration.expected = expected;
2933
+ const operation = { abort: new AbortController() };
2934
+ this.operation = operation;
2935
+ const timeout = setTimeout(() => operation.abort.abort(), SILENT_PROBE_TIMEOUT_MS);
2936
+ const task = (async () => {
2937
+ try {
2938
+ await this.client.restorePersistedSessionIfNeeded();
2939
+ const active = this.client?.getActiveSession();
2940
+ if (!active || !operation.identity || operation.abort.signal.aborted || this.disposed)
2941
+ return null;
2942
+ if (expected && active.providerId !== expected.id) {
2943
+ teardown(active.adapter);
2944
+ this.client.destroy();
2945
+ this.client = null;
2946
+ this.initialization = null;
2947
+ return null;
2948
+ }
2949
+ const id = String(active.providerId);
2950
+ this.projection = { id, identity: operation.identity };
2951
+ this.attach(id);
2952
+ return this.getSession();
2953
+ } finally {
2954
+ clearTimeout(timeout);
2955
+ if (registration) delete registration.expected;
2956
+ if (this.operation === operation) this.operation = null;
2957
+ }
2958
+ })();
2959
+ this.pending = task;
2960
+ try {
2961
+ return await task;
2962
+ } finally {
2963
+ if (this.pending === task) this.pending = null;
2964
+ }
2965
+ }
2966
+ getSession() {
2967
+ if (this.disposed || !this.client?.getActiveSession() || !this.projection) return null;
2968
+ return this.projection;
2969
+ }
2970
+ getProvider(id) {
2971
+ if (!this.getSession() || id && this.projection?.id !== id) throw disconnected();
2972
+ return this.client.getProvider();
2973
+ }
2974
+ /** A bare signature must not be attributed to an old, eventless primary party. */
2975
+ async validateIdentity(id, partyId, network) {
2976
+ const provider = this.getProvider(id);
2977
+ const revision = ++this.refreshRevision;
2978
+ this.identityRefreshing = true;
2979
+ let verified = false;
2980
+ try {
2981
+ const identity2 = await this.probe(provider, this.registrations.get(id));
2982
+ if (revision !== this.refreshRevision || this.getProvider(id) !== provider)
2983
+ throw disconnected();
2984
+ verified = true;
2985
+ this.projection = { id, identity: identity2 };
2986
+ if (identity2.account.partyId !== partyId || detectNetworkMismatch(network, identity2.network)) {
2987
+ this.changed(id, identity2);
2988
+ throw new Error("Wallet identity changed during message signing");
2989
+ }
2990
+ } catch (error) {
2991
+ if (!verified && revision === this.refreshRevision) this.invalidate(id);
2992
+ throw error;
2993
+ } finally {
2994
+ if (revision === this.refreshRevision) this.identityRefreshing = false;
2995
+ }
2996
+ }
2997
+ async probe(provider, registration) {
2998
+ const abort = new AbortController();
2999
+ this.probes.add(abort);
3000
+ const timeout = setTimeout(() => abort.abort(), SILENT_PROBE_TIMEOUT_MS);
3001
+ try {
3002
+ return await readIdentity(provider, registration, abort.signal);
3003
+ } finally {
3004
+ clearTimeout(timeout);
3005
+ this.probes.delete(abort);
3006
+ }
3007
+ }
3008
+ detach() {
3009
+ ++this.refreshRevision;
3010
+ this.identityRefreshing = false;
3011
+ for (const probe of this.probes) probe.abort();
3012
+ this.probes.clear();
3013
+ this.unsubscribers.splice(0).forEach((unsubscribe) => {
3014
+ try {
3015
+ unsubscribe();
3016
+ } catch {
3017
+ }
3018
+ });
3019
+ }
3020
+ attach(id) {
3021
+ const provider = this.getProvider(id);
3022
+ const update = (payload) => {
3023
+ const status = payload;
3024
+ if (status?.connection?.isConnected === false || status?.isConnected === false || Array.isArray(payload) && payload.length === 0) {
3025
+ this.invalidate(id);
3026
+ return;
3027
+ }
3028
+ const revision = ++this.refreshRevision;
3029
+ this.identityRefreshing = true;
3030
+ const registration = this.registrations.get(id);
3031
+ void this.probe(provider, registration).then(
3032
+ (identity2) => {
3033
+ if (revision !== this.refreshRevision || this.projection?.id !== id || this.disposed)
3034
+ return;
3035
+ this.identityRefreshing = false;
3036
+ this.projection = { id, identity: identity2 };
3037
+ this.changed(id, identity2);
3038
+ },
3039
+ () => {
3040
+ if (revision === this.refreshRevision) this.invalidate(id);
3041
+ }
3042
+ );
3043
+ };
3044
+ for (const event of ["accountsChanged", "statusChanged"]) {
3045
+ provider.on(event, update);
3046
+ this.unsubscribers.push(() => provider.removeListener(event, update));
3047
+ }
3048
+ }
3049
+ invalidate(id) {
3050
+ if (this.projection?.id !== id) return;
3051
+ this.detach();
3052
+ this.projection = null;
3053
+ teardown(this.client?.getActiveSession()?.adapter);
3054
+ this.client?.destroy();
3055
+ this.client = null;
3056
+ this.initialization = null;
3057
+ this.changed(id, null);
3058
+ }
3059
+ /** Local transport cleanup when switching to a proprietary integration. */
3060
+ release() {
3061
+ this.assertAvailable();
3062
+ const id = this.projection?.id;
3063
+ this.detach();
3064
+ this.projection = null;
3065
+ teardown(this.client?.getActiveSession()?.adapter);
3066
+ this.client?.destroy();
3067
+ this.client = null;
3068
+ this.initialization = null;
3069
+ if (id) this.changed(id, null);
3070
+ }
3071
+ disconnect() {
3072
+ if (this.closing) return this.closing;
3073
+ this.operation?.abort.abort();
3074
+ const task = (async () => {
3075
+ await this.pending?.catch(() => {
3076
+ });
3077
+ this.detach();
3078
+ const id = this.projection?.id;
3079
+ this.projection = null;
3080
+ const operation = { abort: new AbortController() };
3081
+ this.operation = operation;
3082
+ const timeout = setTimeout(() => operation.abort.abort(), SILENT_PROBE_TIMEOUT_MS);
3083
+ try {
3084
+ await this.client?.disconnect();
3085
+ } finally {
3086
+ clearTimeout(timeout);
3087
+ if (this.client?.getActiveSession()) {
3088
+ this.client.destroy();
3089
+ this.client = null;
3090
+ this.initialization = null;
3091
+ }
3092
+ this.operation = null;
3093
+ if (id) this.changed(id, null);
3094
+ }
3095
+ })();
3096
+ this.closing = task;
3097
+ void task.then(
3098
+ () => {
3099
+ if (this.closing === task) this.closing = null;
3100
+ },
3101
+ () => {
3102
+ if (this.closing === task) this.closing = null;
3103
+ }
3104
+ );
3105
+ return task;
3106
+ }
3107
+ destroy() {
3108
+ if (this.disposed) return;
3109
+ this.disposed = true;
3110
+ this.operation?.abort.abort();
3111
+ this.detach();
3112
+ this.projection = null;
3113
+ teardown(this.client?.getActiveSession()?.adapter);
3114
+ if (!this.client?.getActiveSession() && this.operation?.id)
3115
+ teardown(this.registrations.get(this.operation.id)?.source);
3116
+ this.client?.destroy();
3117
+ this.client = null;
3118
+ }
3119
+ };
3120
+
3121
+ // src/client.ts
3122
+ var PartyLayerClient = class extends PartyLayerClientBase {
3123
+ constructor(config) {
3124
+ super(config, {
3125
+ getBuiltinAdapters,
3126
+ loadDefaultWallet: (id, _sharedConfig, origin) => loadDefaultWallet(id, config, origin),
3127
+ createOwner: (onIdentityChanged) => new NativeConnectionOwner(onIdentityChanged),
3128
+ browserDiscovery: true
3129
+ });
3130
+ }
3131
+ };
3074
3132
  function createPartyLayer(config) {
3075
3133
  return new PartyLayerClient(config);
3076
3134
  }