@partylayer/sdk 0.22.0 → 0.22.2

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,775 @@
1
+ import * as _partylayer_core from '@partylayer/core';
2
+ import { CIP0103Account, NetworkId, OfficialProviderAdapter, CIP0103Provider, WalletAdapter, OfficialAdapterFactory, StorageAdapter, CryptoAdapter, TelemetryAdapter, LoggerAdapter, WalletId, Session, SessionId, TransactionHash, TransactionStatus, WalletInfo, SignMessageParams, SignedMessage, SignTransactionParams, SignedTransaction, SubmitTransactionParams, TxReceipt, LedgerApiParams, LedgerApiResult, TransferIntent, TransferResult, TokenHoldingRef, TokenHoldingV2Ref } from '@partylayer/core';
3
+ import { RegistryClient, RegistryStatus } from '@partylayer/registry-client';
4
+
5
+ interface NativeIdentity {
6
+ account: CIP0103Account;
7
+ network: NetworkId;
8
+ status?: {
9
+ isConnected?: boolean;
10
+ connection?: {
11
+ isConnected?: boolean;
12
+ };
13
+ network?: {
14
+ networkId?: string;
15
+ };
16
+ };
17
+ }
18
+ declare class NativeConnectionOwner {
19
+ private readonly changed;
20
+ private client;
21
+ private initialization;
22
+ private readonly registrations;
23
+ private operation;
24
+ private pending;
25
+ private closing;
26
+ private projection;
27
+ private unsubscribers;
28
+ private disposed;
29
+ private refreshRevision;
30
+ private identityRefreshing;
31
+ private readonly probes;
32
+ constructor(changed?: (id: string, identity: NativeIdentity | null) => void);
33
+ get busy(): boolean;
34
+ assertAvailable(): void;
35
+ /** Run during picker preparation, never between a click and provider.connect. */
36
+ prepare(id: string, source: OfficialProviderAdapter, network: NetworkId): Promise<void>;
37
+ private wrap;
38
+ private guard;
39
+ /** No await precedes the official client's connect call. */
40
+ connect(id: string, signal?: AbortSignal): Promise<NativeIdentity>;
41
+ restore(expected?: {
42
+ id: string;
43
+ partyId: string;
44
+ network: NetworkId;
45
+ }): Promise<{
46
+ id: string;
47
+ identity: NativeIdentity;
48
+ } | null>;
49
+ getSession(): {
50
+ id: string;
51
+ identity: NativeIdentity;
52
+ } | null;
53
+ getProvider(id?: string): CIP0103Provider;
54
+ /** A bare signature must not be attributed to an old, eventless primary party. */
55
+ validateIdentity(id: string, partyId: string, network: NetworkId): Promise<void>;
56
+ private probe;
57
+ private detach;
58
+ private attach;
59
+ private invalidate;
60
+ /** Local transport cleanup when switching to a proprietary integration. */
61
+ release(): void;
62
+ disconnect(): Promise<void>;
63
+ destroy(): void;
64
+ }
65
+
66
+ /**
67
+ * Configuration types for PartyLayer SDK
68
+ */
69
+
70
+ /**
71
+ * Default registry URL for PartyLayer
72
+ * This points to the official registry endpoint.
73
+ */
74
+ declare const DEFAULT_REGISTRY_URL = "https://registry.partylayer.xyz";
75
+ /**
76
+ * Telemetry configuration for opt-in metrics collection
77
+ *
78
+ * @since 0.3.0
79
+ */
80
+ interface TelemetryConfig {
81
+ /**
82
+ * Enable telemetry collection
83
+ * @default false
84
+ */
85
+ enabled: boolean;
86
+ /**
87
+ * Metrics backend endpoint URL
88
+ * If not provided, metrics are collected but not sent
89
+ */
90
+ endpoint?: string;
91
+ /**
92
+ * Sampling rate (0.0 to 1.0)
93
+ * @default 1.0 (100% of events)
94
+ */
95
+ sampleRate?: number;
96
+ /**
97
+ * Application identifier (will be hashed for privacy)
98
+ * Used to calculate Monthly Active dApps (MAD)
99
+ */
100
+ appId?: string;
101
+ /**
102
+ * Include hashed origin in metrics
103
+ * @default false
104
+ */
105
+ includeOrigin?: boolean;
106
+ /**
107
+ * Number of events to buffer before sending
108
+ * @default 10
109
+ */
110
+ batchSize?: number;
111
+ /**
112
+ * Interval to flush metrics in milliseconds
113
+ * @default 30000 (30 seconds)
114
+ */
115
+ flushIntervalMs?: number;
116
+ /**
117
+ * Network to include in metrics
118
+ * If not provided, uses the SDK's configured network
119
+ */
120
+ network?: NetworkId;
121
+ }
122
+ /**
123
+ * Adapter class type (for instantiation)
124
+ */
125
+ type AdapterClass = new () => WalletAdapter;
126
+ /**
127
+ * PartyLayer configuration
128
+ */
129
+ interface PartyLayerBaseConfig {
130
+ /**
131
+ * Delay browser subscriptions and automatic restoration until initialize()
132
+ * or the first explicit client action. Frameworks use this for render safety.
133
+ * @default false
134
+ */
135
+ deferInitialization?: boolean;
136
+ /**
137
+ * Registry base URL (optional). The client appends `/v1/{channel}/registry.json`,
138
+ * so the default fetch is `https://registry.partylayer.xyz/v1/stable/registry.json`.
139
+ * @default 'https://registry.partylayer.xyz'
140
+ */
141
+ registryUrl?: string;
142
+ /** Registry channel */
143
+ channel?: 'stable' | 'beta';
144
+ /** Default network */
145
+ network: NetworkId;
146
+ /**
147
+ * Network-mismatch enforcement policy (default: `'guard'`).
148
+ *
149
+ * When a connected wallet's effective network differs from `network`:
150
+ * - `'off'` — detect + emit `session:networkMismatch` only; never block.
151
+ * - `'guard'` — (default) block wrong-network TRANSACTIONS (signMessage,
152
+ * signTransaction, submitTransaction, ledgerApi); connect still succeeds.
153
+ * - `'strict'` — also block CONNECT (throws `NetworkMismatchError`).
154
+ *
155
+ * BEHAVIOR CHANGE: prior to this, wrong-network transactions always
156
+ * proceeded. Set `'off'` to restore that.
157
+ */
158
+ networkEnforcement?: 'off' | 'guard' | 'strict';
159
+ /**
160
+ * Replace the entrypoint's default wallet catalog. The browser entry includes
161
+ * the reviewed wallet SDKs and loads them lazily for the network/channel.
162
+ * The native entry has no default transports; supply compatible adapters.
163
+ */
164
+ adapters?: (WalletAdapter | AdapterClass | OfficialProviderAdapter | OfficialAdapterFactory)[];
165
+ /** Extend the default catalog with custom adapters (for example a test wallet). */
166
+ additionalAdapters?: PartyLayerBaseConfig['adapters'];
167
+ /** Storage adapter (default: browser localStorage-based encrypted) */
168
+ storage?: StorageAdapter;
169
+ /** Crypto adapter (default: WebCrypto) */
170
+ crypto?: CryptoAdapter;
171
+ /** Registry public keys for signature verification (ed25519) */
172
+ registryPublicKeys?: string[];
173
+ /**
174
+ * EIP-6963-style announce discovery — the canonical Canton provider contract
175
+ * (`canton:requestProvider` → `canton:announceProvider`, see provider.md).
176
+ *
177
+ * When enabled, `listWallets()` aggregates announced CIP-0103 wallets with
178
+ * the `window.canton` namespace scan, the registry, and registered adapters:
179
+ * - an announced id matching a registered/registry wallet's
180
+ * `providerDetection` (provider.id) maps to that adapter — NO duplicate
181
+ * picker entry (e.g. Console's announce `lpnf…` → the Console adapter);
182
+ * - an UNKNOWN announced id surfaces as a dynamic entry routed to its own
183
+ * extension `target` (collision-proof; future announce-capable wallets
184
+ * appear with zero code changes).
185
+ *
186
+ * Default ON in the browser; ALWAYS skipped under SSR (`typeof window` guard).
187
+ * With zero announcers, `listWallets()` output is byte-identical to before.
188
+ */
189
+ discovery?: {
190
+ /** Aggregate `canton:announceProvider` wallets. @default true (in browser) */
191
+ announce?: boolean;
192
+ /** Announce-collection window in ms. @default 300 (canonical ~300ms) */
193
+ announceTimeoutMs?: number;
194
+ };
195
+ /**
196
+ * Telemetry configuration or adapter
197
+ *
198
+ * Can be either:
199
+ * - TelemetryConfig object for built-in metrics collection
200
+ * - TelemetryAdapter instance for custom telemetry
201
+ *
202
+ * @default undefined (telemetry disabled)
203
+ * @since 0.3.0 - Added TelemetryConfig support
204
+ */
205
+ telemetry?: TelemetryAdapter | TelemetryConfig;
206
+ /** Logger adapter (optional) */
207
+ logger?: LoggerAdapter;
208
+ /**
209
+ * Log verbosity. Filtering happens centrally in the client before the adapter is
210
+ * called, so adapters never filter themselves. `silent` suppresses everything.
211
+ * Defaults to `info` when a logger is supplied; with no logger the client is
212
+ * silent regardless.
213
+ */
214
+ logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'silent';
215
+ /** Application metadata */
216
+ app: {
217
+ /** Application name */
218
+ name: string;
219
+ /** Origin (for origin binding checks, defaults to window.location.origin) */
220
+ origin?: string;
221
+ };
222
+ }
223
+ /**
224
+ * Connect options
225
+ */
226
+ interface ConnectOptions {
227
+ /** Specific wallet ID to connect to */
228
+ walletId?: WalletId;
229
+ /** Prefer installed wallets */
230
+ preferInstalled?: boolean;
231
+ /** Allow only specific wallets */
232
+ allowWallets?: WalletId[];
233
+ /** Required capabilities */
234
+ requiredCapabilities?: string[];
235
+ /** Timeout in milliseconds */
236
+ timeoutMs?: number;
237
+ /**
238
+ * Called with a pairing/display URI (e.g. a WalletConnect `wc:` URI) the
239
+ * moment the adapter produces one, before approval. Used by the connect UI
240
+ * to render a QR / deep-link. Adapters without such a URI never call it.
241
+ */
242
+ onDisplayUri?: (uri: string) => void;
243
+ }
244
+ /**
245
+ * Wallet filter options
246
+ */
247
+ interface WalletFilter {
248
+ /** Required capabilities */
249
+ requiredCapabilities?: string[];
250
+ /** Include experimental wallets */
251
+ includeExperimental?: boolean;
252
+ }
253
+
254
+ /**
255
+ * Event types for PartyLayer SDK
256
+ */
257
+
258
+ /**
259
+ * Registry updated event
260
+ */
261
+ interface RegistryUpdatedEvent {
262
+ type: 'registry:updated';
263
+ channel: 'stable' | 'beta';
264
+ version: string;
265
+ }
266
+ /**
267
+ * Registry status event
268
+ */
269
+ interface RegistryStatusEvent {
270
+ type: 'registry:status';
271
+ status: {
272
+ source: 'network' | 'cache';
273
+ verified: boolean;
274
+ channel: 'stable' | 'beta';
275
+ sequence: number;
276
+ stale: boolean;
277
+ fetchedAt: number;
278
+ etag?: string;
279
+ error?: Error;
280
+ };
281
+ }
282
+ /**
283
+ * Session connected event
284
+ */
285
+ interface SessionConnectedEvent {
286
+ type: 'session:connected';
287
+ session: Session;
288
+ }
289
+ /**
290
+ * Session disconnected event
291
+ */
292
+ interface SessionDisconnectedEvent {
293
+ type: 'session:disconnected';
294
+ sessionId: SessionId;
295
+ reason?: string;
296
+ }
297
+ /**
298
+ * Session expired event
299
+ */
300
+ interface SessionExpiredEvent {
301
+ type: 'session:expired';
302
+ sessionId: SessionId;
303
+ }
304
+ /**
305
+ * Network mismatch event — the connected wallet's effective network differs
306
+ * from the dApp's configured network. Emitted under ALL policies (informational);
307
+ * `enforced` is true when the active policy ('guard' | 'strict') will block.
308
+ */
309
+ interface SessionNetworkMismatchEvent {
310
+ type: 'session:networkMismatch';
311
+ sessionId: SessionId;
312
+ /** dApp-configured (expected) network, CAIP-2 normalized. */
313
+ expected: string;
314
+ /** Wallet-reported (actual) network, CAIP-2 normalized. */
315
+ actual: string;
316
+ /** Whether the active policy will block (guard|strict) vs. detect-only (off). */
317
+ enforced: boolean;
318
+ }
319
+ /**
320
+ * Transaction status event
321
+ */
322
+ interface TxStatusEvent {
323
+ type: 'tx:status';
324
+ sessionId: SessionId;
325
+ /**
326
+ * The transaction id, when the wallet reported one. Optional for the same
327
+ * reason as `TxReceipt.transactionHash`, which is where it comes from: a
328
+ * wallet with no hash to give produces an event with no id, and saying so
329
+ * beats emitting an invented one. Prefer reading `updateId` off the receipt
330
+ * when you need a ledger identifier.
331
+ */
332
+ txId?: TransactionHash;
333
+ status: TransactionStatus;
334
+ raw?: unknown;
335
+ }
336
+ /**
337
+ * Error event
338
+ */
339
+ interface ErrorEvent {
340
+ type: 'error';
341
+ error: Error;
342
+ }
343
+ /**
344
+ * Wallet-list changed event — the set of listable wallets changed since the last
345
+ * `listWallets()` (e.g. a wallet announced late via `canton:announceProvider`,
346
+ * after the picker already loaded). SIGNAL-ONLY: it carries no wallet payload
347
+ * because `listWallets()` does registry-merge + discovery-gating + identity-
348
+ * bridging + filtering that a raw announce doesn't reflect — the authoritative
349
+ * read is to re-call `listWallets()` (mirrors EIP-6963/mipd: store emits, UI
350
+ * re-reads). Emitted debounced (coalesces a burst into one). Never emitted when
351
+ * nothing announces (byte-identical idle).
352
+ */
353
+ interface WalletsChangedEvent {
354
+ type: 'wallets:changed';
355
+ /** Why the list changed. Currently only late/inject-time announce discovery. */
356
+ reason: 'announced';
357
+ }
358
+ /**
359
+ * All event types
360
+ */
361
+ type PartyLayerEvent = RegistryUpdatedEvent | RegistryStatusEvent | SessionConnectedEvent | SessionDisconnectedEvent | SessionExpiredEvent | SessionNetworkMismatchEvent | TxStatusEvent | WalletsChangedEvent | ErrorEvent;
362
+ /**
363
+ * Event handler type
364
+ */
365
+ type EventHandler<T extends PartyLayerEvent = PartyLayerEvent> = (event: T) => void | Promise<void>;
366
+
367
+ /** Platform-specific integrations are supplied by the browser/native entrypoint. */
368
+ interface ClientRuntime {
369
+ getBuiltinAdapters?: () => WalletAdapter[];
370
+ loadDefaultWallet?: (id: string, config: PartyLayerBaseConfig, origin: string) => Promise<_partylayer_core.OfficialAdapterFactory | WalletAdapter | undefined>;
371
+ createOwner?: (onIdentityChanged: (id: string, identity: NativeIdentity | null) => void) => NativeConnectionOwner;
372
+ browserDiscovery?: boolean;
373
+ noWalletsMessage?: string;
374
+ }
375
+ declare class PartyLayerClientBase {
376
+ private readonly runtime;
377
+ private config;
378
+ private adapters;
379
+ private destroyed;
380
+ private initialized;
381
+ private readonly defaultLoads;
382
+ private readonly registryDefaultIds;
383
+ /**
384
+ * Pre-resolved connect plans for popup/remote (GenericDiscoveryAdapter)
385
+ * wallets, warmed on `listWallets()` (which the modal calls on open) so a
386
+ * subsequent click can connect gesture-synchronously. Consumed (deleted) on
387
+ * use and cleared on disconnect; a cold miss falls back to the normal path.
388
+ */
389
+ private readonly warmPlans;
390
+ private eventHandlers;
391
+ private activeSession;
392
+ private sessionRevision;
393
+ private connectionAttempt;
394
+ private restoreTask;
395
+ private restorationBlocked;
396
+ private sessionStorageQueue;
397
+ /**
398
+ * True when `activeSession` was revived AS-IS (no live `status()` probe) because
399
+ * its adapter wasn't registered yet at restore time (the lazy configured-announce
400
+ * case). Cleared once a live probe validates it (or on fresh connect). When set,
401
+ * `aggregateAnnouncedWallets` re-probes the session the moment that adapter is born.
402
+ */
403
+ private activeSessionNeedsProbe;
404
+ readonly registryClient: RegistryClient;
405
+ private logger;
406
+ /** Configured log verbosity; filtering happens centrally in {@link log}. */
407
+ private readonly logLevel;
408
+ private crypto;
409
+ private storage;
410
+ private telemetry?;
411
+ /** Cached announce-discovery picker entries (one-shot; cleared by refreshDiscovery). */
412
+ private announceEntriesCache;
413
+ private readonly announceRegistry;
414
+ private readonly announceChannels;
415
+ private announceUnsubscribe;
416
+ /** Pending debounced `wallets:changed` emit (coalesces an announce burst). */
417
+ private walletsChangedTimer;
418
+ private origin;
419
+ private readonly nativeOwner?;
420
+ private sessionProvider?;
421
+ constructor(config: PartyLayerBaseConfig, runtime?: ClientRuntime);
422
+ /** Start browser discovery/restoration once; safe for framework effect replay. */
423
+ initialize(): void;
424
+ private announceChannel;
425
+ /**
426
+ * Register a wallet adapter
427
+ *
428
+ * @internal
429
+ * This is used internally by the SDK to register adapters.
430
+ * In production, adapters would be auto-registered via registry.
431
+ */
432
+ registerAdapter(adapter: WalletAdapter): void;
433
+ private onNativeIdentityChanged;
434
+ /**
435
+ * Look up a registered adapter by wallet id.
436
+ *
437
+ * Returns the adapter instance when one is registered for the given
438
+ * `walletId`, or `undefined` otherwise. Intended for UI integrations
439
+ * that need to call `adapter.detectInstalled()` directly to render a
440
+ * per-wallet readiness indicator (instead of duplicating
441
+ * transport-specific install detection logic in the picker). The
442
+ * returned adapter is the same instance used internally for connect /
443
+ * sign / submit flows; do not mutate it.
444
+ *
445
+ * Accepts both raw string ids and the branded `WalletId` form so
446
+ * consumers can pass `walletInfo.walletId` or a string literal
447
+ * interchangeably.
448
+ */
449
+ getAdapter(walletId: string | WalletId): WalletAdapter | undefined;
450
+ /**
451
+ * List available wallets
452
+ */
453
+ listWallets(filter?: WalletFilter): Promise<WalletInfo[]>;
454
+ /** Resolve only reviewed default SDKs present in the active registry. */
455
+ private ensureDefaultWallets;
456
+ private registryNetworkSupported;
457
+ /**
458
+ * Hide registry entries whose wallet needs an app-registered adapter that is
459
+ * NOT registered. This is the library default (RainbowKit-style): never show a
460
+ * wallet the app cannot actually connect.
461
+ *
462
+ * A wallet is connectable with NO app adapter only when it is driven by the
463
+ * generic announce path (`adapter.transport: 'announce'`, e.g. Console, Send):
464
+ * there the SDK builds a generic announce adapter from the registry entry on
465
+ * demand, so installing the extension is enough and the entry stays visible.
466
+ * Every other transport can only connect through an adapter the app registered:
467
+ * a `discovery-adapter` popup/remote wallet whose official ProviderAdapter
468
+ * the app supplies (bridged under `toWalletId(providerId)`), or a wallet that
469
+ * ships a PartyLayer adapter package (Loop, Cantor8, Nightly, Bron,
470
+ * WalletConnect). Without that adapter, clicking the entry can only fail
471
+ * (connect throws), so it surfaces only when the adapter is present.
472
+ *
473
+ * The decision reads each entry's DECLARED transport, never a hardcoded wallet
474
+ * list. No-op when the registry is unavailable (the list is already
475
+ * adapters-only) or every non-announce entry is registered.
476
+ */
477
+ private gateUnconnectableEntries;
478
+ /**
479
+ * If `walletId` maps to a registry entry with `transport: 'discovery-adapter'`,
480
+ * return the bits to build an actionable "register its adapter" error; else
481
+ * null (truly-unknown or non-discovery → plain WalletNotFoundError). Reads the
482
+ * UNGATED registry (SWR-cached); registry-unavailable → null (safe fallback).
483
+ */
484
+ private unregisteredDiscoveryInfo;
485
+ /**
486
+ * Whether announce discovery is active: explicit `discovery.announce`, else
487
+ * ON in the browser and OFF under SSR (no `window`). Canonical: provider.md.
488
+ */
489
+ private get announceEnabled();
490
+ /**
491
+ * Clear the cached announce round-trip so the next `listWallets()` re-runs the
492
+ * `canton:requestProvider` handshake (e.g. after a wallet is installed).
493
+ */
494
+ refreshDiscovery(): void;
495
+ /**
496
+ * Persistent-accumulator callback (mounted at construction). On each newly
497
+ * announced provider:
498
+ * 1. record it in the live `announceRegistry` (unchanged);
499
+ * 2. invalidate the one-shot `announceEntriesCache` — the SAME invalidation
500
+ * as {@link refreshDiscovery}, so the next `listWallets()` re-aggregates
501
+ * and surfaces the wallet. This does NOT touch `warmPlans` (those hold
502
+ * only GenericDiscoveryAdapter popup plans — a disjoint set);
503
+ * 3. emit a DEBOUNCED `wallets:changed` signal so a reactive consumer (e.g.
504
+ * the React provider) re-lists. The debounce coalesces a burst — and the
505
+ * construction-time reply storm — into one emit (no re-discovery storm).
506
+ *
507
+ * Byte-identical idle: with zero announces this never fires — no invalidation,
508
+ * no emit, no re-list.
509
+ */
510
+ private onAnnounceAccumulated;
511
+ /**
512
+ * Aggregate `canton:announceProvider` wallets into the picker list (A2).
513
+ *
514
+ * One-shot cached per client (refresh via {@link refreshDiscovery}); SSR-skipped.
515
+ * For each discovered provider (announce ∪ `window.canton` scan, deduped):
516
+ * - if its id matches a known wallet's `providerDetection` (provider.id) it
517
+ * IS that wallet — no new entry (identity bridge: Console's `lpnf…` → the
518
+ * `console` entry, Send's `ldmo…` → the `send` entry);
519
+ * - otherwise it is surfaced as a dynamic `browser:ext:<id>` entry routed to
520
+ * its own extension `target`, with a {@link GenericAnnounceAdapter}
521
+ * registered so a click connects through that target ONLY (no shared slot).
522
+ * With zero announcers this returns `base` unchanged.
523
+ */
524
+ private aggregateAnnouncedWallets;
525
+ /** Active network-enforcement policy (default 'guard'). */
526
+ private get enforcement();
527
+ /**
528
+ * Detect a confident network mismatch between the dApp's configured network
529
+ * and the session's (wallet-reported) network. Returns null when they match
530
+ * or the comparison isn't confident (conservative — never a false positive).
531
+ */
532
+ private networkMismatch;
533
+ /**
534
+ * Guard a transaction-class operation: throw `NetworkMismatchError` when the
535
+ * session is on the wrong network AND the policy enforces it ('guard' |
536
+ * 'strict'). Also protects restored sessions and mid-session network switches.
537
+ */
538
+ private assertNetworkOk;
539
+ /**
540
+ * Connect to a wallet
541
+ */
542
+ connect(options?: ConnectOptions): Promise<Session>;
543
+ /**
544
+ * Pre-resolve everything `adapter.connect()` needs WITHOUT calling it: wallet
545
+ * selection, origin-allowlist + capability + install guards, and the adapter
546
+ * context. `prefetchedWallets` (passed during warm-up from `listWallets`)
547
+ * avoids a recursive `listWallets()` call.
548
+ */
549
+ private resolveConnectPlan;
550
+ /**
551
+ * Generate secure entropy, invoke `adapter.connect()` without awaiting the
552
+ * platform RNG path, then build / persist / emit the session. Separated from plan resolution so the
553
+ * popup-safe fast-path can call it gesture-synchronously.
554
+ */
555
+ private completeConnect;
556
+ /**
557
+ * PUBLIC popup-safe primitive: pre-resolve a connect plan ahead of the user
558
+ * gesture; the returned `connect()` invokes `adapter.connect()` as its first
559
+ * statement (no await precedes it) so a popup/remote wallet's `window.open`
560
+ * survives the gesture. For consumers driving such a wallet outside the modal
561
+ * (the modal gets this for free via the `listWallets` warm-up + `connect()`).
562
+ */
563
+ prepareConnect(options?: ConnectOptions): Promise<{
564
+ walletId: WalletId;
565
+ connect: (o?: ConnectOptions) => Promise<Session>;
566
+ }>;
567
+ /**
568
+ * Background warm-up of connect plans for popup/remote
569
+ * (`GenericDiscoveryAdapter`) wallets. Popup-free — `resolveConnectPlan` only
570
+ * runs read/guard probes. Skips already-warm entries; never throws.
571
+ */
572
+ private warmDiscoveryPlans;
573
+ /**
574
+ * SYNCHRONOUS fast-path: if a fresh warm plan exists for a popup/remote wallet
575
+ * — and `options` carries no plan-affecting guards — consume it and START
576
+ * `completeConnect` immediately, reaching `adapter.connect()` with no awaits.
577
+ * Returns the in-flight Session promise, or null to fall back to the normal
578
+ * path (e.g. cold cache, or a non-discovery wallet).
579
+ */
580
+ private tryFastConnect;
581
+ /**
582
+ * Disconnect from wallet
583
+ */
584
+ disconnect(): Promise<void>;
585
+ /**
586
+ * Get active session
587
+ */
588
+ getActiveSession(): Promise<Session | null>;
589
+ /**
590
+ * Sign a message
591
+ */
592
+ signMessage(params: SignMessageParams): Promise<SignedMessage>;
593
+ /**
594
+ * Sign a transaction
595
+ */
596
+ signTransaction(params: SignTransactionParams): Promise<SignedTransaction>;
597
+ /**
598
+ * Submit a transaction
599
+ */
600
+ submitTransaction(params: SubmitTransactionParams): Promise<TxReceipt>;
601
+ /**
602
+ * Proxy a JSON Ledger API request through the active wallet adapter
603
+ */
604
+ ledgerApi(params: LedgerApiParams): Promise<LedgerApiResult>;
605
+ /**
606
+ * Request a typed transfer. The application says what it wants; the wallet
607
+ * builds the command, shows the user what they are authorising, obtains their
608
+ * approval, signs, executes, and returns the real update id.
609
+ *
610
+ * The acting party comes from the active session, never from the caller, and
611
+ * the intent is narrowed to the allowlisted fields before any adapter sees it,
612
+ * so no caller-supplied option can reach the wallet.
613
+ *
614
+ * Throws `CapabilityNotSupportedError` when the active wallet does not
615
+ * implement it. Ask first with `session.capabilitiesSnapshot.includes('transfer')`,
616
+ * or require it at connect with `connect({ requiredCapabilities: ['transfer'] })`.
617
+ */
618
+ requestTransfer(intent: TransferIntent): Promise<TransferResult>;
619
+ /**
620
+ * Subscribe to events
621
+ */
622
+ on<T extends PartyLayerEvent>(event: T['type'], handler: EventHandler<T>): () => void;
623
+ /**
624
+ * Unsubscribe from events
625
+ */
626
+ off<T extends PartyLayerEvent>(event: T['type'], handler: EventHandler<T>): void;
627
+ /**
628
+ * Get the stable provider facade for this client.
629
+ *
630
+ * Browser-native connections expose the official owner's actual accounts,
631
+ * network, execution/events and raw Ledger API response, including standard
632
+ * path/query/header request fields. Signing keeps the reviewed encoding policy.
633
+ * Existing proprietary/custom integrations retain their compatibility bridge.
634
+ * `createProviderBridge(client)` remains available explicitly for legacy callers.
635
+ * Full async server user-URL orchestration needs a verified direct provider path.
636
+ *
637
+ * @returns Stable CIP-0103 provider facade
638
+ */
639
+ asProvider(): _partylayer_core.CIP0103Provider;
640
+ /**
641
+ * Destroy client and cleanup
642
+ */
643
+ destroy(): void;
644
+ /**
645
+ * Create adapter context
646
+ */
647
+ private createAdapterContext;
648
+ /**
649
+ * Persist session to storage
650
+ */
651
+ private persistSession;
652
+ /**
653
+ * Remove session from storage.
654
+ *
655
+ * Accepts a sessionId for call-site symmetry, but since the SDK tracks one
656
+ * active session we always remove the single SESSION_STORAGE_KEY.
657
+ */
658
+ private removeSession;
659
+ /**
660
+ * Restore session from storage
661
+ */
662
+ private restoreSession;
663
+ private restoreSessionOnce;
664
+ /**
665
+ * Update registry status and emit event
666
+ */
667
+ private updateRegistryStatus;
668
+ /**
669
+ * Get registry status
670
+ */
671
+ getRegistryStatus(): RegistryStatus | null;
672
+ /**
673
+ * Emit event to handlers
674
+ */
675
+ /**
676
+ * Central structured log. Filters by the configured level here, before the adapter
677
+ * is called, so adapters never filter themselves; skips entirely when no real
678
+ * logger was configured (the no-op default), so a silent client pays only a check.
679
+ * Every line carries a machine readable payload `{ event, correlationId?, ...fields }`.
680
+ * Privacy: callers pass only non identifying fields, the same rule as telemetry.
681
+ */
682
+ private log;
683
+ private emit;
684
+ }
685
+
686
+ /** The authenticated wallet owns transport and authorization. No participant credentials are accepted. */
687
+ interface WalletLedgerClient {
688
+ getActiveSession(): Promise<Session | null>;
689
+ asProvider(): {
690
+ request<T = unknown>(args: {
691
+ method: string;
692
+ params?: unknown;
693
+ }): Promise<T>;
694
+ };
695
+ }
696
+ interface WalletLedgerReaderOptions {
697
+ /** Explicit expected CAIP-2 network. Never infer a network from an update id. */
698
+ networkId: string;
699
+ /** Exact package-id-qualified HoldingV1 interface id from the asset deployment. */
700
+ holdingInterfaceId?: string;
701
+ /** Exact package-id-qualified HoldingV2 interface id; never inferred from V1. */
702
+ holdingV2InterfaceId?: string;
703
+ /** Default 30s; applies to the complete read, including session checks. */
704
+ timeoutMs?: number;
705
+ /** Reject snapshots at this boundary rather than display potentially incomplete balances. Default 1000. */
706
+ maxContracts?: number;
707
+ }
708
+ interface WalletHoldingsSnapshot {
709
+ walletId: string;
710
+ partyId: string;
711
+ networkId: string;
712
+ offset: number;
713
+ holdings: TokenHoldingRef[];
714
+ }
715
+ interface WalletHoldingsV2Snapshot extends Omit<WalletHoldingsSnapshot, 'holdings'> {
716
+ holdings: TokenHoldingV2Ref[];
717
+ }
718
+ interface WalletTransactionReference {
719
+ walletId: string;
720
+ partyId: string;
721
+ networkId: string;
722
+ /** Original command id generated by the app BEFORE submission, not copied from an untrusted receipt. */
723
+ commandId?: string;
724
+ receipt?: TxReceipt;
725
+ updateId?: string;
726
+ }
727
+ type WalletTransactionConfirmation = {
728
+ status: 'confirmed';
729
+ updateId: string;
730
+ } | {
731
+ status: 'unknown';
732
+ reason: string;
733
+ };
734
+ /**
735
+ * Read-only JSON Ledger API v2 adapter using CIP-0103 ledgerApi. Uses eventFormat
736
+ * and update-by-id (not the removed transaction-by-id endpoint). A wallet may
737
+ * restrict these endpoints; errors remain errors, never empty balances/success.
738
+ */
739
+ declare function createWalletLedgerReader(client: WalletLedgerClient, options: WalletLedgerReaderOptions): {
740
+ /** A bounded, complete ACS snapshot of the connected party's configured HoldingV1 interface. */
741
+ readHoldings(signal?: AbortSignal): Promise<WalletHoldingsSnapshot>;
742
+ /** Owned V2 accounts only. Provider visibility and ownerless admin accounts do not confer ownership. */
743
+ readHoldingsV2(signal?: AbortSignal): Promise<WalletHoldingsV2Snapshot>;
744
+ /** One read, never polling or resubmission. Unknown remains unknown if ids cannot be correlated. */
745
+ confirmTransaction({ transaction, signal }: {
746
+ transaction: WalletTransactionReference;
747
+ signal?: AbortSignal;
748
+ }): Promise<WalletTransactionConfirmation>;
749
+ };
750
+ type WalletLedgerReader = ReturnType<typeof createWalletLedgerReader>;
751
+
752
+ interface ApplicationLedgerReaderOptions extends WalletLedgerReaderOptions {
753
+ /** Same-origin application endpoint implementing the narrow version-1 read contract. */
754
+ endpoint: string;
755
+ /** Stable app-owned ledger source name; never a caller-selected participant URL. */
756
+ sourceId: string;
757
+ /** Required outside the browser. In the browser it must equal location.origin. */
758
+ origin?: string;
759
+ fetch?: typeof globalThis.fetch;
760
+ }
761
+ /**
762
+ * Cookie-authenticated application read preset. The server must derive party and
763
+ * network from its own session and rebuild authorized read filters. No wallet
764
+ * capability is invented when the app backend, rather than the wallet, reads.
765
+ */
766
+ declare function createApplicationLedgerReader(client: WalletLedgerClient, options: ApplicationLedgerReaderOptions): {
767
+ readHoldings(signal?: AbortSignal): Promise<WalletHoldingsSnapshot>;
768
+ readHoldingsV2(signal?: AbortSignal): Promise<WalletHoldingsV2Snapshot>;
769
+ confirmTransaction({ transaction, signal }: {
770
+ transaction: WalletTransactionReference;
771
+ signal?: AbortSignal;
772
+ }): Promise<WalletTransactionConfirmation>;
773
+ };
774
+
775
+ export { type AdapterClass as A, type ConnectOptions as C, DEFAULT_REGISTRY_URL as D, type ErrorEvent as E, type PartyLayerBaseConfig as P, type RegistryUpdatedEvent as R, type SessionConnectedEvent as S, type TelemetryConfig as T, type WalletFilter as W, PartyLayerClientBase as a, type ApplicationLedgerReaderOptions as b, type PartyLayerEvent as c, type EventHandler as d, type SessionDisconnectedEvent as e, type SessionExpiredEvent as f, type TxStatusEvent as g, type WalletHoldingsSnapshot as h, type WalletHoldingsV2Snapshot as i, type WalletLedgerClient as j, type WalletLedgerReader as k, type WalletLedgerReaderOptions as l, type WalletTransactionConfirmation as m, type WalletTransactionReference as n, type WalletsChangedEvent as o, createApplicationLedgerReader as p, createWalletLedgerReader as q };