@partylayer/sdk 0.5.0 → 0.7.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, METRICS, WalletNotFoundError, capabilityGuard, installGuard, toSessionId, CapabilityNotSupportedError, errorMetricName } from '@partylayer/core';
1
+ import { toWalletId, toPartyId, hashForPrivacy, createMetricsPayload, mapUnknownErrorToPartyLayerError, findMatchingWalletInfo, detectNetworkMismatch, NetworkMismatchError, METRICS, WalletNotFoundError, capabilityGuard, installGuard, toSessionId, CapabilityNotSupportedError, errorMetricName } from '@partylayer/core';
2
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';
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,73 @@ 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
+ };
20
87
 
21
88
  // src/config.ts
22
89
  var DEFAULT_REGISTRY_URL = "https://registry.partylayer.xyz";
@@ -379,6 +446,8 @@ var PartyLayerClient = class {
379
446
  crypto;
380
447
  storage;
381
448
  telemetry;
449
+ /** Cached announce-discovery picker entries (one-shot; cleared by refreshDiscovery). */
450
+ announceEntriesCache = null;
382
451
  origin;
383
452
  constructor(config) {
384
453
  this.config = config;
@@ -483,6 +552,7 @@ var PartyLayerClient = class {
483
552
  channel: "stable"
484
553
  });
485
554
  }
555
+ registryWallets = await this.aggregateAnnouncedWallets(registryWallets);
486
556
  if (filter?.requiredCapabilities) {
487
557
  return registryWallets.filter(
488
558
  (walletInfo) => filter.requiredCapabilities.every(
@@ -495,6 +565,106 @@ var PartyLayerClient = class {
495
565
  }
496
566
  return registryWallets;
497
567
  }
568
+ /**
569
+ * Whether announce discovery is active: explicit `discovery.announce`, else
570
+ * ON in the browser and OFF under SSR (no `window`). Canonical: provider.md.
571
+ */
572
+ get announceEnabled() {
573
+ if (typeof window === "undefined") return false;
574
+ return this.config.discovery?.announce ?? true;
575
+ }
576
+ /**
577
+ * Clear the cached announce round-trip so the next `listWallets()` re-runs the
578
+ * `canton:requestProvider` handshake (e.g. after a wallet is installed).
579
+ */
580
+ refreshDiscovery() {
581
+ this.announceEntriesCache = null;
582
+ }
583
+ /**
584
+ * Aggregate `canton:announceProvider` wallets into the picker list (A2).
585
+ *
586
+ * One-shot cached per client (refresh via {@link refreshDiscovery}); SSR-skipped.
587
+ * For each discovered provider (announce ∪ `window.canton` scan, deduped):
588
+ * - if its id matches a known wallet's `providerDetection` (provider.id) it
589
+ * IS that wallet — no new entry (identity bridge: Console's `lpnf…` → the
590
+ * `console` entry, Send's `ldmo…` → the `send` entry);
591
+ * - otherwise it is surfaced as a dynamic `browser:ext:<id>` entry routed to
592
+ * its own extension `target`, with a {@link GenericAnnounceAdapter}
593
+ * registered so a click connects through that target ONLY (no shared slot).
594
+ * With zero announcers this returns `base` unchanged.
595
+ */
596
+ async aggregateAnnouncedWallets(base) {
597
+ if (!this.announceEnabled) return base;
598
+ if (this.announceEntriesCache === null) {
599
+ try {
600
+ const discovered = await discoverProviders({
601
+ timeoutMs: this.config.discovery?.announceTimeoutMs,
602
+ // Working provider over the announce target channel; G4 (provider.md):
603
+ // target defaults to id when omitted — never a shared slot.
604
+ createProvider: (a) => createExtensionChannelProvider({ target: a.target ?? a.id })
605
+ });
606
+ const entries = [];
607
+ for (const d of discovered) {
608
+ if (d.identityResolved === false) continue;
609
+ const known = findMatchingWalletInfo(
610
+ { provider: { id: d.id } },
611
+ base
612
+ );
613
+ if (known) continue;
614
+ const adapter = new GenericAnnounceAdapter({
615
+ announceId: d.id,
616
+ name: d.name,
617
+ icon: d.icon,
618
+ provider: d.provider
619
+ });
620
+ this.adapters.set(adapter.walletId, adapter);
621
+ entries.push({
622
+ walletId: adapter.walletId,
623
+ name: adapter.name,
624
+ website: "",
625
+ icons: d.icon ? { sm: d.icon, md: d.icon, lg: d.icon } : {},
626
+ capabilities: adapter.getCapabilities(),
627
+ adapter: { packageName: "announced", versionRange: "*" },
628
+ docs: [],
629
+ networks: [this.config.network || "devnet"],
630
+ channel: "stable"
631
+ });
632
+ }
633
+ this.announceEntriesCache = entries;
634
+ } catch {
635
+ this.announceEntriesCache = [];
636
+ }
637
+ }
638
+ if (this.announceEntriesCache.length === 0) return base;
639
+ const ids = new Set(base.map((w) => String(w.walletId)));
640
+ return [
641
+ ...base,
642
+ ...this.announceEntriesCache.filter((w) => !ids.has(String(w.walletId)))
643
+ ];
644
+ }
645
+ /** Active network-enforcement policy (default 'guard'). */
646
+ get enforcement() {
647
+ return this.config.networkEnforcement ?? "guard";
648
+ }
649
+ /**
650
+ * Detect a confident network mismatch between the dApp's configured network
651
+ * and the session's (wallet-reported) network. Returns null when they match
652
+ * or the comparison isn't confident (conservative — never a false positive).
653
+ */
654
+ networkMismatch(session) {
655
+ return detectNetworkMismatch(this.config.network, session.network);
656
+ }
657
+ /**
658
+ * Guard a transaction-class operation: throw `NetworkMismatchError` when the
659
+ * session is on the wrong network AND the policy enforces it ('guard' |
660
+ * 'strict'). Also protects restored sessions and mid-session network switches.
661
+ */
662
+ assertNetworkOk(session) {
663
+ const mm = this.networkMismatch(session);
664
+ if (mm && this.enforcement !== "off") {
665
+ throw new NetworkMismatchError(mm.expected, mm.actual);
666
+ }
667
+ }
498
668
  /**
499
669
  * Connect to a wallet
500
670
  */
@@ -588,13 +758,31 @@ var PartyLayerClient = class {
588
758
  sessionId: toSessionId(`session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`),
589
759
  walletId: selectedWallet.walletId,
590
760
  partyId: result.partyId,
591
- network: this.config.network,
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,
592
766
  createdAt: Date.now(),
593
767
  expiresAt: result.session.expiresAt,
594
768
  origin: this.origin,
595
769
  capabilitiesSnapshot: result.capabilities,
596
770
  metadata: result.session.metadata
597
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
+ }
598
786
  await this.persistSession(session);
599
787
  this.activeSession = session;
600
788
  this.updateRegistryStatus();
@@ -678,6 +866,7 @@ var PartyLayerClient = class {
678
866
  );
679
867
  }
680
868
  try {
869
+ this.assertNetworkOk(session);
681
870
  const ctx = this.createAdapterContext();
682
871
  return await adapter.signMessage(ctx, session, params);
683
872
  } catch (err) {
@@ -705,6 +894,7 @@ var PartyLayerClient = class {
705
894
  );
706
895
  }
707
896
  try {
897
+ this.assertNetworkOk(session);
708
898
  const ctx = this.createAdapterContext();
709
899
  const result = await adapter.signTransaction(ctx, session, params);
710
900
  this.emit("tx:status", {
@@ -740,6 +930,7 @@ var PartyLayerClient = class {
740
930
  );
741
931
  }
742
932
  try {
933
+ this.assertNetworkOk(session);
743
934
  const ctx = this.createAdapterContext();
744
935
  const result = await adapter.submitTransaction(ctx, session, params);
745
936
  this.emit("tx:status", {
@@ -775,6 +966,7 @@ var PartyLayerClient = class {
775
966
  );
776
967
  }
777
968
  try {
969
+ this.assertNetworkOk(session);
778
970
  const ctx = this.createAdapterContext();
779
971
  return await adapter.ledgerApi(ctx, session, params);
780
972
  } catch (err) {
@@ -1001,6 +1193,6 @@ function createPartyLayer(config) {
1001
1193
  return new PartyLayerClient(config);
1002
1194
  }
1003
1195
 
1004
- export { PartyLayerClient as CantonConnectClient, DEFAULT_REGISTRY_URL, MetricsTelemetryAdapter, PartyLayerClient, createPartyLayer as createCantonConnect, createPartyLayer, createTelemetryAdapter, getBuiltinAdapters, isTelemetryConfig };
1196
+ export { ANNOUNCED_WALLET_ID_PREFIX, PartyLayerClient as CantonConnectClient, DEFAULT_REGISTRY_URL, GenericAnnounceAdapter, MetricsTelemetryAdapter, PartyLayerClient, announcedWalletId, createPartyLayer as createCantonConnect, createPartyLayer, createTelemetryAdapter, getBuiltinAdapters, isTelemetryConfig };
1005
1197
  //# sourceMappingURL=index.mjs.map
1006
1198
  //# sourceMappingURL=index.mjs.map