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