@partylayer/sdk 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- import { hashForPrivacy, createMetricsPayload, mapUnknownErrorToPartyLayerError, detectNetworkMismatch, NetworkMismatchError, METRICS, WalletNotFoundError, capabilityGuard, installGuard, toSessionId, CapabilityNotSupportedError, errorMetricName } from '@partylayer/core';
2
- export { PartyLayerError as CantonConnectError, CapabilityNotSupportedError, ENABLEMENT_METRICS, ERROR_METRICS, InternalError, METRICS, OriginNotAllowedError, PartyLayerError, REGISTRY_METRICS, RegistryFetchFailedError, RegistrySchemaInvalidError, RegistryVerificationFailedError, SessionExpiredError, TimeoutError, TransportError, UserRejectedError, WalletNotFoundError, WalletNotInstalledError, errorMetricName } from '@partylayer/core';
1
+ import { toWalletId, toPartyId, hashForPrivacy, createMetricsPayload, isOfficialProviderAdapter, mapUnknownErrorToPartyLayerError, findMatchingWalletInfo, detectNetworkMismatch, NetworkMismatchError, METRICS, WalletNotFoundError, capabilityGuard, installGuard, toSessionId, CapabilityNotSupportedError, errorMetricName } from '@partylayer/core';
2
+ export { PartyLayerError as CantonConnectError, CapabilityNotSupportedError, ENABLEMENT_METRICS, ERROR_METRICS, InternalError, METRICS, OriginNotAllowedError, PartyLayerError, REGISTRY_METRICS, RegistryFetchFailedError, RegistrySchemaInvalidError, RegistryVerificationFailedError, SessionExpiredError, TimeoutError, TransportError, UserRejectedError, WalletNotFoundError, WalletNotInstalledError, errorMetricName, isOfficialProviderAdapter } from '@partylayer/core';
3
3
  import { RegistryClient } from '@partylayer/registry-client';
4
4
  export { deriveGenericWalletName, findMatchingWallet, findMatchingWalletInfo, isCip0103Native, matchesProviderDetection } from '@partylayer/registry-client';
5
- import { createProviderBridge } from '@partylayer/provider';
5
+ import { discoverProviders, createExtensionChannelProvider, createProviderBridge } from '@partylayer/provider';
6
6
  export { CANTON_NETWORKS, CIP0103EventBus, CIP0103_EVENTS, CIP0103_MANDATORY_METHODS, CIP0103_METHODS, JSON_RPC_ERRORS, PartyLayerProvider, ProviderRpcError, RPC_ERRORS, createProviderBridge, discoverInjectedProviders, fromCAIP2Network, isCIP0103Provider, isValidCAIP2, toCAIP2Network, waitForProvider } from '@partylayer/provider';
7
7
  import { ConsoleAdapter } from '@partylayer/adapter-console';
8
8
  export { ConsoleAdapter } from '@partylayer/adapter-console';
@@ -17,6 +17,155 @@ export { SendAdapter } from '@partylayer/adapter-send';
17
17
  export { BronAdapter } from '@partylayer/adapter-bron';
18
18
 
19
19
  // src/client.ts
20
+ var ANNOUNCED_WALLET_ID_PREFIX = "browser:ext:";
21
+ function announcedWalletId(announceId) {
22
+ return toWalletId(`${ANNOUNCED_WALLET_ID_PREFIX}${announceId}`);
23
+ }
24
+ var GenericAnnounceAdapter = class {
25
+ walletId;
26
+ name;
27
+ /** Icon surfaced to the picker (announce detail). */
28
+ icon;
29
+ provider;
30
+ constructor(args) {
31
+ this.walletId = announcedWalletId(args.announceId);
32
+ this.name = args.name && args.name.length > 0 ? args.name : `Canton Wallet (${args.announceId.slice(0, 6)}\u2026)`;
33
+ this.icon = args.icon;
34
+ this.provider = args.provider;
35
+ }
36
+ /** Baseline CIP-0103 capabilities every announced wallet must implement. */
37
+ getCapabilities() {
38
+ return ["connect", "signMessage", "submitTransaction"];
39
+ }
40
+ /**
41
+ * The adapter is only ever constructed for a wallet that just announced, so
42
+ * its presence is established by the announce handshake itself.
43
+ */
44
+ async detectInstalled() {
45
+ return { installed: true, reason: "Announced via canton:announceProvider" };
46
+ }
47
+ async connect(ctx) {
48
+ await this.provider.request({ method: "connect" });
49
+ const account = await this.provider.request({
50
+ method: "getPrimaryAccount"
51
+ });
52
+ let reportedNetwork;
53
+ try {
54
+ const status = await this.provider.request({
55
+ method: "status"
56
+ });
57
+ reportedNetwork = status?.network?.networkId;
58
+ } catch {
59
+ }
60
+ const partyId = toPartyId(account.partyId);
61
+ const session = {
62
+ walletId: this.walletId,
63
+ partyId,
64
+ network: reportedNetwork ?? account.networkId ?? ctx.network
65
+ };
66
+ return { partyId, session, capabilities: this.getCapabilities() };
67
+ }
68
+ async disconnect() {
69
+ try {
70
+ await this.provider.request({ method: "disconnect" });
71
+ } catch {
72
+ }
73
+ }
74
+ async signMessage(_ctx, _session, params) {
75
+ return this.provider.request({
76
+ method: "signMessage",
77
+ params: { message: params.message }
78
+ });
79
+ }
80
+ async submitTransaction(_ctx, _session, params) {
81
+ return this.provider.request({
82
+ method: "prepareExecute",
83
+ params
84
+ });
85
+ }
86
+ };
87
+ var GenericDiscoveryAdapter = class {
88
+ walletId;
89
+ name;
90
+ icon;
91
+ official;
92
+ /** Lazily resolved from `official.provider()` — NOT at construction (SSR-safe). */
93
+ providerInstance = null;
94
+ constructor(args) {
95
+ this.official = args.official;
96
+ this.walletId = args.walletId ?? toWalletId(args.official.providerId);
97
+ this.name = args.name && args.name.length > 0 ? args.name : args.official.name;
98
+ this.icon = args.icon ?? args.official.icon;
99
+ }
100
+ /** Lazily obtain (and cache) the official provider — deferred off the init/SSR path.
101
+ * `official.provider()` is typed `OfficialProvider` (loose `request` so real
102
+ * official adapters are assignable); it is call-compatible with CIP0103Provider
103
+ * (the bridge only ever calls `request({ method, params })`). */
104
+ get provider() {
105
+ if (this.providerInstance === null) {
106
+ this.providerInstance = this.official.provider();
107
+ }
108
+ return this.providerInstance;
109
+ }
110
+ /**
111
+ * Baseline CIP-0103 capabilities. NEVER includes `'events'`: popup/remote
112
+ * wallets expose the event surface but do not emit (truthfulness doctrine).
113
+ */
114
+ getCapabilities() {
115
+ return ["connect", "disconnect", "signMessage", "submitTransaction"];
116
+ }
117
+ /** Install/availability probe — delegated to the official adapter (popup-free). */
118
+ async detectInstalled() {
119
+ try {
120
+ const installed = await this.official.detect();
121
+ return {
122
+ installed,
123
+ reason: installed ? void 0 : "Wallet reported not available"
124
+ };
125
+ } catch {
126
+ return { installed: false, reason: "Detection failed" };
127
+ }
128
+ }
129
+ async connect(ctx) {
130
+ await this.provider.request({ method: "connect" });
131
+ const account = await this.provider.request({
132
+ method: "getPrimaryAccount"
133
+ });
134
+ let reportedNetwork;
135
+ try {
136
+ const status = await this.provider.request({
137
+ method: "status"
138
+ });
139
+ reportedNetwork = status?.network?.networkId;
140
+ } catch {
141
+ }
142
+ const partyId = toPartyId(account.partyId);
143
+ const session = {
144
+ walletId: this.walletId,
145
+ partyId,
146
+ network: reportedNetwork ?? account.networkId ?? ctx.network
147
+ };
148
+ return { partyId, session, capabilities: this.getCapabilities() };
149
+ }
150
+ async disconnect() {
151
+ try {
152
+ await this.provider.request({ method: "disconnect" });
153
+ } catch {
154
+ }
155
+ }
156
+ async signMessage(_ctx, _session, params) {
157
+ return this.provider.request({
158
+ method: "signMessage",
159
+ params: { message: params.message }
160
+ });
161
+ }
162
+ async submitTransaction(_ctx, _session, params) {
163
+ return this.provider.request({
164
+ method: "prepareExecute",
165
+ params
166
+ });
167
+ }
168
+ };
20
169
 
21
170
  // src/config.ts
22
171
  var DEFAULT_REGISTRY_URL = "https://registry.partylayer.xyz";
@@ -371,6 +520,13 @@ var SESSION_STORAGE_KEY = "active_session";
371
520
  var PartyLayerClient = class {
372
521
  config;
373
522
  adapters = /* @__PURE__ */ new Map();
523
+ /**
524
+ * Pre-resolved connect plans for popup/remote (GenericDiscoveryAdapter)
525
+ * wallets, warmed on `listWallets()` (which the modal calls on open) so a
526
+ * subsequent click can connect gesture-synchronously. Consumed (deleted) on
527
+ * use and cleared on disconnect; a cold miss falls back to the normal path.
528
+ */
529
+ warmPlans = /* @__PURE__ */ new Map();
374
530
  eventHandlers = /* @__PURE__ */ new Map();
375
531
  activeSession = null;
376
532
  registryClient;
@@ -379,6 +535,8 @@ var PartyLayerClient = class {
379
535
  crypto;
380
536
  storage;
381
537
  telemetry;
538
+ /** Cached announce-discovery picker entries (one-shot; cleared by refreshDiscovery). */
539
+ announceEntriesCache = null;
382
540
  origin;
383
541
  constructor(config) {
384
542
  this.config = config;
@@ -399,6 +557,8 @@ var PartyLayerClient = class {
399
557
  let adapter;
400
558
  if (typeof adapterOrClass === "function") {
401
559
  adapter = new adapterOrClass();
560
+ } else if (isOfficialProviderAdapter(adapterOrClass)) {
561
+ adapter = new GenericDiscoveryAdapter({ official: adapterOrClass });
402
562
  } else {
403
563
  adapter = adapterOrClass;
404
564
  }
@@ -483,6 +643,9 @@ var PartyLayerClient = class {
483
643
  channel: "stable"
484
644
  });
485
645
  }
646
+ registryWallets = await this.gateDiscoveryAdapterEntries(registryWallets);
647
+ registryWallets = await this.aggregateAnnouncedWallets(registryWallets);
648
+ void this.warmDiscoveryPlans(registryWallets);
486
649
  if (filter?.requiredCapabilities) {
487
650
  return registryWallets.filter(
488
651
  (walletInfo) => filter.requiredCapabilities.every(
@@ -495,6 +658,108 @@ var PartyLayerClient = class {
495
658
  }
496
659
  return registryWallets;
497
660
  }
661
+ /**
662
+ * Hide `transport: 'discovery-adapter'` registry entries whose matching
663
+ * adapter is NOT registered. A discovery-adapter wallet's provider is supplied
664
+ * by the app (an official ProviderAdapter the SDK bridges under
665
+ * `toWalletId(providerId)`); without it, clicking the entry can only fail. So
666
+ * the entry surfaces only when its adapter is present. No-op when the registry
667
+ * is unavailable (list is already adapters-only) or has no such entries.
668
+ */
669
+ async gateDiscoveryAdapterEntries(wallets) {
670
+ let hidden = null;
671
+ try {
672
+ const registry = await this.registryClient.getRegistry();
673
+ for (const entry of registry.wallets) {
674
+ if (entry.adapter?.transport !== "discovery-adapter") continue;
675
+ const walletId = toWalletId(entry.id);
676
+ if (!this.adapters.has(walletId)) {
677
+ (hidden ??= /* @__PURE__ */ new Set()).add(String(walletId));
678
+ }
679
+ }
680
+ } catch {
681
+ return wallets;
682
+ }
683
+ if (!hidden || hidden.size === 0) return wallets;
684
+ return wallets.filter((w) => !hidden.has(String(w.walletId)));
685
+ }
686
+ /**
687
+ * Whether announce discovery is active: explicit `discovery.announce`, else
688
+ * ON in the browser and OFF under SSR (no `window`). Canonical: provider.md.
689
+ */
690
+ get announceEnabled() {
691
+ if (typeof window === "undefined") return false;
692
+ return this.config.discovery?.announce ?? true;
693
+ }
694
+ /**
695
+ * Clear the cached announce round-trip so the next `listWallets()` re-runs the
696
+ * `canton:requestProvider` handshake (e.g. after a wallet is installed).
697
+ */
698
+ refreshDiscovery() {
699
+ this.announceEntriesCache = null;
700
+ }
701
+ /**
702
+ * Aggregate `canton:announceProvider` wallets into the picker list (A2).
703
+ *
704
+ * One-shot cached per client (refresh via {@link refreshDiscovery}); SSR-skipped.
705
+ * For each discovered provider (announce ∪ `window.canton` scan, deduped):
706
+ * - if its id matches a known wallet's `providerDetection` (provider.id) it
707
+ * IS that wallet — no new entry (identity bridge: Console's `lpnf…` → the
708
+ * `console` entry, Send's `ldmo…` → the `send` entry);
709
+ * - otherwise it is surfaced as a dynamic `browser:ext:<id>` entry routed to
710
+ * its own extension `target`, with a {@link GenericAnnounceAdapter}
711
+ * registered so a click connects through that target ONLY (no shared slot).
712
+ * With zero announcers this returns `base` unchanged.
713
+ */
714
+ async aggregateAnnouncedWallets(base) {
715
+ if (!this.announceEnabled) return base;
716
+ if (this.announceEntriesCache === null) {
717
+ try {
718
+ const discovered = await discoverProviders({
719
+ timeoutMs: this.config.discovery?.announceTimeoutMs,
720
+ // Working provider over the announce target channel; G4 (provider.md):
721
+ // target defaults to id when omitted — never a shared slot.
722
+ createProvider: (a) => createExtensionChannelProvider({ target: a.target ?? a.id })
723
+ });
724
+ const entries = [];
725
+ for (const d of discovered) {
726
+ if (d.identityResolved === false) continue;
727
+ const known = findMatchingWalletInfo(
728
+ { provider: { id: d.id } },
729
+ base
730
+ );
731
+ if (known) continue;
732
+ const adapter = new GenericAnnounceAdapter({
733
+ announceId: d.id,
734
+ name: d.name,
735
+ icon: d.icon,
736
+ provider: d.provider
737
+ });
738
+ this.adapters.set(adapter.walletId, adapter);
739
+ entries.push({
740
+ walletId: adapter.walletId,
741
+ name: adapter.name,
742
+ website: "",
743
+ icons: d.icon ? { sm: d.icon, md: d.icon, lg: d.icon } : {},
744
+ capabilities: adapter.getCapabilities(),
745
+ adapter: { packageName: "announced", versionRange: "*" },
746
+ docs: [],
747
+ networks: [this.config.network || "devnet"],
748
+ channel: "stable"
749
+ });
750
+ }
751
+ this.announceEntriesCache = entries;
752
+ } catch {
753
+ this.announceEntriesCache = [];
754
+ }
755
+ }
756
+ if (this.announceEntriesCache.length === 0) return base;
757
+ const ids = new Set(base.map((w) => String(w.walletId)));
758
+ return [
759
+ ...base,
760
+ ...this.announceEntriesCache.filter((w) => !ids.has(String(w.walletId)))
761
+ ];
762
+ }
498
763
  /** Active network-enforcement policy (default 'guard'). */
499
764
  get enforcement() {
500
765
  return this.config.networkEnforcement ?? "guard";
@@ -524,128 +789,10 @@ var PartyLayerClient = class {
524
789
  async connect(options) {
525
790
  this.telemetry?.increment?.(METRICS.WALLET_CONNECT_ATTEMPTS);
526
791
  try {
527
- const wallets = await this.listWallets({
528
- requiredCapabilities: options?.requiredCapabilities,
529
- includeExperimental: true
530
- });
531
- let availableWallets = wallets;
532
- if (options?.allowWallets) {
533
- availableWallets = wallets.filter(
534
- (w) => options.allowWallets.includes(w.walletId)
535
- );
536
- }
537
- let selectedWallet;
538
- let isNativeWallet = false;
539
- if (options?.walletId) {
540
- const found = availableWallets.find(
541
- (w) => w.walletId === options.walletId
542
- );
543
- if (found) {
544
- selectedWallet = found;
545
- } else {
546
- const nativeAdapter = this.adapters.get(options.walletId);
547
- if (nativeAdapter) {
548
- isNativeWallet = true;
549
- selectedWallet = {
550
- walletId: options.walletId,
551
- name: nativeAdapter.name,
552
- website: "",
553
- icons: {},
554
- capabilities: nativeAdapter.getCapabilities(),
555
- adapter: { packageName: "native-cip0103", versionRange: "*" },
556
- docs: [],
557
- networks: [this.config.network],
558
- channel: "stable",
559
- metadata: { source: "native-cip0103" }
560
- };
561
- } else {
562
- throw new WalletNotFoundError(String(options.walletId));
563
- }
564
- }
565
- } else if (availableWallets.length === 0) {
566
- throw new WalletNotFoundError("No wallets available");
567
- } else {
568
- selectedWallet = availableWallets[0];
569
- }
570
- const adapter = this.adapters.get(selectedWallet.walletId);
571
- if (!adapter) {
572
- throw new WalletNotFoundError(String(selectedWallet.walletId));
573
- }
574
- if (!isNativeWallet) {
575
- try {
576
- const walletEntry = await this.registryClient.getWalletEntry(String(selectedWallet.walletId));
577
- if (walletEntry.originAllowlist && walletEntry.originAllowlist.length > 0) {
578
- if (!walletEntry.originAllowlist.includes(this.origin)) {
579
- const { OriginNotAllowedError: OriginNotAllowedError2 } = await import('@partylayer/core');
580
- throw new OriginNotAllowedError2(
581
- this.origin,
582
- walletEntry.originAllowlist
583
- );
584
- }
585
- }
586
- } catch (e) {
587
- if (!(e instanceof WalletNotFoundError)) {
588
- throw e;
589
- }
590
- }
591
- }
592
- if (options?.requiredCapabilities) {
593
- capabilityGuard(adapter, options.requiredCapabilities);
594
- }
595
- await installGuard(adapter);
596
- const ctx = this.createAdapterContext();
597
- const timeoutMs = options?.timeoutMs || 12e4;
598
- const connectPromise = adapter.connect(ctx, {
599
- timeoutMs,
600
- partyId: void 0,
601
- preferInstalled: options?.preferInstalled,
602
- onDisplayUri: options?.onDisplayUri
603
- });
604
- const timeoutPromise = new Promise((_, reject) => {
605
- setTimeout(() => {
606
- reject(new Error(`Connection timed out after ${timeoutMs}ms - user did not complete wallet connection`));
607
- }, timeoutMs);
608
- });
609
- const result = await Promise.race([connectPromise, timeoutPromise]);
610
- const session = {
611
- sessionId: toSessionId(`session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`),
612
- walletId: selectedWallet.walletId,
613
- partyId: result.partyId,
614
- // The wallet's reported network (adapters that read the live wallet —
615
- // e.g. Console via getActiveNetwork — surface the actual network here;
616
- // echo-only adapters report ctx.network === config.network). Used for
617
- // mismatch detection; falls back to the configured network.
618
- network: result.session.network ?? this.config.network,
619
- createdAt: Date.now(),
620
- expiresAt: result.session.expiresAt,
621
- origin: this.origin,
622
- capabilitiesSnapshot: result.capabilities,
623
- metadata: result.session.metadata
624
- };
625
- const mismatch = this.networkMismatch(session);
626
- if (mismatch) {
627
- session.networkMismatch = mismatch;
628
- this.emit("session:networkMismatch", {
629
- type: "session:networkMismatch",
630
- sessionId: session.sessionId,
631
- expected: mismatch.expected,
632
- actual: mismatch.actual,
633
- enforced: this.enforcement !== "off"
634
- });
635
- if (this.enforcement === "strict") {
636
- throw new NetworkMismatchError(mismatch.expected, mismatch.actual);
637
- }
638
- }
639
- await this.persistSession(session);
640
- this.activeSession = session;
641
- this.updateRegistryStatus();
642
- this.telemetry?.increment?.(METRICS.WALLET_CONNECT_SUCCESS);
643
- this.telemetry?.increment?.(METRICS.SESSIONS_CREATED);
644
- this.emit("session:connected", {
645
- type: "session:connected",
646
- session
647
- });
648
- return session;
792
+ const fast = this.tryFastConnect(options);
793
+ if (fast) return await fast;
794
+ const plan = await this.resolveConnectPlan(options);
795
+ return await this.completeConnect(plan, options);
649
796
  } catch (err) {
650
797
  const timeoutMs = options?.timeoutMs || 3e4;
651
798
  const error = mapUnknownErrorToPartyLayerError(err, {
@@ -657,6 +804,191 @@ var PartyLayerClient = class {
657
804
  throw error;
658
805
  }
659
806
  }
807
+ /**
808
+ * Pre-resolve everything `adapter.connect()` needs WITHOUT calling it: wallet
809
+ * selection, origin-allowlist + capability + install guards, and the adapter
810
+ * context. `prefetchedWallets` (passed during warm-up from `listWallets`)
811
+ * avoids a recursive `listWallets()` call.
812
+ */
813
+ async resolveConnectPlan(options, prefetchedWallets) {
814
+ const wallets = prefetchedWallets ?? await this.listWallets({
815
+ requiredCapabilities: options?.requiredCapabilities,
816
+ includeExperimental: true
817
+ });
818
+ let availableWallets = wallets;
819
+ if (options?.allowWallets) {
820
+ availableWallets = wallets.filter(
821
+ (w) => options.allowWallets.includes(w.walletId)
822
+ );
823
+ }
824
+ let selectedWallet;
825
+ let isNativeWallet = false;
826
+ if (options?.walletId) {
827
+ const found = availableWallets.find(
828
+ (w) => w.walletId === options.walletId
829
+ );
830
+ if (found) {
831
+ selectedWallet = found;
832
+ } else {
833
+ const nativeAdapter = this.adapters.get(options.walletId);
834
+ if (nativeAdapter) {
835
+ isNativeWallet = true;
836
+ selectedWallet = {
837
+ walletId: options.walletId,
838
+ name: nativeAdapter.name,
839
+ website: "",
840
+ icons: {},
841
+ capabilities: nativeAdapter.getCapabilities(),
842
+ adapter: { packageName: "native-cip0103", versionRange: "*" },
843
+ docs: [],
844
+ networks: [this.config.network],
845
+ channel: "stable",
846
+ metadata: { source: "native-cip0103" }
847
+ };
848
+ } else {
849
+ throw new WalletNotFoundError(String(options.walletId));
850
+ }
851
+ }
852
+ } else if (availableWallets.length === 0) {
853
+ throw new WalletNotFoundError("No wallets available");
854
+ } else {
855
+ selectedWallet = availableWallets[0];
856
+ }
857
+ const adapter = this.adapters.get(selectedWallet.walletId);
858
+ if (!adapter) {
859
+ throw new WalletNotFoundError(String(selectedWallet.walletId));
860
+ }
861
+ if (!isNativeWallet) {
862
+ try {
863
+ const walletEntry = await this.registryClient.getWalletEntry(String(selectedWallet.walletId));
864
+ if (walletEntry.originAllowlist && walletEntry.originAllowlist.length > 0) {
865
+ if (!walletEntry.originAllowlist.includes(this.origin)) {
866
+ const { OriginNotAllowedError: OriginNotAllowedError2 } = await import('@partylayer/core');
867
+ throw new OriginNotAllowedError2(
868
+ this.origin,
869
+ walletEntry.originAllowlist
870
+ );
871
+ }
872
+ }
873
+ } catch (e) {
874
+ if (!(e instanceof WalletNotFoundError)) {
875
+ throw e;
876
+ }
877
+ }
878
+ }
879
+ if (options?.requiredCapabilities) {
880
+ capabilityGuard(adapter, options.requiredCapabilities);
881
+ }
882
+ await installGuard(adapter);
883
+ const ctx = this.createAdapterContext();
884
+ return { selectedWallet, adapter, ctx, isNativeWallet };
885
+ }
886
+ /**
887
+ * Invoke `adapter.connect()` (its FIRST statement — no await precedes it) and
888
+ * build / persist / emit the session. Separated from plan resolution so the
889
+ * popup-safe fast-path can call it gesture-synchronously.
890
+ */
891
+ async completeConnect(plan, options) {
892
+ const { selectedWallet, adapter, ctx } = plan;
893
+ const timeoutMs = options?.timeoutMs || 12e4;
894
+ const connectPromise = adapter.connect(ctx, {
895
+ timeoutMs,
896
+ partyId: void 0,
897
+ preferInstalled: options?.preferInstalled,
898
+ onDisplayUri: options?.onDisplayUri
899
+ });
900
+ const timeoutPromise = new Promise((_, reject) => {
901
+ setTimeout(() => {
902
+ reject(new Error(`Connection timed out after ${timeoutMs}ms - user did not complete wallet connection`));
903
+ }, timeoutMs);
904
+ });
905
+ const result = await Promise.race([connectPromise, timeoutPromise]);
906
+ const session = {
907
+ sessionId: toSessionId(`session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`),
908
+ walletId: selectedWallet.walletId,
909
+ partyId: result.partyId,
910
+ // The wallet's reported network (adapters that read the live wallet —
911
+ // e.g. Console via getActiveNetwork — surface the actual network here;
912
+ // echo-only adapters report ctx.network === config.network). Used for
913
+ // mismatch detection; falls back to the configured network.
914
+ network: result.session.network ?? this.config.network,
915
+ createdAt: Date.now(),
916
+ expiresAt: result.session.expiresAt,
917
+ origin: this.origin,
918
+ capabilitiesSnapshot: result.capabilities,
919
+ metadata: result.session.metadata
920
+ };
921
+ const mismatch = this.networkMismatch(session);
922
+ if (mismatch) {
923
+ session.networkMismatch = mismatch;
924
+ this.emit("session:networkMismatch", {
925
+ type: "session:networkMismatch",
926
+ sessionId: session.sessionId,
927
+ expected: mismatch.expected,
928
+ actual: mismatch.actual,
929
+ enforced: this.enforcement !== "off"
930
+ });
931
+ if (this.enforcement === "strict") {
932
+ throw new NetworkMismatchError(mismatch.expected, mismatch.actual);
933
+ }
934
+ }
935
+ await this.persistSession(session);
936
+ this.activeSession = session;
937
+ this.updateRegistryStatus();
938
+ this.telemetry?.increment?.(METRICS.WALLET_CONNECT_SUCCESS);
939
+ this.telemetry?.increment?.(METRICS.SESSIONS_CREATED);
940
+ this.emit("session:connected", {
941
+ type: "session:connected",
942
+ session
943
+ });
944
+ return session;
945
+ }
946
+ /**
947
+ * PUBLIC popup-safe primitive: pre-resolve a connect plan ahead of the user
948
+ * gesture; the returned `connect()` invokes `adapter.connect()` as its first
949
+ * statement (no await precedes it) so a popup/remote wallet's `window.open`
950
+ * survives the gesture. For consumers driving such a wallet outside the modal
951
+ * (the modal gets this for free via the `listWallets` warm-up + `connect()`).
952
+ */
953
+ async prepareConnect(options) {
954
+ const plan = await this.resolveConnectPlan(options);
955
+ return {
956
+ walletId: plan.selectedWallet.walletId,
957
+ connect: (o) => this.completeConnect(plan, o ?? options)
958
+ };
959
+ }
960
+ /**
961
+ * Background warm-up of connect plans for popup/remote
962
+ * (`GenericDiscoveryAdapter`) wallets. Popup-free — `resolveConnectPlan` only
963
+ * runs read/guard probes. Skips already-warm entries; never throws.
964
+ */
965
+ async warmDiscoveryPlans(wallets) {
966
+ for (const [walletId, adapter] of this.adapters) {
967
+ if (!(adapter instanceof GenericDiscoveryAdapter)) continue;
968
+ if (this.warmPlans.has(walletId)) continue;
969
+ try {
970
+ const plan = await this.resolveConnectPlan({ walletId }, wallets);
971
+ this.warmPlans.set(walletId, plan);
972
+ } catch {
973
+ }
974
+ }
975
+ }
976
+ /**
977
+ * SYNCHRONOUS fast-path: if a fresh warm plan exists for a popup/remote wallet
978
+ * — and `options` carries no plan-affecting guards — consume it and START
979
+ * `completeConnect` immediately, reaching `adapter.connect()` with no awaits.
980
+ * Returns the in-flight Session promise, or null to fall back to the normal
981
+ * path (e.g. cold cache, or a non-discovery wallet).
982
+ */
983
+ tryFastConnect(options) {
984
+ const walletId = options?.walletId;
985
+ if (!walletId) return null;
986
+ if (options?.requiredCapabilities || options?.allowWallets) return null;
987
+ const plan = this.warmPlans.get(walletId);
988
+ if (!plan) return null;
989
+ this.warmPlans.delete(walletId);
990
+ return this.completeConnect(plan, options);
991
+ }
660
992
  /**
661
993
  * Disconnect from wallet
662
994
  */
@@ -673,6 +1005,7 @@ var PartyLayerClient = class {
673
1005
  const sessionId = this.activeSession.sessionId;
674
1006
  await this.removeSession(sessionId);
675
1007
  this.activeSession = null;
1008
+ this.warmPlans.clear();
676
1009
  this.emit("session:disconnected", {
677
1010
  type: "session:disconnected",
678
1011
  sessionId
@@ -1046,6 +1379,6 @@ function createPartyLayer(config) {
1046
1379
  return new PartyLayerClient(config);
1047
1380
  }
1048
1381
 
1049
- export { PartyLayerClient as CantonConnectClient, DEFAULT_REGISTRY_URL, MetricsTelemetryAdapter, PartyLayerClient, createPartyLayer as createCantonConnect, createPartyLayer, createTelemetryAdapter, getBuiltinAdapters, isTelemetryConfig };
1382
+ export { ANNOUNCED_WALLET_ID_PREFIX, PartyLayerClient as CantonConnectClient, DEFAULT_REGISTRY_URL, GenericAnnounceAdapter, GenericDiscoveryAdapter, MetricsTelemetryAdapter, PartyLayerClient, announcedWalletId, createPartyLayer as createCantonConnect, createPartyLayer, createTelemetryAdapter, getBuiltinAdapters, isTelemetryConfig };
1050
1383
  //# sourceMappingURL=index.mjs.map
1051
1384
  //# sourceMappingURL=index.mjs.map