@hsuite/native-connect-angular 2.1.3 → 2.1.5

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.
@@ -7,13 +7,14 @@ import { Platform, IonicModule } from '@ionic/angular';
7
7
  import { IonButton, IonIcon, IonBadge, IonSpinner, AlertController, ToastController, ModalController, IonContent, IonText, IonCard, IonCardHeader, IonCardTitle, IonCardSubtitle, IonCardContent, IonList, IonItem, IonLabel } from '@ionic/angular/standalone';
8
8
  import { addIcons } from 'ionicons';
9
9
  import { addOutline, addCircleOutline, linkOutline, chevronDownOutline, personOutline, peopleOutline, alertCircleOutline, walletOutline, closeOutline, phonePortraitOutline, checkmarkCircle, qrCodeOutline, openOutline, extensionPuzzleOutline, checkmarkOutline, copyOutline, timeOutline, arrowBackOutline, closeCircleOutline, checkmarkCircleOutline, refreshOutline, syncOutline, flashOutline, cloudOutline, wifiOutline, fingerPrintOutline, globeOutline, hourglassOutline } from 'ionicons/icons';
10
- import { getLogger, ChannelClient, encodeChannelInvite, LocalDiscoveryService, XrplTransactionEncoder } from '@hsuite/native-connect-sdk';
10
+ import { getLogger, ChannelClient, encodeChannelInvite, LocalDiscoveryService, decodeHederaSignatureMap, isAuthSigningScheme, XrplTransactionEncoder } from '@hsuite/native-connect-sdk';
11
11
  export { HederaTransactionEncoder, XrplTransactionEncoder } from '@hsuite/native-connect-sdk';
12
12
  import { WalletConnectModal } from '@walletconnect/modal';
13
13
  import SignClient from '@walletconnect/sign-client';
14
14
  import { toObservable } from '@angular/core/rxjs-interop';
15
15
  import * as QRCode from 'qrcode';
16
- import { Subscription } from 'rxjs';
16
+ import { Subscription, firstValueFrom, catchError, from, switchMap, throwError } from 'rxjs';
17
+ import { HttpClient, HttpErrorResponse } from '@angular/common/http';
17
18
  import { PublicKey, KeyList, TransferTransaction, AccountId, Hbar, TokenId, NftId, TokenAssociateTransaction, TokenDissociateTransaction, ScheduleCreateTransaction, TokenCreateTransaction, TokenType, TokenSupplyType, TokenMintTransaction, TokenBurnTransaction, TopicCreateTransaction, TopicMessageSubmitTransaction, AccountCreateTransaction, PrivateKey, AccountUpdateTransaction, TransactionId, BatchTransaction, Client } from '@hashgraph/sdk';
18
19
 
19
20
  /**
@@ -1427,7 +1428,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImpo
1427
1428
  * Each event is available as both an Angular EventEmitter (for template bindings)
1428
1429
  * and an RxJS Observable (for advanced composition with operators).
1429
1430
  */
1430
- const logger$j = getLogger().scoped?.('WalletEventBus') ?? getLogger();
1431
+ const logger$k = getLogger().scoped?.('WalletEventBus') ?? getLogger();
1431
1432
  /**
1432
1433
  * Centralized event bus for wallet events.
1433
1434
  *
@@ -1539,7 +1540,7 @@ class WalletEventBus {
1539
1540
  *
1540
1541
  */
1541
1542
  constructor() {
1542
- logger$j.debug('Event bus initialized');
1543
+ logger$k.debug('Event bus initialized');
1543
1544
  }
1544
1545
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: WalletEventBus, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1545
1546
  static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: WalletEventBus, providedIn: 'root' });
@@ -1726,7 +1727,7 @@ class BaseWalletProvider {
1726
1727
  * }
1727
1728
  * ```
1728
1729
  */
1729
- const logger$i = getLogger().scoped?.('ChannelClientService') ?? getLogger();
1730
+ const logger$j = getLogger().scoped?.('ChannelClientService') ?? getLogger();
1730
1731
  /**
1731
1732
  * ChannelClientService
1732
1733
  *
@@ -1776,6 +1777,7 @@ class ChannelClientService {
1776
1777
  return {
1777
1778
  id: `channel-${account.address}`,
1778
1779
  address: account.address,
1780
+ publicKey: account.publicKey,
1779
1781
  label: account.alias ?? `Account ${index + 1}`,
1780
1782
  ledgerId: account.ledgerId,
1781
1783
  networkId: account.networkId,
@@ -1814,7 +1816,7 @@ class ChannelClientService {
1814
1816
  */
1815
1817
  async connect(config) {
1816
1818
  if (this._state() === 'connecting' || this._state() === 'pending') {
1817
- logger$i.warn('Connection already in progress');
1819
+ logger$j.warn('Connection already in progress');
1818
1820
  const existing = this._currentInvite();
1819
1821
  if (existing)
1820
1822
  return existing;
@@ -1856,7 +1858,7 @@ class ChannelClientService {
1856
1858
  this.runInZone(() => {
1857
1859
  const previousState = this._state();
1858
1860
  if (state !== previousState) {
1859
- logger$i.debug('State change via callback', { from: previousState, to: state });
1861
+ logger$j.debug('State change via callback', { from: previousState, to: state });
1860
1862
  this._state.set(state);
1861
1863
  // Handle error state - this is triggered on rejection
1862
1864
  if (state === 'error') {
@@ -1881,7 +1883,7 @@ class ChannelClientService {
1881
1883
  },
1882
1884
  onAccountsChange: (accounts) => {
1883
1885
  this.runInZone(() => {
1884
- logger$i.debug('Accounts change via callback', { count: accounts.length });
1886
+ logger$j.debug('Accounts change via callback', { count: accounts.length });
1885
1887
  this._accounts.set(accounts);
1886
1888
  // Re-persist when accounts change
1887
1889
  if (this._state() === 'active') {
@@ -1892,7 +1894,7 @@ class ChannelClientService {
1892
1894
  onTransportChange: (transport) => {
1893
1895
  this.runInZone(() => {
1894
1896
  if (transport !== this._transportState()) {
1895
- logger$i.debug('Transport change via callback', { state: transport });
1897
+ logger$j.debug('Transport change via callback', { state: transport });
1896
1898
  this._transportState.set(transport);
1897
1899
  }
1898
1900
  });
@@ -1927,7 +1929,7 @@ class ChannelClientService {
1927
1929
  });
1928
1930
  // Store invite for reconnection
1929
1931
  this.storeInvite(invite);
1930
- logger$i.info('Channel connection initiated', {
1932
+ logger$j.info('Channel connection initiated', {
1931
1933
  channelId: invite.id.slice(0, 8),
1932
1934
  type: invite.type,
1933
1935
  });
@@ -1935,7 +1937,7 @@ class ChannelClientService {
1935
1937
  }
1936
1938
  catch (error) {
1937
1939
  const message = error instanceof Error ? error.message : String(error);
1938
- logger$i.error('Connection failed', { error: message });
1940
+ logger$j.error('Connection failed', { error: message });
1939
1941
  // Reset connecting flag on error
1940
1942
  this.connectingNewSession = false;
1941
1943
  this.runInZone(() => {
@@ -1976,7 +1978,7 @@ class ChannelClientService {
1976
1978
  if (state !== 'active' && state !== 'approved') {
1977
1979
  throw new Error(`Not connected - channel state is '${state}'. Please reconnect to the wallet.`);
1978
1980
  }
1979
- logger$i.debug('Sending RPC request', { method, state });
1981
+ logger$j.debug('Sending RPC request', { method, state });
1980
1982
  return this.client.request(method, params, timeoutMs);
1981
1983
  }
1982
1984
  /**
@@ -2053,7 +2055,7 @@ class ChannelClientService {
2053
2055
  await this.client.disconnect();
2054
2056
  }
2055
2057
  catch (error) {
2056
- logger$i.warn('Disconnect error', { error });
2058
+ logger$j.warn('Disconnect error', { error });
2057
2059
  }
2058
2060
  this.client = null;
2059
2061
  }
@@ -2065,7 +2067,7 @@ class ChannelClientService {
2065
2067
  this._currentInvite.set(null);
2066
2068
  this._error.set(null);
2067
2069
  });
2068
- logger$i.info('Disconnected from channel');
2070
+ logger$j.info('Disconnected from channel');
2069
2071
  }
2070
2072
  /**
2071
2073
  * Attempt to restore a previous session.
@@ -2078,7 +2080,7 @@ class ChannelClientService {
2078
2080
  async attemptRestore() {
2079
2081
  // Skip restore if a new connection is being initiated
2080
2082
  if (this.connectingNewSession) {
2081
- logger$i.debug('Skipping restore - new connection in progress');
2083
+ logger$j.debug('Skipping restore - new connection in progress');
2082
2084
  return false;
2083
2085
  }
2084
2086
  const stored = this.getStoredChannel();
@@ -2094,11 +2096,11 @@ class ChannelClientService {
2094
2096
  // Safe to do unconditionally at this point in the project's lifecycle:
2095
2097
  // no dApp sessions are live in production yet.
2096
2098
  if (stored.localContext === undefined) {
2097
- logger$i.warn('Clearing legacy persisted channel without localContext — user must re-approve the dApp connection (§21.1)', { channelId: stored.id.slice(0, 8) });
2099
+ logger$j.warn('Clearing legacy persisted channel without localContext — user must re-approve the dApp connection (§21.1)', { channelId: stored.id.slice(0, 8) });
2098
2100
  this.clearStoredChannel();
2099
2101
  return false;
2100
2102
  }
2101
- logger$i.info('Attempting session restore', {
2103
+ logger$j.info('Attempting session restore', {
2102
2104
  channelId: stored.id.slice(0, 8),
2103
2105
  });
2104
2106
  this.runInZone(() => {
@@ -2111,7 +2113,7 @@ class ChannelClientService {
2111
2113
  this.runInZone(() => {
2112
2114
  const previousState = this._state();
2113
2115
  if (state !== previousState) {
2114
- logger$i.debug('State change via callback (reconnect)', {
2116
+ logger$j.debug('State change via callback (reconnect)', {
2115
2117
  from: previousState,
2116
2118
  to: state,
2117
2119
  });
@@ -2131,7 +2133,7 @@ class ChannelClientService {
2131
2133
  },
2132
2134
  onAccountsChange: (accounts) => {
2133
2135
  this.runInZone(() => {
2134
- logger$i.debug('Accounts change via callback (reconnect)', { count: accounts.length });
2136
+ logger$j.debug('Accounts change via callback (reconnect)', { count: accounts.length });
2135
2137
  this._accounts.set(accounts);
2136
2138
  if (this._state() === 'active') {
2137
2139
  this.persistCurrentState();
@@ -2141,7 +2143,7 @@ class ChannelClientService {
2141
2143
  onTransportChange: (transport) => {
2142
2144
  this.runInZone(() => {
2143
2145
  if (transport !== this._transportState()) {
2144
- logger$i.debug('Transport change via callback (reconnect)', { state: transport });
2146
+ logger$j.debug('Transport change via callback (reconnect)', { state: transport });
2145
2147
  this._transportState.set(transport);
2146
2148
  }
2147
2149
  });
@@ -2164,14 +2166,14 @@ class ChannelClientService {
2164
2166
  }
2165
2167
  this._state.set('active');
2166
2168
  });
2167
- logger$i.info('Session restored successfully', {
2169
+ logger$j.info('Session restored successfully', {
2168
2170
  channelId: stored.id.slice(0, 8),
2169
2171
  accounts: restoredAccounts.length,
2170
2172
  });
2171
2173
  return true;
2172
2174
  }
2173
2175
  catch (error) {
2174
- logger$i.warn('Session restore failed', {
2176
+ logger$j.warn('Session restore failed', {
2175
2177
  error: error instanceof Error ? error.message : String(error),
2176
2178
  });
2177
2179
  // Clean up the partially initialized client
@@ -2247,7 +2249,7 @@ class ChannelClientService {
2247
2249
  }
2248
2250
  if (clientTransport !== this._transportState()) {
2249
2251
  this._transportState.set(clientTransport);
2250
- logger$i.debug('Transport state updated', { state: clientTransport });
2252
+ logger$j.debug('Transport state updated', { state: clientTransport });
2251
2253
  }
2252
2254
  });
2253
2255
  // Continue polling as long as client exists
@@ -2290,14 +2292,14 @@ class ChannelClientService {
2290
2292
  const persisted = this.client.exportState();
2291
2293
  if (persisted) {
2292
2294
  localStorage.setItem(ChannelClientService.STORAGE_KEY, JSON.stringify(persisted));
2293
- logger$i.debug('Channel state persisted', {
2295
+ logger$j.debug('Channel state persisted', {
2294
2296
  channelId: persisted.id.slice(0, 8),
2295
2297
  accounts: persisted.accounts?.length ?? 0,
2296
2298
  });
2297
2299
  }
2298
2300
  }
2299
2301
  catch (error) {
2300
- logger$i.warn('Failed to persist channel state', { error });
2302
+ logger$j.warn('Failed to persist channel state', { error });
2301
2303
  }
2302
2304
  }
2303
2305
  /**
@@ -2338,7 +2340,7 @@ class ChannelClientService {
2338
2340
  }
2339
2341
  }
2340
2342
  catch {
2341
- logger$i.warn('Failed to store channel');
2343
+ logger$j.warn('Failed to store channel');
2342
2344
  }
2343
2345
  }
2344
2346
  /**
@@ -2352,7 +2354,7 @@ class ChannelClientService {
2352
2354
  }
2353
2355
  }
2354
2356
  catch {
2355
- logger$i.warn('Failed to retrieve stored channel');
2357
+ logger$j.warn('Failed to retrieve stored channel');
2356
2358
  }
2357
2359
  return null;
2358
2360
  }
@@ -2404,7 +2406,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImpo
2404
2406
  * 8. P2P upgrade happens automatically in background
2405
2407
  * ```
2406
2408
  */
2407
- const logger$h = getLogger().scoped?.('HsuiteNativeProvider') ?? getLogger();
2409
+ const logger$i = getLogger().scoped?.('HsuiteNativeProvider') ?? getLogger();
2408
2410
  /**
2409
2411
  * HSuite Native Connect Provider.
2410
2412
  *
@@ -2490,7 +2492,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2490
2492
  const isConnected = this.channelService.isConnected();
2491
2493
  // If we were connected but now disconnected, emit disconnect event
2492
2494
  if (this.previouslyConnected && !isConnected && status === 'disconnected') {
2493
- logger$h.info('[HsuiteNativeProvider] Channel terminated');
2495
+ logger$i.info('[HsuiteNativeProvider] Channel terminated');
2494
2496
  this.eventBus.disconnected.emit({
2495
2497
  providerId: this.id,
2496
2498
  providerType: 'hsuite-native',
@@ -2503,7 +2505,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2503
2505
  });
2504
2506
  // Attempt automatic reconnect when session exists after reload
2505
2507
  void this.attemptReconnect().catch((error) => {
2506
- logger$h.debug('[HsuiteNativeProvider] Auto-reconnect skipped', { error });
2508
+ logger$i.debug('[HsuiteNativeProvider] Auto-reconnect skipped', { error });
2507
2509
  });
2508
2510
  }
2509
2511
  /**
@@ -2597,10 +2599,10 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2597
2599
  // Guard: Don't start a new connection if already connecting
2598
2600
  const currentStatus = this.status();
2599
2601
  if (currentStatus === 'connecting') {
2600
- logger$h.warn('Connection already in progress, ignoring duplicate request');
2602
+ logger$i.warn('Connection already in progress, ignoring duplicate request');
2601
2603
  return;
2602
2604
  }
2603
- logger$h.info('Connecting to HSuite Wallet via unified channel protocol', { config });
2605
+ logger$i.info('Connecting to HSuite Wallet via unified channel protocol', { config });
2604
2606
  try {
2605
2607
  const invite = await this.channelService.connect({
2606
2608
  type: 'session',
@@ -2626,14 +2628,14 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2626
2628
  accounts,
2627
2629
  timestamp: Date.now(),
2628
2630
  });
2629
- logger$h.info('Connected successfully via unified channel', {
2631
+ logger$i.info('Connected successfully via unified channel', {
2630
2632
  channelId: invite.id.slice(0, 8),
2631
2633
  accountCount: accounts.length,
2632
2634
  });
2633
2635
  });
2634
2636
  }
2635
2637
  catch (error) {
2636
- logger$h.error('Connection failed', { error });
2638
+ logger$i.error('Connection failed', { error });
2637
2639
  throw error;
2638
2640
  }
2639
2641
  }
@@ -2666,7 +2668,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2666
2668
  if (wallet) {
2667
2669
  // Send invite directly via BroadcastChannel - instant, no network!
2668
2670
  this.localDiscoveryService.sendInvite(wallet.fingerprint, inviteUrl, config?.appId, config?.appName);
2669
- logger$h.info('[HsuiteNativeProvider] Sent invite via local discovery', {
2671
+ logger$i.info('[HsuiteNativeProvider] Sent invite via local discovery', {
2670
2672
  wallet: wallet.fingerprint.slice(0, 8),
2671
2673
  });
2672
2674
  return;
@@ -2758,7 +2760,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2758
2760
  * @throws {Error} If disconnection fails (event still emitted)
2759
2761
  */
2760
2762
  async disconnect() {
2761
- logger$h.info('Disconnecting from HSuite Wallet');
2763
+ logger$i.info('Disconnecting from HSuite Wallet');
2762
2764
  try {
2763
2765
  await this.channelService.disconnect();
2764
2766
  // Emit disconnection event
@@ -2768,10 +2770,10 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2768
2770
  reason: 'user_initiated',
2769
2771
  timestamp: Date.now(),
2770
2772
  });
2771
- logger$h.info('Disconnected successfully');
2773
+ logger$i.info('Disconnected successfully');
2772
2774
  }
2773
2775
  catch (error) {
2774
- logger$h.error('Disconnection failed', { error });
2776
+ logger$i.error('Disconnection failed', { error });
2775
2777
  // Still emit event even if disconnect fails
2776
2778
  this.eventBus.disconnected.emit({
2777
2779
  providerId: this.id,
@@ -2799,7 +2801,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2799
2801
  * @throws {Error} If channel communication fails
2800
2802
  */
2801
2803
  async signTransaction(options) {
2802
- logger$h.info('Signing transaction', { options });
2804
+ logger$i.info('Signing transaction', { options });
2803
2805
  try {
2804
2806
  const response = await this.channelService.signTransaction({
2805
2807
  accountAddress: options.accountAddress,
@@ -2807,7 +2809,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2807
2809
  ledgerId: options.ledgerId,
2808
2810
  networkId: options.networkId,
2809
2811
  });
2810
- logger$h.info('Transaction signed');
2812
+ logger$i.info('Transaction signed');
2811
2813
  return {
2812
2814
  signedPayload: response.signedPayload || '',
2813
2815
  signature: response.signature,
@@ -2815,7 +2817,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2815
2817
  };
2816
2818
  }
2817
2819
  catch (error) {
2818
- logger$h.error('Transaction signing failed', { error });
2820
+ logger$i.error('Transaction signing failed', { error });
2819
2821
  throw error;
2820
2822
  }
2821
2823
  }
@@ -2839,7 +2841,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2839
2841
  * @throws {Error} If transaction submission fails
2840
2842
  */
2841
2843
  async signAndExecuteTransaction(options) {
2842
- logger$h.info('signAndExecuteTransaction called (single prompt)', {
2844
+ logger$i.info('signAndExecuteTransaction called (single prompt)', {
2843
2845
  accountAddress: options.accountAddress,
2844
2846
  ledgerId: options.ledgerId,
2845
2847
  networkId: options.networkId,
@@ -2876,7 +2878,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2876
2878
  * @param options
2877
2879
  */
2878
2880
  async submitTransactionInternal(options) {
2879
- logger$h.info('Signing and submitting transaction (single prompt)', {
2881
+ logger$i.info('Signing and submitting transaction (single prompt)', {
2880
2882
  accountAddress: options.accountAddress,
2881
2883
  ledgerId: options.ledgerId,
2882
2884
  networkId: options.networkId,
@@ -2894,7 +2896,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2894
2896
  innerTransactions: options.innerTransactions,
2895
2897
  }),
2896
2898
  });
2897
- logger$h.info('Transaction signed and submitted successfully', {
2899
+ logger$i.info('Transaction signed and submitted successfully', {
2898
2900
  transactionId: response.transactionId,
2899
2901
  transactionHash: response.transactionHash?.substring(0, 16),
2900
2902
  });
@@ -2905,7 +2907,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2905
2907
  };
2906
2908
  }
2907
2909
  catch (error) {
2908
- logger$h.error('Transaction sign+submit failed', { error });
2910
+ logger$i.error('Transaction sign+submit failed', { error });
2909
2911
  throw error;
2910
2912
  }
2911
2913
  }
@@ -2927,7 +2929,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2927
2929
  * @throws {Error} If wallet is not connected
2928
2930
  */
2929
2931
  async signMessage(options) {
2930
- logger$h.info('Signing message', {
2932
+ logger$i.info('Signing message', {
2931
2933
  accountAddress: options.accountAddress,
2932
2934
  encoding: options.encoding,
2933
2935
  messageLength: options.message?.length,
@@ -2940,7 +2942,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2940
2942
  ledgerId: options.ledgerId,
2941
2943
  networkId: options.networkId,
2942
2944
  });
2943
- logger$h.info('Message signed successfully', {
2945
+ logger$i.info('Message signed successfully', {
2944
2946
  algorithm: response.algorithm,
2945
2947
  caipChainId: response.caipChainId,
2946
2948
  });
@@ -2957,7 +2959,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2957
2959
  };
2958
2960
  }
2959
2961
  catch (error) {
2960
- logger$h.error('Message signing failed', { error });
2962
+ logger$i.error('Message signing failed', { error });
2961
2963
  throw error;
2962
2964
  }
2963
2965
  }
@@ -2989,7 +2991,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
2989
2991
  * @returns Promise resolving to true if reconnection succeeded, false otherwise
2990
2992
  */
2991
2993
  async attemptReconnect() {
2992
- logger$h.info('Attempting reconnect via unified channel');
2994
+ logger$i.info('Attempting reconnect via unified channel');
2993
2995
  try {
2994
2996
  const success = await this.channelService.attemptRestore();
2995
2997
  if (success) {
@@ -3002,15 +3004,15 @@ class HsuiteNativeProvider extends BaseWalletProvider {
3002
3004
  metadata: { autoReconnected: true },
3003
3005
  timestamp: Date.now(),
3004
3006
  });
3005
- logger$h.info('Reconnect successful');
3007
+ logger$i.info('Reconnect successful');
3006
3008
  }
3007
3009
  else {
3008
- logger$h.warn('Reconnect failed - no session or unable to connect');
3010
+ logger$i.warn('Reconnect failed - no session or unable to connect');
3009
3011
  }
3010
3012
  return success;
3011
3013
  }
3012
3014
  catch (error) {
3013
- logger$h.error('Reconnect failed', { error });
3015
+ logger$i.error('Reconnect failed', { error });
3014
3016
  return false;
3015
3017
  }
3016
3018
  }
@@ -3045,7 +3047,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImpo
3045
3047
  * Implements the IWalletConnectSigner interface for Hedera ledger.
3046
3048
  * Handles Hedera-specific JSON-RPC methods and transaction formats.
3047
3049
  */
3048
- const logger$g = getLogger().scoped?.('HederaSigner') ?? getLogger();
3050
+ const logger$h = getLogger().scoped?.('HederaSigner') ?? getLogger();
3049
3051
  /**
3050
3052
  * Extract a meaningful error message from various error shapes.
3051
3053
  * WalletConnect SDK throws errors that are not standard Error instances.
@@ -3063,7 +3065,7 @@ const logger$g = getLogger().scoped?.('HederaSigner') ?? getLogger();
3063
3065
  */
3064
3066
  function extractErrorMessage$1(error) {
3065
3067
  // Log the raw error for debugging
3066
- logger$g.debug('Extracting error message', {
3068
+ logger$h.debug('Extracting error message', {
3067
3069
  errorType: typeof error,
3068
3070
  isError: error instanceof Error,
3069
3071
  constructorName: error?.constructor?.name,
@@ -3101,7 +3103,7 @@ function extractErrorMessage$1(error) {
3101
3103
  propDebug[prop] = '[err]';
3102
3104
  }
3103
3105
  }
3104
- logger$g.error('WC Error object dump', propDebug);
3106
+ logger$h.error('WC Error object dump', propDebug);
3105
3107
  // Check for code property first (common in SDK errors like PIN_REQUIRED)
3106
3108
  if (typeof errorObj['code'] === 'string') {
3107
3109
  const codeMsg = errorObj['message']
@@ -3182,7 +3184,7 @@ function extractErrorMessage$1(error) {
3182
3184
  }
3183
3185
  // Try getting own property names (includes non-enumerable)
3184
3186
  const ownProps = Object.getOwnPropertyNames(errorObj);
3185
- logger$g.debug('Error object properties', { props: ownProps });
3187
+ logger$h.debug('Error object properties', { props: ownProps });
3186
3188
  if (ownProps.length > 0) {
3187
3189
  // Try to read ALL properties for better debugging
3188
3190
  const propValues = [];
@@ -3203,7 +3205,7 @@ function extractErrorMessage$1(error) {
3203
3205
  propValues.push(k);
3204
3206
  }
3205
3207
  }
3206
- logger$g.debug('Error property values', { values: propValues });
3208
+ logger$h.debug('Error property values', { values: propValues });
3207
3209
  // Return a more informative error
3208
3210
  return `Error with properties: ${propValues.slice(0, 5).join(', ')}`;
3209
3211
  }
@@ -3216,7 +3218,7 @@ function extractErrorMessage$1(error) {
3216
3218
  }
3217
3219
  }
3218
3220
  // Last resort - log what we know about the object
3219
- logger$g.warn('Could not extract error message', {
3221
+ logger$h.warn('Could not extract error message', {
3220
3222
  constructor: error?.constructor?.name,
3221
3223
  prototype: Object.getPrototypeOf(error)?.constructor?.name,
3222
3224
  });
@@ -3315,13 +3317,13 @@ class HederaSigner {
3315
3317
  Object.keys(error).length === 0 &&
3316
3318
  !(error instanceof Error);
3317
3319
  if (isEmptyError) {
3318
- logger$g.warn('WalletConnect SDK empty error - relay subscription may have been stale', {
3320
+ logger$h.warn('WalletConnect SDK empty error - relay subscription may have been stale', {
3319
3321
  topic: params.topic?.substring(0, 16) + '...',
3320
3322
  });
3321
3323
  throw new Error('WalletConnect connection issue - please try again');
3322
3324
  }
3323
3325
  const errorMsg = extractErrorMessage$1(error);
3324
- logger$g.error('Sign failed', { error: errorMsg });
3326
+ logger$h.error('Sign failed', { error: errorMsg });
3325
3327
  throw new Error(`Hedera sign failed: ${errorMsg}`);
3326
3328
  }
3327
3329
  }
@@ -3337,7 +3339,7 @@ class HederaSigner {
3337
3339
  const network = params.networkId.includes('mainnet') ? 'mainnet' : 'testnet';
3338
3340
  // Format account ID in HIP-30 format
3339
3341
  const signerAccountId = `hedera:${network}:${params.accountAddress}`;
3340
- logger$g.debug('Sending hedera_signAndExecuteTransaction request', {
3342
+ logger$h.debug('Sending hedera_signAndExecuteTransaction request', {
3341
3343
  topic: params.topic?.substring(0, 16) + '...',
3342
3344
  chainId: `hedera:${network}`,
3343
3345
  signerAccountId,
@@ -3365,7 +3367,7 @@ class HederaSigner {
3365
3367
  try {
3366
3368
  // Race between the request and our timeout
3367
3369
  const result = await Promise.race([requestPromise, timeoutPromise]);
3368
- logger$g.debug('Received hedera_signAndExecuteTransaction response', {
3370
+ logger$h.debug('Received hedera_signAndExecuteTransaction response', {
3369
3371
  hasResult: !!result,
3370
3372
  resultKeys: result ? Object.keys(result) : [],
3371
3373
  });
@@ -3398,7 +3400,7 @@ class HederaSigner {
3398
3400
  // Get all own property names
3399
3401
  ownProps: error && typeof error === 'object' ? Object.getOwnPropertyNames(error) : [],
3400
3402
  };
3401
- logger$g.error('Submit failed - full error analysis', errorInfo);
3403
+ logger$h.error('Submit failed - full error analysis', errorInfo);
3402
3404
  // Check if this is an empty error object (WalletConnect SDK bug)
3403
3405
  // This typically happens when relay subscription is stale
3404
3406
  const isEmptyError = typeof error === 'object' &&
@@ -3410,7 +3412,7 @@ class HederaSigner {
3410
3412
  // It usually means the relay subscription was stale
3411
3413
  // The SessionHealthManager should have pinged before the request,
3412
3414
  // but if we still get this error, the subscription dropped after the ping
3413
- logger$g.warn('WalletConnect SDK empty error - relay subscription may have been stale', {
3415
+ logger$h.warn('WalletConnect SDK empty error - relay subscription may have been stale', {
3414
3416
  topic: params.topic?.substring(0, 16) + '...',
3415
3417
  hint: 'This can happen when the relay WebSocket connection drops',
3416
3418
  });
@@ -3420,7 +3422,7 @@ class HederaSigner {
3420
3422
  'please check your transaction history as it may have been executed successfully.');
3421
3423
  }
3422
3424
  const errorMsg = extractErrorMessage$1(error);
3423
- logger$g.error('Submit failed', { error: errorMsg });
3425
+ logger$h.error('Submit failed', { error: errorMsg });
3424
3426
  throw new Error(`Hedera submit failed: ${errorMsg}`);
3425
3427
  }
3426
3428
  }
@@ -3444,29 +3446,61 @@ class HederaSigner {
3444
3446
  * @returns Promise resolving to signature and metadata
3445
3447
  */
3446
3448
  async signMessage(params) {
3447
- // Extract network name from networkId (mainnet or testnet)
3448
- const network = params.networkId.includes('mainnet') ? 'mainnet' : 'testnet';
3449
+ // params.networkId IS the CAIP-2 chain id the session was approved for —
3450
+ // use it verbatim (substring sniffing mapped e.g. previewnet to testnet,
3451
+ // mis-routing the request AND mis-labelling the signed bytes).
3452
+ const caipChainId = params.networkId;
3449
3453
  // Format account ID in HIP-30 format
3450
- const signerAccountId = `hedera:${network}:${params.accountAddress}`;
3454
+ const signerAccountId = `${caipChainId}:${params.accountAddress}`;
3455
+ const encoding = params.encoding ?? 'utf-8';
3451
3456
  try {
3452
3457
  // Use 5-minute expiry to give users time to review and approve
3453
- const result = await params.client.request({
3458
+ const result = (await params.client.request({
3454
3459
  topic: params.topic,
3455
- chainId: `hedera:${network}`,
3460
+ chainId: caipChainId,
3456
3461
  request: {
3457
3462
  method: 'hedera_signMessage',
3458
3463
  params: {
3459
3464
  signerAccountId,
3460
- message: params.message, // Can be base64 or utf-8
3465
+ message: params.message,
3461
3466
  },
3462
3467
  },
3463
3468
  expiry: 300, // 5 minutes in seconds
3464
- });
3469
+ }));
3470
+ // The Hedera WalletConnect spec returns the signature as a base64
3471
+ // `proto.SignatureMap` under `signatureMap` (NOT `{ signature, publicKey }`),
3472
+ // signed over `\x19Hedera Signed Message:\n<len><msg>` — a DIFFERENT layout
3473
+ // from the native `hsc:` path's domain-separated blob. Decode it into the
3474
+ // §21.3 result shape and tag `signingScheme: 'hedera-wc'` (the map shape IS
3475
+ // that spec) so a verifier reconstructs the Hedera-standard bytes instead
3476
+ // of the HSuite blob. Without this, WalletConnect-signed auth challenges
3477
+ // are unverifiable and smart-host login silently fails while the native
3478
+ // path works.
3479
+ if (result.signatureMap) {
3480
+ const decoded = await decodeHederaSignatureMap(result.signatureMap);
3481
+ return {
3482
+ signature: decoded.signature,
3483
+ publicKey: decoded.publicKey ?? result.publicKey,
3484
+ algorithm: decoded.algorithm,
3485
+ encoding,
3486
+ caipChainId,
3487
+ signingScheme: 'hedera-wc',
3488
+ metadata: { result },
3489
+ };
3490
+ }
3491
+ // Fallback for non-standard wallets that return a flat `{ signature }`.
3492
+ // No spec shape to infer a byte layout from, so only a scheme the wallet
3493
+ // itself DECLARES (validated) is forwarded — guessing one would send the
3494
+ // verifier reconstructing bytes that were never signed.
3495
+ if (typeof result.signature !== 'string' || result.signature.length === 0) {
3496
+ throw new Error('wallet returned no signature');
3497
+ }
3465
3498
  return {
3466
- signature: String(result.signatureMap ||
3467
- result.signature ||
3468
- JSON.stringify(result)),
3499
+ signature: result.signature,
3469
3500
  publicKey: result.publicKey,
3501
+ caipChainId,
3502
+ encoding,
3503
+ signingScheme: isAuthSigningScheme(result.signingScheme) ? result.signingScheme : undefined,
3470
3504
  metadata: { result },
3471
3505
  };
3472
3506
  }
@@ -3477,13 +3511,13 @@ class HederaSigner {
3477
3511
  Object.keys(error).length === 0 &&
3478
3512
  !(error instanceof Error);
3479
3513
  if (isEmptyError) {
3480
- logger$g.warn('WalletConnect SDK empty error - relay subscription may have been stale', {
3514
+ logger$h.warn('WalletConnect SDK empty error - relay subscription may have been stale', {
3481
3515
  topic: params.topic?.substring(0, 16) + '...',
3482
3516
  });
3483
3517
  throw new Error('WalletConnect connection issue - please try again');
3484
3518
  }
3485
3519
  const errorMsg = extractErrorMessage$1(error);
3486
- logger$g.error('Sign message failed', { error: errorMsg });
3520
+ logger$h.error('Sign message failed', { error: errorMsg });
3487
3521
  throw new Error(`Hedera sign message failed: ${errorMsg}`);
3488
3522
  }
3489
3523
  }
@@ -3501,15 +3535,15 @@ class HederaSigner {
3501
3535
  */
3502
3536
  parseAccounts(namespace, targetNetworkId) {
3503
3537
  if (!namespace) {
3504
- logger$g.warn('Namespace is null or undefined');
3538
+ logger$h.warn('Namespace is null or undefined');
3505
3539
  return [];
3506
3540
  }
3507
3541
  if (!namespace.accounts) {
3508
- logger$g.warn('Namespace has no accounts property');
3542
+ logger$h.warn('Namespace has no accounts property');
3509
3543
  return [];
3510
3544
  }
3511
3545
  if (!Array.isArray(namespace.accounts)) {
3512
- logger$g.warn('Namespace accounts is not an array', {
3546
+ logger$h.warn('Namespace accounts is not an array', {
3513
3547
  type: typeof namespace.accounts,
3514
3548
  });
3515
3549
  return [];
@@ -3519,7 +3553,7 @@ class HederaSigner {
3519
3553
  // HIP-30 format: hedera:testnet:0.0.12345
3520
3554
  const parts = account.split(':');
3521
3555
  if (parts.length < 3) {
3522
- logger$g.warn('Invalid account format', { account, partsLength: parts.length });
3556
+ logger$h.warn('Invalid account format', { account, partsLength: parts.length });
3523
3557
  return { address: account, chainId: 'hedera:testnet' };
3524
3558
  }
3525
3559
  return {
@@ -3532,7 +3566,7 @@ class HederaSigner {
3532
3566
  const targetNetwork = targetNetworkId.split(':')[1]?.toLowerCase(); // e.g., 'mainnet'
3533
3567
  if (targetNetwork) {
3534
3568
  const filteredAccounts = allAccounts.filter((acc) => acc.chainId.toLowerCase().includes(targetNetwork));
3535
- logger$g.debug('Filtered accounts by target network', {
3569
+ logger$h.debug('Filtered accounts by target network', {
3536
3570
  targetNetworkId,
3537
3571
  targetNetwork,
3538
3572
  totalAccounts: allAccounts.length,
@@ -3540,7 +3574,7 @@ class HederaSigner {
3540
3574
  });
3541
3575
  // If no accounts match the target network, log a warning
3542
3576
  if (filteredAccounts.length === 0 && allAccounts.length > 0) {
3543
- logger$g.warn('No accounts found for target network', {
3577
+ logger$h.warn('No accounts found for target network', {
3544
3578
  targetNetwork,
3545
3579
  availableNetworks: [...new Set(allAccounts.map((a) => a.chainId))],
3546
3580
  });
@@ -3568,7 +3602,7 @@ class HederaSigner {
3568
3602
  * Implements the IWalletConnectSigner interface for XRPL ledger.
3569
3603
  * Handles XRPL-specific JSON-RPC methods and transaction formats.
3570
3604
  */
3571
- const logger$f = getLogger().scoped?.('XrplSigner') ?? getLogger();
3605
+ const logger$g = getLogger().scoped?.('XrplSigner') ?? getLogger();
3572
3606
  /**
3573
3607
  * Extract a meaningful error message from various error shapes.
3574
3608
  * WalletConnect SDK throws errors that are not standard Error instances.
@@ -3586,7 +3620,7 @@ const logger$f = getLogger().scoped?.('XrplSigner') ?? getLogger();
3586
3620
  */
3587
3621
  function extractErrorMessage(error) {
3588
3622
  // Log raw error for debugging
3589
- logger$f.debug('Raw error object', {
3623
+ logger$g.debug('Raw error object', {
3590
3624
  errorType: typeof error,
3591
3625
  isError: error instanceof Error,
3592
3626
  errorKeys: typeof error === 'object' && error !== null ? Object.keys(error) : [],
@@ -3722,7 +3756,7 @@ class XrplSigner {
3722
3756
  */
3723
3757
  async signTransaction(params) {
3724
3758
  // Decode base64 payload to JSON transaction
3725
- logger$f.debug('Decoding XRPL transaction payload', {
3759
+ logger$g.debug('Decoding XRPL transaction payload', {
3726
3760
  payloadLength: params.payload?.length,
3727
3761
  networkId: params.networkId,
3728
3762
  topic: params.topic?.substring(0, 16) + '...',
@@ -3730,19 +3764,19 @@ class XrplSigner {
3730
3764
  let transaction;
3731
3765
  try {
3732
3766
  transaction = XrplTransactionEncoder.decodeTransaction(params.payload);
3733
- logger$f.debug('Transaction decoded successfully', {
3767
+ logger$g.debug('Transaction decoded successfully', {
3734
3768
  transactionType: transaction?.TransactionType,
3735
3769
  account: transaction?.Account,
3736
3770
  });
3737
3771
  }
3738
3772
  catch (decodeError) {
3739
- logger$f.error('Failed to decode transaction payload', {
3773
+ logger$g.error('Failed to decode transaction payload', {
3740
3774
  error: decodeError instanceof Error ? decodeError.message : String(decodeError),
3741
3775
  });
3742
3776
  throw decodeError;
3743
3777
  }
3744
3778
  try {
3745
- logger$f.debug('Sending xrpl_signTransaction request to wallet', {
3779
+ logger$g.debug('Sending xrpl_signTransaction request to wallet', {
3746
3780
  method: 'xrpl_signTransaction',
3747
3781
  chainId: params.networkId,
3748
3782
  topic: params.topic?.substring(0, 16) + '...',
@@ -3759,7 +3793,7 @@ class XrplSigner {
3759
3793
  },
3760
3794
  expiry: 300, // 5 minutes in seconds
3761
3795
  });
3762
- logger$f.debug('Received response from wallet', {
3796
+ logger$g.debug('Received response from wallet', {
3763
3797
  hasResult: !!result,
3764
3798
  resultKeys: result ? Object.keys(result) : [],
3765
3799
  });
@@ -3775,13 +3809,13 @@ class XrplSigner {
3775
3809
  Object.keys(error).length === 0 &&
3776
3810
  !(error instanceof Error);
3777
3811
  if (isEmptyError) {
3778
- logger$f.warn('WalletConnect SDK empty error - relay subscription may have been stale', {
3812
+ logger$g.warn('WalletConnect SDK empty error - relay subscription may have been stale', {
3779
3813
  topic: params.topic?.substring(0, 16) + '...',
3780
3814
  });
3781
3815
  throw new Error('WalletConnect connection issue - please try again');
3782
3816
  }
3783
3817
  const errorMsg = extractErrorMessage(error);
3784
- logger$f.error('Sign failed', { error: errorMsg });
3818
+ logger$g.error('Sign failed', { error: errorMsg });
3785
3819
  throw new Error(`XRPL sign failed: ${errorMsg}`);
3786
3820
  }
3787
3821
  }
@@ -3796,7 +3830,7 @@ class XrplSigner {
3796
3830
  // Decode base64 payload to JSON transaction
3797
3831
  const transaction = XrplTransactionEncoder.decodeTransaction(params.payload);
3798
3832
  try {
3799
- logger$f.debug('Sending xrpl_signAndSubmit request to wallet', {
3833
+ logger$g.debug('Sending xrpl_signAndSubmit request to wallet', {
3800
3834
  method: 'xrpl_signAndSubmit',
3801
3835
  chainId: params.networkId,
3802
3836
  topic: params.topic?.substring(0, 16) + '...',
@@ -3813,7 +3847,7 @@ class XrplSigner {
3813
3847
  },
3814
3848
  expiry: 300, // 5 minutes in seconds
3815
3849
  });
3816
- logger$f.debug('Received xrpl_signAndSubmit response', {
3850
+ logger$g.debug('Received xrpl_signAndSubmit response', {
3817
3851
  hasResult: !!result,
3818
3852
  resultKeys: result ? Object.keys(result) : [],
3819
3853
  });
@@ -3835,14 +3869,14 @@ class XrplSigner {
3835
3869
  if (isEmptyError) {
3836
3870
  // Empty error object is a known WalletConnect SDK issue
3837
3871
  // It usually means the relay subscription was stale
3838
- logger$f.warn('WalletConnect SDK empty error - relay subscription may have been stale', {
3872
+ logger$g.warn('WalletConnect SDK empty error - relay subscription may have been stale', {
3839
3873
  topic: params.topic?.substring(0, 16) + '...',
3840
3874
  hint: 'This can happen when the relay WebSocket connection drops',
3841
3875
  });
3842
3876
  throw new Error('WalletConnect connection issue - please try again');
3843
3877
  }
3844
3878
  const errorMsg = extractErrorMessage(error);
3845
- logger$f.error('Submit failed', { error: errorMsg });
3879
+ logger$g.error('Submit failed', { error: errorMsg });
3846
3880
  throw new Error(`XRPL submit failed: ${errorMsg}`);
3847
3881
  }
3848
3882
  }
@@ -3866,22 +3900,42 @@ class XrplSigner {
3866
3900
  * @returns Promise resolving to signature and metadata
3867
3901
  */
3868
3902
  async signMessage(params) {
3903
+ // params.networkId IS the CAIP-2 chain id — it is what this request is
3904
+ // addressed to (`chainId` below), so it is what the wallet binds into the
3905
+ // signed blob. Re-deriving it by substring sniffing loses e.g. devnet.
3906
+ const caipChainId = params.networkId;
3907
+ const encoding = params.encoding ?? 'utf-8';
3869
3908
  try {
3870
3909
  // Use 5-minute expiry to give users time to review and approve
3871
- const result = await params.client.request({
3910
+ const result = (await params.client.request({
3872
3911
  topic: params.topic,
3873
3912
  chainId: params.networkId,
3874
3913
  request: {
3875
3914
  method: 'xrpl_signMessage',
3876
3915
  params: {
3877
- message: params.message, // Can be base64 or utf-8
3916
+ message: params.message,
3917
+ // Transmitted so the wallet decodes the same bytes this result
3918
+ // claims were signed — echoing an encoding the wallet never saw
3919
+ // would let the two sides sign and verify different byte strings.
3920
+ encoding,
3878
3921
  },
3879
3922
  },
3880
3923
  expiry: 300, // 5 minutes in seconds
3881
- });
3924
+ }));
3925
+ if (!result.signature) {
3926
+ throw new Error('wallet returned no signature');
3927
+ }
3928
+ // §21.3 verification fields: caipChainId binds the signed bytes to the
3929
+ // chain. The scheme is whatever the wallet DECLARES (an unknown value
3930
+ // degrades to undefined = the legacy `hsuite-domain` default, which is
3931
+ // also exactly what non-declaring older wallets signed).
3882
3932
  return {
3883
- signature: result.signature || JSON.stringify(result),
3933
+ signature: result.signature,
3884
3934
  publicKey: result.publicKey,
3935
+ algorithm: result.algorithm,
3936
+ encoding,
3937
+ caipChainId,
3938
+ signingScheme: isAuthSigningScheme(result.signingScheme) ? result.signingScheme : undefined,
3885
3939
  metadata: { result },
3886
3940
  };
3887
3941
  }
@@ -3892,13 +3946,13 @@ class XrplSigner {
3892
3946
  Object.keys(error).length === 0 &&
3893
3947
  !(error instanceof Error);
3894
3948
  if (isEmptyError) {
3895
- logger$f.warn('WalletConnect SDK empty error - relay subscription may have been stale', {
3949
+ logger$g.warn('WalletConnect SDK empty error - relay subscription may have been stale', {
3896
3950
  topic: params.topic?.substring(0, 16) + '...',
3897
3951
  });
3898
3952
  throw new Error('WalletConnect connection issue - please try again');
3899
3953
  }
3900
3954
  const errorMsg = extractErrorMessage(error);
3901
- logger$f.error('Sign message failed', { error: errorMsg });
3955
+ logger$g.error('Sign message failed', { error: errorMsg });
3902
3956
  throw new Error(`XRPL sign message failed: ${errorMsg}`);
3903
3957
  }
3904
3958
  }
@@ -3923,7 +3977,7 @@ class XrplSigner {
3923
3977
  // XRPL format: xrpl:testnet:rN7n7otQDd6FczFgLdlqtyMVrn3WnFBrDB
3924
3978
  const parts = account.split(':');
3925
3979
  if (parts.length < 3) {
3926
- logger$f.warn('Invalid account format', { account });
3980
+ logger$g.warn('Invalid account format', { account });
3927
3981
  return { address: account, chainId: 'xrpl:testnet' };
3928
3982
  }
3929
3983
  return {
@@ -3936,7 +3990,7 @@ class XrplSigner {
3936
3990
  const targetNetwork = targetNetworkId.split(':')[1]?.toLowerCase(); // e.g., 'mainnet'
3937
3991
  if (targetNetwork) {
3938
3992
  const filteredAccounts = allAccounts.filter((acc) => acc.chainId.toLowerCase().includes(targetNetwork));
3939
- logger$f.debug('Filtered accounts by target network', {
3993
+ logger$g.debug('Filtered accounts by target network', {
3940
3994
  targetNetworkId,
3941
3995
  targetNetwork,
3942
3996
  totalAccounts: allAccounts.length,
@@ -3944,7 +3998,7 @@ class XrplSigner {
3944
3998
  });
3945
3999
  // If no accounts match the target network, log a warning
3946
4000
  if (filteredAccounts.length === 0 && allAccounts.length > 0) {
3947
- logger$f.warn('No accounts found for target network', {
4001
+ logger$g.warn('No accounts found for target network', {
3948
4002
  targetNetwork,
3949
4003
  availableNetworks: [...new Set(allAccounts.map((a) => a.chainId))],
3950
4004
  });
@@ -3976,7 +4030,7 @@ class XrplSigner {
3976
4030
  * 1. Implementing IWalletConnectSigner interface
3977
4031
  * 2. Registering the signer with SignerFactory
3978
4032
  */
3979
- const logger$e = getLogger().scoped?.('SignerFactory') ?? getLogger();
4033
+ const logger$f = getLogger().scoped?.('SignerFactory') ?? getLogger();
3980
4034
  /**
3981
4035
  * Factory class for creating and managing WalletConnect signers.
3982
4036
  *
@@ -4018,13 +4072,13 @@ class SignerFactory {
4018
4072
  */
4019
4073
  static registerSigner(ledgerId, signer) {
4020
4074
  if (signer.ledgerId !== ledgerId) {
4021
- logger$e.warn('Signer ledgerId does not match registration key', {
4075
+ logger$f.warn('Signer ledgerId does not match registration key', {
4022
4076
  signerLedgerId: signer.ledgerId,
4023
4077
  registrationKey: ledgerId,
4024
4078
  });
4025
4079
  }
4026
4080
  this.signers.set(ledgerId, signer);
4027
- logger$e.debug('Registered signer for ledger', { ledgerId });
4081
+ logger$f.debug('Registered signer for ledger', { ledgerId });
4028
4082
  }
4029
4083
  /**
4030
4084
  * Check if a signer is registered for a ledger.
@@ -4053,7 +4107,7 @@ class SignerFactory {
4053
4107
  static unregisterSigner(ledgerId) {
4054
4108
  const removed = this.signers.delete(ledgerId);
4055
4109
  if (removed) {
4056
- logger$e.debug('Unregistered signer for ledger', { ledgerId });
4110
+ logger$f.debug('Unregistered signer for ledger', { ledgerId });
4057
4111
  }
4058
4112
  return removed;
4059
4113
  }
@@ -4082,7 +4136,7 @@ class SignerFactory {
4082
4136
  * - Automatic ping cache management
4083
4137
  * - Subscription refresh capability
4084
4138
  */
4085
- const logger$d = getLogger().scoped?.('WCSessionHealth') ?? getLogger();
4139
+ const logger$e = getLogger().scoped?.('WCSessionHealth') ?? getLogger();
4086
4140
  /**
4087
4141
  * Manages WalletConnect session health to prevent stale relay subscription issues.
4088
4142
  *
@@ -4113,7 +4167,7 @@ class SessionHealthManager {
4113
4167
  constructor(client) {
4114
4168
  this.client = client;
4115
4169
  this.setupRelayMonitoring();
4116
- logger$d.info('SessionHealthManager initialized');
4170
+ logger$e.info('SessionHealthManager initialized');
4117
4171
  }
4118
4172
  /**
4119
4173
  * Ensure session is healthy before making a request.
@@ -4131,14 +4185,14 @@ class SessionHealthManager {
4131
4185
  const now = Date.now();
4132
4186
  // Skip if we pinged recently
4133
4187
  if (now - lastPing <= this.PING_INTERVAL_MS) {
4134
- logger$d.debug('Skipping ping - recent ping exists', {
4188
+ logger$e.debug('Skipping ping - recent ping exists', {
4135
4189
  topic: topic.substring(0, 16) + '...',
4136
4190
  lastPingAge: now - lastPing,
4137
4191
  });
4138
4192
  return;
4139
4193
  }
4140
4194
  try {
4141
- logger$d.debug('Pinging session to ensure relay subscription', {
4195
+ logger$e.debug('Pinging session to ensure relay subscription', {
4142
4196
  topic: topic.substring(0, 16) + '...',
4143
4197
  });
4144
4198
  // Race ping against timeout
@@ -4147,14 +4201,14 @@ class SessionHealthManager {
4147
4201
  new Promise((_, reject) => setTimeout(() => reject(new Error('Ping timeout')), this.PING_TIMEOUT_MS)),
4148
4202
  ]);
4149
4203
  this.lastPingTime.set(topic, now);
4150
- logger$d.debug('Session ping successful', {
4204
+ logger$e.debug('Session ping successful', {
4151
4205
  topic: topic.substring(0, 16) + '...',
4152
4206
  });
4153
4207
  }
4154
4208
  catch (err) {
4155
4209
  // Log warning but don't throw - let the request attempt proceed
4156
4210
  // The request might still succeed if the subscription is actually active
4157
- logger$d.warn('Session ping failed - relay subscription may be stale', {
4211
+ logger$e.warn('Session ping failed - relay subscription may be stale', {
4158
4212
  topic: topic.substring(0, 16) + '...',
4159
4213
  error: err instanceof Error ? err.message : String(err),
4160
4214
  });
@@ -4176,16 +4230,16 @@ class SessionHealthManager {
4176
4230
  await relayer.subscribe(topic);
4177
4231
  // Clear ping cache so next ensureSessionHealth will ping
4178
4232
  this.lastPingTime.delete(topic);
4179
- logger$d.info('Refreshed relay subscription', {
4233
+ logger$e.info('Refreshed relay subscription', {
4180
4234
  topic: topic.substring(0, 16) + '...',
4181
4235
  });
4182
4236
  }
4183
4237
  else {
4184
- logger$d.warn('Relayer.subscribe not available');
4238
+ logger$e.warn('Relayer.subscribe not available');
4185
4239
  }
4186
4240
  }
4187
4241
  catch (err) {
4188
- logger$d.warn('Failed to refresh subscription', {
4242
+ logger$e.warn('Failed to refresh subscription', {
4189
4243
  topic: topic.substring(0, 16) + '...',
4190
4244
  error: err instanceof Error ? err.message : String(err),
4191
4245
  });
@@ -4218,22 +4272,22 @@ class SessionHealthManager {
4218
4272
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- WalletConnect internal API not typed
4219
4273
  const relayer = this.client.core?.relayer;
4220
4274
  if (!relayer) {
4221
- logger$d.warn('Could not access relayer for monitoring');
4275
+ logger$e.warn('Could not access relayer for monitoring');
4222
4276
  return;
4223
4277
  }
4224
4278
  relayer.on('connect', () => {
4225
- logger$d.info('Relay WebSocket connected');
4279
+ logger$e.info('Relay WebSocket connected');
4226
4280
  });
4227
4281
  relayer.on('disconnect', () => {
4228
- logger$d.warn('Relay WebSocket disconnected - clearing ping cache');
4282
+ logger$e.warn('Relay WebSocket disconnected - clearing ping cache');
4229
4283
  this.lastPingTime.clear();
4230
4284
  });
4231
4285
  relayer.on('error', (err) => {
4232
- logger$d.error('Relay error', {
4286
+ logger$e.error('Relay error', {
4233
4287
  error: err?.message || String(err),
4234
4288
  });
4235
4289
  });
4236
- logger$d.debug('Relay monitoring setup complete');
4290
+ logger$e.debug('Relay monitoring setup complete');
4237
4291
  }
4238
4292
  }
4239
4293
 
@@ -4258,7 +4312,7 @@ class SessionHealthManager {
4258
4312
  *
4259
4313
  * Extracted from WalletConnectV2Provider to reduce file size.
4260
4314
  */
4261
- const logger$c = getLogger().scoped?.('WCClientManager') ?? getLogger();
4315
+ const logger$d = getLogger().scoped?.('WCClientManager') ?? getLogger();
4262
4316
  /**
4263
4317
  * Storage key for persisted projectId
4264
4318
  */
@@ -4285,7 +4339,7 @@ class WalletConnectClientManager {
4285
4339
  if (this.client && this.projectId === projectId) {
4286
4340
  return this.client;
4287
4341
  }
4288
- logger$c.debug('Initializing SignClient', { projectId: projectId.substring(0, 8) });
4342
+ logger$d.debug('Initializing SignClient', { projectId: projectId.substring(0, 8) });
4289
4343
  // Store projectId for session restoration
4290
4344
  this.projectId = projectId;
4291
4345
  this.persistProjectId(projectId);
@@ -4297,7 +4351,7 @@ class WalletConnectClientManager {
4297
4351
  });
4298
4352
  // Initialize session health manager for relay subscription management
4299
4353
  this.sessionHealth = new SessionHealthManager(this.client);
4300
- logger$c.info('SignClient initialized with session health manager');
4354
+ logger$d.info('SignClient initialized with session health manager');
4301
4355
  return this.client;
4302
4356
  }
4303
4357
  /**
@@ -4326,14 +4380,14 @@ class WalletConnectClientManager {
4326
4380
  async restoreClient(metadata) {
4327
4381
  const storedProjectId = this.getStoredProjectId();
4328
4382
  if (!storedProjectId) {
4329
- logger$c.debug('No stored projectId, skipping client restoration');
4383
+ logger$d.debug('No stored projectId, skipping client restoration');
4330
4384
  return undefined;
4331
4385
  }
4332
4386
  try {
4333
4387
  return await this.initialize(storedProjectId, metadata);
4334
4388
  }
4335
4389
  catch (error) {
4336
- logger$c.error('Failed to restore client', {
4390
+ logger$d.error('Failed to restore client', {
4337
4391
  error: error instanceof Error ? error.message : String(error),
4338
4392
  });
4339
4393
  return undefined;
@@ -4400,7 +4454,7 @@ class WalletConnectClientManager {
4400
4454
  if (sessionProperties) {
4401
4455
  connectParams.sessionProperties = sessionProperties;
4402
4456
  }
4403
- logger$c.debug('Connecting with params', {
4457
+ logger$d.debug('Connecting with params', {
4404
4458
  namespaces: Object.keys(optionalNamespaces),
4405
4459
  hasSessionProperties: !!sessionProperties,
4406
4460
  });
@@ -4466,7 +4520,7 @@ class WalletConnectClientManager {
4466
4520
  const startKeepAlive = () => {
4467
4521
  keepAliveInterval = setInterval(async () => {
4468
4522
  try {
4469
- logger$c.debug('Keep-alive ping during request', {
4523
+ logger$d.debug('Keep-alive ping during request', {
4470
4524
  topic: params.topic?.substring(0, 16) + '...',
4471
4525
  method: params.request.method,
4472
4526
  });
@@ -4479,7 +4533,7 @@ class WalletConnectClientManager {
4479
4533
  }
4480
4534
  catch (err) {
4481
4535
  // Log but don't throw - ping failure during wait is not critical
4482
- logger$c.debug('Keep-alive ping failed (non-critical)', {
4536
+ logger$d.debug('Keep-alive ping failed (non-critical)', {
4483
4537
  error: err instanceof Error ? err.message : String(err),
4484
4538
  });
4485
4539
  }
@@ -4521,7 +4575,7 @@ class WalletConnectClientManager {
4521
4575
  window.localStorage?.setItem(STORAGE_KEY_PROJECT_ID, projectId);
4522
4576
  }
4523
4577
  catch {
4524
- logger$c.warn('Failed to persist projectId');
4578
+ logger$d.warn('Failed to persist projectId');
4525
4579
  }
4526
4580
  }
4527
4581
  getStoredProjectId() {
@@ -4566,7 +4620,7 @@ class WalletConnectClientManager {
4566
4620
  * - Aggregate accounts across sessions
4567
4621
  * - Find sessions by account address
4568
4622
  */
4569
- const logger$b = getLogger().scoped?.('WCSessionStore') ?? getLogger();
4623
+ const logger$c = getLogger().scoped?.('WCSessionStore') ?? getLogger();
4570
4624
  /**
4571
4625
  * WalletConnect Session Store
4572
4626
  *
@@ -4604,7 +4658,7 @@ class WalletConnectSessionStore {
4604
4658
  */
4605
4659
  setSession(sessionKey, data) {
4606
4660
  this.sessions.set(sessionKey, data);
4607
- logger$b.debug('Session stored', { sessionKey, accountCount: data.accounts.length });
4661
+ logger$c.debug('Session stored', { sessionKey, accountCount: data.accounts.length });
4608
4662
  }
4609
4663
  /**
4610
4664
  * Delete a session by key.
@@ -4615,7 +4669,7 @@ class WalletConnectSessionStore {
4615
4669
  deleteSession(sessionKey) {
4616
4670
  const deleted = this.sessions.delete(sessionKey);
4617
4671
  if (deleted) {
4618
- logger$b.debug('Session deleted', { sessionKey });
4672
+ logger$c.debug('Session deleted', { sessionKey });
4619
4673
  }
4620
4674
  return deleted;
4621
4675
  }
@@ -4639,7 +4693,7 @@ class WalletConnectSessionStore {
4639
4693
  clear() {
4640
4694
  this.sessions.clear();
4641
4695
  this._accounts.set([]);
4642
- logger$b.debug('All sessions cleared');
4696
+ logger$c.debug('All sessions cleared');
4643
4697
  }
4644
4698
  /**
4645
4699
  * Get all session entries.
@@ -4680,7 +4734,7 @@ class WalletConnectSessionStore {
4680
4734
  for (const sessionData of this.sessions.values()) {
4681
4735
  allAccounts.push(...sessionData.accounts);
4682
4736
  }
4683
- logger$b.debug('Aggregated accounts', {
4737
+ logger$c.debug('Aggregated accounts', {
4684
4738
  sessionCount: this.sessions.size,
4685
4739
  totalAccounts: allAccounts.length,
4686
4740
  });
@@ -4716,7 +4770,7 @@ class WalletConnectSessionStore {
4716
4770
  for (const [sessionKey, sessionData] of this.sessions.entries()) {
4717
4771
  if (sessionData.session.topic === topic) {
4718
4772
  this.sessions.delete(sessionKey);
4719
- logger$b.info('Session removed by topic', { sessionKey, topic: topic.substring(0, 16) });
4773
+ logger$c.info('Session removed by topic', { sessionKey, topic: topic.substring(0, 16) });
4720
4774
  return { sessionKey, data: sessionData };
4721
4775
  }
4722
4776
  }
@@ -4764,7 +4818,7 @@ class WalletConnectSessionStore {
4764
4818
  *
4765
4819
  * Extracted from WalletConnectV2Provider to reduce file size.
4766
4820
  */
4767
- const logger$a = getLogger().scoped?.('WCSigningOrchestrator') ?? getLogger();
4821
+ const logger$b = getLogger().scoped?.('WCSigningOrchestrator') ?? getLogger();
4768
4822
  /**
4769
4823
  * Signing Orchestrator
4770
4824
  *
@@ -4795,7 +4849,7 @@ class WalletConnectSigningOrchestrator {
4795
4849
  const sessionInfo = this.findAndValidateSession(options.accountAddress, 'signTransaction');
4796
4850
  // Use user's selected network from session, with fallback to options.networkId
4797
4851
  const networkId = this.resolveNetworkId(sessionInfo, options.networkId);
4798
- logger$a.debug('Routing sign to signer', {
4852
+ logger$b.debug('Routing sign to signer', {
4799
4853
  ledgerId: sessionInfo.signer.ledgerId,
4800
4854
  topic: sessionInfo.session.topic.substring(0, 16) + '...',
4801
4855
  networkId,
@@ -4818,7 +4872,7 @@ class WalletConnectSigningOrchestrator {
4818
4872
  const sessionInfo = this.findAndValidateSession(options.accountAddress, 'submitTransaction');
4819
4873
  // Use user's selected network from session, with fallback to options.networkId
4820
4874
  const networkId = this.resolveNetworkId(sessionInfo, options.networkId);
4821
- logger$a.debug('Routing submit to signer', {
4875
+ logger$b.debug('Routing submit to signer', {
4822
4876
  ledgerId: sessionInfo.signer.ledgerId,
4823
4877
  topic: sessionInfo.session.topic.substring(0, 16) + '...',
4824
4878
  networkId,
@@ -4841,7 +4895,7 @@ class WalletConnectSigningOrchestrator {
4841
4895
  const sessionInfo = this.findAndValidateSession(options.accountAddress, 'signAndExecuteTransaction');
4842
4896
  // Use user's selected network from session, with fallback to options.networkId
4843
4897
  const networkId = this.resolveNetworkId(sessionInfo, options.networkId);
4844
- logger$a.debug('Routing signAndExecute to signer', {
4898
+ logger$b.debug('Routing signAndExecute to signer', {
4845
4899
  ledgerId: sessionInfo.signer.ledgerId,
4846
4900
  topic: sessionInfo.session.topic.substring(0, 16) + '...',
4847
4901
  networkId,
@@ -4882,7 +4936,7 @@ class WalletConnectSigningOrchestrator {
4882
4936
  const sessionInfo = this.findAndValidateSession(options.accountAddress, 'signMessage');
4883
4937
  // Use user's selected network from session, with fallback to options.networkId
4884
4938
  const networkId = this.resolveNetworkId(sessionInfo, options.networkId);
4885
- logger$a.debug('Routing signMessage to signer', {
4939
+ logger$b.debug('Routing signMessage to signer', {
4886
4940
  ledgerId: sessionInfo.signer.ledgerId,
4887
4941
  topic: sessionInfo.session.topic.substring(0, 16) + '...',
4888
4942
  networkId,
@@ -4923,7 +4977,7 @@ class WalletConnectSigningOrchestrator {
4923
4977
  if (optionsNetworkId &&
4924
4978
  sessionInfo.userSelectedNetwork &&
4925
4979
  optionsNetworkId !== sessionInfo.userSelectedNetwork) {
4926
- logger$a.warn('Network mismatch: using session network over caller-provided network', {
4980
+ logger$b.warn('Network mismatch: using session network over caller-provided network', {
4927
4981
  callerNetwork: optionsNetworkId,
4928
4982
  sessionNetwork: sessionInfo.userSelectedNetwork,
4929
4983
  using: resolvedNetwork,
@@ -4943,7 +4997,7 @@ class WalletConnectSigningOrchestrator {
4943
4997
  }
4944
4998
  // Validate session exists in WC SDK
4945
4999
  if (!this.validateSessionInSdk(sessionInfo.session.topic)) {
4946
- logger$a.error('Session not found in WC SDK', {
5000
+ logger$b.error('Session not found in WC SDK', {
4947
5001
  topic: sessionInfo.session.topic.substring(0, 16) + '...',
4948
5002
  account: accountAddress,
4949
5003
  });
@@ -4970,7 +5024,7 @@ class WalletConnectSigningOrchestrator {
4970
5024
  return !!session;
4971
5025
  }
4972
5026
  catch (error) {
4973
- logger$a.warn('Session validation failed', {
5027
+ logger$b.warn('Session validation failed', {
4974
5028
  topic: topic.substring(0, 16) + '...',
4975
5029
  error: error instanceof Error ? error.message : String(error),
4976
5030
  });
@@ -5006,7 +5060,7 @@ class WalletConnectSigningOrchestrator {
5006
5060
  * - Testable (mock signers for unit tests)
5007
5061
  * - Maintainable (ledger logic is isolated)
5008
5062
  */
5009
- const logger$9 = getLogger().scoped?.('WalletConnectV2Provider') ?? getLogger();
5063
+ const logger$a = getLogger().scoped?.('WalletConnectV2Provider') ?? getLogger();
5010
5064
  /**
5011
5065
  * Storage key prefix for persisting user's network selection per session topic.
5012
5066
  * This is critical for proper session restoration after page reload.
@@ -5070,7 +5124,7 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5070
5124
  clientManager: this.clientManager,
5071
5125
  eventBus: this.eventBus,
5072
5126
  });
5073
- logger$9.info('Initializing - will attempt session restoration');
5127
+ logger$a.info('Initializing - will attempt session restoration');
5074
5128
  void this.restoreSession();
5075
5129
  }
5076
5130
  /**
@@ -5097,7 +5151,7 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5097
5151
  */
5098
5152
  async restoreSession() {
5099
5153
  try {
5100
- logger$9.debug('Attempting to restore sessions...');
5154
+ logger$a.debug('Attempting to restore sessions...');
5101
5155
  // Restore client from stored projectId
5102
5156
  const client = await this.clientManager.restoreClient({
5103
5157
  name: 'HSuite Demo',
@@ -5112,7 +5166,7 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5112
5166
  this.registerSessionDeleteListener();
5113
5167
  // Get all active sessions
5114
5168
  const activeSessions = this.clientManager.getActiveSessions();
5115
- logger$9.info('Found active sessions', { count: activeSessions.length });
5169
+ logger$a.info('Found active sessions', { count: activeSessions.length });
5116
5170
  if (activeSessions.length === 0) {
5117
5171
  return;
5118
5172
  }
@@ -5122,7 +5176,7 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5122
5176
  await this.restoreSingleSession(session);
5123
5177
  }
5124
5178
  catch (error) {
5125
- logger$9.error('Failed to restore session', {
5179
+ logger$a.error('Failed to restore session', {
5126
5180
  topic: session.topic,
5127
5181
  error: error instanceof Error ? error.message : String(error),
5128
5182
  });
@@ -5132,11 +5186,11 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5132
5186
  this.sessionStore.updateAggregatedAccounts();
5133
5187
  if (this.sessionStore.size > 0) {
5134
5188
  this._status.set('connected');
5135
- logger$9.info('Restored sessions', { count: this.sessionStore.size });
5189
+ logger$a.info('Restored sessions', { count: this.sessionStore.size });
5136
5190
  }
5137
5191
  }
5138
5192
  catch (error) {
5139
- logger$9.error('Failed to restore sessions', {
5193
+ logger$a.error('Failed to restore sessions', {
5140
5194
  error: error instanceof Error ? error.message : String(error),
5141
5195
  });
5142
5196
  }
@@ -5151,23 +5205,23 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5151
5205
  * @param session - WalletConnect session object from IndexedDB
5152
5206
  */
5153
5207
  async restoreSingleSession(session) {
5154
- logger$9.debug('Restoring session', { topic: session.topic });
5155
- logger$9.debug('Session namespaces', { namespaces: Object.keys(session.namespaces) });
5208
+ logger$a.debug('Restoring session', { topic: session.topic });
5209
+ logger$a.debug('Session namespaces', { namespaces: Object.keys(session.namespaces) });
5156
5210
  // Determine ledger from session namespaces
5157
5211
  let ledgerId;
5158
5212
  let walletReportedNetwork;
5159
5213
  if (session.namespaces.hedera) {
5160
5214
  ledgerId = 'hedera';
5161
5215
  walletReportedNetwork = session.namespaces.hedera.chains?.[0] || 'hedera:testnet';
5162
- logger$9.debug('Found Hedera namespace', { chains: session.namespaces.hedera.chains });
5216
+ logger$a.debug('Found Hedera namespace', { chains: session.namespaces.hedera.chains });
5163
5217
  }
5164
5218
  else if (session.namespaces.xrpl) {
5165
5219
  ledgerId = 'xrpl';
5166
5220
  walletReportedNetwork = session.namespaces.xrpl.chains?.[0] || 'xrpl:testnet';
5167
- logger$9.debug('Found XRPL namespace', { chains: session.namespaces.xrpl.chains });
5221
+ logger$a.debug('Found XRPL namespace', { chains: session.namespaces.xrpl.chains });
5168
5222
  }
5169
5223
  if (!ledgerId || !walletReportedNetwork) {
5170
- logger$9.warn('Could not determine ledger for session', {
5224
+ logger$a.warn('Could not determine ledger for session', {
5171
5225
  topic: session.topic,
5172
5226
  availableNamespaces: Object.keys(session.namespaces),
5173
5227
  });
@@ -5178,14 +5232,14 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5178
5232
  const userSelectedNetwork = this.getUserNetworkSelection(session.topic);
5179
5233
  const networkId = userSelectedNetwork || walletReportedNetwork;
5180
5234
  if (userSelectedNetwork) {
5181
- logger$9.debug('Restored user network selection', {
5235
+ logger$a.debug('Restored user network selection', {
5182
5236
  userSelectedNetwork,
5183
5237
  walletReportedNetwork,
5184
5238
  topic: session.topic.substring(0, 16),
5185
5239
  });
5186
5240
  }
5187
5241
  else {
5188
- logger$9.warn('No stored network selection found, using wallet-reported network', {
5242
+ logger$a.warn('No stored network selection found, using wallet-reported network', {
5189
5243
  walletReportedNetwork,
5190
5244
  topic: session.topic.substring(0, 16),
5191
5245
  });
@@ -5196,18 +5250,18 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5196
5250
  const sessionKey = this.sessionStore.generateSessionKey(ledgerId, networkId, session.topic);
5197
5251
  // Parse accounts from session, filtering by user's selected network
5198
5252
  const namespace = session.namespaces[ledgerId];
5199
- logger$9.debug('Namespace for restoration', {
5253
+ logger$a.debug('Namespace for restoration', {
5200
5254
  ledgerId,
5201
5255
  accountCount: namespace?.accounts?.length || 0,
5202
5256
  });
5203
5257
  // Pass the user's selected network to filter accounts appropriately
5204
5258
  const parsedAccounts = signer.parseAccounts(namespace, userSelectedNetwork);
5205
- logger$9.debug('Parsed accounts from restored session', {
5259
+ logger$a.debug('Parsed accounts from restored session', {
5206
5260
  count: parsedAccounts.length,
5207
5261
  userSelectedNetwork,
5208
5262
  });
5209
5263
  if (parsedAccounts.length === 0) {
5210
- logger$9.warn('Restored session has no accounts for selected network', {
5264
+ logger$a.warn('Restored session has no accounts for selected network', {
5211
5265
  userSelectedNetwork,
5212
5266
  walletReportedNetwork,
5213
5267
  });
@@ -5239,7 +5293,7 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5239
5293
  signer,
5240
5294
  accounts,
5241
5295
  });
5242
- logger$9.info('Restored session', {
5296
+ logger$a.info('Restored session', {
5243
5297
  sessionKey,
5244
5298
  ledgerId,
5245
5299
  networkId,
@@ -5266,13 +5320,13 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5266
5320
  storeUserNetworkSelection(sessionTopic, networkId) {
5267
5321
  try {
5268
5322
  localStorage.setItem(`${NETWORK_SELECTION_STORAGE_KEY}${sessionTopic}`, networkId);
5269
- logger$9.debug('Stored user network selection', {
5323
+ logger$a.debug('Stored user network selection', {
5270
5324
  topic: sessionTopic.substring(0, 16),
5271
5325
  networkId,
5272
5326
  });
5273
5327
  }
5274
5328
  catch (e) {
5275
- logger$9.warn('Failed to store network selection', { error: e.message });
5329
+ logger$a.warn('Failed to store network selection', { error: e.message });
5276
5330
  }
5277
5331
  }
5278
5332
  /**
@@ -5286,7 +5340,7 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5286
5340
  return localStorage.getItem(`${NETWORK_SELECTION_STORAGE_KEY}${sessionTopic}`) || undefined;
5287
5341
  }
5288
5342
  catch (e) {
5289
- logger$9.warn('Failed to retrieve network selection', { error: e.message });
5343
+ logger$a.warn('Failed to retrieve network selection', { error: e.message });
5290
5344
  return undefined;
5291
5345
  }
5292
5346
  }
@@ -5332,7 +5386,7 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5332
5386
  }
5333
5387
  // Get the appropriate signer for this ledger (Strategy Pattern)
5334
5388
  const signer = SignerFactory.getSigner(wcConfig.ledgerId);
5335
- logger$9.debug('Using signer for ledger', { ledgerId: wcConfig.ledgerId });
5389
+ logger$a.debug('Using signer for ledger', { ledgerId: wcConfig.ledgerId });
5336
5390
  // Initialize client via manager
5337
5391
  await this.clientManager.initialize(projectId, {
5338
5392
  name: wcConfig.appName || 'HSuite Demo',
@@ -5346,14 +5400,14 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5346
5400
  // Build namespace configuration using signer
5347
5401
  const namespaceConfig = signer.buildNamespace(wcConfig.networkId);
5348
5402
  const optionalNamespaces = { [wcConfig.ledgerId]: namespaceConfig };
5349
- logger$9.debug('Namespace config', { ledgerId: wcConfig.ledgerId });
5403
+ logger$a.debug('Namespace config', { ledgerId: wcConfig.ledgerId });
5350
5404
  // Build session properties to pass user's preferred network to wallet
5351
5405
  // This tells the wallet which network accounts to show in the picker
5352
5406
  const sessionProperties = {
5353
5407
  preferredNetwork: wcConfig.networkId,
5354
5408
  preferredLedger: wcConfig.ledgerId,
5355
5409
  };
5356
- logger$9.info('Connecting with preferred network', {
5410
+ logger$a.info('Connecting with preferred network', {
5357
5411
  preferredNetwork: wcConfig.networkId,
5358
5412
  preferredLedger: wcConfig.ledgerId,
5359
5413
  });
@@ -5363,10 +5417,10 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5363
5417
  await modal.openModal({ uri });
5364
5418
  }
5365
5419
  // Wait for wallet approval
5366
- logger$9.info('Waiting for wallet approval...');
5420
+ logger$a.info('Waiting for wallet approval...');
5367
5421
  const session = await approval();
5368
5422
  this.clientManager.closeModal();
5369
- logger$9.info('[WC:DAPP:APPROVED] Session approved by wallet', {
5423
+ logger$a.info('[WC:DAPP:APPROVED] Session approved by wallet', {
5370
5424
  topic: session.topic.substring(0, 16) + '...',
5371
5425
  fullTopic: session.topic,
5372
5426
  namespaces: Object.keys(session.namespaces),
@@ -5376,12 +5430,12 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5376
5430
  const sessionKey = this.sessionStore.generateSessionKey(wcConfig.ledgerId, wcConfig.networkId, session.topic);
5377
5431
  // Parse accounts from session
5378
5432
  const sessionNamespace = session.namespaces[wcConfig.ledgerId];
5379
- logger$9.debug('Session namespace for ledger', {
5433
+ logger$a.debug('Session namespace for ledger', {
5380
5434
  ledgerId: wcConfig.ledgerId,
5381
5435
  accountCount: sessionNamespace?.accounts?.length || 0,
5382
5436
  });
5383
5437
  if (!sessionNamespace) {
5384
- logger$9.error('No namespace found for ledger', {
5438
+ logger$a.error('No namespace found for ledger', {
5385
5439
  ledgerId: wcConfig.ledgerId,
5386
5440
  availableNamespaces: Object.keys(session.namespaces),
5387
5441
  });
@@ -5390,12 +5444,12 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5390
5444
  // Parse accounts from session namespace, filtering by user's selected network
5391
5445
  // This ensures we only show accounts that match the network the user selected
5392
5446
  const parsedAccounts = signer.parseAccounts(sessionNamespace, wcConfig.networkId);
5393
- logger$9.debug('Parsed accounts', {
5447
+ logger$a.debug('Parsed accounts', {
5394
5448
  count: parsedAccounts.length,
5395
5449
  userSelectedNetwork: wcConfig.networkId,
5396
5450
  });
5397
5451
  if (parsedAccounts.length === 0) {
5398
- logger$9.warn('No accounts returned from wallet - possible causes:', {
5452
+ logger$a.warn('No accounts returned from wallet - possible causes:', {
5399
5453
  reason1: 'Wallet has no accounts for the requested network',
5400
5454
  reason2: 'Wallet denied account sharing',
5401
5455
  reason3: 'Wallet returned accounts in unexpected format',
@@ -5434,7 +5488,7 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5434
5488
  this.storeUserNetworkSelection(session.topic, wcConfig.networkId);
5435
5489
  // Verify session exists in WC SDK after storing
5436
5490
  const sdkSession = this.clientManager.getSession(session.topic);
5437
- logger$9.info('[WC:DAPP:STORED] Session stored locally', {
5491
+ logger$a.info('[WC:DAPP:STORED] Session stored locally', {
5438
5492
  sessionKey,
5439
5493
  topic: session.topic.substring(0, 16) + '...',
5440
5494
  fullTopic: session.topic,
@@ -5463,7 +5517,7 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5463
5517
  catch (error) {
5464
5518
  this._status.set('error');
5465
5519
  this._error.set(error instanceof Error ? error.message : 'Connection failed');
5466
- logger$9.error('Connection failed', {
5520
+ logger$a.error('Connection failed', {
5467
5521
  error: error instanceof Error ? error.message : String(error),
5468
5522
  });
5469
5523
  // Emit provider error event
@@ -5528,14 +5582,14 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5528
5582
  // WalletConnect events arrive outside Angular's zone
5529
5583
  this.clientManager.on('session_delete', (event) => {
5530
5584
  this.zone.run(() => {
5531
- logger$9.info('� Session deleted by wallet (session_delete event)', {
5585
+ logger$a.info('� Session deleted by wallet (session_delete event)', {
5532
5586
  topic: event.topic,
5533
5587
  });
5534
5588
  this.removeSessionByTopic(event.topic);
5535
5589
  });
5536
5590
  });
5537
5591
  this.sessionDeleteListenerRegistered = true;
5538
- logger$9.debug('session_delete listener registered');
5592
+ logger$a.debug('session_delete listener registered');
5539
5593
  }
5540
5594
  /**
5541
5595
  * Disconnect from WalletConnect sessions.
@@ -5545,7 +5599,7 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5545
5599
  */
5546
5600
  async disconnect(sessionKey) {
5547
5601
  if (!this.clientManager.isInitialized()) {
5548
- logger$9.warn('No client to disconnect');
5602
+ logger$a.warn('No client to disconnect');
5549
5603
  return;
5550
5604
  }
5551
5605
  if (sessionKey) {
@@ -5557,10 +5611,10 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5557
5611
  code: 6000,
5558
5612
  message: 'User disconnected session',
5559
5613
  });
5560
- logger$9.info('Disconnected session', { sessionKey });
5614
+ logger$a.info('Disconnected session', { sessionKey });
5561
5615
  }
5562
5616
  catch (e) {
5563
- logger$9.error('Disconnect error for session', {
5617
+ logger$a.error('Disconnect error for session', {
5564
5618
  sessionKey,
5565
5619
  error: e instanceof Error ? e.message : String(e),
5566
5620
  });
@@ -5585,14 +5639,14 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5585
5639
  code: 6000,
5586
5640
  message: 'User disconnected all sessions',
5587
5641
  })
5588
- .catch((err) => logger$9.error('Disconnect error', {
5642
+ .catch((err) => logger$a.error('Disconnect error', {
5589
5643
  error: err.message,
5590
5644
  })));
5591
5645
  }
5592
5646
  await Promise.all(disconnectPromises);
5593
5647
  this.sessionStore.clear();
5594
5648
  this._status.set('disconnected');
5595
- logger$9.info('Disconnected all sessions');
5649
+ logger$a.info('Disconnected all sessions');
5596
5650
  }
5597
5651
  this.clientManager.closeModal();
5598
5652
  }
@@ -5695,7 +5749,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImpo
5695
5749
  * - RPC communication over best available transport
5696
5750
  * - Session ownership remains with the wallet
5697
5751
  */
5698
- const logger$8 = getLogger().scoped?.('P2PSessionManager') ?? getLogger();
5752
+ const logger$9 = getLogger().scoped?.('P2PSessionManager') ?? getLogger();
5699
5753
  /**
5700
5754
  * Mobile Native Session Manager
5701
5755
  *
@@ -5764,7 +5818,7 @@ class P2PSessionManager {
5764
5818
  * @returns Promise resolving to offer result with QR data
5765
5819
  */
5766
5820
  async createPairingOffer(options) {
5767
- logger$8.info('Creating pairing offer (Nostr-first)', { options });
5821
+ logger$9.info('Creating pairing offer (Nostr-first)', { options });
5768
5822
  try {
5769
5823
  this.runInZone(() => this._connectionState.set('creating_offer'));
5770
5824
  // Clean up any existing client
@@ -5777,12 +5831,12 @@ class P2PSessionManager {
5777
5831
  this.client = new ChannelClient({
5778
5832
  p2p: { enabled: true },
5779
5833
  onStateChange: (state) => {
5780
- logger$8.debug('ChannelClient state callback', { state });
5834
+ logger$9.debug('ChannelClient state callback', { state });
5781
5835
  const accounts = this.client?.accounts ?? [];
5782
5836
  this.handleStateChange(state, accounts);
5783
5837
  },
5784
5838
  onAccountsChange: (accounts) => {
5785
- logger$8.debug('ChannelClient accounts callback', { count: accounts.length });
5839
+ logger$9.debug('ChannelClient accounts callback', { count: accounts.length });
5786
5840
  const state = this.client?.state ?? 'idle';
5787
5841
  this.handleStateChange(state, accounts);
5788
5842
  },
@@ -5807,7 +5861,7 @@ class P2PSessionManager {
5807
5861
  // Encode invite for QR code
5808
5862
  const qrData = encodeChannelInvite(invite);
5809
5863
  this.runInZone(() => this._connectionState.set('awaiting_connection'));
5810
- logger$8.info('Pairing offer created', {
5864
+ logger$9.info('Pairing offer created', {
5811
5865
  sessionId: invite.id.slice(0, 8),
5812
5866
  qrDataLength: qrData.length,
5813
5867
  });
@@ -5816,7 +5870,7 @@ class P2PSessionManager {
5816
5870
  return { qrData, sessionId: invite.id };
5817
5871
  }
5818
5872
  catch (error) {
5819
- logger$8.error('Failed to create pairing offer', { error });
5873
+ logger$9.error('Failed to create pairing offer', { error });
5820
5874
  this.runInZone(() => this._connectionState.set('error'));
5821
5875
  this.notifyError(error instanceof Error ? error : new Error('Failed to create offer'));
5822
5876
  throw error;
@@ -5834,7 +5888,7 @@ class P2PSessionManager {
5834
5888
  if (!this.client || !this.currentInvite) {
5835
5889
  throw new Error('No active pairing offer - call createPairingOffer first');
5836
5890
  }
5837
- logger$8.info('Waiting for wallet to connect and approve session...');
5891
+ logger$9.info('Waiting for wallet to connect and approve session...');
5838
5892
  return new Promise((resolve, reject) => {
5839
5893
  this.sessionApprovalPromise = { resolve, reject };
5840
5894
  });
@@ -5845,7 +5899,7 @@ class P2PSessionManager {
5845
5899
  * Cleans up the transport without fully disconnecting.
5846
5900
  */
5847
5901
  async cancelPairingOffer() {
5848
- logger$8.debug('Cancelling pairing offer');
5902
+ logger$9.debug('Cancelling pairing offer');
5849
5903
  if (this.sessionApprovalPromise) {
5850
5904
  this.sessionApprovalPromise.reject(new Error('Pairing cancelled'));
5851
5905
  this.sessionApprovalPromise = undefined;
@@ -5887,7 +5941,7 @@ class P2PSessionManager {
5887
5941
  */
5888
5942
  async signTransaction(options) {
5889
5943
  this.requireSession();
5890
- logger$8.info('Signing transaction', { account: options.accountAddress });
5944
+ logger$9.info('Signing transaction', { account: options.accountAddress });
5891
5945
  if (!this.client) {
5892
5946
  throw new Error('Not connected');
5893
5947
  }
@@ -5909,7 +5963,7 @@ class P2PSessionManager {
5909
5963
  */
5910
5964
  async submitTransaction(options) {
5911
5965
  this.requireSession();
5912
- logger$8.info('Submitting transaction', { account: options.accountAddress });
5966
+ logger$9.info('Submitting transaction', { account: options.accountAddress });
5913
5967
  if (!this.client) {
5914
5968
  throw new Error('Not connected');
5915
5969
  }
@@ -5934,7 +5988,7 @@ class P2PSessionManager {
5934
5988
  */
5935
5989
  async signMessage(options) {
5936
5990
  this.requireSession();
5937
- logger$8.info('Signing message', { account: options.accountAddress });
5991
+ logger$9.info('Signing message', { account: options.accountAddress });
5938
5992
  if (!this.client) {
5939
5993
  throw new Error('Not connected');
5940
5994
  }
@@ -5945,8 +5999,14 @@ class P2PSessionManager {
5945
5999
  ledgerId: options.ledgerId,
5946
6000
  networkId: options.networkId,
5947
6001
  });
6002
+ // Fail closed: an empty signature is never a success. Coercing it to ''
6003
+ // would flow all the way into the smart-host verify POST and fail there
6004
+ // with a far less actionable error.
6005
+ if (!response.signature) {
6006
+ throw new Error('Wallet returned no signature for ledger/signMessage');
6007
+ }
5948
6008
  return {
5949
- signature: response.signature || '',
6009
+ signature: response.signature,
5950
6010
  publicKey: response.publicKey,
5951
6011
  algorithm: response.algorithm,
5952
6012
  encoding: response.encoding,
@@ -5959,7 +6019,7 @@ class P2PSessionManager {
5959
6019
  * Terminate the current session
5960
6020
  */
5961
6021
  async terminateSession() {
5962
- logger$8.info('Terminating session');
6022
+ logger$9.info('Terminating session');
5963
6023
  if (this.client) {
5964
6024
  await this.client.disconnect();
5965
6025
  }
@@ -6060,6 +6120,7 @@ class P2PSessionManager {
6060
6120
  accounts: accounts.map((acc, index) => ({
6061
6121
  id: `p2p-${acc.address}`,
6062
6122
  address: acc.address,
6123
+ publicKey: acc.publicKey,
6063
6124
  label: acc.alias || `Account ${index + 1}`,
6064
6125
  ledgerId: acc.ledgerId,
6065
6126
  networkId: acc.networkId,
@@ -6078,7 +6139,7 @@ class P2PSessionManager {
6078
6139
  * @param reason
6079
6140
  */
6080
6141
  handleDisconnection(reason) {
6081
- logger$8.info('Handling disconnection', { reason });
6142
+ logger$9.info('Handling disconnection', { reason });
6082
6143
  this.cleanup();
6083
6144
  this.runInZone(() => {
6084
6145
  this._currentSession.set(null);
@@ -6130,7 +6191,7 @@ class P2PSessionManager {
6130
6191
  callback(session);
6131
6192
  }
6132
6193
  catch (error) {
6133
- logger$8.error('Connected callback error', { error });
6194
+ logger$9.error('Connected callback error', { error });
6134
6195
  }
6135
6196
  }
6136
6197
  }
@@ -6143,7 +6204,7 @@ class P2PSessionManager {
6143
6204
  callback();
6144
6205
  }
6145
6206
  catch (error) {
6146
- logger$8.error('Disconnected callback error', { error });
6207
+ logger$9.error('Disconnected callback error', { error });
6147
6208
  }
6148
6209
  }
6149
6210
  }
@@ -6157,7 +6218,7 @@ class P2PSessionManager {
6157
6218
  callback(error);
6158
6219
  }
6159
6220
  catch (err) {
6160
- logger$8.error('Error callback error', { err });
6221
+ logger$9.error('Error callback error', { err });
6161
6222
  }
6162
6223
  }
6163
6224
  }
@@ -6199,7 +6260,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImpo
6199
6260
  * 4. User approves session in wallet
6200
6261
  * 5. P2P upgrade happens automatically in background
6201
6262
  */
6202
- const logger$7 = getLogger().scoped?.('P2PNativeProvider') ?? getLogger();
6263
+ const logger$8 = getLogger().scoped?.('P2PNativeProvider') ?? getLogger();
6203
6264
  /**
6204
6265
  * Storage key for mobile session metadata (separate from hsuite-native)
6205
6266
  */
@@ -6224,10 +6285,10 @@ class P2PSessionPersistence {
6224
6285
  timestamp: Date.now(),
6225
6286
  };
6226
6287
  window.localStorage.setItem(P2P_SESSION_STORAGE_KEY, JSON.stringify(payload));
6227
- logger$7.debug('Mobile session persisted', { sessionId: session.sessionId });
6288
+ logger$8.debug('Mobile session persisted', { sessionId: session.sessionId });
6228
6289
  }
6229
6290
  catch (error) {
6230
- logger$7.warn('Failed to persist mobile session', { error });
6291
+ logger$8.warn('Failed to persist mobile session', { error });
6231
6292
  }
6232
6293
  }
6233
6294
  /**
@@ -6245,11 +6306,11 @@ class P2PSessionPersistence {
6245
6306
  this.clear();
6246
6307
  return null;
6247
6308
  }
6248
- logger$7.info('Restored mobile session metadata', { sessionId: stored.sessionId });
6309
+ logger$8.info('Restored mobile session metadata', { sessionId: stored.sessionId });
6249
6310
  return stored;
6250
6311
  }
6251
6312
  catch (error) {
6252
- logger$7.warn('Failed to restore mobile session', { error });
6313
+ logger$8.warn('Failed to restore mobile session', { error });
6253
6314
  return null;
6254
6315
  }
6255
6316
  }
@@ -6261,10 +6322,10 @@ class P2PSessionPersistence {
6261
6322
  if (typeof window === 'undefined')
6262
6323
  return;
6263
6324
  window.localStorage.removeItem(P2P_SESSION_STORAGE_KEY);
6264
- logger$7.debug('Mobile session cleared');
6325
+ logger$8.debug('Mobile session cleared');
6265
6326
  }
6266
6327
  catch (error) {
6267
- logger$7.warn('Failed to clear mobile session', { error });
6328
+ logger$8.warn('Failed to clear mobile session', { error });
6268
6329
  }
6269
6330
  }
6270
6331
  /**
@@ -6384,7 +6445,7 @@ class P2PNativeProvider extends BaseWalletProvider {
6384
6445
  restorePersistedSession() {
6385
6446
  const stored = this.sessionPersistence.restore();
6386
6447
  if (stored) {
6387
- logger$7.info('Restoring persisted mobile session', {
6448
+ logger$8.info('Restoring persisted mobile session', {
6388
6449
  sessionId: stored.sessionId,
6389
6450
  accountCount: stored.accounts?.length ?? 0,
6390
6451
  });
@@ -6395,7 +6456,7 @@ class P2PNativeProvider extends BaseWalletProvider {
6395
6456
  }
6396
6457
  // Note: We don't set connected status because WebRTC needs re-pairing
6397
6458
  // The persisted data is for account info only
6398
- logger$7.debug('Mobile session metadata restored (requires re-pairing for connection)');
6459
+ logger$8.debug('Mobile session metadata restored (requires re-pairing for connection)');
6399
6460
  }
6400
6461
  }
6401
6462
  /**
@@ -6418,7 +6479,7 @@ class P2PNativeProvider extends BaseWalletProvider {
6418
6479
  * @throws {Error} If offer generation fails
6419
6480
  */
6420
6481
  async createPairingOffer(config) {
6421
- logger$7.info('Creating pairing offer', { config });
6482
+ logger$8.info('Creating pairing offer', { config });
6422
6483
  try {
6423
6484
  this._connectionState.set('generating_offer');
6424
6485
  this._error.set(null);
@@ -6441,14 +6502,14 @@ class P2PNativeProvider extends BaseWalletProvider {
6441
6502
  this._pairingOffer.set(offerResult);
6442
6503
  this._connectionState.set('awaiting_scan');
6443
6504
  this._status.set('connecting');
6444
- logger$7.info('Pairing offer created', {
6505
+ logger$8.info('Pairing offer created', {
6445
6506
  qrDataLength: result.qrData.length,
6446
6507
  expiresAt: offerResult.expiresAt,
6447
6508
  });
6448
6509
  return offerResult;
6449
6510
  }
6450
6511
  catch (error) {
6451
- logger$7.error('Failed to create pairing offer', { error });
6512
+ logger$8.error('Failed to create pairing offer', { error });
6452
6513
  this._connectionState.set('error');
6453
6514
  this._status.set('error');
6454
6515
  this._error.set(error instanceof Error ? error.message : 'Failed to create pairing offer');
@@ -6462,7 +6523,7 @@ class P2PNativeProvider extends BaseWalletProvider {
6462
6523
  * @returns Promise resolving to new pairing offer
6463
6524
  */
6464
6525
  async refreshPairingOffer(config) {
6465
- logger$7.debug('Refreshing pairing offer');
6526
+ logger$8.debug('Refreshing pairing offer');
6466
6527
  // Cancel any existing offer
6467
6528
  await this.sessionManager.cancelPairingOffer();
6468
6529
  return this.createPairingOffer(config);
@@ -6498,7 +6559,7 @@ class P2PNativeProvider extends BaseWalletProvider {
6498
6559
  * @throws {Error} If no pairing offer was created
6499
6560
  */
6500
6561
  async waitForSessionApproval() {
6501
- logger$7.info('Waiting for wallet to connect and approve session');
6562
+ logger$8.info('Waiting for wallet to connect and approve session');
6502
6563
  this._connectionState.set('pending_approval');
6503
6564
  try {
6504
6565
  // This blocks until wallet connects via Nostr and user approves
@@ -6516,7 +6577,7 @@ class P2PNativeProvider extends BaseWalletProvider {
6516
6577
  return session;
6517
6578
  }
6518
6579
  catch (error) {
6519
- logger$7.error('Session approval failed', { error });
6580
+ logger$8.error('Session approval failed', { error });
6520
6581
  this._connectionState.set('error');
6521
6582
  throw error;
6522
6583
  }
@@ -6541,10 +6602,10 @@ class P2PNativeProvider extends BaseWalletProvider {
6541
6602
  * @throws {Error} If connection times out (2 minutes)
6542
6603
  */
6543
6604
  async connect(config) {
6544
- logger$7.info('Connect called', { config });
6605
+ logger$8.info('Connect called', { config });
6545
6606
  // If already connected, no-op
6546
6607
  if (this._status() === 'connected') {
6547
- logger$7.debug('Already connected');
6608
+ logger$8.debug('Already connected');
6548
6609
  return;
6549
6610
  }
6550
6611
  // Create pairing offer and wait for connection
@@ -6572,7 +6633,7 @@ class P2PNativeProvider extends BaseWalletProvider {
6572
6633
  * persisted session data. The wallet is notified of the disconnection.
6573
6634
  */
6574
6635
  async disconnect() {
6575
- logger$7.info('Disconnecting');
6636
+ logger$8.info('Disconnecting');
6576
6637
  try {
6577
6638
  await this.sessionManager.terminateSession();
6578
6639
  }
@@ -6604,7 +6665,7 @@ class P2PNativeProvider extends BaseWalletProvider {
6604
6665
  if (this._status() !== 'connected') {
6605
6666
  throw new Error('Not connected to wallet');
6606
6667
  }
6607
- logger$7.info('Signing transaction', { account: options.accountAddress });
6668
+ logger$8.info('Signing transaction', { account: options.accountAddress });
6608
6669
  const result = await this.sessionManager.signTransaction({
6609
6670
  accountAddress: options.accountAddress,
6610
6671
  payload: options.payload,
@@ -6635,7 +6696,7 @@ class P2PNativeProvider extends BaseWalletProvider {
6635
6696
  if (this._status() !== 'connected') {
6636
6697
  throw new Error('Not connected to wallet');
6637
6698
  }
6638
- logger$7.info('Submitting transaction', { account: options.accountAddress });
6699
+ logger$8.info('Submitting transaction', { account: options.accountAddress });
6639
6700
  const result = await this.sessionManager.submitTransaction({
6640
6701
  accountAddress: options.accountAddress,
6641
6702
  payload: options.payload,
@@ -6687,7 +6748,7 @@ class P2PNativeProvider extends BaseWalletProvider {
6687
6748
  if (this._status() !== 'connected') {
6688
6749
  throw new Error('Not connected to wallet');
6689
6750
  }
6690
- logger$7.info('Signing message', { account: options.accountAddress });
6751
+ logger$8.info('Signing message', { account: options.accountAddress });
6691
6752
  const result = await this.sessionManager.signMessage({
6692
6753
  accountAddress: options.accountAddress,
6693
6754
  message: options.message,
@@ -6695,9 +6756,16 @@ class P2PNativeProvider extends BaseWalletProvider {
6695
6756
  ledgerId: options.ledgerId,
6696
6757
  networkId: options.networkId,
6697
6758
  });
6759
+ // §21.3: forward the session manager's full result — dropping caipChainId
6760
+ // here breaks smart-host verification (the verifier needs the chain
6761
+ // binding to reconstruct the domain-separated signed bytes).
6698
6762
  return {
6699
6763
  signature: result.signature,
6700
6764
  publicKey: result.publicKey,
6765
+ algorithm: result.algorithm,
6766
+ encoding: result.encoding,
6767
+ caipChainId: result.caipChainId,
6768
+ messageLength: result.messageLength,
6701
6769
  metadata: result.metadata,
6702
6770
  };
6703
6771
  }
@@ -6722,7 +6790,7 @@ class P2PNativeProvider extends BaseWalletProvider {
6722
6790
  // Connection established — wrap in NgZone to ensure Angular change
6723
6791
  // detection picks up signal updates from Nostr/WebSocket callbacks
6724
6792
  this.sessionManager.onConnected((session) => {
6725
- logger$7.info('Session connected', { sessionId: session?.id });
6793
+ logger$8.info('Session connected', { sessionId: session?.id });
6726
6794
  this.ngZone.run(() => {
6727
6795
  this._connectionState.set('connected');
6728
6796
  this._status.set('connected');
@@ -6740,7 +6808,7 @@ class P2PNativeProvider extends BaseWalletProvider {
6740
6808
  });
6741
6809
  // Session terminated
6742
6810
  this.sessionManager.onDisconnected(() => {
6743
- logger$7.info('Session disconnected');
6811
+ logger$8.info('Session disconnected');
6744
6812
  this.ngZone.run(() => {
6745
6813
  this._connectionState.set('disconnected');
6746
6814
  this._status.set('disconnected');
@@ -6751,7 +6819,7 @@ class P2PNativeProvider extends BaseWalletProvider {
6751
6819
  });
6752
6820
  // Error occurred
6753
6821
  this.sessionManager.onError((error) => {
6754
- logger$7.error('Session error', { error });
6822
+ logger$8.error('Session error', { error });
6755
6823
  this.ngZone.run(() => {
6756
6824
  this._connectionState.set('error');
6757
6825
  this._status.set('error');
@@ -6760,7 +6828,7 @@ class P2PNativeProvider extends BaseWalletProvider {
6760
6828
  });
6761
6829
  // Accounts updated
6762
6830
  this.sessionManager.onAccountsChanged((accounts) => {
6763
- logger$7.debug('Accounts updated', { count: accounts.length });
6831
+ logger$8.debug('Accounts updated', { count: accounts.length });
6764
6832
  this.ngZone.run(() => {
6765
6833
  const accountsWithProvider = this.ensureProviderIdOnAccounts(accounts);
6766
6834
  this._accounts.set(accountsWithProvider);
@@ -6830,7 +6898,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImpo
6830
6898
  * +-------------------------------------------------------------------+
6831
6899
  * ```
6832
6900
  */
6833
- const logger$6 = getLogger().scoped?.('UnifiedWalletService') ?? getLogger();
6901
+ const logger$7 = getLogger().scoped?.('UnifiedWalletService') ?? getLogger();
6834
6902
  /**
6835
6903
  * Central service for managing wallet connections across multiple protocols.
6836
6904
  *
@@ -6968,7 +7036,7 @@ class UnifiedWalletService {
6968
7036
  return await reconnect.call(provider);
6969
7037
  }
6970
7038
  catch (error) {
6971
- logger$6.warn('Provider reconnect failed', { providerId, error });
7039
+ logger$7.warn('Provider reconnect failed', { providerId, error });
6972
7040
  return false;
6973
7041
  }
6974
7042
  }
@@ -7032,7 +7100,7 @@ class UnifiedWalletService {
7032
7100
  */
7033
7101
  registerProvider(provider) {
7034
7102
  if (this.providers.has(provider.id)) {
7035
- logger$6.warn('Provider already registered', { providerId: provider.id });
7103
+ logger$7.warn('Provider already registered', { providerId: provider.id });
7036
7104
  return;
7037
7105
  }
7038
7106
  this.providers.set(provider.id, provider);
@@ -7487,7 +7555,7 @@ class UnifiedWalletService {
7487
7555
  switchAccount(accountId) {
7488
7556
  const account = this.getAccountById(accountId);
7489
7557
  if (!account) {
7490
- logger$6.warn('Account not found', { accountId });
7558
+ logger$7.warn('Account not found', { accountId });
7491
7559
  return false;
7492
7560
  }
7493
7561
  this.setActiveAccount(account);
@@ -7542,7 +7610,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImpo
7542
7610
  * - Keyboard navigation support
7543
7611
  * - Toast/alert integration
7544
7612
  */
7545
- const logger$5 = getLogger().scoped?.('AccountSelectorService') ?? getLogger();
7613
+ const logger$6 = getLogger().scoped?.('AccountSelectorService') ?? getLogger();
7546
7614
  /**
7547
7615
  * @service AccountSelectorService
7548
7616
  * Business logic service for account selector component.
@@ -7631,7 +7699,7 @@ class AccountSelectorService {
7631
7699
  return null;
7632
7700
  }
7633
7701
  catch (error) {
7634
- logger$5.error('Error getting currently connected account', { error });
7702
+ logger$6.error('Error getting currently connected account', { error });
7635
7703
  return null;
7636
7704
  }
7637
7705
  }, ...(ngDevMode ? [{ debugName: "currentlyConnectedAccount" }] : []));
@@ -7659,7 +7727,7 @@ class AccountSelectorService {
7659
7727
  return others;
7660
7728
  }
7661
7729
  catch (error) {
7662
- logger$5.error('Error getting other accounts', { error });
7730
+ logger$6.error('Error getting other accounts', { error });
7663
7731
  return [];
7664
7732
  }
7665
7733
  }, ...(ngDevMode ? [{ debugName: "otherAccounts" }] : []));
@@ -7688,10 +7756,10 @@ class AccountSelectorService {
7688
7756
  // Modal mode: show toast and dismiss
7689
7757
  if (mode === 'modal') {
7690
7758
  await this.showSuccessToast(`Switched to ${account.label || 'Account'}`);
7691
- logger$5.info('[Modal] Account changed and modal dismissed', { ...accountData });
7759
+ logger$6.info('[Modal] Account changed and modal dismissed', { ...accountData });
7692
7760
  }
7693
7761
  else {
7694
- logger$5.info('[Inline] Account changed', { ...accountData });
7762
+ logger$6.info('[Inline] Account changed', { ...accountData });
7695
7763
  }
7696
7764
  return accountData;
7697
7765
  }
@@ -7743,7 +7811,7 @@ class AccountSelectorService {
7743
7811
  */
7744
7812
  async disconnectAll(_mode) {
7745
7813
  if (!this.alertController) {
7746
- logger$5.warn('AlertController not available for disconnect confirmation');
7814
+ logger$6.warn('AlertController not available for disconnect confirmation');
7747
7815
  return false;
7748
7816
  }
7749
7817
  return new Promise((resolve) => {
@@ -7768,7 +7836,7 @@ class AccountSelectorService {
7768
7836
  await this.wallet.disconnectSession(session.providerId, session.metadata?.sessionKey);
7769
7837
  }
7770
7838
  catch (error) {
7771
- logger$5.error('Failed to disconnect session', {
7839
+ logger$6.error('Failed to disconnect session', {
7772
7840
  providerId: session.providerId,
7773
7841
  error,
7774
7842
  });
@@ -7778,7 +7846,7 @@ class AccountSelectorService {
7778
7846
  resolve(true);
7779
7847
  }
7780
7848
  catch (error) {
7781
- logger$5.error('Failed to disconnect all sessions', { error });
7849
+ logger$6.error('Failed to disconnect all sessions', { error });
7782
7850
  this.error.set('Failed to disconnect all wallets');
7783
7851
  resolve(false);
7784
7852
  }
@@ -7863,11 +7931,11 @@ class AccountSelectorService {
7863
7931
  if (mode === 'modal') {
7864
7932
  await this.showSuccessToast('Wallet disconnected successfully');
7865
7933
  }
7866
- logger$5.info('Session disconnected', { providerId, sessionKey, mode });
7934
+ logger$6.info('Session disconnected', { providerId, sessionKey, mode });
7867
7935
  return true;
7868
7936
  }
7869
7937
  catch (error) {
7870
- logger$5.error('Failed to disconnect session', { providerId, error });
7938
+ logger$6.error('Failed to disconnect session', { providerId, error });
7871
7939
  if (mode === 'modal') {
7872
7940
  await this.showErrorToast('Failed to disconnect wallet. Please try again.');
7873
7941
  }
@@ -9492,7 +9560,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImpo
9492
9560
  * - HSuite Native + Mobile QR: Network → Protocol → Method → QR Pairing (4 steps)
9493
9561
  * - WalletConnect: Network → Protocol → Ledger → Connect (4 steps)
9494
9562
  */
9495
- const logger$4 = getLogger().scoped?.('WalletConnectionModal') ?? getLogger();
9563
+ const logger$5 = getLogger().scoped?.('WalletConnectionModal') ?? getLogger();
9496
9564
  /**
9497
9565
  * Connection step enumeration for the wizard flow
9498
9566
  */
@@ -10017,7 +10085,7 @@ class WalletConnectionModalComponent {
10017
10085
  await this.modalController.dismiss({ connected: true });
10018
10086
  }
10019
10087
  catch (error) {
10020
- logger$4.error('Connection failed', {
10088
+ logger$5.error('Connection failed', {
10021
10089
  error: error instanceof Error ? error.message : String(error),
10022
10090
  });
10023
10091
  this.connectionError.set(error instanceof Error ? error.message : 'Connection failed. Please try again.');
@@ -10062,7 +10130,7 @@ class WalletConnectionModalComponent {
10062
10130
  this.waitForWalletApproval();
10063
10131
  }
10064
10132
  catch (error) {
10065
- logger$4.error('Failed to create pairing offer', { error });
10133
+ logger$5.error('Failed to create pairing offer', { error });
10066
10134
  this.connectionError.set(error instanceof Error ? error.message : 'Failed to generate QR code');
10067
10135
  this.isGeneratingOffer.set(false);
10068
10136
  }
@@ -10075,7 +10143,7 @@ class WalletConnectionModalComponent {
10075
10143
  try {
10076
10144
  // This blocks until wallet scans QR, connects via Nostr, and user approves
10077
10145
  const session = await this.p2pNativeProvider.waitForSessionApproval();
10078
- logger$4.info('Session approved by wallet', {
10146
+ logger$5.info('Session approved by wallet', {
10079
10147
  sessionId: session?.sessionId,
10080
10148
  accounts: session?.accounts?.length,
10081
10149
  });
@@ -10084,7 +10152,7 @@ class WalletConnectionModalComponent {
10084
10152
  catch (error) {
10085
10153
  // Only show error if we're still on the QR pairing step (not cancelled)
10086
10154
  if (this.currentStep() === ConnectionStep.QrPairing) {
10087
- logger$4.error('Session approval failed', { error });
10155
+ logger$5.error('Session approval failed', { error });
10088
10156
  this.connectionError.set(error instanceof Error ? error.message : 'Session approval failed or rejected');
10089
10157
  }
10090
10158
  this.isWaitingForWallet.set(false);
@@ -10095,7 +10163,7 @@ class WalletConnectionModalComponent {
10095
10163
  * Handle QR code expiry
10096
10164
  */
10097
10165
  onQrExpired() {
10098
- logger$4.debug('QR code expired');
10166
+ logger$5.debug('QR code expired');
10099
10167
  this.pairingOffer.set('');
10100
10168
  this.isWaitingForWallet.set(false);
10101
10169
  }
@@ -10111,7 +10179,7 @@ class WalletConnectionModalComponent {
10111
10179
  * Handle successful mobile connection
10112
10180
  */
10113
10181
  onMobileConnected() {
10114
- logger$4.info('Mobile wallet connected');
10182
+ logger$5.info('Mobile wallet connected');
10115
10183
  this.connected.emit({ protocol: 'mobile-native', method: 'qr' });
10116
10184
  void this.modalController.dismiss({ connected: true });
10117
10185
  }
@@ -10162,7 +10230,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImpo
10162
10230
  * This file is part of HSuite Native Connect. For commercial licensing,
10163
10231
  * visit https://hsuite.finance/licensing
10164
10232
  */
10165
- const logger$3 = getLogger().scoped?.('WalletConnectButton') ?? getLogger();
10233
+ const logger$4 = getLogger().scoped?.('WalletConnectButton') ?? getLogger();
10166
10234
  /**
10167
10235
  * @component WalletConnectButtonComponent
10168
10236
  * Ready-to-use wallet connection button for dApps with multi-protocol support.
@@ -10267,7 +10335,7 @@ class WalletConnectButtonComponent {
10267
10335
  catch (err) {
10268
10336
  const error = err instanceof Error ? err : new Error(String(err));
10269
10337
  this.error.emit(error);
10270
- logger$3.error('Connection failed', { error: error.message });
10338
+ logger$4.error('Connection failed', { error: error.message });
10271
10339
  }
10272
10340
  finally {
10273
10341
  this.isConnecting = false;
@@ -10313,7 +10381,7 @@ class WalletConnectButtonComponent {
10313
10381
  catch (err) {
10314
10382
  const error = err instanceof Error ? err : new Error(String(err));
10315
10383
  this.error.emit(error);
10316
- logger$3.error('Disconnect failed', { error: error.message });
10384
+ logger$4.error('Disconnect failed', { error: error.message });
10317
10385
  }
10318
10386
  }
10319
10387
  /**
@@ -11708,7 +11776,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImpo
11708
11776
  * }
11709
11777
  * ```
11710
11778
  */
11711
- const logger$2 = getLogger().scoped?.('TransactionService') ?? getLogger();
11779
+ const logger$3 = getLogger().scoped?.('TransactionService') ?? getLogger();
11712
11780
  /**
11713
11781
  * High-level transaction service with automatic state management.
11714
11782
  *
@@ -11760,7 +11828,7 @@ class TransactionService {
11760
11828
  async signTransaction(payload) {
11761
11829
  return this.executeTransaction(async () => {
11762
11830
  const result = (await this.walletService.signTransaction(payload));
11763
- logger$2.info('Transaction signed', {
11831
+ logger$3.info('Transaction signed', {
11764
11832
  hasSignature: !!result.signedTransaction,
11765
11833
  });
11766
11834
  await this.showSuccessToast('Transaction Signed', 'Your transaction has been signed successfully.');
@@ -11781,7 +11849,7 @@ class TransactionService {
11781
11849
  async submitTransaction(payload) {
11782
11850
  return this.executeTransaction(async () => {
11783
11851
  const result = (await this.walletService.submitTransaction(payload));
11784
- logger$2.info('Transaction submitted', { transactionId: result.transactionId });
11852
+ logger$3.info('Transaction submitted', { transactionId: result.transactionId });
11785
11853
  await this.showSuccessToast('Transaction Submitted', `Transaction ID: ${result.transactionId || 'Success'}`);
11786
11854
  return result;
11787
11855
  });
@@ -11800,7 +11868,7 @@ class TransactionService {
11800
11868
  // Use the wallet's signAndExecuteTransaction method directly
11801
11869
  // This uses hedera_signAndExecuteTransaction for WalletConnect (one prompt!)
11802
11870
  const result = (await this.walletService.signAndExecuteTransaction(payload));
11803
- logger$2.info('Transaction signed and submitted', { transactionId: result.transactionId });
11871
+ logger$3.info('Transaction signed and submitted', { transactionId: result.transactionId });
11804
11872
  await this.showSuccessToast('Transaction Complete', `Transaction ID: ${result.transactionId || 'Success'}`);
11805
11873
  return result;
11806
11874
  });
@@ -11824,7 +11892,7 @@ class TransactionService {
11824
11892
  batchKey: options.batchKey,
11825
11893
  innerTransactions: options.innerTransactions,
11826
11894
  }));
11827
- logger$2.info('Batch transaction submitted', { transactionId: result.transactionId });
11895
+ logger$3.info('Batch transaction submitted', { transactionId: result.transactionId });
11828
11896
  await this.showSuccessToast('Batch Transaction Complete', `Transaction ID: ${result.transactionId || 'Success'}`);
11829
11897
  return result;
11830
11898
  });
@@ -11837,8 +11905,8 @@ class TransactionService {
11837
11905
  */
11838
11906
  async signMessage(message) {
11839
11907
  return this.executeTransaction(async () => {
11840
- const result = (await this.walletService.signMessage(message));
11841
- logger$2.info('Message signed', { hasSignature: !!result.signature });
11908
+ const result = await this.walletService.signMessage(message);
11909
+ logger$3.info('Message signed', { hasSignature: !!result.signature });
11842
11910
  await this.showSuccessToast('Message Signed', 'Your message has been signed successfully.');
11843
11911
  return result;
11844
11912
  });
@@ -11961,6 +12029,384 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImpo
11961
12029
  args: [{ providedIn: 'root' }]
11962
12030
  }] });
11963
12031
 
12032
+ /**
12033
+ * HSuite Native Connect
12034
+ * Copyright 2024-2025 HSuite (https://hsuite.finance)
12035
+ *
12036
+ * SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
12037
+ *
12038
+ * This file is part of HSuite Native Connect. For commercial licensing,
12039
+ * visit https://hsuite.finance/licensing
12040
+ */
12041
+ /**
12042
+ * @file Smart-host customer session helper.
12043
+ *
12044
+ * @module services/smart-session
12045
+ *
12046
+ * @description
12047
+ * SmartSessionService automates the smart-host authentication handshake for
12048
+ * HSuite dApps. It discovers the host's `appId`, requests a challenge, signs it
12049
+ * with the active wallet account, and exchanges the signed challenge for a
12050
+ * short-lived bearer token.
12051
+ *
12052
+ * **Typical flow:**
12053
+ * ```typescript
12054
+ * const session = inject(SmartSessionService);
12055
+ * await session.login();
12056
+ * const bearer = session.getBearer();
12057
+ * ```
12058
+ *
12059
+ * The service also exposes {@link withSession} for automatic 401 recovery:
12060
+ * operations that fail with HTTP 401 are retried once after a fresh login.
12061
+ */
12062
+ const logger$2 = getLogger().scoped?.('SmartSessionService') ?? getLogger();
12063
+ /**
12064
+ * Configuration token for {@link SmartSessionService}.
12065
+ */
12066
+ const SMART_SESSION_CONFIG = new InjectionToken('SMART_SESSION_CONFIG', {
12067
+ factory: () => ({}),
12068
+ });
12069
+ /**
12070
+ * Smart-host customer session helper.
12071
+ *
12072
+ * @service SmartSessionService
12073
+ *
12074
+ * @description
12075
+ * Encapsulates the full challenge → sign → verify → store JWT flow required by
12076
+ * HSuite smart hosts. The service is intentionally thin: it delegates signing to
12077
+ * {@link TransactionService} and relies on standard Angular `HttpClient` for the
12078
+ * host HTTP calls.
12079
+ *
12080
+ * @providedIn root
12081
+ */
12082
+ class SmartSessionService {
12083
+ http = inject(HttpClient);
12084
+ walletService = inject(UnifiedWalletService);
12085
+ transactionService = inject(TransactionService);
12086
+ config = inject(SMART_SESSION_CONFIG);
12087
+ get baseUrl() {
12088
+ return this.config.baseUrl ?? '';
12089
+ }
12090
+ get healthEndpoint() {
12091
+ return this.config.healthEndpoint ?? '/api/health';
12092
+ }
12093
+ get challengeEndpoint() {
12094
+ return this.config.challengeEndpoint ?? '/api/auth/challenge';
12095
+ }
12096
+ get verifyEndpoint() {
12097
+ return this.config.verifyEndpoint ?? '/api/auth/verify';
12098
+ }
12099
+ get storageKey() {
12100
+ return this.config.storageKey ?? 'hsuite.smart-session';
12101
+ }
12102
+ /**
12103
+ * Returns the currently stored bearer token, or `null` if there is no session.
12104
+ *
12105
+ * @returns Bearer token string or null
12106
+ */
12107
+ getBearer() {
12108
+ const stored = this.readStoredSession();
12109
+ return stored && stored.expiresAt > Date.now() ? stored.bearer : null;
12110
+ }
12111
+ /**
12112
+ * Checks whether a non-expired session is available.
12113
+ *
12114
+ * @returns true if logged in and the bearer has not expired
12115
+ */
12116
+ isLoggedIn() {
12117
+ return this.getBearer() !== null;
12118
+ }
12119
+ /**
12120
+ * Performs the full smart-host login handshake.
12121
+ *
12122
+ * @description
12123
+ * 1. Discovers `appId` from the health endpoint.
12124
+ * 2. Fetches a challenge from the challenge endpoint.
12125
+ * 3. Signs the challenge with the active wallet account.
12126
+ * 4. Exchanges the signed challenge for a bearer token.
12127
+ * 5. Stores the bearer and expiry in `sessionStorage`.
12128
+ *
12129
+ * @returns The verify response from the host
12130
+ *
12131
+ * @throws {Error} If no active account is available
12132
+ * @throws {Error} If the health endpoint does not return an `appId`
12133
+ * @throws {Error} If the challenge endpoint does not return a `challenge`
12134
+ * @throws {Error} If the verify call fails
12135
+ */
12136
+ async login() {
12137
+ const account = this.walletService.activeAccount();
12138
+ if (!account) {
12139
+ throw new Error('No active account');
12140
+ }
12141
+ logger$2.info('Starting smart-host login handshake', {
12142
+ accountAddress: account.address,
12143
+ });
12144
+ const health = await this.fetchHealth();
12145
+ if (!health.appId) {
12146
+ throw new Error('Smart host health endpoint did not return appId');
12147
+ }
12148
+ const challengeResponse = await this.fetchChallenge(health.appId);
12149
+ if (!challengeResponse.challenge) {
12150
+ throw new Error('Smart host challenge endpoint did not return challenge');
12151
+ }
12152
+ const signResult = await this.transactionService.signMessage(challengeResponse.challenge);
12153
+ const verifyResponse = await this.verifyChallenge(health.appId, account, challengeResponse.challenge, signResult);
12154
+ if (!verifyResponse.bearer) {
12155
+ throw new Error('Smart host verify endpoint did not return bearer');
12156
+ }
12157
+ const expiresAt = this.resolveExpiry(verifyResponse);
12158
+ this.storeSession({ bearer: verifyResponse.bearer, expiresAt });
12159
+ logger$2.info('Smart-host login successful', {
12160
+ appId: health.appId,
12161
+ expiresAt,
12162
+ });
12163
+ return verifyResponse;
12164
+ }
12165
+ /**
12166
+ * Clears the stored session.
12167
+ */
12168
+ logout() {
12169
+ this.clearStoredSession();
12170
+ logger$2.info('Smart-host session cleared');
12171
+ }
12172
+ /**
12173
+ * Runs an HTTP operation with automatic 401 recovery.
12174
+ *
12175
+ * @description
12176
+ * Executes the provided operation. If it rejects with an HTTP 401 error,
12177
+ * the service clears the current bearer, performs a fresh login, and retries
12178
+ * the operation once. Any other error is propagated immediately.
12179
+ *
12180
+ * @param operation - Async operation that needs a valid session
12181
+ * @returns The result of the operation
12182
+ *
12183
+ * @throws {Error} The original error if retry is not possible or fails
12184
+ */
12185
+ async withSession(operation) {
12186
+ try {
12187
+ return await operation();
12188
+ }
12189
+ catch (error) {
12190
+ if (this.isUnauthorizedError(error)) {
12191
+ logger$2.warn('Operation received 401; attempting single session refresh');
12192
+ this.logout();
12193
+ await this.login();
12194
+ return await operation();
12195
+ }
12196
+ throw error;
12197
+ }
12198
+ }
12199
+ async fetchHealth() {
12200
+ return firstValueFrom(this.http.get(`${this.baseUrl}${this.healthEndpoint}`));
12201
+ }
12202
+ async fetchChallenge(appId) {
12203
+ return firstValueFrom(this.http.post(`${this.baseUrl}${this.challengeEndpoint}`, { appId }));
12204
+ }
12205
+ async verifyChallenge(appId, account, challenge, signResult) {
12206
+ const payload = {
12207
+ appId,
12208
+ accountAddress: account.address,
12209
+ publicKey: signResult.publicKey ?? account.publicKey,
12210
+ signature: signResult.signature,
12211
+ algorithm: signResult.algorithm,
12212
+ message: challenge,
12213
+ caipChainId: signResult.caipChainId,
12214
+ ledgerId: account.ledgerId,
12215
+ networkId: account.networkId,
12216
+ // Only sent when it deviates from the legacy default (absent = native
12217
+ // `hsc:` domain-separated signing): a dApp-only upgrade must not add
12218
+ // unknown fields to the verify POST of already-deployed hosts.
12219
+ signingScheme: signResult.signingScheme && signResult.signingScheme !== 'hsuite-domain'
12220
+ ? signResult.signingScheme
12221
+ : undefined,
12222
+ };
12223
+ return firstValueFrom(this.http.post(`${this.baseUrl}${this.verifyEndpoint}`, payload));
12224
+ }
12225
+ resolveExpiry(response) {
12226
+ if (response.expiresAt) {
12227
+ return response.expiresAt;
12228
+ }
12229
+ if (response.expiresIn) {
12230
+ return Date.now() + response.expiresIn * 1000;
12231
+ }
12232
+ // Default to 5 minutes if no expiry is provided
12233
+ return Date.now() + 5 * 60 * 1000;
12234
+ }
12235
+ readStoredSession() {
12236
+ try {
12237
+ const raw = sessionStorage.getItem(this.storageKey);
12238
+ if (!raw) {
12239
+ return null;
12240
+ }
12241
+ const parsed = JSON.parse(raw);
12242
+ if (!parsed.bearer || typeof parsed.expiresAt !== 'number') {
12243
+ return null;
12244
+ }
12245
+ return parsed;
12246
+ }
12247
+ catch {
12248
+ return null;
12249
+ }
12250
+ }
12251
+ storeSession(session) {
12252
+ try {
12253
+ sessionStorage.setItem(this.storageKey, JSON.stringify(session));
12254
+ }
12255
+ catch (error) {
12256
+ logger$2.warn('Failed to store smart session', { error });
12257
+ }
12258
+ }
12259
+ clearStoredSession() {
12260
+ try {
12261
+ sessionStorage.removeItem(this.storageKey);
12262
+ }
12263
+ catch (error) {
12264
+ logger$2.warn('Failed to clear smart session', { error });
12265
+ }
12266
+ }
12267
+ isUnauthorizedError(error) {
12268
+ if (!error || typeof error !== 'object') {
12269
+ return false;
12270
+ }
12271
+ const status = error.status;
12272
+ if (typeof status === 'number') {
12273
+ return status === 401;
12274
+ }
12275
+ const message = String(error.message ?? '');
12276
+ return /\b401\b|unauthorized/i.test(message);
12277
+ }
12278
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: SmartSessionService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
12279
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: SmartSessionService, providedIn: 'root' });
12280
+ }
12281
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: SmartSessionService, decorators: [{
12282
+ type: Injectable,
12283
+ args: [{ providedIn: 'root' }]
12284
+ }] });
12285
+
12286
+ /**
12287
+ * HSuite Native Connect
12288
+ * Copyright 2024-2025 HSuite (https://hsuite.finance)
12289
+ *
12290
+ * SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
12291
+ *
12292
+ * This file is part of HSuite Native Connect. For commercial licensing,
12293
+ * visit https://hsuite.finance/licensing
12294
+ */
12295
+ /**
12296
+ * @file HTTP interceptor that attaches wallet-attributed auth headers.
12297
+ *
12298
+ * @module services/hsuite-auth-interceptor
12299
+ *
12300
+ * @description
12301
+ * `HsuiteAuthInterceptor` automatically adds the active smart-host bearer token
12302
+ * and wallet ledger identifier to outgoing HTTP requests. When a request fails
12303
+ * with HTTP 401, it delegates recovery to {@link SmartSessionService} for a
12304
+ * single re-login and retry.
12305
+ *
12306
+ * **Registration (standalone apps):**
12307
+ * ```typescript
12308
+ * provideHttpClient(withInterceptors([provideHsuiteAuthInterceptor()]))
12309
+ * ```
12310
+ *
12311
+ * **Registration (module-based apps):**
12312
+ * ```typescript
12313
+ * { provide: HTTP_INTERCEPTORS, useClass: HsuiteAuthInterceptor, multi: true }
12314
+ * ```
12315
+ */
12316
+ /**
12317
+ * Headers injected by the interceptor.
12318
+ */
12319
+ const HSUITE_AUTH_HEADER = 'Authorization';
12320
+ const HSUITE_LEDGER_HEADER = 'X-Ledger-Id';
12321
+ /**
12322
+ * Functional HTTP interceptor that attaches wallet-attributed auth headers.
12323
+ *
12324
+ * @description
12325
+ * Adds:
12326
+ * - `Authorization: Bearer <token>` when {@link SmartSessionService.getBearer} returns a token
12327
+ * - `X-Ledger-Id: <ledgerId>` when a wallet account is active
12328
+ *
12329
+ * On 401 responses, clears the stale bearer and retries once after re-login.
12330
+ *
12331
+ * @param req - The outgoing HTTP request
12332
+ * @param next - The downstream request handler
12333
+ * @returns Observable of HTTP events
12334
+ */
12335
+ const hsuiteAuthInterceptor = (req, next) => {
12336
+ const session = inject(SmartSessionService);
12337
+ const wallet = inject(UnifiedWalletService);
12338
+ const authenticated = appendAuthHeaders(req, session, wallet);
12339
+ return next(authenticated).pipe(catchError((error) => {
12340
+ if (error instanceof HttpErrorResponse && error.status === 401) {
12341
+ session.logout();
12342
+ return from(session.login()).pipe(switchMap(() => next(appendAuthHeaders(req, session, wallet))), catchError((loginError) => throwError(() => loginError)));
12343
+ }
12344
+ return throwError(() => error);
12345
+ }));
12346
+ };
12347
+ /**
12348
+ * Class-based HTTP interceptor for module-based Angular apps.
12349
+ *
12350
+ * @description
12351
+ * Provides the same behavior as {@link hsuiteAuthInterceptor} in a class form
12352
+ * suitable for registration via `HTTP_INTERCEPTORS`.
12353
+ */
12354
+ class HsuiteAuthInterceptor {
12355
+ session = inject(SmartSessionService);
12356
+ wallet = inject(UnifiedWalletService);
12357
+ /**
12358
+ * Intercepts outgoing HTTP requests to attach wallet-attributed auth headers.
12359
+ *
12360
+ * @param req - The outgoing HTTP request
12361
+ * @param next - The downstream request handler
12362
+ * @returns Observable of HTTP events
12363
+ */
12364
+ intercept(req, next) {
12365
+ const authenticated = appendAuthHeaders(req, this.session, this.wallet);
12366
+ return next.handle(authenticated).pipe(catchError((error) => {
12367
+ if (error instanceof HttpErrorResponse && error.status === 401) {
12368
+ this.session.logout();
12369
+ return from(this.session.login()).pipe(switchMap(() => next.handle(appendAuthHeaders(req, this.session, this.wallet))), catchError((loginError) => throwError(() => loginError)));
12370
+ }
12371
+ return throwError(() => error);
12372
+ }));
12373
+ }
12374
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: HsuiteAuthInterceptor, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
12375
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: HsuiteAuthInterceptor, providedIn: 'root' });
12376
+ }
12377
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: HsuiteAuthInterceptor, decorators: [{
12378
+ type: Injectable,
12379
+ args: [{ providedIn: 'root' }]
12380
+ }] });
12381
+ /**
12382
+ * Helper that clones a request with the active auth headers attached.
12383
+ *
12384
+ * @param req - The outgoing HTTP request
12385
+ * @param session - Smart session service for bearer lookup
12386
+ * @param wallet - Unified wallet service for ledger ID lookup
12387
+ * @returns The request cloned with Authorization and/or X-Ledger-Id headers
12388
+ */
12389
+ function appendAuthHeaders(req, session, wallet) {
12390
+ const bearer = session.getBearer();
12391
+ const activeAccount = wallet.activeAccount();
12392
+ const ledgerId = activeAccount?.ledgerId;
12393
+ // Avoid mutating requests that already carry an Authorization header
12394
+ if (!bearer && !ledgerId) {
12395
+ return req;
12396
+ }
12397
+ const headers = {};
12398
+ if (bearer && !req.headers.has(HSUITE_AUTH_HEADER)) {
12399
+ headers[HSUITE_AUTH_HEADER] = `Bearer ${bearer}`;
12400
+ }
12401
+ if (ledgerId && !req.headers.has(HSUITE_LEDGER_HEADER)) {
12402
+ headers[HSUITE_LEDGER_HEADER] = ledgerId;
12403
+ }
12404
+ if (Object.keys(headers).length === 0) {
12405
+ return req;
12406
+ }
12407
+ return req.clone({ setHeaders: headers });
12408
+ }
12409
+
11964
12410
  /**
11965
12411
  * HSuite Native Connect
11966
12412
  * Copyright 2024-2025 HSuite (https://hsuite.finance)
@@ -14901,5 +15347,5 @@ function provideWalletErrorHandler(config) {
14901
15347
  * Generated bundle index. Do not edit.
14902
15348
  */
14903
15349
 
14904
- export { ACTIVE_ACCOUNT_SOURCE, AccountActionsComponent, AccountFilterComponent, AccountFormattingService, AccountGroupingService, AccountListComponent, AccountSelectorComponent, AccountSelectorService, BaseWalletProvider, ChannelClientService, ChromeExtensionTransport, DEFAULT_LEDGER_ICONS, DEFAULT_WALLET_URL, HederaSigner, HederaTransactionBuilderService, HsuiteNativeProvider, HsuiteWalletModule, LEDGER_COLORS, LEDGER_ICON_NAMES, LEDGER_NAMES, LedgerUIRegistry, LoggerService, P2PNativeProvider, P2PSessionManager, SignerFactory, TransactionService, UnifiedWalletService, WalletAccountDisplayComponent, WalletConnectButtonComponent, WalletConnectClientManager, WalletConnectPromptComponent, WalletConnectSessionStore, WalletConnectSigningOrchestrator, WalletConnectV2Provider, WalletConnectedDirective, WalletConnectedGuardComponent, WalletConnectionModalComponent, WalletContextDirective, WalletContextService, WalletErrorHandler, WalletEventBus, WalletEventsDirective, WalletSessionDisplayComponent, WalletTransactionStatusComponent, XrplSigner, XrplTransactionBuilderService, getExtensionVersion, getLedgerColor, getLedgerIcon, getLedgerName, getTokenIcon, isExtensionInstalled, isHsuiteNativeConfig, isWalletConnectV2Config, provideWalletErrorHandler, registerLedgerIcons, scaleHederaAmountToBaseUnits };
15350
+ export { ACTIVE_ACCOUNT_SOURCE, AccountActionsComponent, AccountFilterComponent, AccountFormattingService, AccountGroupingService, AccountListComponent, AccountSelectorComponent, AccountSelectorService, BaseWalletProvider, ChannelClientService, ChromeExtensionTransport, DEFAULT_LEDGER_ICONS, DEFAULT_WALLET_URL, HSUITE_AUTH_HEADER, HSUITE_LEDGER_HEADER, HederaSigner, HederaTransactionBuilderService, HsuiteAuthInterceptor, HsuiteNativeProvider, HsuiteWalletModule, LEDGER_COLORS, LEDGER_ICON_NAMES, LEDGER_NAMES, LedgerUIRegistry, LoggerService, P2PNativeProvider, P2PSessionManager, SMART_SESSION_CONFIG, SignerFactory, SmartSessionService, TransactionService, UnifiedWalletService, WalletAccountDisplayComponent, WalletConnectButtonComponent, WalletConnectClientManager, WalletConnectPromptComponent, WalletConnectSessionStore, WalletConnectSigningOrchestrator, WalletConnectV2Provider, WalletConnectedDirective, WalletConnectedGuardComponent, WalletConnectionModalComponent, WalletContextDirective, WalletContextService, WalletErrorHandler, WalletEventBus, WalletEventsDirective, WalletSessionDisplayComponent, WalletTransactionStatusComponent, XrplSigner, XrplTransactionBuilderService, getExtensionVersion, getLedgerColor, getLedgerIcon, getLedgerName, getTokenIcon, hsuiteAuthInterceptor, isExtensionInstalled, isHsuiteNativeConfig, isWalletConnectV2Config, provideWalletErrorHandler, registerLedgerIcons, scaleHederaAmountToBaseUnits };
14905
15351
  //# sourceMappingURL=hsuite-native-connect-angular.mjs.map