@hsuite/native-connect-angular 3.0.1 → 3.0.3

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.
@@ -1829,6 +1829,43 @@ class NoAccountsForNetworkError extends Error {
1829
1829
  this.name = 'NoAccountsForNetworkError';
1830
1830
  }
1831
1831
  }
1832
+ /**
1833
+ * A connect was asked for while another one is still waiting for the wallet,
1834
+ * and it cannot share that request: a QR pairing next to a window connect, or
1835
+ * a pending session this call did not start. Nothing was started. The connect
1836
+ * modal shows it as the `'busy'` error.
1837
+ */
1838
+ class ConnectionInProgressError extends Error {
1839
+ providerType;
1840
+ /**
1841
+ * @param providerType - Provider that already has a connect waiting
1842
+ */
1843
+ constructor(providerType) {
1844
+ super('Another connection is still waiting for approval in the wallet');
1845
+ this.providerType = providerType;
1846
+ this.name = 'ConnectionInProgressError';
1847
+ }
1848
+ }
1849
+
1850
+ /**
1851
+ * HSuite Native Connect
1852
+ * Copyright 2024-2025 HSuite (https://hsuite.finance)
1853
+ *
1854
+ * SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
1855
+ *
1856
+ * This file is part of HSuite Native Connect. For commercial licensing,
1857
+ * visit https://hsuite.finance/licensing
1858
+ */
1859
+ const MOBILE_USER_AGENT = /iPhone|iPad|iPod|Android/i;
1860
+ /**
1861
+ * Whether a user agent string names a phone or tablet OS. An iPad that asks for
1862
+ * desktop sites reports a Mac user agent and is NOT matched here.
1863
+ * @param userAgent - `navigator.userAgent`
1864
+ * @returns true for iPhone, iPad, iPod and Android user agents
1865
+ */
1866
+ function isMobileUserAgent(userAgent) {
1867
+ return MOBILE_USER_AGENT.test(userAgent);
1868
+ }
1832
1869
 
1833
1870
  /**
1834
1871
  * HSuite Native Connect
@@ -3302,6 +3339,11 @@ class HsuiteNativeProvider extends BaseWalletProvider {
3302
3339
  this.localDiscoveryService = LocalDiscoveryService.getDAppInstance();
3303
3340
  this.localDiscoveryService.start();
3304
3341
  }
3342
+ /**
3343
+ * The connect waiting for the wallet's answer, if any. A second window
3344
+ * connect returns this promise instead of starting another request.
3345
+ */
3346
+ pendingConnect = null;
3305
3347
  /**
3306
3348
  * Maps the internal channel state to the provider connection status.
3307
3349
  *
@@ -3380,17 +3422,46 @@ class HsuiteNativeProvider extends BaseWalletProvider {
3380
3422
  * @throws {Error} If configuration is invalid
3381
3423
  * @throws {Error} If connection times out (default 120 seconds)
3382
3424
  * @throws {Error} If popup is blocked and wallet cannot be opened
3425
+ * @throws {ConnectionInProgressError} If another connect is waiting for the
3426
+ * wallet and this one cannot share its request
3383
3427
  */
3384
3428
  async connect(config) {
3385
3429
  if (!this.isHsuiteNativeConfig(config)) {
3386
3430
  throw new Error('Invalid HSuite Native configuration');
3387
3431
  }
3388
- // Guard: Don't start a new connection if already connecting
3389
- const currentStatus = this.status();
3390
- if (currentStatus === 'connecting') {
3391
- logger$f.warn('Connection already in progress, ignoring duplicate request');
3392
- return;
3432
+ // One request at a time, and a connect never resolves before the wallet
3433
+ // answers: callers read a resolved connect as "the wallet approved".
3434
+ const manualDelivery = !!config.onInviteReady;
3435
+ const pending = this.pendingConnect;
3436
+ if (pending) {
3437
+ // A second window connect is, to the user, the request the wallet is
3438
+ // still showing, so it waits for that answer. A QR pairing is not: the
3439
+ // pending request cannot carry its invite.
3440
+ if (!manualDelivery && !pending.manualDelivery) {
3441
+ logger$f.warn('Connection already in progress, waiting for it');
3442
+ return pending.promise;
3443
+ }
3444
+ throw new ConnectionInProgressError('hsuite-native');
3393
3445
  }
3446
+ if (this.status() === 'connecting') {
3447
+ // A session is pending that this call did not start and cannot wait on.
3448
+ throw new ConnectionInProgressError('hsuite-native');
3449
+ }
3450
+ const promise = this.startConnect(config);
3451
+ const started = { promise, manualDelivery };
3452
+ this.pendingConnect = started;
3453
+ const clear = () => {
3454
+ if (this.pendingConnect === started)
3455
+ this.pendingConnect = null;
3456
+ };
3457
+ promise.then(clear, clear);
3458
+ return promise;
3459
+ }
3460
+ /**
3461
+ * Create the invite, deliver it and wait for the wallet's answer.
3462
+ * @param config - HSuite Native connection configuration
3463
+ */
3464
+ async startConnect(config) {
3394
3465
  logger$f.info('Connecting to HSuite Wallet via unified channel protocol', { config });
3395
3466
  // Tracked so the catch block can clean up a half-open session created
3396
3467
  // before the failure (the SDK never expires pending invites itself).
@@ -3482,7 +3553,7 @@ class HsuiteNativeProvider extends BaseWalletProvider {
3482
3553
  * @param config - Connection configuration with app metadata
3483
3554
  */
3484
3555
  async openWalletWindow(inviteUrl, walletBaseUrl, config) {
3485
- const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
3556
+ const isMobile = isMobileUserAgent(navigator.userAgent);
3486
3557
  // LOCAL-FIRST DISCOVERY
3487
3558
  // Wait briefly for wallet heartbeat before opening new tab
3488
3559
  if (this.localDiscoveryService?.active) {
@@ -4968,6 +5039,346 @@ class SignerFactory {
4968
5039
  }
4969
5040
  }
4970
5041
 
5042
+ /**
5043
+ * HSuite Native Connect
5044
+ * Copyright 2024-2025 HSuite (https://hsuite.finance)
5045
+ *
5046
+ * SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
5047
+ *
5048
+ * This file is part of HSuite Native Connect. For commercial licensing,
5049
+ * visit https://hsuite.finance/licensing
5050
+ */
5051
+ /**
5052
+ * @file hedera-host-wallet.ts
5053
+ * @description Pair through the Hedera wallet that is HOSTING this page
5054
+ *
5055
+ * WHY: opened inside a wallet's own dApp browser on a phone, WalletConnect's
5056
+ * modal hands the pairing link over by deep link, and a deep link into the app
5057
+ * the page already runs in goes nowhere, so the connection never completes.
5058
+ *
5059
+ * THE PROTOCOL is Hedera's own, from `@hashgraph/hedera-wallet-connect`
5060
+ * (`extensionController`, `DAppConnector.connectExtension`, `DAppSigner.request`),
5061
+ * which wallet extensions and in-app browsers answer:
5062
+ *
5063
+ * page → `hedera-extension-query` (and `hedera-iframe-query` to a parent frame)
5064
+ * wallet → `hedera-extension-response` {metadata: {id, name, …}}
5065
+ * (`hedera-iframe-response` from a parent frame)
5066
+ * page → `hedera-extension-connect-<id>` {pairingString: <wc: uri>}
5067
+ * (`hedera-iframe-connect` to a parent frame)
5068
+ * page → `hedera-extension-open-<id>` before every request, so the wallet
5069
+ * brings up its approval sheet
5070
+ *
5071
+ * WHEN IT APPLIES: a wallet that frames the page, only when the dApp listed
5072
+ * that wallet's origin ({@link HEDERA_HOST_WALLET_PARENT_ORIGINS}); a
5073
+ * same-window answer only on a phone or tablet. A framing page gets the
5074
+ * pairing link, and with it the power to answer the connection with its own
5075
+ * wallet, so one the dApp did not name is never asked and never answered. On desktop the same answer comes from a browser
5076
+ * EXTENSION (HashPack, Kabila), and those users keep the modal and its choice of
5077
+ * wallet. A phone has no Hedera wallet extensions, so an answer there means the
5078
+ * page runs inside that wallet's own browser.
5079
+ *
5080
+ * NOTHING IS POSTED UNTIL IT IS NEEDED: the wallet is asked for on the first
5081
+ * Hedera pairing, or on the first request of a session remembered as paired
5082
+ * through a wallet (after a reload). A page that never uses Hedera, or runs on a
5083
+ * desktop outside a frame, posts no message at all.
5084
+ *
5085
+ * Nothing here signs anything: it routes the pairing link WalletConnect already
5086
+ * produced, and remembers which session was paired this way so the approval
5087
+ * sheet ping goes only to that session.
5088
+ */
5089
+ const HOST_WALLET_EVENTS = {
5090
+ query: 'hedera-extension-query',
5091
+ response: 'hedera-extension-response',
5092
+ connectPrefix: 'hedera-extension-connect-',
5093
+ openPrefix: 'hedera-extension-open-',
5094
+ iframeQuery: 'hedera-iframe-query',
5095
+ iframeResponse: 'hedera-iframe-response',
5096
+ iframeConnect: 'hedera-iframe-connect',
5097
+ };
5098
+ /** A pairing link or a request is due and no wallet has answered yet: how long to wait for an answer. */
5099
+ const HOST_WALLET_REQUERY_WAIT_MS = 600;
5100
+ /** How long a hosting wallet has to approve a handed-over pairing before the modal opens after all. */
5101
+ const HOST_WALLET_HANDOFF_TIMEOUT_MS = 20_000;
5102
+ /** Storage key prefix: the host wallet a session (by WalletConnect topic) was paired through. */
5103
+ const HOST_WALLET_PAIRED_KEY_PREFIX = 'hsuite.walletconnect.hostWallet.';
5104
+ /** Wallet ids are short tokens; anything else is not an answer to act on. */
5105
+ const WALLET_ID = /^[A-Za-z0-9._:-]{1,100}$/;
5106
+ const REAL_CLOCK = {
5107
+ schedule: (fn, ms) => setTimeout(fn, ms),
5108
+ cancel: (timer) => clearTimeout(timer),
5109
+ };
5110
+ /**
5111
+ * A wallet's answer to the query, or null for anything else (malformed, or another message).
5112
+ * @param data - The message payload
5113
+ * @param viaParent - Whether it came from a parent frame
5114
+ * @param origin - The sending window's origin
5115
+ */
5116
+ function parseHostWalletMessage(data, viaParent, origin) {
5117
+ if (!data || typeof data !== 'object')
5118
+ return null;
5119
+ const msg = data;
5120
+ const expected = viaParent ? HOST_WALLET_EVENTS.iframeResponse : HOST_WALLET_EVENTS.response;
5121
+ if (msg.type !== expected || !msg.metadata || typeof msg.metadata !== 'object')
5122
+ return null;
5123
+ const meta = msg.metadata;
5124
+ if (typeof meta.id !== 'string' || !WALLET_ID.test(meta.id))
5125
+ return null;
5126
+ const name = typeof meta.name === 'string' && meta.name.trim() ? meta.name.trim().slice(0, 60) : meta.id;
5127
+ return { id: meta.id, name, viaParent, origin };
5128
+ }
5129
+ /**
5130
+ * A phone or tablet: a mobile UA, or an iPad that asks for desktop sites (Mac UA with touch).
5131
+ * @param device - User agent and touch points
5132
+ */
5133
+ function isTouchDevice(device) {
5134
+ return (isMobileUserAgent(device.userAgent) ||
5135
+ (/Macintosh/.test(device.userAgent) && device.maxTouchPoints > 1));
5136
+ }
5137
+ /**
5138
+ * Whether to route through `wallet`: always when it frames the page, otherwise only on a phone or tablet.
5139
+ * @param wallet - The wallet that answered, if any
5140
+ * @param device - User agent and touch points
5141
+ */
5142
+ function shouldUseHostWallet(wallet, device) {
5143
+ if (!wallet)
5144
+ return false;
5145
+ return wallet.viaParent || isTouchDevice(device);
5146
+ }
5147
+ /**
5148
+ * Finds a hosting Hedera wallet and routes pairing links and approval pings to it.
5149
+ */
5150
+ class HederaHostWalletLink {
5151
+ win;
5152
+ device;
5153
+ store;
5154
+ clock;
5155
+ trustedParentOrigins;
5156
+ found = null;
5157
+ stop = null;
5158
+ waiters = [];
5159
+ /**
5160
+ * @param win - The page's window
5161
+ * @param device - User agent and touch points
5162
+ * @param store - Where paired sessions are remembered, or null
5163
+ * @param clock - Timers
5164
+ * @param trustedParentOrigins - Origins of wallets allowed to frame this
5165
+ * page and take its pairing link. Empty: no framing page is trusted.
5166
+ */
5167
+ constructor(win, device, store, clock = REAL_CLOCK, trustedParentOrigins = []) {
5168
+ this.win = win;
5169
+ this.device = device;
5170
+ this.store = store;
5171
+ this.clock = clock;
5172
+ this.trustedParentOrigins = trustedParentOrigins;
5173
+ }
5174
+ /**
5175
+ * Listen for a hosting wallet's answer. Posts nothing. `handOff` and `ping`
5176
+ * call this themselves; calling it again is a no-op. Returns the disposer.
5177
+ */
5178
+ start() {
5179
+ if (!this.stop) {
5180
+ const listener = (event) => this.onMessage(event);
5181
+ this.win.addEventListener('message', listener);
5182
+ this.stop = () => {
5183
+ this.win.removeEventListener('message', listener);
5184
+ this.stop = null;
5185
+ this.release();
5186
+ };
5187
+ }
5188
+ return this.stop;
5189
+ }
5190
+ /** The hosting wallet, when this page should connect through it. */
5191
+ active() {
5192
+ return shouldUseHostWallet(this.found, this.device) ? this.found : null;
5193
+ }
5194
+ /**
5195
+ * Hand a Hedera pairing link to the hosting wallet. Resolves null, with
5196
+ * nothing sent, when there is none: the caller opens the modal as before.
5197
+ * Otherwise resolves the wallet that took the link, and the modal still opens
5198
+ * if that wallet has not approved within HOST_WALLET_HANDOFF_TIMEOUT_MS, so a
5199
+ * wallet that ignores the link never leaves the user waiting on nothing.
5200
+ * @param pairing - The link, the modal fallback and the approval promise
5201
+ */
5202
+ async handOff(pairing) {
5203
+ if (!pairing.uri.startsWith('wc:'))
5204
+ return null;
5205
+ this.start();
5206
+ if (!this.found && this.mayBeHosted()) {
5207
+ this.query();
5208
+ await this.answer(HOST_WALLET_REQUERY_WAIT_MS);
5209
+ }
5210
+ const wallet = this.active();
5211
+ if (!wallet)
5212
+ return null;
5213
+ this.post(wallet, pairing.uri);
5214
+ let pending = true;
5215
+ const fallback = this.clock.schedule(() => {
5216
+ if (!pending)
5217
+ return;
5218
+ pending = false;
5219
+ // The modal is best effort here: the connection itself still waits on `settled`.
5220
+ Promise.resolve()
5221
+ .then(() => pairing.openModal())
5222
+ .catch(() => undefined);
5223
+ }, HOST_WALLET_HANDOFF_TIMEOUT_MS);
5224
+ const settle = () => {
5225
+ pending = false;
5226
+ this.clock.cancel(fallback);
5227
+ };
5228
+ pairing.settled.then(settle, settle);
5229
+ return wallet;
5230
+ }
5231
+ /**
5232
+ * Remember that the session on `topic` was paired through `wallet`. Call once
5233
+ * the wallet has approved, not when the link is handed over.
5234
+ * @param topic - WalletConnect session topic
5235
+ * @param wallet - The wallet `handOff` resolved
5236
+ */
5237
+ markPaired(topic, wallet) {
5238
+ try {
5239
+ this.store?.setItem(HOST_WALLET_PAIRED_KEY_PREFIX + topic, wallet.id);
5240
+ }
5241
+ catch {
5242
+ // Storage blocked: no ping for this session, nothing else changes.
5243
+ }
5244
+ }
5245
+ /**
5246
+ * Forget a session, when it is disconnected or deleted.
5247
+ * @param topic - WalletConnect session topic
5248
+ */
5249
+ forget(topic) {
5250
+ try {
5251
+ this.store?.removeItem(HOST_WALLET_PAIRED_KEY_PREFIX + topic);
5252
+ }
5253
+ catch {
5254
+ // Storage blocked: there was nothing to forget.
5255
+ }
5256
+ }
5257
+ /**
5258
+ * Before a Hedera request on `topic`: ask the hosting wallet to show its
5259
+ * approval sheet, as `DAppSigner.request` does. Only for a session that was
5260
+ * paired through that wallet, and never to a parent frame (the reference
5261
+ * library has no such message). After a reload the wallet has not been asked
5262
+ * for yet: it is asked now, and pinged as soon as it answers.
5263
+ * @param topic - WalletConnect session topic
5264
+ */
5265
+ ping(topic) {
5266
+ const pairedId = this.pairedWith(topic);
5267
+ if (!pairedId)
5268
+ return;
5269
+ const open = () => {
5270
+ const wallet = this.active();
5271
+ if (!wallet || wallet.viaParent || wallet.id !== pairedId)
5272
+ return;
5273
+ this.win.postMessage({ type: HOST_WALLET_EVENTS.openPrefix + wallet.id }, this.win.location.origin);
5274
+ };
5275
+ this.start();
5276
+ if (this.found || !this.mayBeHosted()) {
5277
+ open();
5278
+ return;
5279
+ }
5280
+ this.query();
5281
+ void this.answer(HOST_WALLET_REQUERY_WAIT_MS).then(open);
5282
+ }
5283
+ mayBeHosted() {
5284
+ return this.isFramedByTrusted() || isTouchDevice(this.device);
5285
+ }
5286
+ isFramed() {
5287
+ return !!this.win.parent && this.win.parent !== this.win;
5288
+ }
5289
+ /** Framed, and the dApp named at least one wallet origin that may frame it. */
5290
+ isFramedByTrusted() {
5291
+ return this.isFramed() && this.trustedParentOrigins.length > 0;
5292
+ }
5293
+ post(wallet, uri) {
5294
+ if (wallet.viaParent) {
5295
+ this.win.parent.postMessage({ type: HOST_WALLET_EVENTS.iframeConnect, pairingString: uri }, wallet.origin);
5296
+ }
5297
+ else {
5298
+ this.win.postMessage({ type: HOST_WALLET_EVENTS.connectPrefix + wallet.id, pairingString: uri }, this.win.location.origin);
5299
+ }
5300
+ }
5301
+ pairedWith(topic) {
5302
+ try {
5303
+ return this.store?.getItem(HOST_WALLET_PAIRED_KEY_PREFIX + topic) ?? null;
5304
+ }
5305
+ catch {
5306
+ return null;
5307
+ }
5308
+ }
5309
+ query() {
5310
+ this.win.postMessage({ type: HOST_WALLET_EVENTS.query }, this.win.location.origin);
5311
+ if (this.isFramedByTrusted()) {
5312
+ // Only to the wallets the dApp named: any other parent never hears of it.
5313
+ for (const origin of this.trustedParentOrigins) {
5314
+ this.win.parent.postMessage({ type: HOST_WALLET_EVENTS.iframeQuery }, origin);
5315
+ }
5316
+ }
5317
+ }
5318
+ /**
5319
+ * Resolves when a wallet answers, or after `ms`.
5320
+ * @param ms - The longest to wait
5321
+ */
5322
+ answer(ms) {
5323
+ return new Promise((resolve) => {
5324
+ const timer = this.clock.schedule(() => resolve(), ms);
5325
+ this.waiters = [
5326
+ ...this.waiters,
5327
+ () => {
5328
+ this.clock.cancel(timer);
5329
+ resolve();
5330
+ },
5331
+ ];
5332
+ });
5333
+ }
5334
+ release() {
5335
+ const waiters = this.waiters;
5336
+ this.waiters = [];
5337
+ waiters.forEach((w) => w());
5338
+ }
5339
+ onMessage(event) {
5340
+ if (this.found)
5341
+ return;
5342
+ const fromParent = this.isFramed() &&
5343
+ event.source === this.win.parent &&
5344
+ this.trustedParentOrigins.includes(event.origin);
5345
+ const fromSelf = event.source === this.win;
5346
+ if (!fromParent && !fromSelf)
5347
+ return;
5348
+ this.found = parseHostWalletMessage(event.data, fromParent, event.origin);
5349
+ if (this.found)
5350
+ this.release();
5351
+ }
5352
+ }
5353
+ /**
5354
+ * Origins of the Hedera wallets allowed to frame this dApp and take its
5355
+ * pairing link (`https://wallet.example`, exact match). Empty by default: a
5356
+ * page that frames the dApp is not trusted, and the WalletConnect modal opens
5357
+ * as it always did. Provide the list to pair inside a wallet that embeds dApps
5358
+ * in a frame.
5359
+ */
5360
+ const HEDERA_HOST_WALLET_PARENT_ORIGINS = new InjectionToken('HEDERA_HOST_WALLET_PARENT_ORIGINS', { providedIn: 'root', factory: () => [] });
5361
+ /**
5362
+ * The page's link to a hosting Hedera wallet. Creating it posts nothing and
5363
+ * listens to nothing (see the file header). Null outside a browser. Override in tests, or provide null to
5364
+ * always use the WalletConnect modal.
5365
+ */
5366
+ const HEDERA_HOST_WALLET_LINK = new InjectionToken('HEDERA_HOST_WALLET_LINK', {
5367
+ providedIn: 'root',
5368
+ factory: () => {
5369
+ if (typeof window === 'undefined' || typeof navigator === 'undefined')
5370
+ return null;
5371
+ let store = null;
5372
+ try {
5373
+ store = window.localStorage;
5374
+ }
5375
+ catch {
5376
+ store = null;
5377
+ }
5378
+ return new HederaHostWalletLink(window, { userAgent: navigator.userAgent, maxTouchPoints: navigator.maxTouchPoints ?? 0 }, store, undefined, inject(HEDERA_HOST_WALLET_PARENT_ORIGINS));
5379
+ },
5380
+ });
5381
+
4971
5382
  /**
4972
5383
  * HSuite Native Connect
4973
5384
  * Copyright 2024-2025 HSuite (https://hsuite.finance)
@@ -5685,6 +6096,7 @@ class WalletConnectSigningOrchestrator {
5685
6096
  sessionStore;
5686
6097
  clientManager;
5687
6098
  eventBus;
6099
+ beforeRequest;
5688
6100
  /**
5689
6101
  *
5690
6102
  * @param config
@@ -5694,6 +6106,7 @@ class WalletConnectSigningOrchestrator {
5694
6106
  this.sessionStore = config.sessionStore;
5695
6107
  this.clientManager = config.clientManager;
5696
6108
  this.eventBus = config.eventBus;
6109
+ this.beforeRequest = config.beforeRequest;
5697
6110
  }
5698
6111
  /**
5699
6112
  * Sign a transaction without submitting.
@@ -5710,6 +6123,7 @@ class WalletConnectSigningOrchestrator {
5710
6123
  networkId,
5711
6124
  userSelectedNetwork: sessionInfo.userSelectedNetwork,
5712
6125
  });
6126
+ this.announceRequest(sessionInfo);
5713
6127
  return sessionInfo.signer.signTransaction({
5714
6128
  client: this.clientManager.getClient(),
5715
6129
  topic: sessionInfo.session.topic,
@@ -5733,6 +6147,7 @@ class WalletConnectSigningOrchestrator {
5733
6147
  networkId,
5734
6148
  userSelectedNetwork: sessionInfo.userSelectedNetwork,
5735
6149
  });
6150
+ this.announceRequest(sessionInfo);
5736
6151
  return sessionInfo.signer.submitTransaction({
5737
6152
  client: this.clientManager.getClient(),
5738
6153
  topic: sessionInfo.session.topic,
@@ -5756,6 +6171,7 @@ class WalletConnectSigningOrchestrator {
5756
6171
  networkId,
5757
6172
  userSelectedNetwork: sessionInfo.userSelectedNetwork,
5758
6173
  });
6174
+ this.announceRequest(sessionInfo);
5759
6175
  // Check if signer supports native signAndExecute
5760
6176
  if (typeof sessionInfo.signer.signAndExecuteTransaction === 'function') {
5761
6177
  return sessionInfo.signer.signAndExecuteTransaction({
@@ -5797,6 +6213,7 @@ class WalletConnectSigningOrchestrator {
5797
6213
  networkId,
5798
6214
  userSelectedNetwork: sessionInfo.userSelectedNetwork,
5799
6215
  });
6216
+ this.announceRequest(sessionInfo);
5800
6217
  return sessionInfo.signer.signMessage({
5801
6218
  client: this.clientManager.getClient(),
5802
6219
  topic: sessionInfo.session.topic,
@@ -5807,6 +6224,27 @@ class WalletConnectSigningOrchestrator {
5807
6224
  encoding: options.encoding,
5808
6225
  });
5809
6226
  }
6227
+ /**
6228
+ * Tell the provider a wallet request is about to go out on this session.
6229
+ * @param sessionInfo - The session the request goes to
6230
+ * @param sessionInfo.signer
6231
+ * @param sessionInfo.signer.ledgerId
6232
+ * @param sessionInfo.session
6233
+ * @param sessionInfo.session.topic
6234
+ */
6235
+ announceRequest(sessionInfo) {
6236
+ try {
6237
+ this.beforeRequest?.({
6238
+ ledgerId: sessionInfo.signer.ledgerId,
6239
+ topic: sessionInfo.session.topic,
6240
+ });
6241
+ }
6242
+ catch (error) {
6243
+ logger$8.warn('beforeRequest hook failed', {
6244
+ error: error instanceof Error ? error.message : String(error),
6245
+ });
6246
+ }
6247
+ }
5810
6248
  /**
5811
6249
  * Resolve the network ID to use for signing.
5812
6250
  *
@@ -5967,6 +6405,8 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5967
6405
  eventBus = inject(WalletEventBus);
5968
6406
  // NgZone for ensuring change detection runs after WalletConnect events
5969
6407
  zone = inject(NgZone);
6408
+ // The Hedera wallet hosting this page (its in-app browser or frame), if any
6409
+ hostWalletLink = inject(HEDERA_HOST_WALLET_LINK, { optional: true });
5970
6410
  /**
5971
6411
  *
5972
6412
  */
@@ -5978,6 +6418,11 @@ class WalletConnectV2Provider extends BaseWalletProvider {
5978
6418
  sessionStore: this.sessionStore,
5979
6419
  clientManager: this.clientManager,
5980
6420
  eventBus: this.eventBus,
6421
+ // Hedera only: have the hosting wallet bring up its approval sheet.
6422
+ beforeRequest: ({ ledgerId, topic }) => {
6423
+ if (ledgerId === 'hedera')
6424
+ this.hostWalletLink?.ping(topic);
6425
+ },
5981
6426
  });
5982
6427
  logger$7.info('Initializing - will attempt session restoration');
5983
6428
  void this.restoreSession();
@@ -6212,6 +6657,16 @@ class WalletConnectV2Provider extends BaseWalletProvider {
6212
6657
  // Ignore cleanup errors
6213
6658
  }
6214
6659
  }
6660
+ /**
6661
+ * Forget everything stored per session topic. Every per-topic key is cleared
6662
+ * here, so a session that ends cannot leave one behind.
6663
+ *
6664
+ * @param sessionTopic - WalletConnect session topic
6665
+ */
6666
+ forgetSessionState(sessionTopic) {
6667
+ this.clearUserNetworkSelection(sessionTopic);
6668
+ this.hostWalletLink?.forget(sessionTopic);
6669
+ }
6215
6670
  /**
6216
6671
  * Connect to a wallet via WalletConnect QR code.
6217
6672
  *
@@ -6270,12 +6725,29 @@ class WalletConnectV2Provider extends BaseWalletProvider {
6270
6725
  });
6271
6726
  // Connect and show QR code
6272
6727
  const { uri, approval } = await this.clientManager.connect(optionalNamespaces, sessionProperties);
6728
+ // approval() makes a NEW promise per call and drops the previous one's
6729
+ // resolver: call it exactly once and share the promise.
6730
+ const approved = approval();
6731
+ // Awaited below; this only keeps an early rejection from going unhandled.
6732
+ approved.catch(() => undefined);
6733
+ // Inside a Hedera wallet's own browser or frame, hand the pairing link to
6734
+ // that wallet: the modal's deep link cannot open the app the page runs in.
6735
+ // The modal still opens if the wallet has not approved in time.
6736
+ let hostWallet = null;
6273
6737
  if (uri) {
6274
- await modal.openModal({ uri });
6738
+ const openModal = () => modal.openModal({ uri });
6739
+ if (wcConfig.ledgerId === 'hedera' && this.hostWalletLink) {
6740
+ hostWallet = await this.hostWalletLink
6741
+ .handOff({ uri, openModal, settled: approved })
6742
+ .catch(() => null);
6743
+ }
6744
+ if (!hostWallet) {
6745
+ await openModal();
6746
+ }
6275
6747
  }
6276
6748
  // Wait for wallet approval
6277
- logger$7.info('Waiting for wallet approval...');
6278
- const session = await approval();
6749
+ logger$7.info('Waiting for wallet approval...', { viaHostWallet: !!hostWallet });
6750
+ const session = await approved;
6279
6751
  this.clientManager.closeModal();
6280
6752
  logger$7.info('[WC:DAPP:APPROVED] Session approved by wallet', {
6281
6753
  topic: session.topic.substring(0, 16) + '...',
@@ -6354,6 +6826,11 @@ class WalletConnectV2Provider extends BaseWalletProvider {
6354
6826
  });
6355
6827
  // Persist user's network selection for session restoration after page reload
6356
6828
  this.storeUserNetworkSelection(session.topic, wcConfig.networkId);
6829
+ // Approved through the hosting wallet: its approval sheet is pinged before
6830
+ // each request on this session.
6831
+ if (hostWallet) {
6832
+ this.hostWalletLink?.markPaired(session.topic, hostWallet);
6833
+ }
6357
6834
  // Verify session exists in WC SDK after storing
6358
6835
  const sdkSession = this.clientManager.getSession(session.topic);
6359
6836
  logger$7.info('[WC:DAPP:STORED] Session stored locally', {
@@ -6410,8 +6887,8 @@ class WalletConnectV2Provider extends BaseWalletProvider {
6410
6887
  removeSessionByTopic(topic) {
6411
6888
  // Find and remove the session using session store
6412
6889
  const removed = this.sessionStore.removeSessionByTopic(topic);
6413
- // Clean up stored network selection
6414
- this.clearUserNetworkSelection(topic);
6890
+ // Clean up what was stored for this session
6891
+ this.forgetSessionState(topic);
6415
6892
  // Update aggregated accounts
6416
6893
  this.sessionStore.updateAggregatedAccounts();
6417
6894
  // Update status
@@ -6489,8 +6966,8 @@ class WalletConnectV2Provider extends BaseWalletProvider {
6489
6966
  error: e instanceof Error ? e.message : String(e),
6490
6967
  });
6491
6968
  }
6492
- // Clean up stored network selection
6493
- this.clearUserNetworkSelection(sessionData.session.topic);
6969
+ // Clean up what was stored for this session
6970
+ this.forgetSessionState(sessionData.session.topic);
6494
6971
  this.sessionStore.deleteSession(sessionKey);
6495
6972
  this.sessionStore.updateAggregatedAccounts();
6496
6973
  if (this.sessionStore.size === 0) {
@@ -6502,8 +6979,8 @@ class WalletConnectV2Provider extends BaseWalletProvider {
6502
6979
  // Disconnect all sessions
6503
6980
  const disconnectPromises = [];
6504
6981
  for (const [_key, sessionData] of this.sessionStore.entries()) {
6505
- // Clean up stored network selection for each session
6506
- this.clearUserNetworkSelection(sessionData.session.topic);
6982
+ // Clean up what was stored for each session
6983
+ this.forgetSessionState(sessionData.session.topic);
6507
6984
  disconnectPromises.push(this.clientManager
6508
6985
  .disconnect(sessionData.session.topic, {
6509
6986
  code: 6000,
@@ -7649,28 +8126,24 @@ function networkName(networkId) {
7649
8126
  * This file is part of HSuite Native Connect. For commercial licensing,
7650
8127
  * visit https://hsuite.finance/licensing
7651
8128
  */
7652
- /** `shard.realm.num` — short enough to show whole outside compact layouts. */
8129
+ /** `shard.realm.num` — short enough to show whole, in a phone header too. */
7653
8130
  const HEDERA_ID = /^\d+\.\d+\.\d+$/;
7654
8131
  /**
7655
8132
  * Display form of an account address for the account UI (canvas page "Conta").
7656
- * Hedera ids are shown whole (`0.0.4821937`), or `0.0.48…937` in compact
7657
- * layouts; longer addresses (XRPL, EVM) become `rN7f…k2Qp`. Screens that
8133
+ * Hedera ids are shown whole (`0.0.4821937`) at every width: shortening one
8134
+ * saves a character or two and hides the digits the user reads to tell their
8135
+ * accounts apart. Longer addresses (XRPL, EVM) become `rN7f…k2Qp`. Screens that
7658
8136
  * shorten an address also expose the full one (accessible name / title).
7659
8137
  *
7660
8138
  * `AccountFormattingService.truncateAddress` is not used: it keeps a 11-char
7661
8139
  * id whole at any length and joins with three dots.
7662
8140
  * @param address
7663
- * @param opts
7664
- * @param opts.compact - phone header chip (A07)
7665
8141
  */
7666
- function shortAddress$1(address, opts = {}) {
8142
+ function shortAddress$1(address) {
7667
8143
  if (!address)
7668
8144
  return '';
7669
- if (HEDERA_ID.test(address)) {
7670
- return opts.compact && address.length > 10
7671
- ? `${address.slice(0, 6)}…${address.slice(-3)}`
7672
- : address;
7673
- }
8145
+ if (HEDERA_ID.test(address))
8146
+ return address;
7674
8147
  return address.length > 12 ? `${address.slice(0, 4)}…${address.slice(-4)}` : address;
7675
8148
  }
7676
8149
 
@@ -7799,7 +8272,7 @@ class AccountSelectorService {
7799
8272
  for (const s of sessions)
7800
8273
  counts.set(s.name, (counts.get(s.name) ?? 0) + 1);
7801
8274
  return sessions.map((s) => (counts.get(s.name) ?? 0) > 1 && s.accounts[0]
7802
- ? { ...s, name: `${s.name} · ${shortAddress$1(s.accounts[0].address, { compact: true })}` }
8275
+ ? { ...s, name: `${s.name} · ${shortAddress$1(s.accounts[0].address)}` }
7803
8276
  : s);
7804
8277
  }, ...(ngDevMode ? [{ debugName: "sessionsVm" }] : []));
7805
8278
  /**
@@ -10834,13 +11307,18 @@ function isPhoneLayout(platform) {
10834
11307
  * messages come from `channel-client.service.ts` (rejected / timeout);
10835
11308
  * WalletConnect wallets report rejections as "User rejected …" and stale
10836
11309
  * pairings as "… expired", which reads as a timeout to the user. A connect
10837
- * that shared no account on the selected network is matched by name as well,
10838
- * in case the error comes from another copy of the package.
11310
+ * that shared no account on the selected network, and one refused because
11311
+ * another is still waiting for the wallet, are matched by name as well, in
11312
+ * case the error comes from another copy of the package.
10839
11313
  * @param err
10840
11314
  */
10841
11315
  function classifyConnectError(err) {
10842
11316
  if (err instanceof NativeSessionLimitError)
10843
11317
  return 'session-limit';
11318
+ if (err instanceof ConnectionInProgressError ||
11319
+ (err instanceof Error && err.name === 'ConnectionInProgressError')) {
11320
+ return 'busy';
11321
+ }
10844
11322
  if (err instanceof NoAccountsForNetworkError ||
10845
11323
  (err instanceof Error && err.name === 'NoAccountsForNetworkError')) {
10846
11324
  return 'wrong-network';
@@ -13093,9 +13571,10 @@ class WalletConnectionModalComponent {
13093
13571
  this.onAttemptSucceeded(attempt, ledger ? 'walletconnect-v2' : 'hsuite-native', network, before);
13094
13572
  }
13095
13573
  /**
13096
- * The provider ignores a connect while another one is pending (it resolves
13097
- * immediately), so re-picking HSuite Wallet after backing out re-attaches to
13098
- * the request the wallet is still showing instead of starting a new one.
13574
+ * Re-picking HSuite Wallet after backing out re-attaches to the request the
13575
+ * wallet is still showing instead of starting a new one. The provider does
13576
+ * the same for a request this modal did not start (one left pending by a
13577
+ * modal that was closed): its connect waits for that request's answer.
13099
13578
  * @param network
13100
13579
  */
13101
13580
  connectHsuiteWallet(network) {
@@ -13192,8 +13671,8 @@ class WalletConnectionModalComponent {
13192
13671
  async startQrPairing(attempt) {
13193
13672
  this.pairingOffer.set('');
13194
13673
  this.pairingInviteUrl.set('');
13195
- // The provider ignores a connect while another is pending: never start
13196
- // next to a pending HSuite Wallet one.
13674
+ // The provider refuses a pairing while a window connect is pending: say
13675
+ // so here without asking it.
13197
13676
  if (this.nativeConnect) {
13198
13677
  // Waiting for it could take the whole approval timeout; say why instead.
13199
13678
  this.onAttemptFailed(attempt, new Error('Another HSuite Wallet connection is still waiting for approval'), 'busy');
@@ -18661,7 +19140,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.26", ngImpo
18661
19140
  class AccountChipComponent {
18662
19141
  // Decorator inputs (not signal inputs): this package's Vitest setup has no
18663
19142
  // Angular compiler plugin, and JIT cannot see `input()` initializers.
18664
- /** Phone header (A07): shorter address, no caret. */
19143
+ /** Phone header (A07): tighter chip, no caret. */
18665
19144
  compact = false;
18666
19145
  /** Whether the account menu this chip opens is showing (`aria-expanded`). */
18667
19146
  expanded = false;
@@ -18672,9 +19151,9 @@ class AccountChipComponent {
18672
19151
  wallet = inject(UnifiedWalletService);
18673
19152
  account = computed(() => this.wallet.activeAccount(), ...(ngDevMode ? [{ debugName: "account" }] : []));
18674
19153
  avatar = computed(() => avatarColor(this.account()?.address ?? ''), ...(ngDevMode ? [{ debugName: "avatar" }] : []));
18675
- /** Address as shown; `compact` is a plain input, so this is a method. */
19154
+ /** Address as shown: a Hedera id whole, in the compact chip too. */
18676
19155
  displayAddress() {
18677
- return shortAddress$1(this.account()?.address ?? '', { compact: this.compact });
19156
+ return shortAddress$1(this.account()?.address ?? '');
18678
19157
  }
18679
19158
  /** Full address (the visible one may be shortened) and the account count. */
18680
19159
  accessibleName() {
@@ -19310,5 +19789,5 @@ function provideWalletErrorHandler(config) {
19310
19789
  * Generated bundle index. Do not edit.
19311
19790
  */
19312
19791
 
19313
- export { ACTIVE_ACCOUNT_SOURCE, AccountActionsComponent, AccountChipComponent, AccountFilterComponent, AccountFormattingService, AccountGroupingService, AccountListComponent, AccountMenuComponent, 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$1 as LEDGER_NAMES, LedgerUIRegistry, LoggerService, MAX_NATIVE_SESSIONS, NATIVE_SESSION_KEY_PREFIX, NativeSessionLimitError, NoAccountsForNetworkError, SMART_SESSION_CONFIG, SessionNoticeService, SignerFactory, SmartSessionService, TransactionService, UnifiedWalletService, WALLET_UI_CONFIG, WalletAccountDisplayComponent, WalletButtonComponent, WalletConnectButtonComponent, WalletConnectClientManager, WalletConnectPromptComponent, WalletConnectSessionStore, WalletConnectSigningOrchestrator, WalletConnectV2Provider, WalletConnectedDirective, WalletConnectedGuardComponent, WalletConnectionModalComponent, WalletContextDirective, WalletContextService, WalletErrorHandler, WalletEventBus, WalletEventsDirective, WalletSessionDisplayComponent, WalletTransactionStatusComponent, WalletUiService, XrplSigner, XrplTransactionBuilderService, channelIdFromSessionKey, getExtensionVersion, getLedgerColor, getLedgerIcon, getLedgerName, getTokenIcon, hsuiteAuthInterceptor, isExtensionInstalled, isHsuiteNativeConfig, isWalletConnectV2Config, nativeSessionKeyFor, parseNativeSessionKey, provideWalletErrorHandler, provideWalletUi, registerLedgerIcons, scaleHederaAmountToBaseUnits, supportsSessionManagement };
19792
+ export { ACTIVE_ACCOUNT_SOURCE, AccountActionsComponent, AccountChipComponent, AccountFilterComponent, AccountFormattingService, AccountGroupingService, AccountListComponent, AccountMenuComponent, AccountSelectorComponent, AccountSelectorService, BaseWalletProvider, ChannelClientService, ChromeExtensionTransport, ConnectionInProgressError, DEFAULT_LEDGER_ICONS, DEFAULT_WALLET_URL, HEDERA_HOST_WALLET_LINK, HEDERA_HOST_WALLET_PARENT_ORIGINS, HOST_WALLET_EVENTS, HOST_WALLET_HANDOFF_TIMEOUT_MS, HOST_WALLET_PAIRED_KEY_PREFIX, HOST_WALLET_REQUERY_WAIT_MS, HSUITE_AUTH_HEADER, HSUITE_LEDGER_HEADER, HederaHostWalletLink, HederaSigner, HederaTransactionBuilderService, HsuiteAuthInterceptor, HsuiteNativeProvider, HsuiteWalletModule, LEDGER_COLORS, LEDGER_ICON_NAMES, LEDGER_NAMES$1 as LEDGER_NAMES, LedgerUIRegistry, LoggerService, MAX_NATIVE_SESSIONS, NATIVE_SESSION_KEY_PREFIX, NativeSessionLimitError, NoAccountsForNetworkError, SMART_SESSION_CONFIG, SessionNoticeService, SignerFactory, SmartSessionService, TransactionService, UnifiedWalletService, WALLET_UI_CONFIG, WalletAccountDisplayComponent, WalletButtonComponent, WalletConnectButtonComponent, WalletConnectClientManager, WalletConnectPromptComponent, WalletConnectSessionStore, WalletConnectSigningOrchestrator, WalletConnectV2Provider, WalletConnectedDirective, WalletConnectedGuardComponent, WalletConnectionModalComponent, WalletContextDirective, WalletContextService, WalletErrorHandler, WalletEventBus, WalletEventsDirective, WalletSessionDisplayComponent, WalletTransactionStatusComponent, WalletUiService, XrplSigner, XrplTransactionBuilderService, channelIdFromSessionKey, getExtensionVersion, getLedgerColor, getLedgerIcon, getLedgerName, getTokenIcon, hsuiteAuthInterceptor, isExtensionInstalled, isHsuiteNativeConfig, isTouchDevice, isWalletConnectV2Config, nativeSessionKeyFor, parseHostWalletMessage, parseNativeSessionKey, provideWalletErrorHandler, provideWalletUi, registerLedgerIcons, scaleHederaAmountToBaseUnits, shouldUseHostWallet, supportsSessionManagement };
19314
19793
  //# sourceMappingURL=hsuite-native-connect-angular.mjs.map