@partylayer/sdk 0.10.2 → 0.12.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
@@ -21,21 +21,54 @@ var ANNOUNCED_WALLET_ID_PREFIX = "browser:ext:";
21
21
  function announcedWalletId(announceId) {
22
22
  return toWalletId(`${ANNOUNCED_WALLET_ID_PREFIX}${announceId}`);
23
23
  }
24
+ function mapTxStatus(status) {
25
+ switch (status) {
26
+ case "pending":
27
+ return "pending";
28
+ case "signed":
29
+ return "submitted";
30
+ case "executed":
31
+ return "committed";
32
+ case "failed":
33
+ default:
34
+ return "failed";
35
+ }
36
+ }
24
37
  var GenericAnnounceAdapter = class {
25
38
  walletId;
26
39
  name;
27
40
  /** Icon surfaced to the picker (announce detail). */
28
41
  icon;
29
42
  provider;
43
+ metadataEnabled;
44
+ mapError;
45
+ // Optional WalletAdapter surface — assigned in the ctor ONLY when configured,
46
+ // so `getCapabilities()` and `'x' in adapter` feature-detection stay honest.
47
+ restore;
48
+ on;
49
+ ledgerApi;
30
50
  constructor(args) {
31
- this.walletId = announcedWalletId(args.announceId);
51
+ this.walletId = args.walletId ?? announcedWalletId(args.announceId);
32
52
  this.name = args.name && args.name.length > 0 ? args.name : `Canton Wallet (${args.announceId.slice(0, 6)}\u2026)`;
33
53
  this.icon = args.icon;
34
54
  this.provider = args.provider;
55
+ const config = args.config;
56
+ this.metadataEnabled = config?.metadata === true;
57
+ this.mapError = config?.mapError;
58
+ if (config?.events) this.on = this.makeOn();
59
+ if (config?.restore) this.restore = this.makeRestore();
60
+ if (config?.ledgerApi) this.ledgerApi = this.makeLedgerApi();
35
61
  }
36
- /** Baseline CIP-0103 capabilities every announced wallet must implement. */
62
+ /**
63
+ * Capabilities: the baseline three plus whatever optional methods were
64
+ * configured (derived from actual presence, never advertised when absent).
65
+ */
37
66
  getCapabilities() {
38
- return ["connect", "signMessage", "submitTransaction"];
67
+ const caps = ["connect", "signMessage", "submitTransaction"];
68
+ if (this.restore) caps.push("restore");
69
+ if (this.ledgerApi) caps.push("ledgerApi");
70
+ if (this.on) caps.push("events");
71
+ return caps;
39
72
  }
40
73
  /**
41
74
  * The adapter is only ever constructed for a wallet that just announced, so
@@ -45,25 +78,28 @@ var GenericAnnounceAdapter = class {
45
78
  return { installed: true, reason: "Announced via canton:announceProvider" };
46
79
  }
47
80
  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"
81
+ return this.guarded(async () => {
82
+ await this.provider.request({ method: "connect" });
83
+ const account = await this.provider.request({
84
+ method: "getPrimaryAccount"
56
85
  });
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() };
86
+ let status;
87
+ try {
88
+ status = await this.provider.request({ method: "status" });
89
+ } catch {
90
+ }
91
+ const reportedNetwork = status?.network?.networkId;
92
+ const partyId = toPartyId(account.partyId);
93
+ const session = {
94
+ walletId: this.walletId,
95
+ partyId,
96
+ network: reportedNetwork ?? account.networkId ?? ctx.network
97
+ };
98
+ if (this.metadataEnabled) {
99
+ session.metadata = buildMetadata(status, account);
100
+ }
101
+ return { partyId, session, capabilities: this.getCapabilities() };
102
+ });
67
103
  }
68
104
  async disconnect() {
69
105
  try {
@@ -72,18 +108,108 @@ var GenericAnnounceAdapter = class {
72
108
  }
73
109
  }
74
110
  async signMessage(_ctx, _session, params) {
75
- return this.provider.request({
76
- method: "signMessage",
77
- params: { message: params.message }
78
- });
111
+ return this.guarded(
112
+ () => this.provider.request({
113
+ method: "signMessage",
114
+ params: { message: params.message }
115
+ })
116
+ );
79
117
  }
80
118
  async submitTransaction(_ctx, _session, params) {
81
- return this.provider.request({
82
- method: "prepareExecute",
83
- params
119
+ return this.guarded(
120
+ () => this.provider.request({
121
+ method: "prepareExecute",
122
+ params
123
+ })
124
+ );
125
+ }
126
+ // ── Optional-method factories (assigned only when configured) ──────────────
127
+ /** events: bridge the provider's CIP-0103 `txChanged` push event → `txStatus`. */
128
+ makeOn() {
129
+ return (event, handler) => {
130
+ if (event !== "txStatus") return () => {
131
+ };
132
+ const listener = (...args) => {
133
+ const tx = args[0];
134
+ if (!tx) return;
135
+ handler({ status: mapTxStatus(tx.status), commandId: tx.commandId, raw: tx });
136
+ };
137
+ try {
138
+ this.provider.on("txChanged", listener);
139
+ } catch {
140
+ return () => {
141
+ };
142
+ }
143
+ return () => this.provider.removeListener("txChanged", listener);
144
+ };
145
+ }
146
+ /** restore: silent status()/getPrimaryAccount() probe + expiry + party-match. */
147
+ makeRestore() {
148
+ return (_ctx, persisted) => this.guarded(async () => {
149
+ if (persisted.expiresAt && Date.now() >= persisted.expiresAt) return null;
150
+ let status;
151
+ try {
152
+ status = await this.provider.request({ method: "status" });
153
+ } catch {
154
+ }
155
+ const connected = status?.isConnected ?? status?.connection?.isConnected;
156
+ if (connected === false) return null;
157
+ const account = await this.provider.request({
158
+ method: "getPrimaryAccount"
159
+ });
160
+ if (account.partyId !== persisted.partyId) return null;
161
+ return {
162
+ ...persisted,
163
+ walletId: this.walletId,
164
+ metadata: { ...persisted.metadata ?? {}, ...buildMetadata(status, account) }
165
+ };
166
+ });
167
+ }
168
+ /** ledgerApi: proxy the standard CIP-0103 ledgerApi call; shape to {response:string}. */
169
+ makeLedgerApi() {
170
+ return (_ctx, _session, params) => this.guarded(async () => {
171
+ const result = await this.provider.request({
172
+ method: "ledgerApi",
173
+ params: {
174
+ requestMethod: params.requestMethod,
175
+ resource: params.resource,
176
+ body: params.body
177
+ }
178
+ });
179
+ if (result && typeof result.response === "string") return { response: result.response };
180
+ return { response: JSON.stringify(result ?? null) };
84
181
  });
85
182
  }
183
+ /**
184
+ * Run an operation, giving the optional `mapError` hook first crack at any
185
+ * thrown error. With NO hook configured this is a direct pass-through (no
186
+ * try/catch) — byte-identical to the baseline, and the SDK's built-in standard
187
+ * error mapping still applies downstream.
188
+ */
189
+ async guarded(op) {
190
+ if (!this.mapError) return op();
191
+ try {
192
+ return await op();
193
+ } catch (err) {
194
+ const mapped = this.mapError(err);
195
+ throw mapped ?? err;
196
+ }
197
+ }
86
198
  };
199
+ function buildMetadata(status, account) {
200
+ const meta = {};
201
+ const put = (k, v) => {
202
+ if (typeof v === "string" && v.length > 0) meta[k] = v;
203
+ };
204
+ put("publicKey", account.publicKey);
205
+ put("namespace", account.namespace);
206
+ put("networkId", account.networkId);
207
+ put("signingProviderId", account.signingProviderId);
208
+ put("hint", account.hint);
209
+ put("ledgerApiBaseUrl", status?.network?.ledgerApi?.baseUrl);
210
+ put("userId", status?.session?.userId);
211
+ return meta;
212
+ }
87
213
  var GenericDiscoveryAdapter = class {
88
214
  walletId;
89
215
  name;
@@ -585,6 +711,16 @@ function createTelemetryAdapter(config) {
585
711
  return config;
586
712
  }
587
713
  var SESSION_STORAGE_KEY = "active_session";
714
+ var WALLETS_CHANGED_DEBOUNCE_MS = 50;
715
+ function deriveAnnounceConfig(entry) {
716
+ const cfg = entry.adapter?.config ?? {};
717
+ return {
718
+ events: entry.capabilities?.events === true,
719
+ restore: cfg.restore === true,
720
+ ledgerApi: cfg.ledgerApi === true,
721
+ metadata: cfg.metadata === true
722
+ };
723
+ }
588
724
  var PartyLayerClient = class {
589
725
  config;
590
726
  adapters = /* @__PURE__ */ new Map();
@@ -611,6 +747,8 @@ var PartyLayerClient = class {
611
747
  // torn down in destroy(). Empty → listWallets() output is byte-identical.
612
748
  announceRegistry = /* @__PURE__ */ new Map();
613
749
  announceUnsubscribe = null;
750
+ /** Pending debounced `wallets:changed` emit (coalesces an announce burst). */
751
+ walletsChangedTimer = null;
614
752
  origin;
615
753
  constructor(config) {
616
754
  this.config = config;
@@ -654,7 +792,7 @@ var PartyLayerClient = class {
654
792
  this.updateRegistryStatus();
655
793
  if (this.announceEnabled) {
656
794
  this.announceUnsubscribe = subscribeAnnouncedProviders(
657
- (p) => this.announceRegistry.set(p.id, p),
795
+ (p) => this.onAnnounceAccumulated(p),
658
796
  { createProvider: (a) => createExtensionChannelProvider({ target: a.target ?? a.id }) }
659
797
  );
660
798
  }
@@ -801,6 +939,30 @@ var PartyLayerClient = class {
801
939
  refreshDiscovery() {
802
940
  this.announceEntriesCache = null;
803
941
  }
942
+ /**
943
+ * Persistent-accumulator callback (mounted at construction). On each newly
944
+ * announced provider:
945
+ * 1. record it in the live `announceRegistry` (unchanged);
946
+ * 2. invalidate the one-shot `announceEntriesCache` — the SAME invalidation
947
+ * as {@link refreshDiscovery}, so the next `listWallets()` re-aggregates
948
+ * and surfaces the wallet. This does NOT touch `warmPlans` (those hold
949
+ * only GenericDiscoveryAdapter popup plans — a disjoint set);
950
+ * 3. emit a DEBOUNCED `wallets:changed` signal so a reactive consumer (e.g.
951
+ * the React provider) re-lists. The debounce coalesces a burst — and the
952
+ * construction-time reply storm — into one emit (no re-discovery storm).
953
+ *
954
+ * Byte-identical idle: with zero announces this never fires — no invalidation,
955
+ * no emit, no re-list.
956
+ */
957
+ onAnnounceAccumulated(p) {
958
+ this.announceRegistry.set(p.id, p);
959
+ this.announceEntriesCache = null;
960
+ if (this.walletsChangedTimer !== null) return;
961
+ this.walletsChangedTimer = setTimeout(() => {
962
+ this.walletsChangedTimer = null;
963
+ this.emit("wallets:changed", { type: "wallets:changed", reason: "announced" });
964
+ }, WALLETS_CHANGED_DEBOUNCE_MS);
965
+ }
804
966
  /**
805
967
  * Aggregate `canton:announceProvider` wallets into the picker list (A2).
806
968
  *
@@ -836,7 +998,25 @@ var PartyLayerClient = class {
836
998
  { provider: { id: d.id } },
837
999
  base
838
1000
  );
839
- if (known) continue;
1001
+ if (known) {
1002
+ if (this.adapters.has(known.walletId)) continue;
1003
+ try {
1004
+ const entry = await this.registryClient.getWalletEntry(String(known.walletId));
1005
+ if (entry?.adapter?.transport === "announce") {
1006
+ const configured = new GenericAnnounceAdapter({
1007
+ announceId: d.id,
1008
+ walletId: known.walletId,
1009
+ name: d.name ?? known.name,
1010
+ icon: d.icon,
1011
+ provider: d.provider,
1012
+ config: deriveAnnounceConfig(entry)
1013
+ });
1014
+ this.adapters.set(configured.walletId, configured);
1015
+ }
1016
+ } catch {
1017
+ }
1018
+ continue;
1019
+ }
840
1020
  const adapter = new GenericAnnounceAdapter({
841
1021
  announceId: d.id,
842
1022
  name: d.name,
@@ -1341,6 +1521,10 @@ var PartyLayerClient = class {
1341
1521
  this.announceUnsubscribe?.();
1342
1522
  this.announceUnsubscribe = null;
1343
1523
  this.announceRegistry.clear();
1524
+ if (this.walletsChangedTimer !== null) {
1525
+ clearTimeout(this.walletsChangedTimer);
1526
+ this.walletsChangedTimer = null;
1527
+ }
1344
1528
  this.eventHandlers.clear();
1345
1529
  this.activeSession = null;
1346
1530
  }