@partylayer/sdk 0.7.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,5 +1,5 @@
1
- import { toWalletId, toPartyId, hashForPrivacy, createMetricsPayload, 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 } 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
5
  import { discoverProviders, createExtensionChannelProvider, createProviderBridge } from '@partylayer/provider';
@@ -84,6 +84,88 @@ var GenericAnnounceAdapter = class {
84
84
  });
85
85
  }
86
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
+ };
87
169
 
88
170
  // src/config.ts
89
171
  var DEFAULT_REGISTRY_URL = "https://registry.partylayer.xyz";
@@ -438,6 +520,13 @@ var SESSION_STORAGE_KEY = "active_session";
438
520
  var PartyLayerClient = class {
439
521
  config;
440
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();
441
530
  eventHandlers = /* @__PURE__ */ new Map();
442
531
  activeSession = null;
443
532
  registryClient;
@@ -468,6 +557,8 @@ var PartyLayerClient = class {
468
557
  let adapter;
469
558
  if (typeof adapterOrClass === "function") {
470
559
  adapter = new adapterOrClass();
560
+ } else if (isOfficialProviderAdapter(adapterOrClass)) {
561
+ adapter = new GenericDiscoveryAdapter({ official: adapterOrClass });
471
562
  } else {
472
563
  adapter = adapterOrClass;
473
564
  }
@@ -552,7 +643,9 @@ var PartyLayerClient = class {
552
643
  channel: "stable"
553
644
  });
554
645
  }
646
+ registryWallets = await this.gateDiscoveryAdapterEntries(registryWallets);
555
647
  registryWallets = await this.aggregateAnnouncedWallets(registryWallets);
648
+ void this.warmDiscoveryPlans(registryWallets);
556
649
  if (filter?.requiredCapabilities) {
557
650
  return registryWallets.filter(
558
651
  (walletInfo) => filter.requiredCapabilities.every(
@@ -565,6 +658,31 @@ var PartyLayerClient = class {
565
658
  }
566
659
  return registryWallets;
567
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
+ }
568
686
  /**
569
687
  * Whether announce discovery is active: explicit `discovery.announce`, else
570
688
  * ON in the browser and OFF under SSR (no `window`). Canonical: provider.md.
@@ -671,128 +789,10 @@ var PartyLayerClient = class {
671
789
  async connect(options) {
672
790
  this.telemetry?.increment?.(METRICS.WALLET_CONNECT_ATTEMPTS);
673
791
  try {
674
- const wallets = await this.listWallets({
675
- requiredCapabilities: options?.requiredCapabilities,
676
- includeExperimental: true
677
- });
678
- let availableWallets = wallets;
679
- if (options?.allowWallets) {
680
- availableWallets = wallets.filter(
681
- (w) => options.allowWallets.includes(w.walletId)
682
- );
683
- }
684
- let selectedWallet;
685
- let isNativeWallet = false;
686
- if (options?.walletId) {
687
- const found = availableWallets.find(
688
- (w) => w.walletId === options.walletId
689
- );
690
- if (found) {
691
- selectedWallet = found;
692
- } else {
693
- const nativeAdapter = this.adapters.get(options.walletId);
694
- if (nativeAdapter) {
695
- isNativeWallet = true;
696
- selectedWallet = {
697
- walletId: options.walletId,
698
- name: nativeAdapter.name,
699
- website: "",
700
- icons: {},
701
- capabilities: nativeAdapter.getCapabilities(),
702
- adapter: { packageName: "native-cip0103", versionRange: "*" },
703
- docs: [],
704
- networks: [this.config.network],
705
- channel: "stable",
706
- metadata: { source: "native-cip0103" }
707
- };
708
- } else {
709
- throw new WalletNotFoundError(String(options.walletId));
710
- }
711
- }
712
- } else if (availableWallets.length === 0) {
713
- throw new WalletNotFoundError("No wallets available");
714
- } else {
715
- selectedWallet = availableWallets[0];
716
- }
717
- const adapter = this.adapters.get(selectedWallet.walletId);
718
- if (!adapter) {
719
- throw new WalletNotFoundError(String(selectedWallet.walletId));
720
- }
721
- if (!isNativeWallet) {
722
- try {
723
- const walletEntry = await this.registryClient.getWalletEntry(String(selectedWallet.walletId));
724
- if (walletEntry.originAllowlist && walletEntry.originAllowlist.length > 0) {
725
- if (!walletEntry.originAllowlist.includes(this.origin)) {
726
- const { OriginNotAllowedError: OriginNotAllowedError2 } = await import('@partylayer/core');
727
- throw new OriginNotAllowedError2(
728
- this.origin,
729
- walletEntry.originAllowlist
730
- );
731
- }
732
- }
733
- } catch (e) {
734
- if (!(e instanceof WalletNotFoundError)) {
735
- throw e;
736
- }
737
- }
738
- }
739
- if (options?.requiredCapabilities) {
740
- capabilityGuard(adapter, options.requiredCapabilities);
741
- }
742
- await installGuard(adapter);
743
- const ctx = this.createAdapterContext();
744
- const timeoutMs = options?.timeoutMs || 12e4;
745
- const connectPromise = adapter.connect(ctx, {
746
- timeoutMs,
747
- partyId: void 0,
748
- preferInstalled: options?.preferInstalled,
749
- onDisplayUri: options?.onDisplayUri
750
- });
751
- const timeoutPromise = new Promise((_, reject) => {
752
- setTimeout(() => {
753
- reject(new Error(`Connection timed out after ${timeoutMs}ms - user did not complete wallet connection`));
754
- }, timeoutMs);
755
- });
756
- const result = await Promise.race([connectPromise, timeoutPromise]);
757
- const session = {
758
- sessionId: toSessionId(`session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`),
759
- walletId: selectedWallet.walletId,
760
- partyId: result.partyId,
761
- // The wallet's reported network (adapters that read the live wallet —
762
- // e.g. Console via getActiveNetwork — surface the actual network here;
763
- // echo-only adapters report ctx.network === config.network). Used for
764
- // mismatch detection; falls back to the configured network.
765
- network: result.session.network ?? this.config.network,
766
- createdAt: Date.now(),
767
- expiresAt: result.session.expiresAt,
768
- origin: this.origin,
769
- capabilitiesSnapshot: result.capabilities,
770
- metadata: result.session.metadata
771
- };
772
- const mismatch = this.networkMismatch(session);
773
- if (mismatch) {
774
- session.networkMismatch = mismatch;
775
- this.emit("session:networkMismatch", {
776
- type: "session:networkMismatch",
777
- sessionId: session.sessionId,
778
- expected: mismatch.expected,
779
- actual: mismatch.actual,
780
- enforced: this.enforcement !== "off"
781
- });
782
- if (this.enforcement === "strict") {
783
- throw new NetworkMismatchError(mismatch.expected, mismatch.actual);
784
- }
785
- }
786
- await this.persistSession(session);
787
- this.activeSession = session;
788
- this.updateRegistryStatus();
789
- this.telemetry?.increment?.(METRICS.WALLET_CONNECT_SUCCESS);
790
- this.telemetry?.increment?.(METRICS.SESSIONS_CREATED);
791
- this.emit("session:connected", {
792
- type: "session:connected",
793
- session
794
- });
795
- 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);
796
796
  } catch (err) {
797
797
  const timeoutMs = options?.timeoutMs || 3e4;
798
798
  const error = mapUnknownErrorToPartyLayerError(err, {
@@ -804,6 +804,191 @@ var PartyLayerClient = class {
804
804
  throw error;
805
805
  }
806
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
+ }
807
992
  /**
808
993
  * Disconnect from wallet
809
994
  */
@@ -820,6 +1005,7 @@ var PartyLayerClient = class {
820
1005
  const sessionId = this.activeSession.sessionId;
821
1006
  await this.removeSession(sessionId);
822
1007
  this.activeSession = null;
1008
+ this.warmPlans.clear();
823
1009
  this.emit("session:disconnected", {
824
1010
  type: "session:disconnected",
825
1011
  sessionId
@@ -1193,6 +1379,6 @@ function createPartyLayer(config) {
1193
1379
  return new PartyLayerClient(config);
1194
1380
  }
1195
1381
 
1196
- export { ANNOUNCED_WALLET_ID_PREFIX, PartyLayerClient as CantonConnectClient, DEFAULT_REGISTRY_URL, GenericAnnounceAdapter, MetricsTelemetryAdapter, PartyLayerClient, announcedWalletId, 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 };
1197
1383
  //# sourceMappingURL=index.mjs.map
1198
1384
  //# sourceMappingURL=index.mjs.map