@partylayer/sdk 0.20.1 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -119,10 +119,20 @@ Your app constructs valid commands and independently confirms ledger settlement.
119
119
 
120
120
  ## Native CIP-0103 provider and migration
121
121
 
122
+ Starting with SDK 0.21.0, `createWalletLedgerReader(client, { networkId, holdingInterfaceId })` provides
123
+ read-only, session-bound JSON Ledger API v2 holdings snapshots and independent
124
+ transaction confirmation by original command id and real update id. Wallets must
125
+ expose `ledgerApi`; unsupported responses fail instead of appearing as zero
126
+ balances or confirmed transfers. See the [reader guide](https://github.com/PartyLayer/PartyLayer/blob/main/docs/wallet-ledger-reader.md).
127
+
122
128
  Use `client.asProvider()` for the connected provider surface. Native connections use official Canton discovery and forward native accounts, events and Ledger API requests through a stable facade. Native Ledger API responses are **raw JSON**. Existing `client.ledgerApi()` and explicit `createProviderBridge(client)` compatibility paths retain their documented wrapper/limits.
123
129
 
124
130
  Existing native caches without the official provider hint need one explicit reconnect. Restored state must agree with the wallet's live party, network, origin and expiry. See [protocol ownership and migration](https://github.com/PartyLayer/PartyLayer/blob/main/docs/protocol-ownership.md).
125
131
 
132
+ `createApplicationLedgerReader` uses the same validation through an explicitly
133
+ configured, same-origin application endpoint instead. Its server session authorizes
134
+ the party/network; it does not require or pretend the wallet has a ledger proxy.
135
+
126
136
  ## Errors and cleanup
127
137
 
128
138
  Handle user rejection, unavailable wallets, timeouts, network mismatch and unsupported capabilities as separate application states. Do not silently retry a ledger write after an ambiguous error. See [error handling](https://partylayer.xyz/docs/error-handling).
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _partylayer_core from '@partylayer/core';
2
- import { WalletAdapter, NetworkId, OfficialProviderAdapter, OfficialAdapterFactory, StorageAdapter, CryptoAdapter, TelemetryAdapter, LoggerAdapter, WalletId, Session, SessionId, TransactionHash, TransactionStatus, WalletInfo, SignMessageParams, SignedMessage, SignTransactionParams, SignedTransaction, SubmitTransactionParams, TxReceipt, LedgerApiParams, LedgerApiResult, TransferIntent, TransferResult, CIP0103Provider, CapabilityKey, AdapterDetectResult, AdapterContext, AdapterConnectResult, NetworkHosts, PersistedSession } from '@partylayer/core';
2
+ import { WalletAdapter, NetworkId, OfficialProviderAdapter, OfficialAdapterFactory, StorageAdapter, CryptoAdapter, TelemetryAdapter, LoggerAdapter, WalletId, Session, SessionId, TransactionHash, TransactionStatus, WalletInfo, SignMessageParams, SignedMessage, SignTransactionParams, SignedTransaction, SubmitTransactionParams, TxReceipt, LedgerApiParams, LedgerApiResult, TransferIntent, TransferResult, TokenHoldingRef, CIP0103Provider, CapabilityKey, AdapterDetectResult, AdapterContext, AdapterConnectResult, NetworkHosts, PersistedSession } from '@partylayer/core';
3
3
  export { AdapterConnectResult, AdapterContext, AdapterDetectResult, AdapterNotRegisteredError, PartyLayerError as CantonConnectError, CapabilityKey, CapabilityNotSupportedError, ENABLEMENT_METRICS, ERROR_METRICS, ErrorCode, InternalError, LedgerApiParams, LedgerApiResult, METRICS, MetricName, MetricsPayload, NetworkHosts, NetworkId, OfficialAdapterFactory, OfficialProviderAdapter, OriginNotAllowedError, PartyId, PartyLayerError, REGISTRY_METRICS, RegistryFetchFailedError, RegistrySchemaInvalidError, RegistryVerificationFailedError, Session, SessionExpiredError, SessionId, SignMessageParams, SignTransactionParams, SignedMessage, SignedTransaction, SubmitTransactionParams, TRANSFER_INTENT_FIELDS, TimeoutError, TokenInstrumentId, TransactionStatus, TransferIntent, TransferResult, TransportError, TxReceipt, UserRejectedError, WalletAdapter, WalletId, WalletInfo, WalletNotFoundError, WalletNotInstalledError, errorMetricName, isOfficialAdapterFactory, isOfficialProviderAdapter, toTransferIntent } from '@partylayer/core';
4
4
  import { RegistryClient, RegistryStatus } from '@partylayer/registry-client';
5
5
  export { Cip0103StatusForDetection, Cip0103Support, ProviderDetection, ProviderMatcher, RegistryStatus, deriveGenericWalletName, findMatchingWallet, findMatchingWalletInfo, isCip0103Native, matchesProviderDetection } from '@partylayer/registry-client';
@@ -646,6 +646,87 @@ declare class PartyLayerClient {
646
646
  */
647
647
  declare function createPartyLayer(config: PartyLayerConfig): PartyLayerClient;
648
648
 
649
+ /** The authenticated wallet owns transport and authorization. No participant credentials are accepted. */
650
+ interface WalletLedgerClient {
651
+ getActiveSession(): Promise<Session | null>;
652
+ asProvider(): {
653
+ request<T = unknown>(args: {
654
+ method: string;
655
+ params?: unknown;
656
+ }): Promise<T>;
657
+ };
658
+ }
659
+ interface WalletLedgerReaderOptions {
660
+ /** Explicit expected CAIP-2 network. Never infer a network from an update id. */
661
+ networkId: string;
662
+ /** Exact package-id-qualified HoldingV1 interface id from the asset deployment. */
663
+ holdingInterfaceId?: string;
664
+ /** Default 30s; applies to the complete read, including session checks. */
665
+ timeoutMs?: number;
666
+ /** Reject snapshots at this boundary rather than display potentially incomplete balances. Default 1000. */
667
+ maxContracts?: number;
668
+ }
669
+ interface WalletHoldingsSnapshot {
670
+ walletId: string;
671
+ partyId: string;
672
+ networkId: string;
673
+ offset: number;
674
+ holdings: TokenHoldingRef[];
675
+ }
676
+ interface WalletTransactionReference {
677
+ walletId: string;
678
+ partyId: string;
679
+ networkId: string;
680
+ /** Original command id generated by the app BEFORE submission, not copied from an untrusted receipt. */
681
+ commandId?: string;
682
+ receipt?: TxReceipt;
683
+ updateId?: string;
684
+ }
685
+ type WalletTransactionConfirmation = {
686
+ status: 'confirmed';
687
+ updateId: string;
688
+ } | {
689
+ status: 'unknown';
690
+ reason: string;
691
+ };
692
+ /**
693
+ * Read-only JSON Ledger API v2 adapter using CIP-0103 ledgerApi. Uses eventFormat
694
+ * and update-by-id (not the removed transaction-by-id endpoint). A wallet may
695
+ * restrict these endpoints; errors remain errors, never empty balances/success.
696
+ */
697
+ declare function createWalletLedgerReader(client: WalletLedgerClient, options: WalletLedgerReaderOptions): {
698
+ /** A bounded, complete ACS snapshot of the connected party's configured HoldingV1 interface. */
699
+ readHoldings(signal?: AbortSignal): Promise<WalletHoldingsSnapshot>;
700
+ /** One read, never polling or resubmission. Unknown remains unknown if ids cannot be correlated. */
701
+ confirmTransaction({ transaction, signal }: {
702
+ transaction: WalletTransactionReference;
703
+ signal?: AbortSignal;
704
+ }): Promise<WalletTransactionConfirmation>;
705
+ };
706
+ type WalletLedgerReader = ReturnType<typeof createWalletLedgerReader>;
707
+
708
+ interface ApplicationLedgerReaderOptions extends WalletLedgerReaderOptions {
709
+ /** Same-origin application endpoint implementing the narrow version-1 read contract. */
710
+ endpoint: string;
711
+ /** Stable app-owned ledger source name; never a caller-selected participant URL. */
712
+ sourceId: string;
713
+ /** Required outside the browser. In the browser it must equal location.origin. */
714
+ origin?: string;
715
+ fetch?: typeof globalThis.fetch;
716
+ }
717
+ /**
718
+ * Cookie-authenticated application read preset. The server must derive party and
719
+ * network from its own session and rebuild authorized read filters. No wallet
720
+ * capability is invented when the app backend, rather than the wallet, reads.
721
+ */
722
+ declare function createApplicationLedgerReader(client: WalletLedgerClient, options: ApplicationLedgerReaderOptions): {
723
+ readHoldings(signal?: AbortSignal): Promise<WalletHoldingsSnapshot>;
724
+ confirmTransaction({ transaction, signal }: {
725
+ transaction: WalletTransactionReference;
726
+ signal?: AbortSignal;
727
+ }): Promise<WalletTransactionConfirmation>;
728
+ };
729
+
649
730
  /**
650
731
  * Dynamic adapter for an announced CIP-0103 wallet that has no first-party
651
732
  * PartyLayer adapter.
@@ -1076,4 +1157,4 @@ declare function isTelemetryConfig(value: unknown): value is TelemetryConfig;
1076
1157
  */
1077
1158
  declare function createTelemetryAdapter(config: TelemetryAdapter | TelemetryConfig | undefined): TelemetryAdapter | undefined;
1078
1159
 
1079
- export { ANNOUNCED_WALLET_ID_PREFIX, type AdapterClass, PartyLayerClient as CantonConnectClient, type PartyLayerConfig as CantonConnectConfig, type PartyLayerEvent as CantonConnectEvent, type ConnectOptions, DEFAULT_REGISTRY_URL, type ErrorEvent, type EventHandler, GenericAnnounceAdapter, type GenericAnnounceAdapterArgs, GenericDiscoveryAdapter, type GenericDiscoveryAdapterArgs, MetricsTelemetryAdapter, PartyLayerClient, type PartyLayerConfig, type PartyLayerEvent, type RegistryUpdatedEvent, type SessionConnectedEvent, type SessionDisconnectedEvent, type SessionExpiredEvent, type TelemetryConfig, type TxStatusEvent, type WalletFilter, type WalletsChangedEvent, PartyLayerClient as _PartyLayerClientInternal, announcedWalletId, createPartyLayer as createCantonConnect, createPartyLayer, createTelemetryAdapter, getBuiltinAdapters, getDiscoveryCapabilities, isTelemetryConfig };
1160
+ export { ANNOUNCED_WALLET_ID_PREFIX, type AdapterClass, type ApplicationLedgerReaderOptions, PartyLayerClient as CantonConnectClient, type PartyLayerConfig as CantonConnectConfig, type PartyLayerEvent as CantonConnectEvent, type ConnectOptions, DEFAULT_REGISTRY_URL, type ErrorEvent, type EventHandler, GenericAnnounceAdapter, type GenericAnnounceAdapterArgs, GenericDiscoveryAdapter, type GenericDiscoveryAdapterArgs, MetricsTelemetryAdapter, PartyLayerClient, type PartyLayerConfig, type PartyLayerEvent, type RegistryUpdatedEvent, type SessionConnectedEvent, type SessionDisconnectedEvent, type SessionExpiredEvent, type TelemetryConfig, type TxStatusEvent, type WalletFilter, type WalletHoldingsSnapshot, type WalletLedgerClient, type WalletLedgerReader, type WalletLedgerReaderOptions, type WalletTransactionConfirmation, type WalletTransactionReference, type WalletsChangedEvent, PartyLayerClient as _PartyLayerClientInternal, announcedWalletId, createApplicationLedgerReader, createPartyLayer as createCantonConnect, createPartyLayer, createTelemetryAdapter, createWalletLedgerReader, getBuiltinAdapters, getDiscoveryCapabilities, isTelemetryConfig };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _partylayer_core from '@partylayer/core';
2
- import { WalletAdapter, NetworkId, OfficialProviderAdapter, OfficialAdapterFactory, StorageAdapter, CryptoAdapter, TelemetryAdapter, LoggerAdapter, WalletId, Session, SessionId, TransactionHash, TransactionStatus, WalletInfo, SignMessageParams, SignedMessage, SignTransactionParams, SignedTransaction, SubmitTransactionParams, TxReceipt, LedgerApiParams, LedgerApiResult, TransferIntent, TransferResult, CIP0103Provider, CapabilityKey, AdapterDetectResult, AdapterContext, AdapterConnectResult, NetworkHosts, PersistedSession } from '@partylayer/core';
2
+ import { WalletAdapter, NetworkId, OfficialProviderAdapter, OfficialAdapterFactory, StorageAdapter, CryptoAdapter, TelemetryAdapter, LoggerAdapter, WalletId, Session, SessionId, TransactionHash, TransactionStatus, WalletInfo, SignMessageParams, SignedMessage, SignTransactionParams, SignedTransaction, SubmitTransactionParams, TxReceipt, LedgerApiParams, LedgerApiResult, TransferIntent, TransferResult, TokenHoldingRef, CIP0103Provider, CapabilityKey, AdapterDetectResult, AdapterContext, AdapterConnectResult, NetworkHosts, PersistedSession } from '@partylayer/core';
3
3
  export { AdapterConnectResult, AdapterContext, AdapterDetectResult, AdapterNotRegisteredError, PartyLayerError as CantonConnectError, CapabilityKey, CapabilityNotSupportedError, ENABLEMENT_METRICS, ERROR_METRICS, ErrorCode, InternalError, LedgerApiParams, LedgerApiResult, METRICS, MetricName, MetricsPayload, NetworkHosts, NetworkId, OfficialAdapterFactory, OfficialProviderAdapter, OriginNotAllowedError, PartyId, PartyLayerError, REGISTRY_METRICS, RegistryFetchFailedError, RegistrySchemaInvalidError, RegistryVerificationFailedError, Session, SessionExpiredError, SessionId, SignMessageParams, SignTransactionParams, SignedMessage, SignedTransaction, SubmitTransactionParams, TRANSFER_INTENT_FIELDS, TimeoutError, TokenInstrumentId, TransactionStatus, TransferIntent, TransferResult, TransportError, TxReceipt, UserRejectedError, WalletAdapter, WalletId, WalletInfo, WalletNotFoundError, WalletNotInstalledError, errorMetricName, isOfficialAdapterFactory, isOfficialProviderAdapter, toTransferIntent } from '@partylayer/core';
4
4
  import { RegistryClient, RegistryStatus } from '@partylayer/registry-client';
5
5
  export { Cip0103StatusForDetection, Cip0103Support, ProviderDetection, ProviderMatcher, RegistryStatus, deriveGenericWalletName, findMatchingWallet, findMatchingWalletInfo, isCip0103Native, matchesProviderDetection } from '@partylayer/registry-client';
@@ -646,6 +646,87 @@ declare class PartyLayerClient {
646
646
  */
647
647
  declare function createPartyLayer(config: PartyLayerConfig): PartyLayerClient;
648
648
 
649
+ /** The authenticated wallet owns transport and authorization. No participant credentials are accepted. */
650
+ interface WalletLedgerClient {
651
+ getActiveSession(): Promise<Session | null>;
652
+ asProvider(): {
653
+ request<T = unknown>(args: {
654
+ method: string;
655
+ params?: unknown;
656
+ }): Promise<T>;
657
+ };
658
+ }
659
+ interface WalletLedgerReaderOptions {
660
+ /** Explicit expected CAIP-2 network. Never infer a network from an update id. */
661
+ networkId: string;
662
+ /** Exact package-id-qualified HoldingV1 interface id from the asset deployment. */
663
+ holdingInterfaceId?: string;
664
+ /** Default 30s; applies to the complete read, including session checks. */
665
+ timeoutMs?: number;
666
+ /** Reject snapshots at this boundary rather than display potentially incomplete balances. Default 1000. */
667
+ maxContracts?: number;
668
+ }
669
+ interface WalletHoldingsSnapshot {
670
+ walletId: string;
671
+ partyId: string;
672
+ networkId: string;
673
+ offset: number;
674
+ holdings: TokenHoldingRef[];
675
+ }
676
+ interface WalletTransactionReference {
677
+ walletId: string;
678
+ partyId: string;
679
+ networkId: string;
680
+ /** Original command id generated by the app BEFORE submission, not copied from an untrusted receipt. */
681
+ commandId?: string;
682
+ receipt?: TxReceipt;
683
+ updateId?: string;
684
+ }
685
+ type WalletTransactionConfirmation = {
686
+ status: 'confirmed';
687
+ updateId: string;
688
+ } | {
689
+ status: 'unknown';
690
+ reason: string;
691
+ };
692
+ /**
693
+ * Read-only JSON Ledger API v2 adapter using CIP-0103 ledgerApi. Uses eventFormat
694
+ * and update-by-id (not the removed transaction-by-id endpoint). A wallet may
695
+ * restrict these endpoints; errors remain errors, never empty balances/success.
696
+ */
697
+ declare function createWalletLedgerReader(client: WalletLedgerClient, options: WalletLedgerReaderOptions): {
698
+ /** A bounded, complete ACS snapshot of the connected party's configured HoldingV1 interface. */
699
+ readHoldings(signal?: AbortSignal): Promise<WalletHoldingsSnapshot>;
700
+ /** One read, never polling or resubmission. Unknown remains unknown if ids cannot be correlated. */
701
+ confirmTransaction({ transaction, signal }: {
702
+ transaction: WalletTransactionReference;
703
+ signal?: AbortSignal;
704
+ }): Promise<WalletTransactionConfirmation>;
705
+ };
706
+ type WalletLedgerReader = ReturnType<typeof createWalletLedgerReader>;
707
+
708
+ interface ApplicationLedgerReaderOptions extends WalletLedgerReaderOptions {
709
+ /** Same-origin application endpoint implementing the narrow version-1 read contract. */
710
+ endpoint: string;
711
+ /** Stable app-owned ledger source name; never a caller-selected participant URL. */
712
+ sourceId: string;
713
+ /** Required outside the browser. In the browser it must equal location.origin. */
714
+ origin?: string;
715
+ fetch?: typeof globalThis.fetch;
716
+ }
717
+ /**
718
+ * Cookie-authenticated application read preset. The server must derive party and
719
+ * network from its own session and rebuild authorized read filters. No wallet
720
+ * capability is invented when the app backend, rather than the wallet, reads.
721
+ */
722
+ declare function createApplicationLedgerReader(client: WalletLedgerClient, options: ApplicationLedgerReaderOptions): {
723
+ readHoldings(signal?: AbortSignal): Promise<WalletHoldingsSnapshot>;
724
+ confirmTransaction({ transaction, signal }: {
725
+ transaction: WalletTransactionReference;
726
+ signal?: AbortSignal;
727
+ }): Promise<WalletTransactionConfirmation>;
728
+ };
729
+
649
730
  /**
650
731
  * Dynamic adapter for an announced CIP-0103 wallet that has no first-party
651
732
  * PartyLayer adapter.
@@ -1076,4 +1157,4 @@ declare function isTelemetryConfig(value: unknown): value is TelemetryConfig;
1076
1157
  */
1077
1158
  declare function createTelemetryAdapter(config: TelemetryAdapter | TelemetryConfig | undefined): TelemetryAdapter | undefined;
1078
1159
 
1079
- export { ANNOUNCED_WALLET_ID_PREFIX, type AdapterClass, PartyLayerClient as CantonConnectClient, type PartyLayerConfig as CantonConnectConfig, type PartyLayerEvent as CantonConnectEvent, type ConnectOptions, DEFAULT_REGISTRY_URL, type ErrorEvent, type EventHandler, GenericAnnounceAdapter, type GenericAnnounceAdapterArgs, GenericDiscoveryAdapter, type GenericDiscoveryAdapterArgs, MetricsTelemetryAdapter, PartyLayerClient, type PartyLayerConfig, type PartyLayerEvent, type RegistryUpdatedEvent, type SessionConnectedEvent, type SessionDisconnectedEvent, type SessionExpiredEvent, type TelemetryConfig, type TxStatusEvent, type WalletFilter, type WalletsChangedEvent, PartyLayerClient as _PartyLayerClientInternal, announcedWalletId, createPartyLayer as createCantonConnect, createPartyLayer, createTelemetryAdapter, getBuiltinAdapters, getDiscoveryCapabilities, isTelemetryConfig };
1160
+ export { ANNOUNCED_WALLET_ID_PREFIX, type AdapterClass, type ApplicationLedgerReaderOptions, PartyLayerClient as CantonConnectClient, type PartyLayerConfig as CantonConnectConfig, type PartyLayerEvent as CantonConnectEvent, type ConnectOptions, DEFAULT_REGISTRY_URL, type ErrorEvent, type EventHandler, GenericAnnounceAdapter, type GenericAnnounceAdapterArgs, GenericDiscoveryAdapter, type GenericDiscoveryAdapterArgs, MetricsTelemetryAdapter, PartyLayerClient, type PartyLayerConfig, type PartyLayerEvent, type RegistryUpdatedEvent, type SessionConnectedEvent, type SessionDisconnectedEvent, type SessionExpiredEvent, type TelemetryConfig, type TxStatusEvent, type WalletFilter, type WalletHoldingsSnapshot, type WalletLedgerClient, type WalletLedgerReader, type WalletLedgerReaderOptions, type WalletTransactionConfirmation, type WalletTransactionReference, type WalletsChangedEvent, PartyLayerClient as _PartyLayerClientInternal, announcedWalletId, createApplicationLedgerReader, createPartyLayer as createCantonConnect, createPartyLayer, createTelemetryAdapter, createWalletLedgerReader, getBuiltinAdapters, getDiscoveryCapabilities, isTelemetryConfig };
package/dist/index.js CHANGED
@@ -435,13 +435,13 @@ var NativeConnectionOwner = class {
435
435
  this.identityRefreshing = true;
436
436
  let verified = false;
437
437
  try {
438
- const identity = await this.probe(provider, this.registrations.get(id));
438
+ const identity2 = await this.probe(provider, this.registrations.get(id));
439
439
  if (revision !== this.refreshRevision || this.getProvider(id) !== provider)
440
440
  throw disconnected();
441
441
  verified = true;
442
- this.projection = { id, identity };
443
- if (identity.account.partyId !== partyId || core.detectNetworkMismatch(network, identity.network)) {
444
- this.changed(id, identity);
442
+ this.projection = { id, identity: identity2 };
443
+ if (identity2.account.partyId !== partyId || core.detectNetworkMismatch(network, identity2.network)) {
444
+ this.changed(id, identity2);
445
445
  throw new Error("Wallet identity changed during message signing");
446
446
  }
447
447
  } catch (error) {
@@ -486,12 +486,12 @@ var NativeConnectionOwner = class {
486
486
  this.identityRefreshing = true;
487
487
  const registration = this.registrations.get(id);
488
488
  void this.probe(provider, registration).then(
489
- (identity) => {
489
+ (identity2) => {
490
490
  if (revision !== this.refreshRevision || this.projection?.id !== id || this.disposed)
491
491
  return;
492
492
  this.identityRefreshing = false;
493
- this.projection = { id, identity };
494
- this.changed(id, identity);
493
+ this.projection = { id, identity: identity2 };
494
+ this.changed(id, identity2);
495
495
  },
496
496
  () => {
497
497
  if (revision === this.refreshRevision) this.invalidate(id);
@@ -1728,7 +1728,7 @@ var PartyLayerClient = class {
1728
1728
  this.crypto = config.crypto || new DefaultCrypto();
1729
1729
  this.storage = config.storage || new DefaultStorage();
1730
1730
  if (typeof window !== "undefined") {
1731
- this.nativeOwner = new NativeConnectionOwner((id, identity) => this.onNativeIdentityChanged(id, identity));
1731
+ this.nativeOwner = new NativeConnectionOwner((id, identity2) => this.onNativeIdentityChanged(id, identity2));
1732
1732
  }
1733
1733
  const telemetryAdapter = createTelemetryAdapter(config.telemetry);
1734
1734
  this.telemetry = telemetryAdapter || new DefaultTelemetry();
@@ -1806,11 +1806,11 @@ var PartyLayerClient = class {
1806
1806
  nativeOwnerBindings.set(adapter, this.nativeOwner);
1807
1807
  }
1808
1808
  }
1809
- onNativeIdentityChanged(id, identity) {
1809
+ onNativeIdentityChanged(id, identity2) {
1810
1810
  const active = this.activeSession;
1811
1811
  if (this.destroyed || !active || String(active.walletId) !== id) return;
1812
1812
  ++this.sessionRevision;
1813
- if (!identity) {
1813
+ if (!identity2) {
1814
1814
  this.restorationBlocked = true;
1815
1815
  this.warmPlans.clear();
1816
1816
  this.activeSession = null;
@@ -1818,7 +1818,7 @@ var PartyLayerClient = class {
1818
1818
  this.emit("session:disconnected", { type: "session:disconnected", sessionId: active.sessionId });
1819
1819
  return;
1820
1820
  }
1821
- const session = { ...active, partyId: identity.account.partyId, network: identity.network };
1821
+ const session = { ...active, partyId: identity2.account.partyId, network: identity2.network };
1822
1822
  const mismatch = this.networkMismatch(session);
1823
1823
  if (mismatch) session.networkMismatch = mismatch;
1824
1824
  else delete session.networkMismatch;
@@ -3065,6 +3065,209 @@ var PartyLayerClient = class {
3065
3065
  function createPartyLayer(config) {
3066
3066
  return new PartyLayerClient(config);
3067
3067
  }
3068
+ function object(value) {
3069
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Malformed Ledger API response");
3070
+ return value;
3071
+ }
3072
+ function text(value) {
3073
+ if (typeof value !== "string" || !value || value.length > 2048 || /\p{Cc}/u.test(value)) {
3074
+ throw new Error("Invalid Ledger API identifier");
3075
+ }
3076
+ return value;
3077
+ }
3078
+ var identity = (s) => JSON.stringify([s.sessionId, s.walletId, s.partyId, core.toCAIP2Network(s.network).networkId]);
3079
+ function createWalletLedgerReader(client, options) {
3080
+ return createScopedLedgerReader(client, options);
3081
+ }
3082
+ function createScopedLedgerReader(client, options, applicationRequest) {
3083
+ const networkId = text(options.networkId);
3084
+ if (!/^canton:[a-zA-Z0-9_-]+$/.test(networkId)) throw new Error("Expected a Canton CAIP-2 network id");
3085
+ const interfaceId = options.holdingInterfaceId === void 0 ? void 0 : text(options.holdingInterfaceId);
3086
+ if (interfaceId && !/^[^:#\s]+:[^:\s]+:[^:\s]+$/.test(interfaceId)) throw new Error("Use an exact package-id-qualified holding interface id");
3087
+ const timeoutMs = options.timeoutMs ?? 3e4;
3088
+ const maxContracts = options.maxContracts ?? 1e3;
3089
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 3e5) throw new Error("Invalid ledger read timeout");
3090
+ if (!Number.isInteger(maxContracts) || maxContracts < 1 || maxContracts > 1e4) throw new Error("Invalid snapshot limit");
3091
+ async function read(signal, action) {
3092
+ let timer;
3093
+ let stop;
3094
+ let stopped = false;
3095
+ const controller = new AbortController();
3096
+ const aborted = new Promise((_resolve, reject) => {
3097
+ stop = () => {
3098
+ stopped = true;
3099
+ controller.abort();
3100
+ reject(new Error("Ledger read cancelled or timed out"));
3101
+ };
3102
+ if (signal?.aborted) stop();
3103
+ else signal?.addEventListener("abort", stop, { once: true });
3104
+ timer = setTimeout(stop, timeoutMs);
3105
+ });
3106
+ const run = async () => {
3107
+ const session = await client.getActiveSession();
3108
+ if (stopped) throw new Error("Ledger read cancelled");
3109
+ if (!session || session.networkMismatch || core.toCAIP2Network(session.network).networkId !== networkId) {
3110
+ throw new Error("Connect a wallet on the expected network before reading the ledger");
3111
+ }
3112
+ if (!applicationRequest && !session.capabilitiesSnapshot.includes("ledgerApi")) throw new Error("This wallet does not expose ledgerApi");
3113
+ const captured = identity(session);
3114
+ const assertCurrent = async () => {
3115
+ const current = await client.getActiveSession();
3116
+ if (stopped || !current || current.networkMismatch || identity(current) !== captured) throw new Error("Wallet session changed during ledger read");
3117
+ };
3118
+ const request = async (resource, body) => {
3119
+ await assertCurrent();
3120
+ let result2 = applicationRequest ? await applicationRequest(session, resource, body, controller.signal) : await client.asProvider().request({ method: "ledgerApi", params: {
3121
+ requestMethod: body ? "post" : "get",
3122
+ resource,
3123
+ ...body ? { body } : {}
3124
+ } });
3125
+ await assertCurrent();
3126
+ if (result2 && typeof result2 === "object" && !Array.isArray(result2) && Object.keys(result2).length === 1 && typeof result2.response === "string") result2 = result2.response;
3127
+ if (typeof result2 === "string") {
3128
+ if (result2.length > 8e6) throw new Error("Ledger response is too large");
3129
+ result2 = JSON.parse(result2);
3130
+ }
3131
+ return result2;
3132
+ };
3133
+ const result = await action(session, request);
3134
+ await assertCurrent();
3135
+ return result;
3136
+ };
3137
+ try {
3138
+ return await Promise.race([run(), aborted]);
3139
+ } finally {
3140
+ if (timer) clearTimeout(timer);
3141
+ if (stop) signal?.removeEventListener("abort", stop);
3142
+ }
3143
+ }
3144
+ return {
3145
+ /** A bounded, complete ACS snapshot of the connected party's configured HoldingV1 interface. */
3146
+ readHoldings(signal) {
3147
+ return read(signal, async (session, request) => {
3148
+ if (!interfaceId) throw new Error("Configure holdingInterfaceId before reading holdings");
3149
+ const end = object(await request("/v2/state/ledger-end"));
3150
+ if (!Number.isSafeInteger(end.offset) || end.offset < 0) throw new Error("Unsafe or invalid ledger offset");
3151
+ const rows = await request("/v2/state/active-contracts", {
3152
+ activeAtOffset: end.offset,
3153
+ eventFormat: { filtersByParty: { [String(session.partyId)]: { cumulative: [{
3154
+ identifierFilter: { InterfaceFilter: { value: { interfaceId, includeInterfaceView: true } } }
3155
+ }] } }, verbose: false }
3156
+ });
3157
+ if (!Array.isArray(rows) || rows.length >= maxContracts) throw new Error("Incomplete or oversized holdings snapshot");
3158
+ const seen = /* @__PURE__ */ new Set();
3159
+ const holdings = rows.map((row) => {
3160
+ const entry = object(object(row).contractEntry);
3161
+ if (Object.keys(entry).length !== 1 || !entry.JsActiveContract) throw new Error("Snapshot contains an incomplete reassignment");
3162
+ const created = object(object(entry.JsActiveContract).createdEvent);
3163
+ const cid = text(created.contractId);
3164
+ if (seen.has(cid)) throw new Error("Duplicate holding contract in snapshot");
3165
+ seen.add(cid);
3166
+ if (!Array.isArray(created.interfaceViews)) throw new Error("Missing holding interface view");
3167
+ const views = created.interfaceViews.filter((v) => object(v).interfaceId === interfaceId);
3168
+ if (views.length !== 1) throw new Error("Missing or ambiguous holding interface view");
3169
+ const view = object(views[0]);
3170
+ if (object(view.viewStatus).code !== 0) throw new Error("Holding interface view failed");
3171
+ const value = object(view.viewValue);
3172
+ if (value.owner !== String(session.partyId)) throw new Error("Holding belongs to another party");
3173
+ const instrument = object(value.instrumentId);
3174
+ if (typeof value.amount !== "string" || !/^(?:0|[1-9]\d{0,27})(?:\.\d{1,10})?$/.test(value.amount)) throw new Error("Invalid token decimal");
3175
+ let lock;
3176
+ if (value.lock !== null && value.lock !== void 0) {
3177
+ const raw = object(value.lock);
3178
+ if (!Array.isArray(raw.holders)) throw new Error("Invalid holding lock");
3179
+ lock = { holders: raw.holders.map(text) };
3180
+ for (const key of ["expiresAt", "expiresAfter", "context"]) {
3181
+ if (raw[key] !== void 0 && raw[key] !== null) lock[key] = text(raw[key]);
3182
+ }
3183
+ }
3184
+ let meta;
3185
+ if (value.meta !== void 0 && value.meta !== null) {
3186
+ const raw = object(value.meta);
3187
+ const values = Object.hasOwn(raw, "values") ? object(raw.values) : raw;
3188
+ if (Object.values(values).some((v) => typeof v !== "string")) throw new Error("Invalid holding metadata");
3189
+ meta = { ...values };
3190
+ }
3191
+ return { cid, holding: {
3192
+ owner: String(session.partyId),
3193
+ instrumentId: { admin: text(instrument.admin), id: text(instrument.id) },
3194
+ amount: value.amount,
3195
+ ...lock ? { lock } : {},
3196
+ ...meta ? { meta } : {}
3197
+ } };
3198
+ });
3199
+ return { walletId: String(session.walletId), partyId: String(session.partyId), networkId, offset: end.offset, holdings };
3200
+ });
3201
+ },
3202
+ /** One read, never polling or resubmission. Unknown remains unknown if ids cannot be correlated. */
3203
+ async confirmTransaction({ transaction, signal }) {
3204
+ const updateId = transaction.receipt?.updateId ?? transaction.updateId;
3205
+ if (!updateId || !transaction.commandId) return { status: "unknown", reason: "An update id and the original app command id are required" };
3206
+ if (transaction.receipt?.commandId && transaction.receipt.commandId !== transaction.commandId) {
3207
+ return { status: "unknown", reason: "Wallet receipt conflicts with the original command id" };
3208
+ }
3209
+ text(updateId);
3210
+ text(transaction.commandId);
3211
+ return read(signal, async (session, request) => {
3212
+ if (transaction.networkId !== networkId || transaction.partyId !== String(session.partyId) || transaction.walletId !== String(session.walletId)) {
3213
+ throw new Error("Transaction does not belong to the connected wallet account and network");
3214
+ }
3215
+ if (transaction.updateId && transaction.updateId !== updateId) throw new Error("Conflicting update ids");
3216
+ const result = object(await request("/v2/updates/update-by-id", {
3217
+ updateId,
3218
+ updateFormat: { includeTransactions: {
3219
+ eventFormat: { filtersByParty: { [String(session.partyId)]: {} }, verbose: false },
3220
+ transactionShape: "TRANSACTION_SHAPE_ACS_DELTA"
3221
+ } }
3222
+ }));
3223
+ const update = object(result.update);
3224
+ if (Object.keys(update).length !== 1 || !update.Transaction) throw new Error("Requested update is not a transaction");
3225
+ const tx = object(object(update.Transaction).value);
3226
+ if (tx.updateId !== updateId || tx.commandId !== transaction.commandId || !Array.isArray(tx.events)) {
3227
+ return { status: "unknown", reason: "Ledger transaction cannot be correlated with the original command" };
3228
+ }
3229
+ return { status: "confirmed", updateId };
3230
+ });
3231
+ }
3232
+ };
3233
+ }
3234
+ function createApplicationLedgerReader(client, options) {
3235
+ if (!/^[\w.:-]{1,100}$/.test(options.sourceId)) throw new Error("Invalid application ledger source id");
3236
+ return createScopedLedgerReader(client, options, async (session, resource, body, signal) => {
3237
+ const browserOrigin = typeof window !== "undefined" ? window.location.origin : void 0;
3238
+ const origin = browserOrigin ?? options.origin;
3239
+ if (!origin || browserOrigin && options.origin && options.origin !== browserOrigin) throw new Error("Application reads require the current application origin");
3240
+ const base = new URL(origin);
3241
+ 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");
3242
+ const url = new URL(options.endpoint, origin);
3243
+ if (url.origin !== origin || url.username || url.password || url.hash) throw new Error("Application ledger endpoint must be same-origin");
3244
+ if (!["/v2/state/ledger-end", "/v2/state/active-contracts", "/v2/updates/update-by-id"].includes(resource)) throw new Error("Unsupported application ledger read");
3245
+ const response = await (options.fetch ?? globalThis.fetch)(url.href, {
3246
+ method: "POST",
3247
+ credentials: "same-origin",
3248
+ cache: "no-store",
3249
+ redirect: "error",
3250
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
3251
+ signal,
3252
+ body: JSON.stringify({
3253
+ version: 1,
3254
+ sourceId: options.sourceId,
3255
+ partyId: String(session.partyId),
3256
+ networkId: core.toCAIP2Network(session.network).networkId,
3257
+ resource,
3258
+ ...body ? { body } : {}
3259
+ })
3260
+ });
3261
+ if (!response.ok || !/^application\/json\b/i.test(response.headers.get("content-type") ?? "")) throw new Error("Authorized application ledger read is unavailable");
3262
+ const raw = await response.text();
3263
+ if (raw.length > 8e6) throw new Error("Application ledger response is too large");
3264
+ const result = JSON.parse(raw);
3265
+ 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")) {
3266
+ throw new Error("Incomplete or incorrectly scoped application ledger response");
3267
+ }
3268
+ return result.value;
3269
+ });
3270
+ }
3068
3271
 
3069
3272
  Object.defineProperty(exports, "AdapterNotRegisteredError", {
3070
3273
  enumerable: true,
@@ -3278,9 +3481,11 @@ exports.GenericDiscoveryAdapter = GenericDiscoveryAdapter;
3278
3481
  exports.MetricsTelemetryAdapter = MetricsTelemetryAdapter;
3279
3482
  exports.PartyLayerClient = PartyLayerClient;
3280
3483
  exports.announcedWalletId = announcedWalletId;
3484
+ exports.createApplicationLedgerReader = createApplicationLedgerReader;
3281
3485
  exports.createCantonConnect = createPartyLayer;
3282
3486
  exports.createPartyLayer = createPartyLayer;
3283
3487
  exports.createTelemetryAdapter = createTelemetryAdapter;
3488
+ exports.createWalletLedgerReader = createWalletLedgerReader;
3284
3489
  exports.getBuiltinAdapters = getBuiltinAdapters;
3285
3490
  exports.getDiscoveryCapabilities = getDiscoveryCapabilities;
3286
3491
  exports.isTelemetryConfig = isTelemetryConfig;