@partylayer/sdk 0.21.0 → 0.22.1

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/native.js ADDED
@@ -0,0 +1,2832 @@
1
+ 'use strict';
2
+
3
+ var core = require('@partylayer/core');
4
+ var registryClient = require('@partylayer/registry-client');
5
+ var provider = require('@partylayer/provider');
6
+
7
+ // src/client-base.ts
8
+ var UNSUPPORTED_METHOD = 4200;
9
+ var METHOD_NOT_FOUND = -32601;
10
+ function isUnsupportedMethod(err) {
11
+ const code = err?.code;
12
+ return code === UNSUPPORTED_METHOD || code === METHOD_NOT_FOUND;
13
+ }
14
+ function assertExecuteCorrelation(result, request) {
15
+ const expected = request?.commandId;
16
+ if (typeof expected !== "string" || !expected) return;
17
+ const value = result;
18
+ for (const actual of [value?.commandId, value?.tx?.commandId]) {
19
+ if (typeof actual === "string" && actual && actual !== expected) {
20
+ throw new core.TransportError("Wallet returned a different commandId; transaction outcome is unknown. Reconcile before retrying.");
21
+ }
22
+ }
23
+ }
24
+ function receiptFromExecutedTx(result) {
25
+ const tx = result?.tx;
26
+ const updateId = tx?.payload?.updateId;
27
+ if (typeof updateId !== "string" || updateId.length === 0) return null;
28
+ return {
29
+ transactionHash: core.toTransactionHash(updateId),
30
+ submittedAt: Date.now(),
31
+ commandId: typeof tx?.commandId === "string" ? tx.commandId : void 0,
32
+ updateId,
33
+ ...validOffset(tx?.payload?.completionOffset) ? { completionOffset: tx.payload.completionOffset } : {}
34
+ };
35
+ }
36
+ function normalizeReceipt(result, request) {
37
+ assertExecuteCorrelation(result, request);
38
+ const executed = receiptFromExecutedTx(result);
39
+ if (executed) return executed;
40
+ const value = result && typeof result === "object" ? result : {};
41
+ const timestamp = typeof value.submittedAt === "number" ? value.submittedAt : typeof value.submittedAt === "string" ? Date.parse(value.submittedAt) : NaN;
42
+ const tx = value.tx && typeof value.tx === "object" ? value.tx : {};
43
+ const commandId = typeof value.commandId === "string" ? value.commandId : typeof tx.commandId === "string" ? tx.commandId : typeof request.commandId === "string" ? request.commandId : void 0;
44
+ return {
45
+ submittedAt: Number.isFinite(timestamp) ? timestamp : Date.now(),
46
+ ...typeof value.transactionHash === "string" && value.transactionHash.length > 0 ? { transactionHash: core.toTransactionHash(value.transactionHash) } : {},
47
+ ...typeof value.updateId === "string" && value.updateId.length > 0 ? { updateId: value.updateId } : {},
48
+ ...validOffset(value.completionOffset) ? { completionOffset: value.completionOffset } : {},
49
+ ...commandId ? { commandId } : {}
50
+ };
51
+ }
52
+ function validOffset(value) {
53
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
54
+ }
55
+ function reportOnce(state, walletId, detail, logger) {
56
+ if (state.logged) return;
57
+ state.logged = true;
58
+ logger?.warn(
59
+ `[PartyLayer] ${walletId}: ${detail} Confirm ledger completion only when the receipt contains a real updateId.`
60
+ );
61
+ }
62
+ async function submitViaPrepareExecute(provider, params, opts) {
63
+ const payload = Object.prototype.hasOwnProperty.call(params, "signedTx") ? params.signedTx : params;
64
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
65
+ throw new core.TransportError("CIP-0103 submission requires a command payload object as signedTx");
66
+ }
67
+ const rpcParams = payload;
68
+ const { walletId, state, logger } = opts;
69
+ if (state.verb !== "plain") {
70
+ try {
71
+ const result2 = await provider.request({
72
+ method: "prepareExecuteAndWait",
73
+ params: rpcParams
74
+ });
75
+ state.verb = "awaited";
76
+ const receipt = normalizeReceipt(result2, rpcParams);
77
+ if (receipt.updateId) return receipt;
78
+ reportOnce(
79
+ state,
80
+ walletId,
81
+ "prepareExecuteAndWait returned no updateId.",
82
+ logger
83
+ );
84
+ return receipt;
85
+ } catch (err) {
86
+ if (!isUnsupportedMethod(err)) throw err;
87
+ state.verb = "plain";
88
+ reportOnce(
89
+ state,
90
+ walletId,
91
+ "has no prepareExecuteAndWait; using prepareExecute, which the CIP-0103 types return as null.",
92
+ logger
93
+ );
94
+ }
95
+ }
96
+ const result = await provider.request({ method: "prepareExecute", params: rpcParams });
97
+ return normalizeReceipt(result, rpcParams);
98
+ }
99
+ function normalizeSignedMessage(response, session, params) {
100
+ const signature = typeof response === "string" ? response : response?.signature;
101
+ if (typeof signature !== "string" || signature.trim().length === 0) {
102
+ throw new core.TransportError("The wallet returned an invalid message signature");
103
+ }
104
+ const reportedParty = response && typeof response === "object" ? response.partyId : void 0;
105
+ if (reportedParty !== void 0 && reportedParty !== session.partyId) {
106
+ throw new core.TransportError("The wallet account changed while signing; reconnect before retrying");
107
+ }
108
+ const reportedMessage = response && typeof response === "object" ? response.message : void 0;
109
+ if (reportedMessage !== void 0 && reportedMessage !== params.message) {
110
+ throw new core.TransportError("Wallet signed an unexpected message");
111
+ }
112
+ return {
113
+ signature: core.toSignature(signature),
114
+ partyId: session.partyId,
115
+ message: params.message,
116
+ nonce: params.nonce,
117
+ domain: params.domain
118
+ };
119
+ }
120
+ function assertConnectionAccepted(result) {
121
+ if (result === false || result && typeof result === "object" && result.isConnected === false) {
122
+ throw new core.TransportError("The wallet did not establish a connection");
123
+ }
124
+ }
125
+ function assertPrimaryParty(account) {
126
+ if (typeof account?.partyId !== "string" || !account.partyId.trim()) throw new core.TransportError("The wallet did not return a primary party");
127
+ }
128
+
129
+ // src/native-owner-bindings.ts
130
+ var nativeOwnerBindings = /* @__PURE__ */ new WeakMap();
131
+ var nativeAdapterCopies = /* @__PURE__ */ new WeakMap();
132
+
133
+ // src/announce-adapter.ts
134
+ function getAnnounceCapabilities(config = {}) {
135
+ const caps = ["connect"];
136
+ if (config.signMessage !== false) caps.push("signMessage");
137
+ caps.push("submitTransaction");
138
+ if (config.restore) caps.push("restore");
139
+ if (config.ledgerApi) caps.push("ledgerApi");
140
+ if (config.events) caps.push("events");
141
+ return caps;
142
+ }
143
+ var ANNOUNCED_WALLET_ID_PREFIX = "browser:ext:";
144
+ function announcedWalletId(announceId) {
145
+ return core.toWalletId(`${ANNOUNCED_WALLET_ID_PREFIX}${announceId}`);
146
+ }
147
+ function mapTxStatus(status) {
148
+ switch (status) {
149
+ case "pending":
150
+ return "pending";
151
+ case "signed":
152
+ return "submitted";
153
+ case "executed":
154
+ return "committed";
155
+ case "failed":
156
+ default:
157
+ return "failed";
158
+ }
159
+ }
160
+ function toBase64Message(message) {
161
+ const bytes = new TextEncoder().encode(message);
162
+ let binary = "";
163
+ for (const b of bytes) binary += String.fromCharCode(b);
164
+ return btoa(binary);
165
+ }
166
+ var GenericAnnounceAdapter = class _GenericAnnounceAdapter {
167
+ walletId;
168
+ name;
169
+ /** Icon surfaced to the picker (announce detail). */
170
+ icon;
171
+ rawProvider;
172
+ metadataEnabled;
173
+ staticMetadata;
174
+ mapError;
175
+ signMessageBase64;
176
+ /**
177
+ * Which execute verb this wallet turned out to support. Resolved on the first
178
+ * submit and reused, so the wallet is asked at most once.
179
+ */
180
+ executeVerb = {};
181
+ // Optional WalletAdapter surface — assigned in the ctor ONLY when configured,
182
+ // so `getCapabilities()` and `'x' in adapter` feature-detection stay honest.
183
+ restore;
184
+ on;
185
+ ledgerApi;
186
+ // signMessage is optional too: assigned in the ctor only when the wallet
187
+ // declares support, so a wallet that cannot sign is not advertised as able to.
188
+ signMessage;
189
+ constructor(args) {
190
+ const configuration = { ...args, config: args.config && {
191
+ ...args.config,
192
+ staticMetadata: args.config.staticMetadata && { ...args.config.staticMetadata }
193
+ } };
194
+ nativeAdapterCopies.set(this, () => new _GenericAnnounceAdapter(configuration));
195
+ this.walletId = args.walletId ?? announcedWalletId(args.announceId);
196
+ this.name = args.name && args.name.length > 0 ? args.name : `Canton Wallet (${args.announceId.slice(0, 6)}\u2026)`;
197
+ this.icon = args.icon;
198
+ this.rawProvider = args.provider;
199
+ const config = args.config;
200
+ this.metadataEnabled = config?.metadata === true;
201
+ this.staticMetadata = config?.staticMetadata;
202
+ this.mapError = config?.mapError;
203
+ this.signMessageBase64 = config?.signMessageBase64 === true;
204
+ if (config?.events) this.on = this.makeOn();
205
+ if (config?.restore) this.restore = this.makeRestore();
206
+ if (config?.ledgerApi) this.ledgerApi = this.makeLedgerApi();
207
+ if (config?.signMessage !== false) this.signMessage = this.signMessageImpl.bind(this);
208
+ }
209
+ get provider() {
210
+ return nativeOwnerBindings.get(this)?.getProvider(String(this.walletId)) ?? this.rawProvider;
211
+ }
212
+ /** @internal Register the discovered transport with the one official owner. */
213
+ async prepareNativeConnection(network) {
214
+ const owner = nativeOwnerBindings.get(this);
215
+ if (!owner) return;
216
+ await owner.prepare(String(this.walletId), {
217
+ providerId: String(this.walletId),
218
+ name: this.name,
219
+ type: "browser",
220
+ icon: this.icon,
221
+ provider: () => this.rawProvider,
222
+ detect: async () => true
223
+ }, network);
224
+ }
225
+ /**
226
+ * Capabilities derived from actual presence: connect and submitTransaction are
227
+ * always present; signMessage, restore, ledgerApi, and events are each included
228
+ * only when the matching method was assigned, so the set is never advertised
229
+ * beyond what the adapter can do.
230
+ */
231
+ getCapabilities() {
232
+ return getAnnounceCapabilities({
233
+ signMessage: !!this.signMessage,
234
+ restore: !!this.restore,
235
+ ledgerApi: !!this.ledgerApi,
236
+ events: !!this.on
237
+ });
238
+ }
239
+ /**
240
+ * The adapter is only ever constructed for a wallet that just announced, so
241
+ * its presence is established by the announce handshake itself.
242
+ */
243
+ async detectInstalled() {
244
+ return {
245
+ installed: true,
246
+ // Presence by CONSTRUCTION: this adapter only exists because an announce
247
+ // arrived on the wallet's own target channel. There is no probe to be
248
+ // wrong about, which is why this is the one path that cannot report a
249
+ // wallet that is not there.
250
+ availability: { kind: "installed" },
251
+ reason: "Announced via canton:announceProvider"
252
+ };
253
+ }
254
+ async connect(ctx, options) {
255
+ return this.guarded(async () => {
256
+ const owner = nativeOwnerBindings.get(this);
257
+ const native = owner ? await owner.connect(String(this.walletId), options?.signal) : void 0;
258
+ if (!owner) assertConnectionAccepted(await this.provider.request({ method: "connect" }));
259
+ const account = native?.account ?? await this.provider.request({
260
+ method: "getPrimaryAccount"
261
+ });
262
+ assertPrimaryParty(account);
263
+ let status;
264
+ try {
265
+ status = native?.status ?? await this.provider.request({ method: "status" });
266
+ } catch {
267
+ }
268
+ const reportedNetwork = status?.network?.networkId;
269
+ const partyId = core.toPartyId(account.partyId);
270
+ const network = [reportedNetwork, account.networkId, ctx.network].find(
271
+ (n) => typeof n === "string" && core.isRecognizedNetwork(n)
272
+ ) ?? ctx.network;
273
+ const session = {
274
+ walletId: this.walletId,
275
+ partyId,
276
+ network
277
+ };
278
+ if (this.metadataEnabled) {
279
+ session.metadata = { ...this.staticMetadata ?? {}, ...buildMetadata(status, account) };
280
+ }
281
+ return { partyId, session, capabilities: this.getCapabilities() };
282
+ });
283
+ }
284
+ async disconnect() {
285
+ const owner = nativeOwnerBindings.get(this);
286
+ if (owner) {
287
+ await owner.disconnect();
288
+ return;
289
+ }
290
+ try {
291
+ await this.provider.request({ method: "disconnect" });
292
+ } catch {
293
+ }
294
+ }
295
+ // Real signMessage implementation. Exposed as `this.signMessage` from the ctor
296
+ // only when the wallet declares support, so getCapabilities and feature
297
+ // detection stay honest for a wallet that cannot sign.
298
+ async signMessageImpl(_ctx, session, params) {
299
+ return this.guarded(async () => {
300
+ const rpcParams = this.signMessageBase64 ? { message: toBase64Message(params.message) } : { message: params.message };
301
+ const res = await this.provider.request({ method: "signMessage", params: rpcParams });
302
+ return normalizeSignedMessage(res, session, params);
303
+ });
304
+ }
305
+ async submitTransaction(ctx, _session, params) {
306
+ return this.guarded(
307
+ () => submitViaPrepareExecute(this.provider, params, {
308
+ walletId: String(this.walletId),
309
+ state: this.executeVerb,
310
+ logger: ctx.logger
311
+ })
312
+ );
313
+ }
314
+ // ── Optional-method factories (assigned only when configured) ──────────────
315
+ /** events: bridge the provider's CIP-0103 `txChanged` push event → `txStatus`. */
316
+ makeOn() {
317
+ return (event, handler) => {
318
+ if (event !== "txStatus") return () => {
319
+ };
320
+ const listener = (...args) => {
321
+ const tx = args[0];
322
+ if (!tx) return;
323
+ handler({ status: mapTxStatus(tx.status), commandId: tx.commandId, raw: tx });
324
+ };
325
+ try {
326
+ this.provider.on("txChanged", listener);
327
+ } catch {
328
+ return () => {
329
+ };
330
+ }
331
+ return () => this.provider.removeListener("txChanged", listener);
332
+ };
333
+ }
334
+ /** restore: silent status()/getPrimaryAccount() probe + expiry + party-match. */
335
+ makeRestore() {
336
+ return (_ctx, persisted) => this.guarded(async () => {
337
+ const owner = nativeOwnerBindings.get(this);
338
+ if (owner) {
339
+ await this.prepareNativeConnection(_ctx.network);
340
+ const restored = await owner.restore({ id: String(this.walletId), partyId: persisted.partyId, network: persisted.network });
341
+ return restored?.id === String(this.walletId) ? { ...persisted, capabilitiesSnapshot: this.getCapabilities() } : null;
342
+ }
343
+ if (persisted.expiresAt && Date.now() >= persisted.expiresAt) return null;
344
+ let status;
345
+ try {
346
+ status = await this.provider.request({ method: "status" });
347
+ } catch {
348
+ }
349
+ const connected = status?.isConnected ?? status?.connection?.isConnected;
350
+ if (connected === false) return null;
351
+ const account = await this.provider.request({
352
+ method: "getPrimaryAccount"
353
+ });
354
+ if (account.partyId !== persisted.partyId) return null;
355
+ const network = [status?.network?.networkId, account.networkId].find(
356
+ (value) => typeof value === "string" && core.isRecognizedNetwork(value)
357
+ );
358
+ if (network && core.detectNetworkMismatch(persisted.network, network)) return null;
359
+ return {
360
+ ...persisted,
361
+ walletId: this.walletId,
362
+ // persisted (lowest) → static config → runtime RPC (wins).
363
+ metadata: {
364
+ ...persisted.metadata ?? {},
365
+ ...this.staticMetadata ?? {},
366
+ ...buildMetadata(status, account)
367
+ }
368
+ };
369
+ });
370
+ }
371
+ /** ledgerApi: proxy the standard CIP-0103 ledgerApi call; shape to {response:string}. */
372
+ makeLedgerApi() {
373
+ return (_ctx, _session, params) => this.guarded(async () => {
374
+ const result = await this.provider.request({
375
+ method: "ledgerApi",
376
+ params: {
377
+ requestMethod: core.normalizeLedgerMethodLower(params.requestMethod),
378
+ resource: params.resource,
379
+ body: core.ledgerApiBodyToObject(params.body)
380
+ }
381
+ });
382
+ if (result && typeof result.response === "string") return { response: result.response };
383
+ return { response: JSON.stringify(result ?? null) };
384
+ });
385
+ }
386
+ /**
387
+ * Run an operation, giving the optional `mapError` hook first crack at any
388
+ * thrown error. With NO hook configured this is a direct pass-through (no
389
+ * try/catch) — byte-identical to the baseline, and the SDK's built-in standard
390
+ * error mapping still applies downstream.
391
+ */
392
+ async guarded(op) {
393
+ if (!this.mapError) return op();
394
+ try {
395
+ return await op();
396
+ } catch (err) {
397
+ const mapped = this.mapError(err);
398
+ throw mapped ?? err;
399
+ }
400
+ }
401
+ };
402
+ function buildMetadata(status, account) {
403
+ const meta = {};
404
+ const put = (k, v) => {
405
+ if (typeof v === "string" && v.length > 0) meta[k] = v;
406
+ };
407
+ put("kernelId", status?.kernel?.id);
408
+ put("publicKey", account.publicKey);
409
+ put("namespace", account.namespace);
410
+ put("networkId", account.networkId);
411
+ put("signingProviderId", account.signingProviderId);
412
+ put("hint", account.hint);
413
+ put("ledgerApiBaseUrl", status?.network?.ledgerApi?.baseUrl);
414
+ put("userId", status?.session?.userId);
415
+ return meta;
416
+ }
417
+ function getDiscoveryCapabilities(declared) {
418
+ const capabilities = ["connect", "disconnect"];
419
+ if (declared?.signMessage !== false) capabilities.push("signMessage");
420
+ if (declared?.submitTransaction !== false) capabilities.push("submitTransaction");
421
+ if (declared?.ledgerApi) capabilities.push("ledgerApi");
422
+ return capabilities;
423
+ }
424
+ var GenericDiscoveryAdapter = class _GenericDiscoveryAdapter {
425
+ walletId;
426
+ name;
427
+ icon;
428
+ /**
429
+ * Resolved official adapter. Set at construction for the instance form; for
430
+ * the factory form it stays null until {@link resolveOfficial} constructs it
431
+ * with the network-resolved host.
432
+ */
433
+ official;
434
+ /** Factory form (null for the instance form). */
435
+ factory;
436
+ /** Network→host map for the factory form; injected by the SDK post-registry. */
437
+ networkHosts;
438
+ /** Lazily resolved from `official.provider()` — NOT at construction (SSR-safe). */
439
+ providerInstance = null;
440
+ /**
441
+ * Which execute verb this wallet turned out to support. Resolved on the first
442
+ * submit and reused, so the wallet is asked at most once.
443
+ */
444
+ executeVerb = {};
445
+ capabilities;
446
+ ledgerApi;
447
+ constructor(args) {
448
+ const configuration = { ...args, capabilities: args.capabilities && { ...args.capabilities } };
449
+ nativeAdapterCopies.set(this, () => new _GenericDiscoveryAdapter({
450
+ ...configuration,
451
+ networkHosts: { ...this.networkHosts }
452
+ }));
453
+ this.capabilities = getDiscoveryCapabilities(args.capabilities);
454
+ if (args.capabilities?.ledgerApi) {
455
+ this.ledgerApi = async (_ctx, _session, params) => {
456
+ const result = await this.provider.request({
457
+ method: "ledgerApi",
458
+ params: {
459
+ requestMethod: core.normalizeLedgerMethodLower(params.requestMethod),
460
+ resource: params.resource,
461
+ body: core.ledgerApiBodyToObject(params.body)
462
+ }
463
+ });
464
+ return { response: typeof result?.response === "string" ? result.response : JSON.stringify(result ?? null) };
465
+ };
466
+ }
467
+ if (args.official) {
468
+ this.official = args.official;
469
+ this.factory = null;
470
+ this.networkHosts = {};
471
+ this.walletId = args.walletId ?? core.toWalletId(args.official.providerId);
472
+ this.name = args.name && args.name.length > 0 ? args.name : args.official.name;
473
+ this.icon = args.icon ?? args.official.icon;
474
+ } else if (args.factory) {
475
+ this.official = null;
476
+ this.factory = args.factory;
477
+ this.networkHosts = args.networkHosts ?? {};
478
+ this.walletId = args.walletId ?? core.toWalletId(args.factory.providerId);
479
+ this.name = args.name && args.name.length > 0 ? args.name : args.factory.name ?? args.factory.providerId;
480
+ this.icon = args.icon ?? args.factory.icon;
481
+ } else {
482
+ throw new Error(
483
+ "GenericDiscoveryAdapter requires either `official` (instance) or `factory`."
484
+ );
485
+ }
486
+ }
487
+ /** Whether this bridge resolves its host from `networkHosts` (factory form). */
488
+ usesFactory() {
489
+ return this.factory !== null;
490
+ }
491
+ /**
492
+ * Inject the registry's network→host map (factory form only). SYNCHRONOUS —
493
+ * the SDK calls this during the async warm phase once the registry entry is
494
+ * loaded, BEFORE the (possibly gesture-synchronous) connect.
495
+ */
496
+ setNetworkHosts(networkHosts) {
497
+ if (this.factory) this.networkHosts = networkHosts ?? {};
498
+ }
499
+ /**
500
+ * Resolve + construct the official adapter for `network` — SYNCHRONOUS, so the
501
+ * popup-safe gesture path reaches `window.open` with NO awaits. Idempotent.
502
+ * The SDK pre-calls it during warm-up; `connect()` also calls it as its first
503
+ * statement so a cold (un-warmed) connect is still gesture-safe.
504
+ *
505
+ * Failure is CLEAR, never a silent wrong-network host: a factory wallet with
506
+ * no host for `network` in `networkHosts` throws, naming the network.
507
+ */
508
+ resolveOfficial(network) {
509
+ if (this.official) return;
510
+ if (!this.factory) return;
511
+ const host = this.networkHosts[network];
512
+ if (!host) {
513
+ throw new Error(
514
+ `Wallet "${String(this.walletId)}" has no host for network "${network}". Add it to the registry entry's adapter.networkHosts, or supply a pre-constructed official adapter with an explicit host.`
515
+ );
516
+ }
517
+ this.official = this.factory.create(host);
518
+ }
519
+ /** @internal Prepare the official owner before a popup-opening click. */
520
+ async prepareNativeConnection(network) {
521
+ const owner = nativeOwnerBindings.get(this);
522
+ if (!owner) return;
523
+ this.resolveOfficial(network);
524
+ await owner.prepare(String(this.walletId), this.official, network);
525
+ }
526
+ /** Lazily obtain (and cache) the official provider — deferred off the init/SSR path.
527
+ * `official.provider()` is typed `OfficialProvider` (loose `request` so real
528
+ * official adapters are assignable); it is call-compatible with CIP0103Provider
529
+ * (the bridge only ever calls `request({ method, params })`). */
530
+ get provider() {
531
+ const owner = nativeOwnerBindings.get(this);
532
+ if (owner) return owner.getProvider(String(this.walletId));
533
+ if (this.providerInstance === null) {
534
+ if (!this.official) {
535
+ throw new Error(
536
+ `Wallet "${String(this.walletId)}" provider requested before host resolution \u2014 call resolveOfficial(network) first.`
537
+ );
538
+ }
539
+ this.providerInstance = this.official.provider();
540
+ }
541
+ return this.providerInstance;
542
+ }
543
+ /** Implemented, registry-declared capabilities; popup event listeners are never claimed. */
544
+ getCapabilities() {
545
+ return [...this.capabilities];
546
+ }
547
+ /**
548
+ * THE SINGLE PLACE THE discovery-adapter RULE IS APPLIED.
549
+ *
550
+ * **A `discovery-adapter` transport implies there is no local install.** Every
551
+ * wallet on that transport is a hosted popup or remote gateway reached with
552
+ * `window.open` — Walley, Cauri and OneSwap today. There is no extension, no
553
+ * injected global, nothing on the machine to probe. The honest answer is
554
+ * `no-local-install`, and it follows from the registry entry alone.
555
+ *
556
+ * SO THE VENDOR'S `detect()` IS NOT CALLED, and reinstating that call would be
557
+ * a regression however much it looks like rigour. Read from their shipped
558
+ * source, all three are constants:
559
+ *
560
+ * walley: typeof window < "u" && typeof window.open == "function"
561
+ * cauri: Promise.resolve(true)
562
+ * oneswap: typeof window !== 'undefined'
563
+ *
564
+ * Each returns true in any browser. Awaiting them bought a value carrying no
565
+ * information, at the cost of an async hop on the picker's render path and a
566
+ * dependency on three third parties independently choosing to answer
567
+ * honestly. The registry already knows, it is signed, and it cannot drift.
568
+ *
569
+ * `installed: false` is deliberate and is NOT "not available": there is no
570
+ * local install, so the only truthful value for a field that asks about one
571
+ * is false. A picker must read `availability`, which says why.
572
+ */
573
+ async detectInstalled() {
574
+ return {
575
+ installed: false,
576
+ availability: { kind: "no-local-install" },
577
+ reason: "Hosted popup wallet \u2014 opens in a window; nothing is installed locally"
578
+ };
579
+ }
580
+ async connect(ctx, options) {
581
+ this.resolveOfficial(ctx.network);
582
+ const owner = nativeOwnerBindings.get(this);
583
+ const native = owner ? await owner.connect(String(this.walletId), options?.signal) : void 0;
584
+ if (!owner) assertConnectionAccepted(await this.provider.request({ method: "connect" }));
585
+ const account = native?.account ?? await this.provider.request({
586
+ method: "getPrimaryAccount"
587
+ });
588
+ assertPrimaryParty(account);
589
+ let reportedNetwork;
590
+ try {
591
+ const status = native?.status ?? await this.provider.request({
592
+ method: "status"
593
+ });
594
+ reportedNetwork = status?.network?.networkId;
595
+ } catch {
596
+ }
597
+ const partyId = core.toPartyId(account.partyId);
598
+ const network = [reportedNetwork, account.networkId, ctx.network].find(
599
+ (n) => typeof n === "string" && core.isRecognizedNetwork(n)
600
+ ) ?? ctx.network;
601
+ const session = {
602
+ walletId: this.walletId,
603
+ partyId,
604
+ network
605
+ };
606
+ return { partyId, session, capabilities: this.getCapabilities() };
607
+ }
608
+ /** Restore silently and validate the live party before exposing a connected session. */
609
+ async restore(ctx, persisted) {
610
+ try {
611
+ if (persisted.expiresAt && Date.now() >= persisted.expiresAt) return null;
612
+ this.resolveOfficial(ctx.network);
613
+ const owner = nativeOwnerBindings.get(this);
614
+ if (owner) {
615
+ await this.prepareNativeConnection(ctx.network);
616
+ const restored = await owner.restore({
617
+ id: String(this.walletId),
618
+ partyId: persisted.partyId,
619
+ network: persisted.network
620
+ });
621
+ return restored?.id === String(this.walletId) ? { ...persisted, walletId: this.walletId, capabilitiesSnapshot: this.getCapabilities() } : null;
622
+ }
623
+ if (this.official?.restore) {
624
+ const restored = await this.official.restore();
625
+ if (!restored) return null;
626
+ this.providerInstance = restored;
627
+ }
628
+ const account = await this.provider.request({ method: "getPrimaryAccount" });
629
+ if (account.partyId !== persisted.partyId) return null;
630
+ let status;
631
+ try {
632
+ status = await this.provider.request({ method: "status" });
633
+ } catch {
634
+ }
635
+ if (status?.connection?.isConnected === false) return null;
636
+ const network = [status?.network?.networkId, account.networkId].find(
637
+ (value) => typeof value === "string" && core.isRecognizedNetwork(value)
638
+ );
639
+ if (network && core.detectNetworkMismatch(persisted.network, network)) return null;
640
+ return { ...persisted, walletId: this.walletId, capabilitiesSnapshot: this.getCapabilities() };
641
+ } catch {
642
+ return null;
643
+ }
644
+ }
645
+ async disconnect() {
646
+ const owner = nativeOwnerBindings.get(this);
647
+ if (owner) {
648
+ await owner.disconnect();
649
+ return;
650
+ }
651
+ try {
652
+ await this.provider.request({ method: "disconnect" });
653
+ } catch {
654
+ }
655
+ }
656
+ async signMessage(_ctx, session, params) {
657
+ const response = await this.provider.request({
658
+ method: "signMessage",
659
+ params: { message: params.message }
660
+ });
661
+ return normalizeSignedMessage(response, session, params);
662
+ }
663
+ async submitTransaction(ctx, _session, params) {
664
+ return submitViaPrepareExecute(this.provider, params, {
665
+ walletId: String(this.walletId),
666
+ state: this.executeVerb,
667
+ logger: ctx.logger
668
+ });
669
+ }
670
+ };
671
+ function createSessionProvider(options) {
672
+ const events = new provider.CIP0103EventBus();
673
+ let current = null;
674
+ let disposed = false;
675
+ let revision = 0;
676
+ const nativeSubscriptions = [];
677
+ const bridgeSubscriptions = [];
678
+ const provider$1 = {
679
+ request: async (args) => {
680
+ try {
681
+ if (args === null || typeof args !== "object" || Array.isArray(args) || typeof args.method !== "string") {
682
+ throw new provider.ProviderRpcError("Request must be an object with a string method", provider.JSON_RPC_ERRORS.INVALID_REQUEST);
683
+ }
684
+ if (args.params !== void 0 && (args.params === null || typeof args.params !== "object")) {
685
+ throw new provider.ProviderRpcError("Request params must be an object or array", provider.JSON_RPC_ERRORS.INVALID_PARAMS);
686
+ }
687
+ if (disposed) throw new Error("PartyLayer client was destroyed");
688
+ if (args.method === "connect" || args.method === "disconnect" || args.method === "signMessage") {
689
+ return options.bridge.request(args);
690
+ }
691
+ await options.ensureSession();
692
+ const native = options.native();
693
+ if (!native) return options.bridge.request(args);
694
+ if ([
695
+ "prepareExecute",
696
+ "prepareExecuteAndWait",
697
+ "prepareTransaction",
698
+ "executeTransaction",
699
+ "signTransaction",
700
+ "ledgerApi"
701
+ ].includes(args.method))
702
+ options.guardNetwork();
703
+ const result = await native.request(args);
704
+ if (args.method === "prepareExecute" || args.method === "prepareExecuteAndWait")
705
+ assertExecuteCorrelation(result, args.params);
706
+ return result;
707
+ } catch (error) {
708
+ throw provider.toProviderRpcError(error);
709
+ }
710
+ },
711
+ on: (event, listener) => {
712
+ events.on(event, listener);
713
+ return provider$1;
714
+ },
715
+ emit: (event, ...args) => events.emit(event, ...args),
716
+ removeListener: (event, listener) => {
717
+ events.removeListener(event, listener);
718
+ return provider$1;
719
+ }
720
+ };
721
+ events.setOwner(provider$1);
722
+ const refresh = () => {
723
+ const next = options.native();
724
+ if (next === current) return;
725
+ ++revision;
726
+ nativeSubscriptions.splice(0).forEach((unsubscribe2) => unsubscribe2());
727
+ current = next;
728
+ if (!next || disposed) return;
729
+ const captured = revision;
730
+ for (const name of ["statusChanged", "accountsChanged", "txChanged", "connected"]) {
731
+ const listener = (...args) => {
732
+ if (!disposed && next === options.native()) events.emit(name, ...args);
733
+ };
734
+ next.on(name, listener);
735
+ nativeSubscriptions.push(() => next.removeListener(name, listener));
736
+ }
737
+ for (const [method, event] of [
738
+ ["status", "statusChanged"],
739
+ ["listAccounts", "accountsChanged"]
740
+ ]) {
741
+ void next.request({ method }).then(
742
+ (value) => {
743
+ if (!disposed && captured === revision && next === options.native())
744
+ events.emit(event, value);
745
+ },
746
+ () => {
747
+ }
748
+ );
749
+ }
750
+ events.emit("connected", { isConnected: true });
751
+ };
752
+ for (const name of ["statusChanged", "accountsChanged", "txChanged", "connected"]) {
753
+ const listener = (...args) => {
754
+ if (!options.native() && !disposed) events.emit(name, ...args);
755
+ };
756
+ options.bridge.on(name, listener);
757
+ bridgeSubscriptions.push(() => options.bridge.removeListener(name, listener));
758
+ }
759
+ const unsubscribe = options.subscribe(refresh);
760
+ refresh();
761
+ return {
762
+ provider: provider$1,
763
+ destroy: () => {
764
+ if (disposed) return;
765
+ disposed = true;
766
+ ++revision;
767
+ unsubscribe();
768
+ nativeSubscriptions.splice(0).forEach((remove) => remove());
769
+ bridgeSubscriptions.splice(0).forEach((remove) => remove());
770
+ current = null;
771
+ events.removeAllListeners();
772
+ }
773
+ };
774
+ }
775
+
776
+ // src/config-base.ts
777
+ var DEFAULT_REGISTRY_URL = "https://registry.partylayer.xyz";
778
+
779
+ // src/adapters.ts
780
+ var DefaultLogger = class {
781
+ debug(_message, ..._args) {
782
+ }
783
+ info(_message, ..._args) {
784
+ }
785
+ warn(_message, ..._args) {
786
+ }
787
+ error(_message, _error, ..._args) {
788
+ }
789
+ };
790
+ var DefaultCrypto = class {
791
+ async getKey(origin) {
792
+ if (typeof crypto === "undefined" || !crypto.subtle) {
793
+ throw new Error("Web Crypto API not available");
794
+ }
795
+ const encoder = new TextEncoder();
796
+ const data = encoder.encode(origin);
797
+ const hash = await crypto.subtle.digest("SHA-256", data);
798
+ return crypto.subtle.importKey(
799
+ "raw",
800
+ hash.slice(0, 32),
801
+ { name: "AES-GCM" },
802
+ false,
803
+ ["encrypt", "decrypt"]
804
+ );
805
+ }
806
+ async encrypt(data, key) {
807
+ const iv = new Uint8Array(this.randomBytes(12));
808
+ const cryptoKey = await this.getKey(key);
809
+ const encrypted = await globalThis.crypto.subtle.encrypt(
810
+ { name: "AES-GCM", iv },
811
+ cryptoKey,
812
+ new TextEncoder().encode(data)
813
+ );
814
+ const combined = new Uint8Array(iv.length + encrypted.byteLength);
815
+ combined.set(iv);
816
+ combined.set(new Uint8Array(encrypted), iv.length);
817
+ return btoa(String.fromCharCode(...combined));
818
+ }
819
+ async decrypt(encrypted, key) {
820
+ const cryptoKey = await this.getKey(key);
821
+ const combined = Uint8Array.from(atob(encrypted), (character) => character.charCodeAt(0));
822
+ if (combined.length < 28) throw new Error("Invalid AES-GCM session ciphertext");
823
+ const decrypted = await globalThis.crypto.subtle.decrypt(
824
+ { name: "AES-GCM", iv: combined.slice(0, 12) },
825
+ cryptoKey,
826
+ combined.slice(12)
827
+ );
828
+ return new TextDecoder("utf-8", { fatal: true }).decode(decrypted);
829
+ }
830
+ randomBytes(byteLength) {
831
+ if (!globalThis.crypto?.getRandomValues) throw new Error("Secure random entropy is unavailable");
832
+ if (!Number.isInteger(byteLength) || byteLength < 1 || byteLength > 65536) throw new Error("Invalid secure byte length");
833
+ return globalThis.crypto.getRandomValues(new Uint8Array(byteLength));
834
+ }
835
+ async generateKey() {
836
+ return Array.from(this.randomBytes(32), (byte) => byte.toString(16).padStart(2, "0")).join("");
837
+ }
838
+ };
839
+ var DefaultStorage = class {
840
+ prefix;
841
+ constructor(prefix = "partylayer_") {
842
+ this.prefix = prefix;
843
+ }
844
+ async get(key) {
845
+ if (typeof window === "undefined" || !window.localStorage) {
846
+ return null;
847
+ }
848
+ try {
849
+ return localStorage.getItem(`${this.prefix}${key}`);
850
+ } catch {
851
+ return null;
852
+ }
853
+ }
854
+ async set(key, value) {
855
+ if (typeof window === "undefined" || !window.localStorage) {
856
+ return;
857
+ }
858
+ try {
859
+ localStorage.setItem(`${this.prefix}${key}`, value);
860
+ } catch {
861
+ }
862
+ }
863
+ async remove(key) {
864
+ if (typeof window === "undefined" || !window.localStorage) {
865
+ return;
866
+ }
867
+ try {
868
+ localStorage.removeItem(`${this.prefix}${key}`);
869
+ } catch {
870
+ }
871
+ }
872
+ async clear() {
873
+ if (typeof window === "undefined" || !window.localStorage) {
874
+ return;
875
+ }
876
+ try {
877
+ const keys = [];
878
+ for (let i = 0; i < localStorage.length; i++) {
879
+ const key = localStorage.key(i);
880
+ if (key?.startsWith(this.prefix)) {
881
+ keys.push(key);
882
+ }
883
+ }
884
+ for (const key of keys) {
885
+ localStorage.removeItem(key);
886
+ }
887
+ } catch {
888
+ }
889
+ }
890
+ };
891
+ var DefaultTelemetry = class {
892
+ track(_event, _properties) {
893
+ }
894
+ error(_error, _properties) {
895
+ }
896
+ };
897
+ var SDK_VERSION = "0.3.0";
898
+ var MetricsTelemetryAdapter = class {
899
+ config;
900
+ metrics = /* @__PURE__ */ new Map();
901
+ buffer = [];
902
+ flushTimer = null;
903
+ appIdHash = null;
904
+ originHash = null;
905
+ initialized = false;
906
+ constructor(config) {
907
+ this.config = {
908
+ enabled: config.enabled ?? false,
909
+ endpoint: config.endpoint,
910
+ sampleRate: config.sampleRate ?? 1,
911
+ appId: config.appId,
912
+ includeOrigin: config.includeOrigin ?? false,
913
+ batchSize: config.batchSize ?? 10,
914
+ flushIntervalMs: config.flushIntervalMs ?? 3e4,
915
+ network: config.network
916
+ };
917
+ this.initialize();
918
+ }
919
+ /**
920
+ * Initialize async components (hashing)
921
+ */
922
+ async initialize() {
923
+ if (this.initialized) return;
924
+ if (this.config.appId) {
925
+ this.appIdHash = await core.hashForPrivacy(this.config.appId);
926
+ }
927
+ if (this.config.includeOrigin && typeof window !== "undefined") {
928
+ this.originHash = await core.hashForPrivacy(window.location.origin);
929
+ }
930
+ if (this.config.enabled && this.config.flushIntervalMs) {
931
+ this.flushTimer = setInterval(() => {
932
+ this.flush().catch(console.error);
933
+ }, this.config.flushIntervalMs);
934
+ }
935
+ this.initialized = true;
936
+ }
937
+ /**
938
+ * Check if telemetry is enabled
939
+ */
940
+ isEnabled() {
941
+ return this.config.enabled;
942
+ }
943
+ /**
944
+ * Track a named event (TelemetryAdapter interface)
945
+ */
946
+ track(event, properties) {
947
+ if (!this.config.enabled) return;
948
+ const sampleRate = this.config.sampleRate ?? 1;
949
+ if (sampleRate < 1 && Math.random() >= sampleRate) {
950
+ return;
951
+ }
952
+ const current = this.metrics.get(`event_${event}`) ?? 0;
953
+ this.metrics.set(`event_${event}`, current + 1);
954
+ this.bufferEvent({ type: "increment", metric: `event_${event}`, value: 1, timestamp: Date.now() });
955
+ if (properties) {
956
+ for (const [key, value] of Object.entries(properties)) {
957
+ if (typeof value === "number") {
958
+ this.gauge(`${event}_${key}`, value);
959
+ }
960
+ }
961
+ }
962
+ }
963
+ /**
964
+ * Track an error (TelemetryAdapter interface)
965
+ */
966
+ error(error, properties) {
967
+ if (!this.config.enabled) return;
968
+ const code = error.code ?? "UNKNOWN";
969
+ this.increment(`error_${code}`);
970
+ if (properties) {
971
+ this.track("error", properties);
972
+ }
973
+ }
974
+ /**
975
+ * Increment a metric counter
976
+ */
977
+ increment(metric, value = 1) {
978
+ if (!this.config.enabled) return;
979
+ const sampleRate = this.config.sampleRate ?? 1;
980
+ if (sampleRate < 1 && Math.random() >= sampleRate) {
981
+ return;
982
+ }
983
+ const current = this.metrics.get(metric) ?? 0;
984
+ this.metrics.set(metric, current + value);
985
+ this.bufferEvent({
986
+ type: "increment",
987
+ metric,
988
+ value,
989
+ timestamp: Date.now()
990
+ });
991
+ }
992
+ /**
993
+ * Set a gauge metric value
994
+ */
995
+ gauge(metric, value) {
996
+ if (!this.config.enabled) return;
997
+ this.metrics.set(metric, value);
998
+ this.bufferEvent({
999
+ type: "gauge",
1000
+ metric,
1001
+ value,
1002
+ timestamp: Date.now()
1003
+ });
1004
+ }
1005
+ /**
1006
+ * Buffer an event for batched sending
1007
+ */
1008
+ bufferEvent(event) {
1009
+ this.buffer.push(event);
1010
+ if (this.config.batchSize && this.buffer.length >= this.config.batchSize) {
1011
+ this.flush().catch(console.error);
1012
+ }
1013
+ }
1014
+ /**
1015
+ * Flush buffered metrics to backend
1016
+ */
1017
+ async flush() {
1018
+ if (!this.config.enabled) return;
1019
+ if (this.metrics.size === 0) return;
1020
+ if (!this.config.endpoint) {
1021
+ this.buffer = [];
1022
+ return;
1023
+ }
1024
+ if (!this.initialized) {
1025
+ await this.initialize();
1026
+ }
1027
+ try {
1028
+ const payload = core.createMetricsPayload({
1029
+ sdkVersion: SDK_VERSION,
1030
+ network: this.config.network ?? "unknown",
1031
+ metrics: Object.fromEntries(this.metrics),
1032
+ appIdHash: this.appIdHash ?? void 0,
1033
+ originHash: this.originHash ?? void 0
1034
+ });
1035
+ await fetch(this.config.endpoint, {
1036
+ method: "POST",
1037
+ headers: {
1038
+ "Content-Type": "application/json"
1039
+ },
1040
+ body: JSON.stringify(payload)
1041
+ });
1042
+ this.buffer = [];
1043
+ } catch (error) {
1044
+ console.debug("[PartyLayer Telemetry] Flush failed:", error);
1045
+ }
1046
+ }
1047
+ /**
1048
+ * Get current metrics snapshot (for testing/debugging)
1049
+ */
1050
+ getMetrics() {
1051
+ return Object.fromEntries(this.metrics);
1052
+ }
1053
+ /**
1054
+ * Reset all metrics (for testing)
1055
+ */
1056
+ reset() {
1057
+ this.metrics.clear();
1058
+ this.buffer = [];
1059
+ }
1060
+ /**
1061
+ * Destroy the adapter (cleanup timers)
1062
+ */
1063
+ destroy() {
1064
+ if (this.flushTimer) {
1065
+ clearInterval(this.flushTimer);
1066
+ this.flushTimer = null;
1067
+ }
1068
+ this.flush().catch(console.error);
1069
+ }
1070
+ };
1071
+ function isTelemetryConfig(value) {
1072
+ return typeof value === "object" && value !== null && "enabled" in value && typeof value.enabled === "boolean";
1073
+ }
1074
+ function createTelemetryAdapter(config) {
1075
+ if (!config) return void 0;
1076
+ if (isTelemetryConfig(config)) {
1077
+ return new MetricsTelemetryAdapter(config);
1078
+ }
1079
+ return config;
1080
+ }
1081
+
1082
+ // src/event-telemetry.ts
1083
+ function errorProperties(error) {
1084
+ const code = error.code;
1085
+ return code ? { code } : {};
1086
+ }
1087
+ function eventTelemetryProperties(event) {
1088
+ switch (event.type) {
1089
+ case "registry:updated":
1090
+ return { channel: event.channel, version: event.version };
1091
+ case "registry:status":
1092
+ return {
1093
+ source: event.status.source,
1094
+ channel: event.status.channel,
1095
+ verified: event.status.verified,
1096
+ stale: event.status.stale,
1097
+ sequence: event.status.sequence
1098
+ };
1099
+ case "session:connected":
1100
+ return { walletId: event.session.walletId, network: event.session.network };
1101
+ case "session:disconnected":
1102
+ return {};
1103
+ case "session:expired":
1104
+ return {};
1105
+ case "session:networkMismatch":
1106
+ return { expected: event.expected, actual: event.actual, enforced: event.enforced };
1107
+ case "tx:status":
1108
+ return { status: event.status };
1109
+ case "error":
1110
+ return errorProperties(event.error);
1111
+ case "wallets:changed":
1112
+ return { reason: event.reason };
1113
+ default:
1114
+ return {};
1115
+ }
1116
+ }
1117
+
1118
+ // src/logging.ts
1119
+ var LEVEL_PRIORITY = {
1120
+ debug: 10,
1121
+ info: 20,
1122
+ warn: 30,
1123
+ error: 40,
1124
+ silent: 100
1125
+ };
1126
+ function shouldLog(level, threshold) {
1127
+ if (threshold === "silent") return false;
1128
+ return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[threshold];
1129
+ }
1130
+ function newCorrelationId() {
1131
+ const scope = typeof globalThis !== "undefined" ? globalThis : {};
1132
+ if (scope.crypto && typeof scope.crypto.getRandomValues === "function") {
1133
+ const bytes = new Uint8Array(6);
1134
+ scope.crypto.getRandomValues(bytes);
1135
+ let hex = "";
1136
+ for (const byte of bytes) hex += byte.toString(16).padStart(2, "0");
1137
+ return hex;
1138
+ }
1139
+ return Math.random().toString(16).slice(2, 14).padStart(12, "0");
1140
+ }
1141
+ function eventLogLevel(type) {
1142
+ switch (type) {
1143
+ case "error":
1144
+ return "error";
1145
+ case "session:networkMismatch":
1146
+ return "warn";
1147
+ case "session:connected":
1148
+ case "session:disconnected":
1149
+ return "info";
1150
+ case "registry:status":
1151
+ case "registry:updated":
1152
+ case "session:expired":
1153
+ case "tx:status":
1154
+ case "wallets:changed":
1155
+ return "debug";
1156
+ default:
1157
+ return "info";
1158
+ }
1159
+ }
1160
+ var SESSION_ENTROPY_BYTES = 32;
1161
+ function createSecureSessionId(crypto2) {
1162
+ if (typeof globalThis.crypto?.getRandomValues === "function") return core.generateSessionId();
1163
+ if (!crypto2.randomBytes) throw new Error("Secure session entropy requires platform getRandomValues or CryptoAdapter.randomBytes");
1164
+ const encode = (bytes2) => {
1165
+ if (!(bytes2 instanceof Uint8Array) || bytes2.byteLength !== SESSION_ENTROPY_BYTES) {
1166
+ throw new Error("Session entropy must be a Uint8Array of exactly 32 bytes");
1167
+ }
1168
+ return core.toSessionId(`session_${Date.now()}_${Array.from(bytes2, (byte) => byte.toString(16).padStart(2, "0")).join("")}`);
1169
+ };
1170
+ const bytes = crypto2.randomBytes(SESSION_ENTROPY_BYTES);
1171
+ if (bytes instanceof Uint8Array) return encode(bytes);
1172
+ if (bytes && typeof bytes.then === "function") return Promise.resolve(bytes).then(encode);
1173
+ throw new Error("Session entropy must be a Uint8Array of exactly 32 bytes");
1174
+ }
1175
+
1176
+ // src/client-base.ts
1177
+ var SESSION_STORAGE_KEY = "active_session";
1178
+ var WALLETS_CHANGED_DEBOUNCE_MS = 50;
1179
+ function deriveAnnounceConfig(entry) {
1180
+ const cfg = entry.adapter?.config ?? {};
1181
+ const config = {
1182
+ events: entry.capabilities?.events === true,
1183
+ // signMessage is ON unless the entry declares capabilities.signMessage:false,
1184
+ // so a wallet that cannot sign is reported honestly. The default preserves the
1185
+ // baseline for every entry that omits it or sets it true.
1186
+ signMessage: entry.capabilities?.signMessage !== false,
1187
+ restore: cfg.restore === true,
1188
+ ledgerApi: cfg.ledgerApi === true,
1189
+ metadata: cfg.metadata === true,
1190
+ signMessageBase64: cfg.signMessageBase64 === true
1191
+ };
1192
+ const sm = cfg.staticMetadata;
1193
+ if (sm && typeof sm === "object") {
1194
+ const out = {};
1195
+ for (const [k, v] of Object.entries(sm)) {
1196
+ if (typeof v === "string") out[k] = v;
1197
+ }
1198
+ if (Object.keys(out).length > 0) config.staticMetadata = out;
1199
+ }
1200
+ return config;
1201
+ }
1202
+ function matchKnownByIdentity(providerId, base) {
1203
+ return base.find((w) => {
1204
+ const k = w.installHints?.injectedKey;
1205
+ return providerId === String(w.walletId) || !!k && (providerId === k || providerId.startsWith(`${k}.`));
1206
+ });
1207
+ }
1208
+ var DEFAULT_CONNECT_TIMEOUT_MS = 12e4;
1209
+ var PartyLayerClientBase = class {
1210
+ constructor(config, runtime = {}) {
1211
+ this.runtime = runtime;
1212
+ this.config = config;
1213
+ if (config.app.origin) {
1214
+ this.origin = config.app.origin;
1215
+ } else if (typeof window !== "undefined") {
1216
+ this.origin = window.location.origin;
1217
+ } else {
1218
+ this.origin = "unknown";
1219
+ }
1220
+ this.logger = config.logger || new DefaultLogger();
1221
+ this.logLevel = config.logLevel ?? "info";
1222
+ this.crypto = config.crypto || new DefaultCrypto();
1223
+ this.storage = config.storage || new DefaultStorage();
1224
+ if (typeof window !== "undefined" && runtime.createOwner) {
1225
+ this.nativeOwner = runtime.createOwner((id, identity2) => this.onNativeIdentityChanged(id, identity2));
1226
+ }
1227
+ const telemetryAdapter = createTelemetryAdapter(config.telemetry);
1228
+ this.telemetry = telemetryAdapter || new DefaultTelemetry();
1229
+ const defaults = config.adapters ?? runtime.getBuiltinAdapters?.() ?? [];
1230
+ const adaptersToRegister = [...defaults, ...config.additionalAdapters ?? []];
1231
+ for (const adapterOrClass of adaptersToRegister) {
1232
+ let adapter;
1233
+ if (typeof adapterOrClass === "function") {
1234
+ adapter = new adapterOrClass();
1235
+ } else if (core.isOfficialAdapterFactory(adapterOrClass)) {
1236
+ adapter = new GenericDiscoveryAdapter({ factory: adapterOrClass });
1237
+ } else if (core.isOfficialProviderAdapter(adapterOrClass)) {
1238
+ adapter = new GenericDiscoveryAdapter({ official: adapterOrClass });
1239
+ } else {
1240
+ adapter = adapterOrClass;
1241
+ }
1242
+ this.registerAdapter(adapter);
1243
+ this.log("debug", "adapter:registered", "Registered wallet adapter", {
1244
+ walletId: adapter.walletId,
1245
+ name: adapter.name,
1246
+ capabilities: adapter.getCapabilities()
1247
+ });
1248
+ }
1249
+ this.registryClient = new registryClient.RegistryClient({
1250
+ registryUrl: config.registryUrl || DEFAULT_REGISTRY_URL,
1251
+ channel: config.channel || "stable",
1252
+ registryPublicKeys: config.registryPublicKeys,
1253
+ storage: this.storage
1254
+ });
1255
+ this.updateRegistryStatus();
1256
+ if (!config.deferInitialization) this.initialize();
1257
+ }
1258
+ config;
1259
+ adapters = /* @__PURE__ */ new Map();
1260
+ destroyed = false;
1261
+ initialized = false;
1262
+ defaultLoads = /* @__PURE__ */ new Map();
1263
+ registryDefaultIds = /* @__PURE__ */ new Set();
1264
+ /**
1265
+ * Pre-resolved connect plans for popup/remote (GenericDiscoveryAdapter)
1266
+ * wallets, warmed on `listWallets()` (which the modal calls on open) so a
1267
+ * subsequent click can connect gesture-synchronously. Consumed (deleted) on
1268
+ * use and cleared on disconnect; a cold miss falls back to the normal path.
1269
+ */
1270
+ warmPlans = /* @__PURE__ */ new Map();
1271
+ eventHandlers = /* @__PURE__ */ new Map();
1272
+ activeSession = null;
1273
+ sessionRevision = 0;
1274
+ connectionAttempt = 0;
1275
+ restoreTask = null;
1276
+ restorationBlocked = false;
1277
+ sessionStorageQueue = Promise.resolve();
1278
+ /**
1279
+ * True when `activeSession` was revived AS-IS (no live `status()` probe) because
1280
+ * its adapter wasn't registered yet at restore time (the lazy configured-announce
1281
+ * case). Cleared once a live probe validates it (or on fresh connect). When set,
1282
+ * `aggregateAnnouncedWallets` re-probes the session the moment that adapter is born.
1283
+ */
1284
+ activeSessionNeedsProbe = false;
1285
+ registryClient;
1286
+ // Expose for React hooks
1287
+ logger;
1288
+ /** Configured log verbosity; filtering happens centrally in {@link log}. */
1289
+ logLevel;
1290
+ crypto;
1291
+ storage;
1292
+ telemetry;
1293
+ /** Cached announce-discovery picker entries (one-shot; cleared by refreshDiscovery). */
1294
+ announceEntriesCache = null;
1295
+ // Persistent announce accumulator (option 1): one window subscription mounted
1296
+ // at construction so LATE / inject-time `canton:announceProvider` replies are
1297
+ // captured (not just a one-shot window). Read by aggregateAnnouncedWallets;
1298
+ // torn down in destroy(). Empty → listWallets() output is byte-identical.
1299
+ announceRegistry = /* @__PURE__ */ new Map();
1300
+ announceChannels = /* @__PURE__ */ new Map();
1301
+ announceUnsubscribe = null;
1302
+ /** Pending debounced `wallets:changed` emit (coalesces an announce burst). */
1303
+ walletsChangedTimer = null;
1304
+ origin;
1305
+ nativeOwner;
1306
+ sessionProvider;
1307
+ /** Start browser discovery/restoration once; safe for framework effect replay. */
1308
+ initialize() {
1309
+ if (this.initialized || this.destroyed) return;
1310
+ this.initialized = true;
1311
+ if (this.announceEnabled) {
1312
+ this.announceUnsubscribe = provider.subscribeAnnouncedProviders(
1313
+ (p) => this.onAnnounceAccumulated(p),
1314
+ { createProvider: (a) => this.announceChannel(a.target ?? a.id) }
1315
+ );
1316
+ }
1317
+ this.restoreSession().catch((err) => {
1318
+ this.emit("error", {
1319
+ type: "error",
1320
+ error: core.mapUnknownErrorToPartyLayerError(err, {
1321
+ phase: "restore"
1322
+ })
1323
+ });
1324
+ });
1325
+ }
1326
+ announceChannel(target) {
1327
+ if (this.destroyed) throw new Error("PartyLayer client was destroyed");
1328
+ let provider$1 = this.announceChannels.get(target);
1329
+ if (!provider$1) {
1330
+ provider$1 = provider.createExtensionChannelProvider({ target });
1331
+ this.announceChannels.set(target, provider$1);
1332
+ }
1333
+ return provider$1;
1334
+ }
1335
+ /**
1336
+ * Register a wallet adapter
1337
+ *
1338
+ * @internal
1339
+ * This is used internally by the SDK to register adapters.
1340
+ * In production, adapters would be auto-registered via registry.
1341
+ */
1342
+ registerAdapter(adapter) {
1343
+ const boundOwner = nativeOwnerBindings.get(adapter);
1344
+ if (this.nativeOwner && boundOwner && boundOwner !== this.nativeOwner) {
1345
+ adapter = nativeAdapterCopies.get(adapter)();
1346
+ }
1347
+ this.adapters.set(adapter.walletId, adapter);
1348
+ if (this.nativeOwner && (adapter instanceof GenericDiscoveryAdapter || adapter instanceof GenericAnnounceAdapter)) {
1349
+ nativeOwnerBindings.set(adapter, this.nativeOwner);
1350
+ }
1351
+ }
1352
+ onNativeIdentityChanged(id, identity2) {
1353
+ const active = this.activeSession;
1354
+ if (this.destroyed || !active || String(active.walletId) !== id) return;
1355
+ ++this.sessionRevision;
1356
+ if (!identity2) {
1357
+ this.restorationBlocked = true;
1358
+ this.warmPlans.clear();
1359
+ this.activeSession = null;
1360
+ void this.removeSession(active.sessionId);
1361
+ this.emit("session:disconnected", { type: "session:disconnected", sessionId: active.sessionId });
1362
+ return;
1363
+ }
1364
+ const session = { ...active, partyId: identity2.account.partyId, network: identity2.network };
1365
+ const mismatch = this.networkMismatch(session);
1366
+ if (mismatch) session.networkMismatch = mismatch;
1367
+ else delete session.networkMismatch;
1368
+ this.activeSession = session;
1369
+ void this.persistSession(session);
1370
+ this.emit("session:connected", { type: "session:connected", session });
1371
+ }
1372
+ /**
1373
+ * Look up a registered adapter by wallet id.
1374
+ *
1375
+ * Returns the adapter instance when one is registered for the given
1376
+ * `walletId`, or `undefined` otherwise. Intended for UI integrations
1377
+ * that need to call `adapter.detectInstalled()` directly to render a
1378
+ * per-wallet readiness indicator (instead of duplicating
1379
+ * transport-specific install detection logic in the picker). The
1380
+ * returned adapter is the same instance used internally for connect /
1381
+ * sign / submit flows; do not mutate it.
1382
+ *
1383
+ * Accepts both raw string ids and the branded `WalletId` form so
1384
+ * consumers can pass `walletInfo.walletId` or a string literal
1385
+ * interchangeably.
1386
+ */
1387
+ getAdapter(walletId) {
1388
+ return this.adapters.get(walletId);
1389
+ }
1390
+ /**
1391
+ * List available wallets
1392
+ */
1393
+ async listWallets(filter) {
1394
+ this.initialize();
1395
+ let registryWallets;
1396
+ try {
1397
+ registryWallets = await this.registryClient.getWallets();
1398
+ this.updateRegistryStatus();
1399
+ } catch (err) {
1400
+ this.updateRegistryStatus();
1401
+ this.log("warn", "registry:fetch_failed", "Registry fetch failed, using registered adapters only", {
1402
+ error: err instanceof Error ? err.message : String(err)
1403
+ });
1404
+ registryWallets = [];
1405
+ }
1406
+ await this.ensureDefaultWallets();
1407
+ const registryIds = new Set(registryWallets.map((w) => String(w.walletId)));
1408
+ for (const [, adapter] of this.adapters) {
1409
+ if (registryIds.has(String(adapter.walletId)) || this.registryDefaultIds.has(adapter.walletId)) continue;
1410
+ registryWallets.push({
1411
+ walletId: adapter.walletId,
1412
+ name: adapter.name,
1413
+ website: "",
1414
+ icons: {},
1415
+ capabilities: adapter.getCapabilities(),
1416
+ adapter: { packageName: "builtin", versionRange: "*" },
1417
+ docs: [],
1418
+ networks: [this.config.network || "devnet"],
1419
+ channel: this.config.channel || "stable"
1420
+ });
1421
+ }
1422
+ registryWallets = await this.gateUnconnectableEntries(registryWallets);
1423
+ registryWallets = await this.aggregateAnnouncedWallets(registryWallets);
1424
+ registryWallets = registryWallets.map((wallet) => {
1425
+ const adapter = this.adapters.get(wallet.walletId);
1426
+ return adapter ? { ...wallet, capabilities: adapter.getCapabilities() } : wallet;
1427
+ }).filter(
1428
+ (wallet) => wallet.networks.includes(this.config.network) && (filter?.includeExperimental || wallet.channel === (this.config.channel || "stable")) && (!filter?.requiredCapabilities || filter.requiredCapabilities.every((cap) => wallet.capabilities.includes(cap)))
1429
+ );
1430
+ await this.warmDiscoveryPlans(registryWallets);
1431
+ return registryWallets;
1432
+ }
1433
+ /** Resolve only reviewed default SDKs present in the active registry. */
1434
+ async ensureDefaultWallets() {
1435
+ if (this.config.adapters !== void 0 || !this.runtime.loadDefaultWallet) return;
1436
+ let registry;
1437
+ try {
1438
+ registry = await this.registryClient.getRegistry();
1439
+ } catch {
1440
+ return;
1441
+ }
1442
+ await Promise.all(registry.wallets.map(async (entry) => {
1443
+ const id = core.toWalletId(entry.id);
1444
+ if (this.adapters.has(id) || !entry.supportedNetworks.includes(this.config.network) || entry.adapter?.transport === "discovery-adapter" && !entry.adapter.networkHosts?.[this.config.network]) return;
1445
+ let pending = this.defaultLoads.get(entry.id);
1446
+ if (!pending) {
1447
+ pending = (async () => {
1448
+ try {
1449
+ const entryAdapter = await this.runtime.loadDefaultWallet(entry.id, this.config, this.origin);
1450
+ if (!entryAdapter || this.destroyed) return;
1451
+ const adapter = core.isOfficialAdapterFactory(entryAdapter) ? new GenericDiscoveryAdapter({
1452
+ factory: entryAdapter,
1453
+ name: entry.name,
1454
+ networkHosts: entry.adapter?.networkHosts,
1455
+ capabilities: entry.capabilities
1456
+ }) : entryAdapter;
1457
+ if (typeof window !== "undefined" && adapter instanceof GenericDiscoveryAdapter) {
1458
+ adapter.resolveOfficial(this.config.network);
1459
+ }
1460
+ this.registerAdapter(adapter);
1461
+ this.registryDefaultIds.add(id);
1462
+ } catch (error) {
1463
+ this.defaultLoads.delete(entry.id);
1464
+ this.log("warn", "wallet:load_failed", "Official wallet SDK could not load", {
1465
+ walletId: entry.id,
1466
+ error: String(error)
1467
+ });
1468
+ }
1469
+ })();
1470
+ this.defaultLoads.set(entry.id, pending);
1471
+ }
1472
+ await pending;
1473
+ }));
1474
+ }
1475
+ /**
1476
+ * Hide registry entries whose wallet needs an app-registered adapter that is
1477
+ * NOT registered. This is the library default (RainbowKit-style): never show a
1478
+ * wallet the app cannot actually connect.
1479
+ *
1480
+ * A wallet is connectable with NO app adapter only when it is driven by the
1481
+ * generic announce path (`adapter.transport: 'announce'`, e.g. Console, Send):
1482
+ * there the SDK builds a generic announce adapter from the registry entry on
1483
+ * demand, so installing the extension is enough and the entry stays visible.
1484
+ * Every other transport can only connect through an adapter the app registered:
1485
+ * a `discovery-adapter` popup/remote wallet whose official ProviderAdapter
1486
+ * the app supplies (bridged under `toWalletId(providerId)`), or a wallet that
1487
+ * ships a PartyLayer adapter package (Loop, Cantor8, Nightly, Bron,
1488
+ * WalletConnect). Without that adapter, clicking the entry can only fail
1489
+ * (connect throws), so it surfaces only when the adapter is present.
1490
+ *
1491
+ * The decision reads each entry's DECLARED transport, never a hardcoded wallet
1492
+ * list. No-op when the registry is unavailable (the list is already
1493
+ * adapters-only) or every non-announce entry is registered.
1494
+ */
1495
+ async gateUnconnectableEntries(wallets) {
1496
+ if (!this.runtime.browserDiscovery) return wallets.filter((wallet) => this.adapters.has(wallet.walletId));
1497
+ let hidden = null;
1498
+ const announceCapabilities = /* @__PURE__ */ new Map();
1499
+ try {
1500
+ const registry = await this.registryClient.getRegistry();
1501
+ for (const entry of registry.wallets) {
1502
+ if (entry.adapter?.transport === "announce" && this.runtime.browserDiscovery) {
1503
+ announceCapabilities.set(entry.id, getAnnounceCapabilities(deriveAnnounceConfig(entry)));
1504
+ continue;
1505
+ }
1506
+ const walletId = core.toWalletId(entry.id);
1507
+ if (!this.adapters.has(walletId)) {
1508
+ (hidden ??= /* @__PURE__ */ new Set()).add(String(walletId));
1509
+ }
1510
+ }
1511
+ } catch {
1512
+ return wallets;
1513
+ }
1514
+ return wallets.filter((w) => !hidden?.has(String(w.walletId))).map((w) => {
1515
+ const capabilities = announceCapabilities.get(String(w.walletId));
1516
+ return capabilities ? { ...w, capabilities } : w;
1517
+ });
1518
+ }
1519
+ /**
1520
+ * If `walletId` maps to a registry entry with `transport: 'discovery-adapter'`,
1521
+ * return the bits to build an actionable "register its adapter" error; else
1522
+ * null (truly-unknown or non-discovery → plain WalletNotFoundError). Reads the
1523
+ * UNGATED registry (SWR-cached); registry-unavailable → null (safe fallback).
1524
+ */
1525
+ async unregisteredDiscoveryInfo(walletId) {
1526
+ try {
1527
+ const registry = await this.registryClient.getRegistry();
1528
+ const entry = registry.wallets.find((w) => core.toWalletId(w.id) === walletId);
1529
+ if (entry?.adapter?.transport !== "discovery-adapter") return null;
1530
+ const pid = entry.adapter?.config?.providerId;
1531
+ return {
1532
+ name: entry.name,
1533
+ providerId: typeof pid === "string" ? pid : entry.id,
1534
+ adapterPackage: typeof entry.adapter?.type === "string" ? entry.adapter.type : void 0
1535
+ };
1536
+ } catch {
1537
+ return null;
1538
+ }
1539
+ }
1540
+ /**
1541
+ * Whether announce discovery is active: explicit `discovery.announce`, else
1542
+ * ON in the browser and OFF under SSR (no `window`). Canonical: provider.md.
1543
+ */
1544
+ get announceEnabled() {
1545
+ if (typeof window === "undefined" || !this.runtime.browserDiscovery) return false;
1546
+ return this.config.discovery?.announce ?? true;
1547
+ }
1548
+ /**
1549
+ * Clear the cached announce round-trip so the next `listWallets()` re-runs the
1550
+ * `canton:requestProvider` handshake (e.g. after a wallet is installed).
1551
+ */
1552
+ refreshDiscovery() {
1553
+ this.announceEntriesCache = null;
1554
+ }
1555
+ /**
1556
+ * Persistent-accumulator callback (mounted at construction). On each newly
1557
+ * announced provider:
1558
+ * 1. record it in the live `announceRegistry` (unchanged);
1559
+ * 2. invalidate the one-shot `announceEntriesCache` — the SAME invalidation
1560
+ * as {@link refreshDiscovery}, so the next `listWallets()` re-aggregates
1561
+ * and surfaces the wallet. This does NOT touch `warmPlans` (those hold
1562
+ * only GenericDiscoveryAdapter popup plans — a disjoint set);
1563
+ * 3. emit a DEBOUNCED `wallets:changed` signal so a reactive consumer (e.g.
1564
+ * the React provider) re-lists. The debounce coalesces a burst — and the
1565
+ * construction-time reply storm — into one emit (no re-discovery storm).
1566
+ *
1567
+ * Byte-identical idle: with zero announces this never fires — no invalidation,
1568
+ * no emit, no re-list.
1569
+ */
1570
+ onAnnounceAccumulated(p) {
1571
+ this.announceRegistry.set(p.id, p);
1572
+ this.announceEntriesCache = null;
1573
+ if (this.walletsChangedTimer !== null) return;
1574
+ this.walletsChangedTimer = setTimeout(() => {
1575
+ this.walletsChangedTimer = null;
1576
+ this.emit("wallets:changed", { type: "wallets:changed", reason: "announced" });
1577
+ }, WALLETS_CHANGED_DEBOUNCE_MS);
1578
+ }
1579
+ /**
1580
+ * Aggregate `canton:announceProvider` wallets into the picker list (A2).
1581
+ *
1582
+ * One-shot cached per client (refresh via {@link refreshDiscovery}); SSR-skipped.
1583
+ * For each discovered provider (announce ∪ `window.canton` scan, deduped):
1584
+ * - if its id matches a known wallet's `providerDetection` (provider.id) it
1585
+ * IS that wallet — no new entry (identity bridge: Console's `lpnf…` → the
1586
+ * `console` entry, Send's `ldmo…` → the `send` entry);
1587
+ * - otherwise it is surfaced as a dynamic `browser:ext:<id>` entry routed to
1588
+ * its own extension `target`, with a {@link GenericAnnounceAdapter}
1589
+ * registered so a click connects through that target ONLY (no shared slot).
1590
+ * With zero announcers this returns `base` unchanged.
1591
+ */
1592
+ async aggregateAnnouncedWallets(base) {
1593
+ if (!this.announceEnabled) return base;
1594
+ if (this.announceEntriesCache === null) {
1595
+ try {
1596
+ let injectionPaths;
1597
+ try {
1598
+ const registry = await this.registryClient.getRegistry();
1599
+ const props = registry.wallets.filter((w) => w.adapter?.transport === "announce").map((w) => w.installation?.windowProperty).filter((p) => typeof p === "string" && p.length > 0);
1600
+ if (props.length > 0) injectionPaths = [...new Set(props)];
1601
+ } catch {
1602
+ }
1603
+ const snapshot = await provider.discoverProviders({
1604
+ timeoutMs: this.config.discovery?.announceTimeoutMs,
1605
+ injectionPaths,
1606
+ // Working provider over the announce target channel; G4 (provider.md):
1607
+ // target defaults to id when omitted — never a shared slot.
1608
+ createProvider: (a) => this.announceChannel(a.target ?? a.id)
1609
+ });
1610
+ const byId = /* @__PURE__ */ new Map();
1611
+ for (const d of snapshot) byId.set(d.id, d);
1612
+ for (const d of this.announceRegistry.values())
1613
+ if (!byId.has(d.id)) byId.set(d.id, d);
1614
+ const discovered = [...byId.values()];
1615
+ const entries = [];
1616
+ for (const d of discovered) {
1617
+ if (d.identityResolved === false) continue;
1618
+ const known = core.findMatchingWalletInfo(
1619
+ { provider: { id: d.id } },
1620
+ base
1621
+ ) ?? matchKnownByIdentity(d.id, base);
1622
+ if (known) {
1623
+ if (this.adapters.has(known.walletId)) continue;
1624
+ try {
1625
+ const entry = await this.registryClient.getWalletEntry(String(known.walletId));
1626
+ if (entry?.adapter?.transport === "announce") {
1627
+ const configured = new GenericAnnounceAdapter({
1628
+ announceId: d.id,
1629
+ walletId: known.walletId,
1630
+ name: d.name ?? known.name,
1631
+ icon: d.icon,
1632
+ provider: d.provider,
1633
+ config: deriveAnnounceConfig(entry)
1634
+ });
1635
+ this.registerAdapter(configured);
1636
+ const active = this.activeSession;
1637
+ if (active && this.activeSessionNeedsProbe && active.walletId === configured.walletId && configured.restore) {
1638
+ const revision = this.sessionRevision;
1639
+ try {
1640
+ const reprobed = await configured.restore(this.createAdapterContext(), {
1641
+ ...active,
1642
+ encrypted: ""
1643
+ });
1644
+ if (this.destroyed || revision !== this.sessionRevision || this.activeSession !== active) continue;
1645
+ if (reprobed) {
1646
+ this.activeSession = reprobed;
1647
+ this.activeSessionNeedsProbe = false;
1648
+ await this.persistSession(reprobed);
1649
+ if (this.destroyed || revision !== this.sessionRevision || this.activeSession !== reprobed) continue;
1650
+ this.emit("session:connected", { type: "session:connected", session: reprobed });
1651
+ } else {
1652
+ await this.removeSession(active.sessionId);
1653
+ if (this.destroyed || revision !== this.sessionRevision || this.activeSession !== active) continue;
1654
+ this.activeSession = null;
1655
+ this.activeSessionNeedsProbe = false;
1656
+ this.emit("session:expired", { type: "session:expired", sessionId: active.sessionId });
1657
+ }
1658
+ } catch (err) {
1659
+ this.log("warn", "session:reprobe_failed", "Restore re-probe failed; leaving session as-is", {
1660
+ error: err instanceof Error ? err.message : String(err)
1661
+ });
1662
+ }
1663
+ }
1664
+ }
1665
+ } catch {
1666
+ }
1667
+ continue;
1668
+ }
1669
+ const adapter = new GenericAnnounceAdapter({
1670
+ announceId: d.id,
1671
+ name: d.name,
1672
+ icon: d.icon,
1673
+ provider: d.provider
1674
+ });
1675
+ this.registerAdapter(adapter);
1676
+ entries.push({
1677
+ walletId: adapter.walletId,
1678
+ name: adapter.name,
1679
+ website: "",
1680
+ icons: d.icon ? { sm: d.icon, md: d.icon, lg: d.icon } : {},
1681
+ capabilities: adapter.getCapabilities(),
1682
+ adapter: { packageName: "announced", versionRange: "*" },
1683
+ docs: [],
1684
+ networks: [this.config.network || "devnet"],
1685
+ channel: "stable"
1686
+ });
1687
+ }
1688
+ this.announceEntriesCache = entries;
1689
+ } catch {
1690
+ this.announceEntriesCache = [];
1691
+ }
1692
+ }
1693
+ if (this.announceEntriesCache.length === 0) return base;
1694
+ const ids = new Set(base.map((w) => String(w.walletId)));
1695
+ return [
1696
+ ...base,
1697
+ ...this.announceEntriesCache.filter((w) => !ids.has(String(w.walletId)))
1698
+ ];
1699
+ }
1700
+ /** Active network-enforcement policy (default 'guard'). */
1701
+ get enforcement() {
1702
+ return this.config.networkEnforcement ?? "guard";
1703
+ }
1704
+ /**
1705
+ * Detect a confident network mismatch between the dApp's configured network
1706
+ * and the session's (wallet-reported) network. Returns null when they match
1707
+ * or the comparison isn't confident (conservative — never a false positive).
1708
+ */
1709
+ networkMismatch(session) {
1710
+ return core.detectNetworkMismatch(this.config.network, session.network);
1711
+ }
1712
+ /**
1713
+ * Guard a transaction-class operation: throw `NetworkMismatchError` when the
1714
+ * session is on the wrong network AND the policy enforces it ('guard' |
1715
+ * 'strict'). Also protects restored sessions and mid-session network switches.
1716
+ */
1717
+ assertNetworkOk(session) {
1718
+ const mm = this.networkMismatch(session);
1719
+ if (mm && this.enforcement !== "off") {
1720
+ throw new core.NetworkMismatchError(mm.expected, mm.actual);
1721
+ }
1722
+ }
1723
+ /**
1724
+ * Connect to a wallet
1725
+ */
1726
+ async connect(options) {
1727
+ this.initialize();
1728
+ this.nativeOwner?.assertAvailable();
1729
+ this.restorationBlocked = true;
1730
+ const attempt = ++this.connectionAttempt;
1731
+ ++this.sessionRevision;
1732
+ this.telemetry?.increment?.(core.METRICS.WALLET_CONNECT_ATTEMPTS);
1733
+ const correlationId = newCorrelationId();
1734
+ this.log("debug", "connect:start", "connect", {}, correlationId);
1735
+ try {
1736
+ const fast = this.tryFastConnect(options, correlationId, attempt);
1737
+ if (fast) return await fast;
1738
+ const plan = await this.resolveConnectPlan(options);
1739
+ return await this.completeConnect(plan, options, correlationId, attempt);
1740
+ } catch (err) {
1741
+ this.warmPlans.clear();
1742
+ const timeoutMs = options?.timeoutMs || DEFAULT_CONNECT_TIMEOUT_MS;
1743
+ const error = core.mapUnknownErrorToPartyLayerError(err, {
1744
+ phase: "connect",
1745
+ walletId: options?.walletId ? String(options.walletId) : void 0,
1746
+ timeoutMs
1747
+ });
1748
+ this.emit("error", { type: "error", error }, correlationId);
1749
+ throw error;
1750
+ }
1751
+ }
1752
+ /**
1753
+ * Pre-resolve everything `adapter.connect()` needs WITHOUT calling it: wallet
1754
+ * selection, origin-allowlist + capability + install guards, and the adapter
1755
+ * context. `prefetchedWallets` (passed during warm-up from `listWallets`)
1756
+ * avoids a recursive `listWallets()` call.
1757
+ */
1758
+ async resolveConnectPlan(options, prefetchedWallets) {
1759
+ const wallets = prefetchedWallets ?? await this.listWallets({
1760
+ requiredCapabilities: options?.requiredCapabilities,
1761
+ includeExperimental: true
1762
+ });
1763
+ let availableWallets = wallets;
1764
+ if (options?.allowWallets) {
1765
+ availableWallets = wallets.filter(
1766
+ (w) => options.allowWallets.includes(w.walletId)
1767
+ );
1768
+ }
1769
+ let selectedWallet;
1770
+ let isNativeWallet = false;
1771
+ if (options?.walletId) {
1772
+ const found = availableWallets.find(
1773
+ (w) => w.walletId === options.walletId
1774
+ );
1775
+ if (found) {
1776
+ selectedWallet = found;
1777
+ } else {
1778
+ const nativeAdapter = this.adapters.get(options.walletId);
1779
+ if (nativeAdapter) {
1780
+ const entry = await this.registryClient.getWalletEntry(String(options.walletId)).catch(() => null);
1781
+ if (entry?.supportedNetworks?.length && !entry.supportedNetworks.includes(this.config.network)) {
1782
+ throw new core.WalletNotFoundError(`${String(options.walletId)} is unavailable on ${this.config.network}`);
1783
+ }
1784
+ isNativeWallet = true;
1785
+ selectedWallet = {
1786
+ walletId: options.walletId,
1787
+ name: nativeAdapter.name,
1788
+ website: "",
1789
+ icons: {},
1790
+ capabilities: nativeAdapter.getCapabilities(),
1791
+ adapter: { packageName: "native-cip0103", versionRange: "*" },
1792
+ docs: [],
1793
+ networks: [this.config.network],
1794
+ channel: "stable",
1795
+ metadata: { source: "native-cip0103" }
1796
+ };
1797
+ } else {
1798
+ const info = await this.unregisteredDiscoveryInfo(options.walletId);
1799
+ if (info) {
1800
+ throw new core.AdapterNotRegisteredError(String(options.walletId), info);
1801
+ }
1802
+ throw new core.WalletNotFoundError(String(options.walletId));
1803
+ }
1804
+ }
1805
+ } else if (availableWallets.length === 0) {
1806
+ throw new core.WalletNotFoundError(this.runtime.noWalletsMessage ?? "No wallets available");
1807
+ } else {
1808
+ selectedWallet = availableWallets[0];
1809
+ }
1810
+ const adapter = this.adapters.get(selectedWallet.walletId);
1811
+ if (!adapter) {
1812
+ throw new core.WalletNotFoundError(String(selectedWallet.walletId));
1813
+ }
1814
+ if (!isNativeWallet) {
1815
+ try {
1816
+ const walletEntry = await this.registryClient.getWalletEntry(String(selectedWallet.walletId));
1817
+ if (walletEntry.originAllowlist && walletEntry.originAllowlist.length > 0) {
1818
+ if (!walletEntry.originAllowlist.includes(this.origin)) {
1819
+ throw new core.OriginNotAllowedError(
1820
+ this.origin,
1821
+ walletEntry.originAllowlist
1822
+ );
1823
+ }
1824
+ }
1825
+ } catch (e) {
1826
+ if (!(e instanceof core.WalletNotFoundError)) {
1827
+ throw e;
1828
+ }
1829
+ }
1830
+ }
1831
+ if (options?.requiredCapabilities) {
1832
+ core.capabilityGuard(adapter, options.requiredCapabilities);
1833
+ }
1834
+ await core.installGuard(adapter);
1835
+ const ctx = this.createAdapterContext();
1836
+ if (adapter instanceof GenericDiscoveryAdapter && adapter.usesFactory()) {
1837
+ let networkHosts = {};
1838
+ try {
1839
+ const entry = await this.registryClient.getWalletEntry(
1840
+ String(selectedWallet.walletId)
1841
+ );
1842
+ networkHosts = entry.adapter?.networkHosts ?? {};
1843
+ } catch {
1844
+ }
1845
+ adapter.setNetworkHosts(networkHosts);
1846
+ adapter.resolveOfficial(ctx.network);
1847
+ }
1848
+ if (adapter instanceof GenericDiscoveryAdapter || adapter instanceof GenericAnnounceAdapter) {
1849
+ await adapter.prepareNativeConnection(ctx.network);
1850
+ }
1851
+ return { selectedWallet, adapter, ctx, isNativeWallet };
1852
+ }
1853
+ /**
1854
+ * Generate secure entropy, invoke `adapter.connect()` without awaiting the
1855
+ * platform RNG path, then build / persist / emit the session. Separated from plan resolution so the
1856
+ * popup-safe fast-path can call it gesture-synchronously.
1857
+ */
1858
+ async completeConnect(plan, options, correlationId = newCorrelationId(), attempt) {
1859
+ this.nativeOwner?.assertAvailable();
1860
+ this.restorationBlocked = true;
1861
+ const currentAttempt = attempt ?? ++this.connectionAttempt;
1862
+ if (attempt === void 0) ++this.sessionRevision;
1863
+ if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
1864
+ const { selectedWallet, adapter, ctx } = plan;
1865
+ const entropy = createSecureSessionId(this.crypto);
1866
+ const sessionId = typeof entropy === "string" ? entropy : await entropy;
1867
+ if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
1868
+ if (!nativeOwnerBindings.has(adapter) && this.nativeOwner?.getSession()) this.nativeOwner.release();
1869
+ const timeoutMs = options?.timeoutMs || DEFAULT_CONNECT_TIMEOUT_MS;
1870
+ const abort = new AbortController();
1871
+ const connectPromise = adapter.connect(ctx, {
1872
+ timeoutMs,
1873
+ signal: abort.signal,
1874
+ partyId: void 0,
1875
+ preferInstalled: options?.preferInstalled,
1876
+ onDisplayUri: options?.onDisplayUri
1877
+ });
1878
+ let timeoutHandle;
1879
+ const timeoutPromise = new Promise((_, reject) => {
1880
+ timeoutHandle = setTimeout(() => {
1881
+ abort.abort();
1882
+ reject(new Error(`Connection timed out after ${timeoutMs}ms - user did not complete wallet connection`));
1883
+ }, timeoutMs);
1884
+ });
1885
+ let result;
1886
+ try {
1887
+ result = await Promise.race([connectPromise, timeoutPromise]);
1888
+ } finally {
1889
+ if (timeoutHandle !== void 0) clearTimeout(timeoutHandle);
1890
+ }
1891
+ if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
1892
+ const session = {
1893
+ sessionId,
1894
+ walletId: selectedWallet.walletId,
1895
+ partyId: result.partyId,
1896
+ // The wallet's reported network (adapters that read the live wallet —
1897
+ // e.g. Console via getActiveNetwork — surface the actual network here;
1898
+ // echo-only adapters report ctx.network === config.network). Used for
1899
+ // mismatch detection; falls back to the configured network.
1900
+ network: result.session.network ?? this.config.network,
1901
+ createdAt: Date.now(),
1902
+ expiresAt: result.session.expiresAt,
1903
+ origin: this.origin,
1904
+ capabilitiesSnapshot: result.capabilities,
1905
+ metadata: result.session.metadata,
1906
+ // Fund-safety passthrough: the wallet's payout-preapproval signal, if the
1907
+ // adapter surfaced it at connect. Optional; absent when not reported.
1908
+ hasPreapproval: result.session.hasPreapproval,
1909
+ utilityPreapprovalAdmins: result.session.utilityPreapprovalAdmins
1910
+ };
1911
+ const mismatch = this.networkMismatch(session);
1912
+ if (mismatch) {
1913
+ session.networkMismatch = mismatch;
1914
+ this.emit("session:networkMismatch", {
1915
+ type: "session:networkMismatch",
1916
+ sessionId: session.sessionId,
1917
+ expected: mismatch.expected,
1918
+ actual: mismatch.actual,
1919
+ enforced: this.enforcement !== "off"
1920
+ }, correlationId);
1921
+ if (this.enforcement === "strict") {
1922
+ if (nativeOwnerBindings.has(adapter)) await this.nativeOwner?.disconnect();
1923
+ throw new core.NetworkMismatchError(mismatch.expected, mismatch.actual);
1924
+ }
1925
+ }
1926
+ ++this.sessionRevision;
1927
+ this.activeSession = session;
1928
+ this.restorationBlocked = false;
1929
+ this.activeSessionNeedsProbe = false;
1930
+ await this.persistSession(session);
1931
+ if (this.destroyed || currentAttempt !== this.connectionAttempt || this.activeSession !== session) {
1932
+ throw new Error("Wallet connection was superseded");
1933
+ }
1934
+ this.updateRegistryStatus();
1935
+ this.telemetry?.increment?.(core.METRICS.WALLET_CONNECT_SUCCESS);
1936
+ this.telemetry?.increment?.(core.METRICS.SESSIONS_CREATED);
1937
+ this.emit("session:connected", {
1938
+ type: "session:connected",
1939
+ session
1940
+ }, correlationId);
1941
+ return session;
1942
+ }
1943
+ /**
1944
+ * PUBLIC popup-safe primitive: pre-resolve a connect plan ahead of the user
1945
+ * gesture; the returned `connect()` invokes `adapter.connect()` as its first
1946
+ * statement (no await precedes it) so a popup/remote wallet's `window.open`
1947
+ * survives the gesture. For consumers driving such a wallet outside the modal
1948
+ * (the modal gets this for free via the `listWallets` warm-up + `connect()`).
1949
+ */
1950
+ async prepareConnect(options) {
1951
+ const plan = await this.resolveConnectPlan(options);
1952
+ return {
1953
+ walletId: plan.selectedWallet.walletId,
1954
+ connect: (o) => this.completeConnect(plan, o ?? options)
1955
+ };
1956
+ }
1957
+ /**
1958
+ * Background warm-up of connect plans for popup/remote
1959
+ * (`GenericDiscoveryAdapter`) wallets. Popup-free — `resolveConnectPlan` only
1960
+ * runs read/guard probes. Skips already-warm entries; never throws.
1961
+ */
1962
+ async warmDiscoveryPlans(wallets) {
1963
+ for (const [walletId, adapter] of this.adapters) {
1964
+ if (!(adapter instanceof GenericDiscoveryAdapter || adapter instanceof GenericAnnounceAdapter)) continue;
1965
+ if (this.warmPlans.has(walletId)) continue;
1966
+ try {
1967
+ const plan = await this.resolveConnectPlan({ walletId }, wallets);
1968
+ this.warmPlans.set(walletId, plan);
1969
+ } catch {
1970
+ }
1971
+ }
1972
+ }
1973
+ /**
1974
+ * SYNCHRONOUS fast-path: if a fresh warm plan exists for a popup/remote wallet
1975
+ * — and `options` carries no plan-affecting guards — consume it and START
1976
+ * `completeConnect` immediately, reaching `adapter.connect()` with no awaits.
1977
+ * Returns the in-flight Session promise, or null to fall back to the normal
1978
+ * path (e.g. cold cache, or a non-discovery wallet).
1979
+ */
1980
+ tryFastConnect(options, correlationId, attempt) {
1981
+ const walletId = options?.walletId;
1982
+ if (!walletId) return null;
1983
+ if (options?.requiredCapabilities || options?.allowWallets) return null;
1984
+ const plan = this.warmPlans.get(walletId);
1985
+ if (!plan) return null;
1986
+ this.warmPlans.delete(walletId);
1987
+ return this.completeConnect(plan, options, correlationId, attempt);
1988
+ }
1989
+ /**
1990
+ * Disconnect from wallet
1991
+ */
1992
+ async disconnect() {
1993
+ this.restorationBlocked = true;
1994
+ this.warmPlans.clear();
1995
+ const revision = ++this.sessionRevision;
1996
+ ++this.connectionAttempt;
1997
+ const session = this.activeSession;
1998
+ if (!session) {
1999
+ if (this.nativeOwner?.busy) await this.nativeOwner.disconnect();
2000
+ await this.removeSession();
2001
+ return;
2002
+ }
2003
+ try {
2004
+ const adapter = this.adapters.get(session.walletId);
2005
+ if (adapter) {
2006
+ const ctx = this.createAdapterContext();
2007
+ await adapter.disconnect(ctx, session);
2008
+ }
2009
+ if (revision !== this.sessionRevision || this.activeSession !== session) return;
2010
+ const sessionId = session.sessionId;
2011
+ await this.removeSession(sessionId);
2012
+ if (revision !== this.sessionRevision || this.activeSession !== session) return;
2013
+ this.activeSession = null;
2014
+ this.warmPlans.clear();
2015
+ this.emit("session:disconnected", {
2016
+ type: "session:disconnected",
2017
+ sessionId
2018
+ });
2019
+ } catch (err) {
2020
+ const error = core.mapUnknownErrorToPartyLayerError(err, {
2021
+ phase: "connect"
2022
+ // Use connect as default phase
2023
+ });
2024
+ this.emit("error", { type: "error", error });
2025
+ throw error;
2026
+ }
2027
+ }
2028
+ /**
2029
+ * Get active session
2030
+ */
2031
+ async getActiveSession() {
2032
+ if (this.destroyed) return null;
2033
+ this.initialize();
2034
+ if (this.activeSession) {
2035
+ const adapter = this.adapters.get(this.activeSession.walletId);
2036
+ if (adapter && nativeOwnerBindings.has(adapter) && this.nativeOwner?.getSession()?.id !== String(this.activeSession.walletId)) {
2037
+ this.onNativeIdentityChanged(String(this.activeSession.walletId), null);
2038
+ return null;
2039
+ }
2040
+ if (this.activeSession.expiresAt && Date.now() >= this.activeSession.expiresAt) {
2041
+ const sessionId = this.activeSession.sessionId;
2042
+ await this.disconnect();
2043
+ this.emit("session:expired", {
2044
+ type: "session:expired",
2045
+ sessionId
2046
+ });
2047
+ return null;
2048
+ }
2049
+ return this.activeSession;
2050
+ }
2051
+ return this.restoreSession();
2052
+ }
2053
+ /**
2054
+ * Sign a message
2055
+ */
2056
+ async signMessage(params) {
2057
+ const session = await this.getActiveSession();
2058
+ if (!session) {
2059
+ throw new Error("No active session");
2060
+ }
2061
+ const adapter = this.adapters.get(session.walletId);
2062
+ if (!adapter || !adapter.signMessage) {
2063
+ throw new core.CapabilityNotSupportedError(
2064
+ session.walletId,
2065
+ "signMessage"
2066
+ );
2067
+ }
2068
+ try {
2069
+ this.assertNetworkOk(session);
2070
+ const ctx = this.createAdapterContext();
2071
+ const result = await adapter.signMessage(ctx, session, params);
2072
+ if (nativeOwnerBindings.has(adapter)) {
2073
+ await this.nativeOwner.validateIdentity(String(session.walletId), session.partyId, session.network);
2074
+ }
2075
+ return normalizeSignedMessage(result, session, params);
2076
+ } catch (err) {
2077
+ const error = core.mapUnknownErrorToPartyLayerError(err, {
2078
+ phase: "signMessage",
2079
+ walletId: String(session.walletId)
2080
+ });
2081
+ this.emit("error", { type: "error", error });
2082
+ throw error;
2083
+ }
2084
+ }
2085
+ /**
2086
+ * Sign a transaction
2087
+ */
2088
+ async signTransaction(params) {
2089
+ const session = await this.getActiveSession();
2090
+ if (!session) {
2091
+ throw new Error("No active session");
2092
+ }
2093
+ const adapter = this.adapters.get(session.walletId);
2094
+ if (!adapter || !adapter.signTransaction) {
2095
+ throw new core.CapabilityNotSupportedError(
2096
+ session.walletId,
2097
+ "signTransaction"
2098
+ );
2099
+ }
2100
+ const correlationId = newCorrelationId();
2101
+ this.log("debug", "signTransaction:start", "signTransaction", {}, correlationId);
2102
+ try {
2103
+ this.assertNetworkOk(session);
2104
+ const ctx = this.createAdapterContext();
2105
+ const result = await adapter.signTransaction(ctx, session, params);
2106
+ this.emit("tx:status", {
2107
+ type: "tx:status",
2108
+ sessionId: session.sessionId,
2109
+ txId: result.transactionHash,
2110
+ status: "pending",
2111
+ raw: result.signedTx
2112
+ }, correlationId);
2113
+ return result;
2114
+ } catch (err) {
2115
+ const error = core.mapUnknownErrorToPartyLayerError(err, {
2116
+ phase: "signTransaction",
2117
+ walletId: String(session.walletId)
2118
+ });
2119
+ this.emit("error", { type: "error", error }, correlationId);
2120
+ throw error;
2121
+ }
2122
+ }
2123
+ /**
2124
+ * Submit a transaction
2125
+ */
2126
+ async submitTransaction(params) {
2127
+ const session = await this.getActiveSession();
2128
+ if (!session) {
2129
+ throw new Error("No active session");
2130
+ }
2131
+ const adapter = this.adapters.get(session.walletId);
2132
+ if (!adapter || !adapter.submitTransaction) {
2133
+ throw new core.CapabilityNotSupportedError(
2134
+ session.walletId,
2135
+ "submitTransaction"
2136
+ );
2137
+ }
2138
+ const correlationId = newCorrelationId();
2139
+ this.log("debug", "submitTransaction:start", "submitTransaction", {}, correlationId);
2140
+ try {
2141
+ this.assertNetworkOk(session);
2142
+ const ctx = this.createAdapterContext();
2143
+ const result = await adapter.submitTransaction(ctx, session, params);
2144
+ this.emit("tx:status", {
2145
+ type: "tx:status",
2146
+ sessionId: session.sessionId,
2147
+ txId: result.transactionHash,
2148
+ status: "submitted",
2149
+ raw: result
2150
+ }, correlationId);
2151
+ return result;
2152
+ } catch (err) {
2153
+ const error = core.mapUnknownErrorToPartyLayerError(err, {
2154
+ phase: "submitTransaction",
2155
+ walletId: String(session.walletId)
2156
+ });
2157
+ this.emit("error", { type: "error", error }, correlationId);
2158
+ throw error;
2159
+ }
2160
+ }
2161
+ /**
2162
+ * Proxy a JSON Ledger API request through the active wallet adapter
2163
+ */
2164
+ async ledgerApi(params) {
2165
+ const session = await this.getActiveSession();
2166
+ if (!session) {
2167
+ throw new Error("No active session");
2168
+ }
2169
+ const adapter = this.adapters.get(session.walletId);
2170
+ if (!adapter || !adapter.ledgerApi) {
2171
+ throw new core.CapabilityNotSupportedError(
2172
+ session.walletId,
2173
+ "ledgerApi"
2174
+ );
2175
+ }
2176
+ try {
2177
+ this.assertNetworkOk(session);
2178
+ const ctx = this.createAdapterContext();
2179
+ return await adapter.ledgerApi(ctx, session, params);
2180
+ } catch (err) {
2181
+ const error = core.mapUnknownErrorToPartyLayerError(err, {
2182
+ phase: "ledgerApi",
2183
+ walletId: String(session.walletId)
2184
+ });
2185
+ this.emit("error", { type: "error", error });
2186
+ throw error;
2187
+ }
2188
+ }
2189
+ /**
2190
+ * Request a typed transfer. The application says what it wants; the wallet
2191
+ * builds the command, shows the user what they are authorising, obtains their
2192
+ * approval, signs, executes, and returns the real update id.
2193
+ *
2194
+ * The acting party comes from the active session, never from the caller, and
2195
+ * the intent is narrowed to the allowlisted fields before any adapter sees it,
2196
+ * so no caller-supplied option can reach the wallet.
2197
+ *
2198
+ * Throws `CapabilityNotSupportedError` when the active wallet does not
2199
+ * implement it. Ask first with `session.capabilitiesSnapshot.includes('transfer')`,
2200
+ * or require it at connect with `connect({ requiredCapabilities: ['transfer'] })`.
2201
+ */
2202
+ async requestTransfer(intent) {
2203
+ const session = await this.getActiveSession();
2204
+ if (!session) {
2205
+ throw new Error("No active session");
2206
+ }
2207
+ const adapter = this.adapters.get(session.walletId);
2208
+ if (!adapter || !adapter.requestTransfer) {
2209
+ throw new core.CapabilityNotSupportedError(
2210
+ session.walletId,
2211
+ "transfer"
2212
+ );
2213
+ }
2214
+ const safeIntent = core.toTransferIntent(intent);
2215
+ const correlationId = newCorrelationId();
2216
+ this.log("debug", "requestTransfer:start", "requestTransfer", {}, correlationId);
2217
+ try {
2218
+ this.assertNetworkOk(session);
2219
+ const ctx = this.createAdapterContext();
2220
+ const result = await adapter.requestTransfer(ctx, session, safeIntent);
2221
+ this.emit("tx:status", {
2222
+ type: "tx:status",
2223
+ sessionId: session.sessionId,
2224
+ txId: result.updateId,
2225
+ status: "committed",
2226
+ raw: result
2227
+ }, correlationId);
2228
+ return result;
2229
+ } catch (err) {
2230
+ const error = core.mapUnknownErrorToPartyLayerError(err, {
2231
+ phase: "requestTransfer",
2232
+ walletId: String(session.walletId)
2233
+ });
2234
+ this.emit("error", { type: "error", error }, correlationId);
2235
+ throw error;
2236
+ }
2237
+ }
2238
+ /**
2239
+ * Subscribe to events
2240
+ */
2241
+ on(event, handler) {
2242
+ if (!this.eventHandlers.has(event)) {
2243
+ this.eventHandlers.set(event, /* @__PURE__ */ new Set());
2244
+ }
2245
+ this.eventHandlers.get(event).add(handler);
2246
+ return () => {
2247
+ this.off(event, handler);
2248
+ };
2249
+ }
2250
+ /**
2251
+ * Unsubscribe from events
2252
+ */
2253
+ off(event, handler) {
2254
+ const handlers = this.eventHandlers.get(event);
2255
+ if (handlers) {
2256
+ handlers.delete(handler);
2257
+ }
2258
+ }
2259
+ /**
2260
+ * Get the stable provider facade for this client.
2261
+ *
2262
+ * Browser-native connections expose the official owner's actual accounts,
2263
+ * network, execution/events and raw Ledger API response, including standard
2264
+ * path/query/header request fields. Signing keeps the reviewed encoding policy.
2265
+ * Existing proprietary/custom integrations retain their compatibility bridge.
2266
+ * `createProviderBridge(client)` remains available explicitly for legacy callers.
2267
+ * Full async server user-URL orchestration needs a verified direct provider path.
2268
+ *
2269
+ * @returns Stable CIP-0103 provider facade
2270
+ */
2271
+ asProvider() {
2272
+ if (!this.sessionProvider) {
2273
+ this.sessionProvider = createSessionProvider({
2274
+ bridge: provider.createProviderBridge(this),
2275
+ native: () => {
2276
+ const session = this.activeSession;
2277
+ const adapter = session && this.adapters.get(session.walletId);
2278
+ if (!adapter || !nativeOwnerBindings.has(adapter) || !this.nativeOwner?.getSession()) return null;
2279
+ return this.nativeOwner.getProvider(String(session.walletId));
2280
+ },
2281
+ ensureSession: () => this.getActiveSession(),
2282
+ guardNetwork: () => {
2283
+ if (this.activeSession) this.assertNetworkOk(this.activeSession);
2284
+ },
2285
+ subscribe: (changed) => {
2286
+ const connected = this.on("session:connected", changed);
2287
+ const disconnected = this.on("session:disconnected", changed);
2288
+ const expired = this.on("session:expired", changed);
2289
+ return () => {
2290
+ connected();
2291
+ disconnected();
2292
+ expired();
2293
+ };
2294
+ }
2295
+ });
2296
+ }
2297
+ return this.sessionProvider.provider;
2298
+ }
2299
+ /**
2300
+ * Destroy client and cleanup
2301
+ */
2302
+ destroy() {
2303
+ if (this.destroyed) return;
2304
+ ++this.sessionRevision;
2305
+ ++this.connectionAttempt;
2306
+ this.destroyed = true;
2307
+ this.sessionProvider?.destroy();
2308
+ this.nativeOwner?.destroy();
2309
+ if (this.telemetry && "destroy" in this.telemetry && typeof this.telemetry.destroy === "function") {
2310
+ this.telemetry.destroy();
2311
+ } else if (this.telemetry?.flush) {
2312
+ this.telemetry.flush().catch(() => {
2313
+ });
2314
+ }
2315
+ this.announceUnsubscribe?.();
2316
+ this.announceUnsubscribe = null;
2317
+ this.announceRegistry.clear();
2318
+ for (const channel of this.announceChannels.values()) channel.destroy();
2319
+ this.announceChannels.clear();
2320
+ if (this.walletsChangedTimer !== null) {
2321
+ clearTimeout(this.walletsChangedTimer);
2322
+ this.walletsChangedTimer = null;
2323
+ }
2324
+ this.eventHandlers.clear();
2325
+ this.activeSession = null;
2326
+ }
2327
+ /**
2328
+ * Create adapter context
2329
+ */
2330
+ createAdapterContext() {
2331
+ return {
2332
+ appName: this.config.app.name,
2333
+ origin: this.origin,
2334
+ network: this.config.network,
2335
+ logger: this.logger,
2336
+ telemetry: this.telemetry,
2337
+ registry: {
2338
+ getWallet: async (walletId) => {
2339
+ return this.registryClient.getWallet(String(walletId));
2340
+ }
2341
+ },
2342
+ crypto: this.crypto,
2343
+ storage: this.storage,
2344
+ timeout: (ms) => {
2345
+ return new Promise((_, reject) => {
2346
+ setTimeout(() => reject(new Error("Timeout")), ms);
2347
+ });
2348
+ }
2349
+ };
2350
+ }
2351
+ /**
2352
+ * Persist session to storage
2353
+ */
2354
+ async persistSession(session) {
2355
+ const revision = this.sessionRevision;
2356
+ try {
2357
+ const data = JSON.stringify(session);
2358
+ const encrypted = await this.crypto.encrypt(data, this.origin);
2359
+ const write = this.sessionStorageQueue.then(async () => {
2360
+ if (!this.destroyed && revision === this.sessionRevision) await this.storage.set(SESSION_STORAGE_KEY, encrypted);
2361
+ });
2362
+ this.sessionStorageQueue = write.catch(() => {
2363
+ });
2364
+ await write;
2365
+ } catch (err) {
2366
+ this.log("warn", "session:persist_failed", "Failed to persist session", {
2367
+ error: err instanceof Error ? err.message : String(err)
2368
+ });
2369
+ }
2370
+ }
2371
+ /**
2372
+ * Remove session from storage.
2373
+ *
2374
+ * Accepts a sessionId for call-site symmetry, but since the SDK tracks one
2375
+ * active session we always remove the single SESSION_STORAGE_KEY.
2376
+ */
2377
+ async removeSession(_sessionId) {
2378
+ const revision = this.sessionRevision;
2379
+ try {
2380
+ const remove = this.sessionStorageQueue.then(async () => {
2381
+ if (!this.destroyed && revision === this.sessionRevision) await this.storage.remove(SESSION_STORAGE_KEY);
2382
+ });
2383
+ this.sessionStorageQueue = remove.catch(() => {
2384
+ });
2385
+ await remove;
2386
+ } catch (err) {
2387
+ this.log("warn", "session:remove_failed", "Failed to remove session", {
2388
+ error: err instanceof Error ? err.message : String(err)
2389
+ });
2390
+ }
2391
+ }
2392
+ /**
2393
+ * Restore session from storage
2394
+ */
2395
+ restoreSession() {
2396
+ if (this.destroyed || this.restorationBlocked) return Promise.resolve(null);
2397
+ if (this.restoreTask) return this.restoreTask;
2398
+ const task = this.restoreSessionOnce();
2399
+ this.restoreTask = task;
2400
+ const clear = () => {
2401
+ if (this.restoreTask === task) this.restoreTask = null;
2402
+ };
2403
+ void task.then(clear, clear);
2404
+ return task;
2405
+ }
2406
+ async restoreSessionOnce() {
2407
+ const revision = this.sessionRevision;
2408
+ const current = () => !this.destroyed && !this.restorationBlocked && revision === this.sessionRevision;
2409
+ this.telemetry?.increment?.(core.METRICS.RESTORE_ATTEMPTS);
2410
+ const correlationId = newCorrelationId();
2411
+ this.log("debug", "session:restore_start", "restoreSession", {}, correlationId);
2412
+ try {
2413
+ const encrypted = await this.storage.get(SESSION_STORAGE_KEY);
2414
+ if (!current()) return this.activeSession;
2415
+ if (!encrypted) {
2416
+ return null;
2417
+ }
2418
+ const decrypted = await this.crypto.decrypt(encrypted, this.origin);
2419
+ if (!current()) return this.activeSession;
2420
+ const session = JSON.parse(decrypted);
2421
+ if (session.expiresAt && Date.now() >= session.expiresAt) {
2422
+ await this.removeSession(session.sessionId);
2423
+ return null;
2424
+ }
2425
+ if (session.origin !== this.origin) {
2426
+ return null;
2427
+ }
2428
+ const mismatch = this.networkMismatch(session);
2429
+ if (mismatch) {
2430
+ this.emit("session:networkMismatch", {
2431
+ type: "session:networkMismatch",
2432
+ sessionId: session.sessionId,
2433
+ expected: mismatch.expected,
2434
+ actual: mismatch.actual,
2435
+ enforced: this.enforcement !== "off"
2436
+ }, correlationId);
2437
+ if (this.enforcement !== "off") {
2438
+ this.log("warn", "session:restore_network_mismatch", "Refused session restore: network mismatch", {
2439
+ expected: mismatch.expected,
2440
+ actual: mismatch.actual
2441
+ }, correlationId);
2442
+ await this.removeSession(session.sessionId);
2443
+ this.emit("session:expired", {
2444
+ type: "session:expired",
2445
+ sessionId: session.sessionId
2446
+ }, correlationId);
2447
+ return null;
2448
+ }
2449
+ session.networkMismatch = mismatch;
2450
+ }
2451
+ await this.ensureDefaultWallets();
2452
+ if (!current()) return this.activeSession;
2453
+ let adapter = this.adapters.get(session.walletId);
2454
+ if (this.nativeOwner && !adapter) {
2455
+ try {
2456
+ await this.aggregateAnnouncedWallets(await this.registryClient.getWallets());
2457
+ } catch {
2458
+ }
2459
+ if (!current()) return this.activeSession;
2460
+ adapter = this.adapters.get(session.walletId);
2461
+ }
2462
+ if (adapter?.restore) {
2463
+ const ctx = this.createAdapterContext();
2464
+ if (adapter instanceof GenericDiscoveryAdapter && adapter.usesFactory()) {
2465
+ let networkHosts = {};
2466
+ try {
2467
+ const entry = await this.registryClient.getWalletEntry(String(session.walletId));
2468
+ networkHosts = entry.adapter?.networkHosts ?? {};
2469
+ } catch {
2470
+ }
2471
+ adapter.setNetworkHosts(networkHosts);
2472
+ try {
2473
+ adapter.resolveOfficial(session.network);
2474
+ } catch {
2475
+ }
2476
+ }
2477
+ const restored = await adapter.restore(ctx, {
2478
+ ...session,
2479
+ encrypted
2480
+ });
2481
+ if (!current()) return this.activeSession;
2482
+ if (restored && restored.partyId === session.partyId && !core.detectNetworkMismatch(session.network, restored.network)) {
2483
+ this.activeSession = restored;
2484
+ this.activeSessionNeedsProbe = false;
2485
+ await this.persistSession(restored);
2486
+ if (!current()) return this.activeSession;
2487
+ this.telemetry?.increment?.(core.METRICS.SESSIONS_RESTORED);
2488
+ this.telemetry?.increment?.(core.METRICS.WALLET_CONNECT_SUCCESS);
2489
+ this.emit("session:connected", {
2490
+ type: "session:connected",
2491
+ session: restored
2492
+ }, correlationId);
2493
+ return restored;
2494
+ } else {
2495
+ await this.removeSession(session.sessionId);
2496
+ this.emit("session:expired", {
2497
+ type: "session:expired",
2498
+ sessionId: session.sessionId
2499
+ }, correlationId);
2500
+ return null;
2501
+ }
2502
+ }
2503
+ if (this.nativeOwner && (!adapter || nativeOwnerBindings.has(adapter))) {
2504
+ await this.removeSession(session.sessionId);
2505
+ this.emit("session:expired", { type: "session:expired", sessionId: session.sessionId }, correlationId);
2506
+ return null;
2507
+ }
2508
+ this.activeSession = session;
2509
+ this.activeSessionNeedsProbe = true;
2510
+ return session;
2511
+ } catch (err) {
2512
+ if (!current()) return this.activeSession;
2513
+ await this.removeSession();
2514
+ this.log("warn", "session:restore_failed", "Failed to restore session", {
2515
+ error: err instanceof Error ? err.message : String(err)
2516
+ }, correlationId);
2517
+ return null;
2518
+ }
2519
+ }
2520
+ /**
2521
+ * Update registry status and emit event
2522
+ */
2523
+ updateRegistryStatus() {
2524
+ const status = this.registryClient.getStatus();
2525
+ if (status) {
2526
+ if (status.source === "network") {
2527
+ this.telemetry?.increment?.(core.METRICS.REGISTRY_FETCH);
2528
+ } else if (status.source === "cache") {
2529
+ this.telemetry?.increment?.(core.METRICS.REGISTRY_CACHE_HIT);
2530
+ }
2531
+ if (status.stale) {
2532
+ this.telemetry?.increment?.(core.METRICS.REGISTRY_STALE);
2533
+ }
2534
+ this.emit("registry:status", {
2535
+ type: "registry:status",
2536
+ status: {
2537
+ source: status.source,
2538
+ verified: status.verified,
2539
+ channel: status.channel,
2540
+ sequence: status.sequence,
2541
+ stale: status.stale,
2542
+ fetchedAt: status.fetchedAt,
2543
+ etag: status.etag,
2544
+ error: status.error
2545
+ }
2546
+ });
2547
+ }
2548
+ }
2549
+ /**
2550
+ * Get registry status
2551
+ */
2552
+ getRegistryStatus() {
2553
+ return this.registryClient.getStatus();
2554
+ }
2555
+ /**
2556
+ * Emit event to handlers
2557
+ */
2558
+ /**
2559
+ * Central structured log. Filters by the configured level here, before the adapter
2560
+ * is called, so adapters never filter themselves; skips entirely when no real
2561
+ * logger was configured (the no-op default), so a silent client pays only a check.
2562
+ * Every line carries a machine readable payload `{ event, correlationId?, ...fields }`.
2563
+ * Privacy: callers pass only non identifying fields, the same rule as telemetry.
2564
+ */
2565
+ log(level, event, message, fields, correlationId) {
2566
+ if (this.logger instanceof DefaultLogger) return;
2567
+ if (!shouldLog(level, this.logLevel)) return;
2568
+ const payload = {
2569
+ event,
2570
+ ...correlationId ? { correlationId } : {},
2571
+ ...fields ?? {}
2572
+ };
2573
+ switch (level) {
2574
+ case "debug":
2575
+ this.logger.debug(message, payload);
2576
+ break;
2577
+ case "info":
2578
+ this.logger.info(message, payload);
2579
+ break;
2580
+ case "warn":
2581
+ this.logger.warn(message, payload);
2582
+ break;
2583
+ case "error":
2584
+ this.logger.error(message, payload);
2585
+ break;
2586
+ }
2587
+ }
2588
+ emit(event, payload, correlationId) {
2589
+ if (event === "error" && "error" in payload) {
2590
+ const error = payload.error;
2591
+ if (error.code) {
2592
+ this.telemetry?.increment?.(core.errorMetricName(error.code));
2593
+ }
2594
+ }
2595
+ if (this.telemetry && !(this.telemetry instanceof DefaultTelemetry)) {
2596
+ this.telemetry.track(event, eventTelemetryProperties(payload));
2597
+ }
2598
+ this.log(eventLogLevel(event), event, event, eventTelemetryProperties(payload), correlationId);
2599
+ const handlers = this.eventHandlers.get(event);
2600
+ if (handlers) {
2601
+ for (const handler of handlers) {
2602
+ try {
2603
+ handler(payload);
2604
+ } catch (err) {
2605
+ this.log("error", "event:handler_error", "Error in event handler", {
2606
+ error: err instanceof Error ? err.message : String(err)
2607
+ });
2608
+ }
2609
+ }
2610
+ }
2611
+ }
2612
+ };
2613
+ function object(value) {
2614
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Malformed Ledger API response");
2615
+ return value;
2616
+ }
2617
+ function text(value) {
2618
+ if (typeof value !== "string" || !value || value.length > 2048 || /\p{Cc}/u.test(value)) {
2619
+ throw new Error("Invalid Ledger API identifier");
2620
+ }
2621
+ return value;
2622
+ }
2623
+ var identity = (s) => JSON.stringify([s.sessionId, s.walletId, s.partyId, core.toCAIP2Network(s.network).networkId]);
2624
+ function createWalletLedgerReader(client, options) {
2625
+ return createScopedLedgerReader(client, options);
2626
+ }
2627
+ function createScopedLedgerReader(client, options, applicationRequest) {
2628
+ const networkId = text(options.networkId);
2629
+ if (!/^canton:[a-zA-Z0-9_-]+$/.test(networkId)) throw new Error("Expected a Canton CAIP-2 network id");
2630
+ function configuredInterface(value) {
2631
+ if (value === void 0) return void 0;
2632
+ const id = text(value);
2633
+ if (!/^[^:#\s]+:[^:\s]+:[^:\s]+$/.test(id)) throw new Error("Use an exact package-id-qualified holding interface id");
2634
+ return id;
2635
+ }
2636
+ const interfaceId = configuredInterface(options.holdingInterfaceId);
2637
+ const v2InterfaceId = configuredInterface(options.holdingV2InterfaceId);
2638
+ const timeoutMs = options.timeoutMs ?? 3e4;
2639
+ const maxContracts = options.maxContracts ?? 1e3;
2640
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 3e5) throw new Error("Invalid ledger read timeout");
2641
+ if (!Number.isInteger(maxContracts) || maxContracts < 1 || maxContracts > 1e4) throw new Error("Invalid snapshot limit");
2642
+ async function read(signal, action) {
2643
+ let timer;
2644
+ let stop;
2645
+ let stopped = false;
2646
+ const controller = new AbortController();
2647
+ const aborted = new Promise((_resolve, reject) => {
2648
+ stop = () => {
2649
+ stopped = true;
2650
+ controller.abort();
2651
+ reject(new Error("Ledger read cancelled or timed out"));
2652
+ };
2653
+ if (signal?.aborted) stop();
2654
+ else signal?.addEventListener("abort", stop, { once: true });
2655
+ timer = setTimeout(stop, timeoutMs);
2656
+ });
2657
+ const run = async () => {
2658
+ const session = await client.getActiveSession();
2659
+ if (stopped) throw new Error("Ledger read cancelled");
2660
+ if (!session || session.networkMismatch || core.toCAIP2Network(session.network).networkId !== networkId) {
2661
+ throw new Error("Connect a wallet on the expected network before reading the ledger");
2662
+ }
2663
+ if (!applicationRequest && !session.capabilitiesSnapshot.includes("ledgerApi")) throw new Error("This wallet does not expose ledgerApi");
2664
+ const captured = identity(session);
2665
+ const assertCurrent = async () => {
2666
+ const current = await client.getActiveSession();
2667
+ if (stopped || !current || current.networkMismatch || identity(current) !== captured) throw new Error("Wallet session changed during ledger read");
2668
+ };
2669
+ const request = async (resource, body) => {
2670
+ await assertCurrent();
2671
+ let result2 = applicationRequest ? await applicationRequest(session, resource, body, controller.signal) : await client.asProvider().request({ method: "ledgerApi", params: {
2672
+ requestMethod: body ? "post" : "get",
2673
+ resource,
2674
+ ...body ? { body } : {}
2675
+ } });
2676
+ await assertCurrent();
2677
+ if (result2 && typeof result2 === "object" && !Array.isArray(result2) && Object.keys(result2).length === 1 && typeof result2.response === "string") result2 = result2.response;
2678
+ if (typeof result2 === "string") {
2679
+ if (result2.length > 8e6) throw new Error("Ledger response is too large");
2680
+ result2 = JSON.parse(result2);
2681
+ }
2682
+ return result2;
2683
+ };
2684
+ const result = await action(session, request);
2685
+ await assertCurrent();
2686
+ return result;
2687
+ };
2688
+ try {
2689
+ return await Promise.race([run(), aborted]);
2690
+ } finally {
2691
+ if (timer) clearTimeout(timer);
2692
+ if (stop) signal?.removeEventListener("abort", stop);
2693
+ }
2694
+ }
2695
+ function readHoldings(requestedInterface, parse, include, signal) {
2696
+ return read(signal, async (session, request) => {
2697
+ if (!requestedInterface) throw new Error("Configure the version-specific holding interface id before reading holdings");
2698
+ const end = object(await request("/v2/state/ledger-end"));
2699
+ if (!Number.isSafeInteger(end.offset) || end.offset < 0) throw new Error("Unsafe or invalid ledger offset");
2700
+ const rows = await request("/v2/state/active-contracts", {
2701
+ activeAtOffset: end.offset,
2702
+ eventFormat: { filtersByParty: { [String(session.partyId)]: { cumulative: [{
2703
+ identifierFilter: { InterfaceFilter: { value: { interfaceId: requestedInterface, includeInterfaceView: true } } }
2704
+ }] } }, verbose: false }
2705
+ });
2706
+ if (!Array.isArray(rows) || rows.length >= maxContracts) throw new Error("Incomplete or oversized holdings snapshot");
2707
+ const seen = /* @__PURE__ */ new Set();
2708
+ const holdings = [];
2709
+ for (const row of rows) {
2710
+ const entry = object(object(row).contractEntry);
2711
+ if (Object.keys(entry).length !== 1 || !entry.JsActiveContract) throw new Error("Snapshot contains an incomplete reassignment");
2712
+ const created = object(object(entry.JsActiveContract).createdEvent);
2713
+ const cid = text(created.contractId);
2714
+ if (seen.has(cid)) throw new Error("Duplicate holding contract in snapshot");
2715
+ seen.add(cid);
2716
+ if (!Array.isArray(created.interfaceViews)) throw new Error("Missing holding interface view");
2717
+ const views = created.interfaceViews.filter((v) => object(v).interfaceId === requestedInterface);
2718
+ if (views.length !== 1) throw new Error("Missing or ambiguous holding interface view");
2719
+ const view = object(views[0]);
2720
+ if (object(view.viewStatus).code !== 0) throw new Error("Holding interface view failed");
2721
+ const holding = parse(view.viewValue);
2722
+ if (include(holding, String(session.partyId))) holdings.push({ cid, holding });
2723
+ }
2724
+ return { walletId: String(session.walletId), partyId: String(session.partyId), networkId, offset: end.offset, holdings };
2725
+ });
2726
+ }
2727
+ return {
2728
+ /** A bounded, complete ACS snapshot of the connected party's configured HoldingV1 interface. */
2729
+ readHoldings(signal) {
2730
+ return readHoldings(interfaceId, core.parseTokenHoldingV1, (holding, owner) => {
2731
+ if (holding.owner !== owner) throw new Error("Holding belongs to another party");
2732
+ return true;
2733
+ }, signal);
2734
+ },
2735
+ /** Owned V2 accounts only. Provider visibility and ownerless admin accounts do not confer ownership. */
2736
+ readHoldingsV2(signal) {
2737
+ return readHoldings(v2InterfaceId, core.parseTokenHoldingV2, (holding, owner) => holding.account.owner === owner, signal);
2738
+ },
2739
+ /** One read, never polling or resubmission. Unknown remains unknown if ids cannot be correlated. */
2740
+ async confirmTransaction({ transaction, signal }) {
2741
+ const updateId = transaction.receipt?.updateId ?? transaction.updateId;
2742
+ if (!updateId || !transaction.commandId) return { status: "unknown", reason: "An update id and the original app command id are required" };
2743
+ if (transaction.receipt?.commandId && transaction.receipt.commandId !== transaction.commandId) {
2744
+ return { status: "unknown", reason: "Wallet receipt conflicts with the original command id" };
2745
+ }
2746
+ text(updateId);
2747
+ text(transaction.commandId);
2748
+ return read(signal, async (session, request) => {
2749
+ if (transaction.networkId !== networkId || transaction.partyId !== String(session.partyId) || transaction.walletId !== String(session.walletId)) {
2750
+ throw new Error("Transaction does not belong to the connected wallet account and network");
2751
+ }
2752
+ if (transaction.updateId && transaction.updateId !== updateId) throw new Error("Conflicting update ids");
2753
+ const result = object(await request("/v2/updates/update-by-id", {
2754
+ updateId,
2755
+ updateFormat: { includeTransactions: {
2756
+ eventFormat: { filtersByParty: { [String(session.partyId)]: {} }, verbose: false },
2757
+ transactionShape: "TRANSACTION_SHAPE_ACS_DELTA"
2758
+ } }
2759
+ }));
2760
+ const update = object(result.update);
2761
+ if (Object.keys(update).length !== 1 || !update.Transaction) throw new Error("Requested update is not a transaction");
2762
+ const tx = object(object(update.Transaction).value);
2763
+ if (tx.updateId !== updateId || tx.commandId !== transaction.commandId || !Array.isArray(tx.events)) {
2764
+ return { status: "unknown", reason: "Ledger transaction cannot be correlated with the original command" };
2765
+ }
2766
+ return { status: "confirmed", updateId };
2767
+ });
2768
+ }
2769
+ };
2770
+ }
2771
+ function createApplicationLedgerReader(client, options) {
2772
+ if (!/^[\w.:-]{1,100}$/.test(options.sourceId)) throw new Error("Invalid application ledger source id");
2773
+ return createScopedLedgerReader(client, options, async (session, resource, body, signal) => {
2774
+ const browserOrigin = typeof window !== "undefined" ? window.location.origin : void 0;
2775
+ const origin = browserOrigin ?? options.origin;
2776
+ if (!origin || browserOrigin && options.origin && options.origin !== browserOrigin) throw new Error("Application reads require the current application origin");
2777
+ const base = new URL(origin);
2778
+ if (base.origin !== origin || base.protocol !== "https:" && !(base.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname))) throw new Error("Invalid application origin");
2779
+ const url = new URL(options.endpoint, origin);
2780
+ if (url.origin !== origin || url.username || url.password || url.hash) throw new Error("Application ledger endpoint must be same-origin");
2781
+ if (!["/v2/state/ledger-end", "/v2/state/active-contracts", "/v2/updates/update-by-id"].includes(resource)) throw new Error("Unsupported application ledger read");
2782
+ const response = await (options.fetch ?? globalThis.fetch)(url.href, {
2783
+ method: "POST",
2784
+ credentials: "same-origin",
2785
+ cache: "no-store",
2786
+ redirect: "error",
2787
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
2788
+ signal,
2789
+ body: JSON.stringify({
2790
+ version: 1,
2791
+ sourceId: options.sourceId,
2792
+ partyId: String(session.partyId),
2793
+ networkId: core.toCAIP2Network(session.network).networkId,
2794
+ resource,
2795
+ ...body ? { body } : {}
2796
+ })
2797
+ });
2798
+ if (!response.ok || !/^application\/json\b/i.test(response.headers.get("content-type") ?? "")) throw new Error("Authorized application ledger read is unavailable");
2799
+ const raw = await response.text();
2800
+ if (raw.length > 8e6) throw new Error("Application ledger response is too large");
2801
+ const result = JSON.parse(raw);
2802
+ if (!result || result.version !== 1 || result.sourceId !== options.sourceId || result.partyId !== String(session.partyId) || result.networkId !== options.networkId || result.resource !== resource || result.complete !== true || !Object.hasOwn(result, "value")) {
2803
+ throw new Error("Incomplete or incorrectly scoped application ledger response");
2804
+ }
2805
+ return result.value;
2806
+ });
2807
+ }
2808
+
2809
+ // src/native.ts
2810
+ var PartyLayerClient = class extends PartyLayerClientBase {
2811
+ constructor(config) {
2812
+ if ("walletConnect" in config && config.walletConnect !== void 0 || "bron" in config && config.bron !== void 0) {
2813
+ throw new Error("Automatic walletConnect/bron setup uses browser wallet runtimes. On native platforms, register a native-compatible WalletAdapter or provider through adapters.");
2814
+ }
2815
+ super({
2816
+ ...config,
2817
+ app: { ...config.app, origin: config.app.origin ?? "unknown" },
2818
+ adapters: config.adapters ?? [],
2819
+ discovery: { announce: false }
2820
+ }, { noWalletsMessage: "No native wallet transports are configured. Register a native-compatible adapter through adapters." });
2821
+ }
2822
+ };
2823
+ function createPartyLayer(config) {
2824
+ return new PartyLayerClient(config);
2825
+ }
2826
+
2827
+ exports.PartyLayerClient = PartyLayerClient;
2828
+ exports.createApplicationLedgerReader = createApplicationLedgerReader;
2829
+ exports.createPartyLayer = createPartyLayer;
2830
+ exports.createWalletLedgerReader = createWalletLedgerReader;
2831
+ //# sourceMappingURL=native.js.map
2832
+ //# sourceMappingURL=native.js.map