@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.js CHANGED
@@ -78,6 +78,88 @@ var GenericAnnounceAdapter = class {
78
78
  });
79
79
  }
80
80
  };
81
+ var GenericDiscoveryAdapter = class {
82
+ walletId;
83
+ name;
84
+ icon;
85
+ official;
86
+ /** Lazily resolved from `official.provider()` — NOT at construction (SSR-safe). */
87
+ providerInstance = null;
88
+ constructor(args) {
89
+ this.official = args.official;
90
+ this.walletId = args.walletId ?? core.toWalletId(args.official.providerId);
91
+ this.name = args.name && args.name.length > 0 ? args.name : args.official.name;
92
+ this.icon = args.icon ?? args.official.icon;
93
+ }
94
+ /** Lazily obtain (and cache) the official provider — deferred off the init/SSR path.
95
+ * `official.provider()` is typed `OfficialProvider` (loose `request` so real
96
+ * official adapters are assignable); it is call-compatible with CIP0103Provider
97
+ * (the bridge only ever calls `request({ method, params })`). */
98
+ get provider() {
99
+ if (this.providerInstance === null) {
100
+ this.providerInstance = this.official.provider();
101
+ }
102
+ return this.providerInstance;
103
+ }
104
+ /**
105
+ * Baseline CIP-0103 capabilities. NEVER includes `'events'`: popup/remote
106
+ * wallets expose the event surface but do not emit (truthfulness doctrine).
107
+ */
108
+ getCapabilities() {
109
+ return ["connect", "disconnect", "signMessage", "submitTransaction"];
110
+ }
111
+ /** Install/availability probe — delegated to the official adapter (popup-free). */
112
+ async detectInstalled() {
113
+ try {
114
+ const installed = await this.official.detect();
115
+ return {
116
+ installed,
117
+ reason: installed ? void 0 : "Wallet reported not available"
118
+ };
119
+ } catch {
120
+ return { installed: false, reason: "Detection failed" };
121
+ }
122
+ }
123
+ async connect(ctx) {
124
+ await this.provider.request({ method: "connect" });
125
+ const account = await this.provider.request({
126
+ method: "getPrimaryAccount"
127
+ });
128
+ let reportedNetwork;
129
+ try {
130
+ const status = await this.provider.request({
131
+ method: "status"
132
+ });
133
+ reportedNetwork = status?.network?.networkId;
134
+ } catch {
135
+ }
136
+ const partyId = core.toPartyId(account.partyId);
137
+ const session = {
138
+ walletId: this.walletId,
139
+ partyId,
140
+ network: reportedNetwork ?? account.networkId ?? ctx.network
141
+ };
142
+ return { partyId, session, capabilities: this.getCapabilities() };
143
+ }
144
+ async disconnect() {
145
+ try {
146
+ await this.provider.request({ method: "disconnect" });
147
+ } catch {
148
+ }
149
+ }
150
+ async signMessage(_ctx, _session, params) {
151
+ return this.provider.request({
152
+ method: "signMessage",
153
+ params: { message: params.message }
154
+ });
155
+ }
156
+ async submitTransaction(_ctx, _session, params) {
157
+ return this.provider.request({
158
+ method: "prepareExecute",
159
+ params
160
+ });
161
+ }
162
+ };
81
163
 
82
164
  // src/config.ts
83
165
  var DEFAULT_REGISTRY_URL = "https://registry.partylayer.xyz";
@@ -432,6 +514,13 @@ var SESSION_STORAGE_KEY = "active_session";
432
514
  var PartyLayerClient = class {
433
515
  config;
434
516
  adapters = /* @__PURE__ */ new Map();
517
+ /**
518
+ * Pre-resolved connect plans for popup/remote (GenericDiscoveryAdapter)
519
+ * wallets, warmed on `listWallets()` (which the modal calls on open) so a
520
+ * subsequent click can connect gesture-synchronously. Consumed (deleted) on
521
+ * use and cleared on disconnect; a cold miss falls back to the normal path.
522
+ */
523
+ warmPlans = /* @__PURE__ */ new Map();
435
524
  eventHandlers = /* @__PURE__ */ new Map();
436
525
  activeSession = null;
437
526
  registryClient;
@@ -462,6 +551,8 @@ var PartyLayerClient = class {
462
551
  let adapter;
463
552
  if (typeof adapterOrClass === "function") {
464
553
  adapter = new adapterOrClass();
554
+ } else if (core.isOfficialProviderAdapter(adapterOrClass)) {
555
+ adapter = new GenericDiscoveryAdapter({ official: adapterOrClass });
465
556
  } else {
466
557
  adapter = adapterOrClass;
467
558
  }
@@ -546,7 +637,9 @@ var PartyLayerClient = class {
546
637
  channel: "stable"
547
638
  });
548
639
  }
640
+ registryWallets = await this.gateDiscoveryAdapterEntries(registryWallets);
549
641
  registryWallets = await this.aggregateAnnouncedWallets(registryWallets);
642
+ void this.warmDiscoveryPlans(registryWallets);
550
643
  if (filter?.requiredCapabilities) {
551
644
  return registryWallets.filter(
552
645
  (walletInfo) => filter.requiredCapabilities.every(
@@ -559,6 +652,31 @@ var PartyLayerClient = class {
559
652
  }
560
653
  return registryWallets;
561
654
  }
655
+ /**
656
+ * Hide `transport: 'discovery-adapter'` registry entries whose matching
657
+ * adapter is NOT registered. A discovery-adapter wallet's provider is supplied
658
+ * by the app (an official ProviderAdapter the SDK bridges under
659
+ * `toWalletId(providerId)`); without it, clicking the entry can only fail. So
660
+ * the entry surfaces only when its adapter is present. No-op when the registry
661
+ * is unavailable (list is already adapters-only) or has no such entries.
662
+ */
663
+ async gateDiscoveryAdapterEntries(wallets) {
664
+ let hidden = null;
665
+ try {
666
+ const registry = await this.registryClient.getRegistry();
667
+ for (const entry of registry.wallets) {
668
+ if (entry.adapter?.transport !== "discovery-adapter") continue;
669
+ const walletId = core.toWalletId(entry.id);
670
+ if (!this.adapters.has(walletId)) {
671
+ (hidden ??= /* @__PURE__ */ new Set()).add(String(walletId));
672
+ }
673
+ }
674
+ } catch {
675
+ return wallets;
676
+ }
677
+ if (!hidden || hidden.size === 0) return wallets;
678
+ return wallets.filter((w) => !hidden.has(String(w.walletId)));
679
+ }
562
680
  /**
563
681
  * Whether announce discovery is active: explicit `discovery.announce`, else
564
682
  * ON in the browser and OFF under SSR (no `window`). Canonical: provider.md.
@@ -665,128 +783,10 @@ var PartyLayerClient = class {
665
783
  async connect(options) {
666
784
  this.telemetry?.increment?.(core.METRICS.WALLET_CONNECT_ATTEMPTS);
667
785
  try {
668
- const wallets = await this.listWallets({
669
- requiredCapabilities: options?.requiredCapabilities,
670
- includeExperimental: true
671
- });
672
- let availableWallets = wallets;
673
- if (options?.allowWallets) {
674
- availableWallets = wallets.filter(
675
- (w) => options.allowWallets.includes(w.walletId)
676
- );
677
- }
678
- let selectedWallet;
679
- let isNativeWallet = false;
680
- if (options?.walletId) {
681
- const found = availableWallets.find(
682
- (w) => w.walletId === options.walletId
683
- );
684
- if (found) {
685
- selectedWallet = found;
686
- } else {
687
- const nativeAdapter = this.adapters.get(options.walletId);
688
- if (nativeAdapter) {
689
- isNativeWallet = true;
690
- selectedWallet = {
691
- walletId: options.walletId,
692
- name: nativeAdapter.name,
693
- website: "",
694
- icons: {},
695
- capabilities: nativeAdapter.getCapabilities(),
696
- adapter: { packageName: "native-cip0103", versionRange: "*" },
697
- docs: [],
698
- networks: [this.config.network],
699
- channel: "stable",
700
- metadata: { source: "native-cip0103" }
701
- };
702
- } else {
703
- throw new core.WalletNotFoundError(String(options.walletId));
704
- }
705
- }
706
- } else if (availableWallets.length === 0) {
707
- throw new core.WalletNotFoundError("No wallets available");
708
- } else {
709
- selectedWallet = availableWallets[0];
710
- }
711
- const adapter = this.adapters.get(selectedWallet.walletId);
712
- if (!adapter) {
713
- throw new core.WalletNotFoundError(String(selectedWallet.walletId));
714
- }
715
- if (!isNativeWallet) {
716
- try {
717
- const walletEntry = await this.registryClient.getWalletEntry(String(selectedWallet.walletId));
718
- if (walletEntry.originAllowlist && walletEntry.originAllowlist.length > 0) {
719
- if (!walletEntry.originAllowlist.includes(this.origin)) {
720
- const { OriginNotAllowedError: OriginNotAllowedError2 } = await import('@partylayer/core');
721
- throw new OriginNotAllowedError2(
722
- this.origin,
723
- walletEntry.originAllowlist
724
- );
725
- }
726
- }
727
- } catch (e) {
728
- if (!(e instanceof core.WalletNotFoundError)) {
729
- throw e;
730
- }
731
- }
732
- }
733
- if (options?.requiredCapabilities) {
734
- core.capabilityGuard(adapter, options.requiredCapabilities);
735
- }
736
- await core.installGuard(adapter);
737
- const ctx = this.createAdapterContext();
738
- const timeoutMs = options?.timeoutMs || 12e4;
739
- const connectPromise = adapter.connect(ctx, {
740
- timeoutMs,
741
- partyId: void 0,
742
- preferInstalled: options?.preferInstalled,
743
- onDisplayUri: options?.onDisplayUri
744
- });
745
- const timeoutPromise = new Promise((_, reject) => {
746
- setTimeout(() => {
747
- reject(new Error(`Connection timed out after ${timeoutMs}ms - user did not complete wallet connection`));
748
- }, timeoutMs);
749
- });
750
- const result = await Promise.race([connectPromise, timeoutPromise]);
751
- const session = {
752
- sessionId: core.toSessionId(`session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`),
753
- walletId: selectedWallet.walletId,
754
- partyId: result.partyId,
755
- // The wallet's reported network (adapters that read the live wallet —
756
- // e.g. Console via getActiveNetwork — surface the actual network here;
757
- // echo-only adapters report ctx.network === config.network). Used for
758
- // mismatch detection; falls back to the configured network.
759
- network: result.session.network ?? this.config.network,
760
- createdAt: Date.now(),
761
- expiresAt: result.session.expiresAt,
762
- origin: this.origin,
763
- capabilitiesSnapshot: result.capabilities,
764
- metadata: result.session.metadata
765
- };
766
- const mismatch = this.networkMismatch(session);
767
- if (mismatch) {
768
- session.networkMismatch = mismatch;
769
- this.emit("session:networkMismatch", {
770
- type: "session:networkMismatch",
771
- sessionId: session.sessionId,
772
- expected: mismatch.expected,
773
- actual: mismatch.actual,
774
- enforced: this.enforcement !== "off"
775
- });
776
- if (this.enforcement === "strict") {
777
- throw new core.NetworkMismatchError(mismatch.expected, mismatch.actual);
778
- }
779
- }
780
- await this.persistSession(session);
781
- this.activeSession = session;
782
- this.updateRegistryStatus();
783
- this.telemetry?.increment?.(core.METRICS.WALLET_CONNECT_SUCCESS);
784
- this.telemetry?.increment?.(core.METRICS.SESSIONS_CREATED);
785
- this.emit("session:connected", {
786
- type: "session:connected",
787
- session
788
- });
789
- return session;
786
+ const fast = this.tryFastConnect(options);
787
+ if (fast) return await fast;
788
+ const plan = await this.resolveConnectPlan(options);
789
+ return await this.completeConnect(plan, options);
790
790
  } catch (err) {
791
791
  const timeoutMs = options?.timeoutMs || 3e4;
792
792
  const error = core.mapUnknownErrorToPartyLayerError(err, {
@@ -798,6 +798,191 @@ var PartyLayerClient = class {
798
798
  throw error;
799
799
  }
800
800
  }
801
+ /**
802
+ * Pre-resolve everything `adapter.connect()` needs WITHOUT calling it: wallet
803
+ * selection, origin-allowlist + capability + install guards, and the adapter
804
+ * context. `prefetchedWallets` (passed during warm-up from `listWallets`)
805
+ * avoids a recursive `listWallets()` call.
806
+ */
807
+ async resolveConnectPlan(options, prefetchedWallets) {
808
+ const wallets = prefetchedWallets ?? await this.listWallets({
809
+ requiredCapabilities: options?.requiredCapabilities,
810
+ includeExperimental: true
811
+ });
812
+ let availableWallets = wallets;
813
+ if (options?.allowWallets) {
814
+ availableWallets = wallets.filter(
815
+ (w) => options.allowWallets.includes(w.walletId)
816
+ );
817
+ }
818
+ let selectedWallet;
819
+ let isNativeWallet = false;
820
+ if (options?.walletId) {
821
+ const found = availableWallets.find(
822
+ (w) => w.walletId === options.walletId
823
+ );
824
+ if (found) {
825
+ selectedWallet = found;
826
+ } else {
827
+ const nativeAdapter = this.adapters.get(options.walletId);
828
+ if (nativeAdapter) {
829
+ isNativeWallet = true;
830
+ selectedWallet = {
831
+ walletId: options.walletId,
832
+ name: nativeAdapter.name,
833
+ website: "",
834
+ icons: {},
835
+ capabilities: nativeAdapter.getCapabilities(),
836
+ adapter: { packageName: "native-cip0103", versionRange: "*" },
837
+ docs: [],
838
+ networks: [this.config.network],
839
+ channel: "stable",
840
+ metadata: { source: "native-cip0103" }
841
+ };
842
+ } else {
843
+ throw new core.WalletNotFoundError(String(options.walletId));
844
+ }
845
+ }
846
+ } else if (availableWallets.length === 0) {
847
+ throw new core.WalletNotFoundError("No wallets available");
848
+ } else {
849
+ selectedWallet = availableWallets[0];
850
+ }
851
+ const adapter = this.adapters.get(selectedWallet.walletId);
852
+ if (!adapter) {
853
+ throw new core.WalletNotFoundError(String(selectedWallet.walletId));
854
+ }
855
+ if (!isNativeWallet) {
856
+ try {
857
+ const walletEntry = await this.registryClient.getWalletEntry(String(selectedWallet.walletId));
858
+ if (walletEntry.originAllowlist && walletEntry.originAllowlist.length > 0) {
859
+ if (!walletEntry.originAllowlist.includes(this.origin)) {
860
+ const { OriginNotAllowedError: OriginNotAllowedError2 } = await import('@partylayer/core');
861
+ throw new OriginNotAllowedError2(
862
+ this.origin,
863
+ walletEntry.originAllowlist
864
+ );
865
+ }
866
+ }
867
+ } catch (e) {
868
+ if (!(e instanceof core.WalletNotFoundError)) {
869
+ throw e;
870
+ }
871
+ }
872
+ }
873
+ if (options?.requiredCapabilities) {
874
+ core.capabilityGuard(adapter, options.requiredCapabilities);
875
+ }
876
+ await core.installGuard(adapter);
877
+ const ctx = this.createAdapterContext();
878
+ return { selectedWallet, adapter, ctx, isNativeWallet };
879
+ }
880
+ /**
881
+ * Invoke `adapter.connect()` (its FIRST statement — no await precedes it) and
882
+ * build / persist / emit the session. Separated from plan resolution so the
883
+ * popup-safe fast-path can call it gesture-synchronously.
884
+ */
885
+ async completeConnect(plan, options) {
886
+ const { selectedWallet, adapter, ctx } = plan;
887
+ const timeoutMs = options?.timeoutMs || 12e4;
888
+ const connectPromise = adapter.connect(ctx, {
889
+ timeoutMs,
890
+ partyId: void 0,
891
+ preferInstalled: options?.preferInstalled,
892
+ onDisplayUri: options?.onDisplayUri
893
+ });
894
+ const timeoutPromise = new Promise((_, reject) => {
895
+ setTimeout(() => {
896
+ reject(new Error(`Connection timed out after ${timeoutMs}ms - user did not complete wallet connection`));
897
+ }, timeoutMs);
898
+ });
899
+ const result = await Promise.race([connectPromise, timeoutPromise]);
900
+ const session = {
901
+ sessionId: core.toSessionId(`session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`),
902
+ walletId: selectedWallet.walletId,
903
+ partyId: result.partyId,
904
+ // The wallet's reported network (adapters that read the live wallet —
905
+ // e.g. Console via getActiveNetwork — surface the actual network here;
906
+ // echo-only adapters report ctx.network === config.network). Used for
907
+ // mismatch detection; falls back to the configured network.
908
+ network: result.session.network ?? this.config.network,
909
+ createdAt: Date.now(),
910
+ expiresAt: result.session.expiresAt,
911
+ origin: this.origin,
912
+ capabilitiesSnapshot: result.capabilities,
913
+ metadata: result.session.metadata
914
+ };
915
+ const mismatch = this.networkMismatch(session);
916
+ if (mismatch) {
917
+ session.networkMismatch = mismatch;
918
+ this.emit("session:networkMismatch", {
919
+ type: "session:networkMismatch",
920
+ sessionId: session.sessionId,
921
+ expected: mismatch.expected,
922
+ actual: mismatch.actual,
923
+ enforced: this.enforcement !== "off"
924
+ });
925
+ if (this.enforcement === "strict") {
926
+ throw new core.NetworkMismatchError(mismatch.expected, mismatch.actual);
927
+ }
928
+ }
929
+ await this.persistSession(session);
930
+ this.activeSession = session;
931
+ this.updateRegistryStatus();
932
+ this.telemetry?.increment?.(core.METRICS.WALLET_CONNECT_SUCCESS);
933
+ this.telemetry?.increment?.(core.METRICS.SESSIONS_CREATED);
934
+ this.emit("session:connected", {
935
+ type: "session:connected",
936
+ session
937
+ });
938
+ return session;
939
+ }
940
+ /**
941
+ * PUBLIC popup-safe primitive: pre-resolve a connect plan ahead of the user
942
+ * gesture; the returned `connect()` invokes `adapter.connect()` as its first
943
+ * statement (no await precedes it) so a popup/remote wallet's `window.open`
944
+ * survives the gesture. For consumers driving such a wallet outside the modal
945
+ * (the modal gets this for free via the `listWallets` warm-up + `connect()`).
946
+ */
947
+ async prepareConnect(options) {
948
+ const plan = await this.resolveConnectPlan(options);
949
+ return {
950
+ walletId: plan.selectedWallet.walletId,
951
+ connect: (o) => this.completeConnect(plan, o ?? options)
952
+ };
953
+ }
954
+ /**
955
+ * Background warm-up of connect plans for popup/remote
956
+ * (`GenericDiscoveryAdapter`) wallets. Popup-free — `resolveConnectPlan` only
957
+ * runs read/guard probes. Skips already-warm entries; never throws.
958
+ */
959
+ async warmDiscoveryPlans(wallets) {
960
+ for (const [walletId, adapter] of this.adapters) {
961
+ if (!(adapter instanceof GenericDiscoveryAdapter)) continue;
962
+ if (this.warmPlans.has(walletId)) continue;
963
+ try {
964
+ const plan = await this.resolveConnectPlan({ walletId }, wallets);
965
+ this.warmPlans.set(walletId, plan);
966
+ } catch {
967
+ }
968
+ }
969
+ }
970
+ /**
971
+ * SYNCHRONOUS fast-path: if a fresh warm plan exists for a popup/remote wallet
972
+ * — and `options` carries no plan-affecting guards — consume it and START
973
+ * `completeConnect` immediately, reaching `adapter.connect()` with no awaits.
974
+ * Returns the in-flight Session promise, or null to fall back to the normal
975
+ * path (e.g. cold cache, or a non-discovery wallet).
976
+ */
977
+ tryFastConnect(options) {
978
+ const walletId = options?.walletId;
979
+ if (!walletId) return null;
980
+ if (options?.requiredCapabilities || options?.allowWallets) return null;
981
+ const plan = this.warmPlans.get(walletId);
982
+ if (!plan) return null;
983
+ this.warmPlans.delete(walletId);
984
+ return this.completeConnect(plan, options);
985
+ }
801
986
  /**
802
987
  * Disconnect from wallet
803
988
  */
@@ -814,6 +999,7 @@ var PartyLayerClient = class {
814
999
  const sessionId = this.activeSession.sessionId;
815
1000
  await this.removeSession(sessionId);
816
1001
  this.activeSession = null;
1002
+ this.warmPlans.clear();
817
1003
  this.emit("session:disconnected", {
818
1004
  type: "session:disconnected",
819
1005
  sessionId
@@ -1263,6 +1449,10 @@ Object.defineProperty(exports, "errorMetricName", {
1263
1449
  enumerable: true,
1264
1450
  get: function () { return core.errorMetricName; }
1265
1451
  });
1452
+ Object.defineProperty(exports, "isOfficialProviderAdapter", {
1453
+ enumerable: true,
1454
+ get: function () { return core.isOfficialProviderAdapter; }
1455
+ });
1266
1456
  Object.defineProperty(exports, "deriveGenericWalletName", {
1267
1457
  enumerable: true,
1268
1458
  get: function () { return registryClient.deriveGenericWalletName; }
@@ -1375,6 +1565,7 @@ exports.ANNOUNCED_WALLET_ID_PREFIX = ANNOUNCED_WALLET_ID_PREFIX;
1375
1565
  exports.CantonConnectClient = PartyLayerClient;
1376
1566
  exports.DEFAULT_REGISTRY_URL = DEFAULT_REGISTRY_URL;
1377
1567
  exports.GenericAnnounceAdapter = GenericAnnounceAdapter;
1568
+ exports.GenericDiscoveryAdapter = GenericDiscoveryAdapter;
1378
1569
  exports.MetricsTelemetryAdapter = MetricsTelemetryAdapter;
1379
1570
  exports.PartyLayerClient = PartyLayerClient;
1380
1571
  exports.announcedWalletId = announcedWalletId;