@meshconnect/uwc-injected-connector 0.27.5 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/injected-connector.d.ts.map +1 -1
  2. package/dist/injected-connector.js +62 -47
  3. package/dist/injected-connector.js.map +1 -1
  4. package/dist/services/connection-manager.d.ts +17 -13
  5. package/dist/services/connection-manager.d.ts.map +1 -1
  6. package/dist/services/connection-manager.js +93 -65
  7. package/dist/services/connection-manager.js.map +1 -1
  8. package/dist/services/solana/solana-wallet-service.d.ts +2 -0
  9. package/dist/services/solana/solana-wallet-service.d.ts.map +1 -1
  10. package/dist/services/solana/solana-wallet-service.js +1 -0
  11. package/dist/services/solana/solana-wallet-service.js.map +1 -1
  12. package/dist/services/ton/ton-wallet-service.d.ts +7 -1
  13. package/dist/services/ton/ton-wallet-service.d.ts.map +1 -1
  14. package/dist/services/ton/ton-wallet-service.js +21 -1
  15. package/dist/services/ton/ton-wallet-service.js.map +1 -1
  16. package/dist/utils/secondary-prompt-gap.d.ts +47 -0
  17. package/dist/utils/secondary-prompt-gap.d.ts.map +1 -0
  18. package/dist/utils/secondary-prompt-gap.js +65 -0
  19. package/dist/utils/secondary-prompt-gap.js.map +1 -0
  20. package/package.json +6 -6
  21. package/src/injected-connector.test.ts +374 -7
  22. package/src/injected-connector.ts +100 -55
  23. package/src/services/connection-manager.test.ts +841 -171
  24. package/src/services/connection-manager.ts +157 -86
  25. package/src/services/solana/solana-wallet-service.check-existing.test.ts +24 -0
  26. package/src/services/solana/solana-wallet-service.ts +6 -1
  27. package/src/services/ton/ton-wallet-service.test.ts +69 -0
  28. package/src/services/ton/ton-wallet-service.ts +22 -1
  29. package/src/utils/secondary-prompt-gap.test.ts +288 -0
  30. package/src/utils/secondary-prompt-gap.ts +95 -0
@@ -9,7 +9,12 @@ import type {
9
9
  SolanaMetadata,
10
10
  WalletStepInfo
11
11
  } from '@meshconnect/uwc-types'
12
- import { withDeadline } from '../utils/with-deadline'
12
+ import {
13
+ beforeSecondaryPrompt,
14
+ markPrompted,
15
+ runSecondaryLeg,
16
+ type SecondaryLeg
17
+ } from '../utils/secondary-prompt-gap'
13
18
  import { createStepReporter, type StepReporter } from '../utils/step-reporter'
14
19
  import type { EthereumProvider } from '../eip6963-discovery'
15
20
  import type { EthereumWalletService } from './ethereum/ethereum-wallet-service'
@@ -532,10 +537,12 @@ export class ConnectionManager {
532
537
  targetNamespace: Namespace,
533
538
  provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
534
539
  requiredAddresses?: readonly string[],
535
- options?: { silentOnly?: boolean }
540
+ options?: { silentOnly?: boolean; secondaryPromptGapMs?: number }
536
541
  ): Promise<{
537
542
  address: string | null
538
543
  availableAddresses: AvailableAddress[]
544
+ /** Whether a secondary gather here sent a request that can prompt. */
545
+ secondaryPrompted: boolean
539
546
  }> {
540
547
  // A different wallet's live state must not be reused as "already
541
548
  // connected" — drop it first so every branch below only ever sees state
@@ -544,20 +551,36 @@ export class ConnectionManager {
544
551
 
545
552
  const availableAddresses: AvailableAddress[] = []
546
553
  let currentAddress: string | null = null
554
+ let secondaryPrompted = false
547
555
  // Silent-only (see `ConnectorConnectOptions.silentOnly`): every probe here
548
556
  // must stay non-prompting. The secondary gathers normally fall back to a
549
557
  // PROMPTING connect, so under silent-only they run only once the target is
550
558
  // authorized, and then without those fallbacks.
551
559
  const silentOnly = options?.silentOnly === true
560
+ const promptGapMs = options?.secondaryPromptGapMs ?? 0
561
+ // An EVM target that is not authorized yet skips these gathers: the
562
+ // caller's prompting connect for it comes next, and a gather here would sit
563
+ // in front of it, waiting up to `secondaryGatherTimeoutMs` and able to open
564
+ // a prompt of its own. On a site the wallet had not approved, that put a
565
+ // Solana prompt ahead of the EVM one (MetaMask then refused the EVM request
566
+ // with -32002; Trust iOS never answered the TON gather sent right after it,
567
+ // holding the EVM prompt back for 15s). Nothing is lost: the caller replaces
568
+ // these addresses with the connect result, and `connectEthereum` gathers
569
+ // the other namespaces after the EVM connect.
570
+ // Other targets keep this pass: its EVM leg is MetaMask's single prompt
571
+ // that grants every chain, where gathering after a Bitcoin connect (which
572
+ // grants Bitcoin alone) would ask twice.
552
573
  const gatherOthers = async (
553
574
  connectedNamespace: 'eip155' | 'solana' | 'tron' | 'tvm' | 'bip122'
554
575
  ): Promise<void> => {
555
- if (silentOnly && !currentAddress) return
556
- await this.checkAndAddOtherNamespaceAddresses(
576
+ const coldEvmTarget = connectedNamespace === 'eip155'
577
+ if (!currentAddress && (silentOnly || coldEvmTarget)) return
578
+ secondaryPrompted = await this.checkAndAddOtherNamespaceAddresses(
557
579
  connectedNamespace,
558
580
  provider,
559
581
  availableAddresses,
560
- silentOnly
582
+ silentOnly,
583
+ promptGapMs
561
584
  )
562
585
  }
563
586
 
@@ -751,7 +774,7 @@ export class ConnectionManager {
751
774
  await gatherOthers('bip122')
752
775
  }
753
776
 
754
- return { address: currentAddress, availableAddresses }
777
+ return { address: currentAddress, availableAddresses, secondaryPrompted }
755
778
  }
756
779
 
757
780
  /**
@@ -760,7 +783,9 @@ export class ConnectionManager {
760
783
  private async checkAndAddEthereumAddresses(
761
784
  provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
762
785
  availableAddresses: AvailableAddress[],
763
- silentOnly = false
786
+ silentOnly = false,
787
+ promptGapMs = 0,
788
+ leg?: SecondaryLeg
764
789
  ): Promise<SecondaryGatherOutcome> {
765
790
  // Default 'ok'; the internal catch below flips it so a swallowed wallet
766
791
  // error is still REPORTED as a failure (see SecondaryGatherOutcome).
@@ -785,9 +810,11 @@ export class ConnectionManager {
785
810
  ? accounts[0]
786
811
  : silentOnly || skipFramedSecondaryConnect()
787
812
  ? undefined
788
- : await this.ethereumService.connect(
789
- ethWallet.provider,
790
- ethWalletUuid
813
+ : await beforeSecondaryPrompt(leg, promptGapMs).then(() =>
814
+ this.ethereumService.connect(
815
+ ethWallet.provider,
816
+ ethWalletUuid
817
+ )
791
818
  )
792
819
  if (ethAddress) {
793
820
  ethAccount = ethAddress
@@ -824,7 +851,9 @@ export class ConnectionManager {
824
851
  private async checkAndAddSolanaAddresses(
825
852
  provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
826
853
  availableAddresses: AvailableAddress[],
827
- silentOnly = false
854
+ silentOnly = false,
855
+ promptGapMs = 0,
856
+ leg?: SecondaryLeg
828
857
  ): Promise<SecondaryGatherOutcome> {
829
858
  // Default 'ok'; the internal catch below flips it so a swallowed wallet
830
859
  // error is still REPORTED as a failure (see SecondaryGatherOutcome).
@@ -847,16 +876,26 @@ export class ConnectionManager {
847
876
  this.solanaService.findWalletByUuid(solanaWalletUuid)
848
877
  if (solanaWallet?.adapter) {
849
878
  try {
879
+ // With a prompt gap the read skips the reconnect of a wallet this
880
+ // browser connected before: it is a `connect()` too, and opens a
881
+ // prompt when the wallet has since revoked the site. The gapped
882
+ // connect below reconnects instead.
883
+ const gapped = !silentOnly && promptGapMs > 0
884
+ const adapter = solanaWallet.adapter
850
885
  const existingAddress = silentOnly
851
886
  ? await this.solanaService.checkExistingConnectionSilently(
852
- solanaWallet.adapter,
887
+ adapter,
853
888
  solanaWalletUuid,
854
889
  supportsStandardConnect(solanaWallet)
855
890
  )
856
891
  : await this.solanaService.checkExistingConnection(
857
- solanaWallet.adapter,
892
+ adapter,
858
893
  solanaWalletUuid,
859
- { allowSilentReconnect: !skipLegacyConnect }
894
+ {
895
+ allowSilentReconnect: !skipLegacyConnect && !gapped,
896
+ // An abandoned leg must not reconnect (it can prompt).
897
+ onReconnect: () => markPrompted(leg)
898
+ }
860
899
  )
861
900
  const canConnect =
862
901
  !silentOnly &&
@@ -865,9 +904,8 @@ export class ConnectionManager {
865
904
  const solanaAddress =
866
905
  existingAddress ||
867
906
  (canConnect
868
- ? await this.solanaService.connect(
869
- solanaWallet.adapter,
870
- solanaWalletUuid
907
+ ? await beforeSecondaryPrompt(leg, promptGapMs).then(() =>
908
+ this.solanaService.connect(adapter, solanaWalletUuid)
871
909
  )
872
910
  : undefined)
873
911
  if (solanaAddress) {
@@ -927,7 +965,9 @@ export class ConnectionManager {
927
965
  private async checkAndAddTronAddresses(
928
966
  provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
929
967
  availableAddresses: AvailableAddress[],
930
- silentOnly = false
968
+ silentOnly = false,
969
+ promptGapMs = 0,
970
+ leg?: SecondaryLeg
931
971
  ): Promise<SecondaryGatherOutcome> {
932
972
  // Default 'ok'; the internal catch below flips it so a swallowed wallet
933
973
  // error is still REPORTED as a failure (see SecondaryGatherOutcome).
@@ -949,7 +989,9 @@ export class ConnectionManager {
949
989
  (silentOnly ||
950
990
  skipFramedSecondaryConnect(/* namespaceSafeFramed */ true)
951
991
  ? undefined
952
- : await this.tronService.connect(tronWallet.provider))
992
+ : await beforeSecondaryPrompt(leg, promptGapMs).then(() =>
993
+ this.tronService.connect(tronWallet.provider)
994
+ ))
953
995
  if (address) {
954
996
  tronAccount = address
955
997
  this.tronService.setConnectionState(tronWallet.provider, address)
@@ -982,7 +1024,9 @@ export class ConnectionManager {
982
1024
  private async checkAndAddTonAddresses(
983
1025
  provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
984
1026
  availableAddresses: AvailableAddress[],
985
- silentOnly = false
1027
+ silentOnly = false,
1028
+ promptGapMs = 0,
1029
+ leg?: SecondaryLeg
986
1030
  ): Promise<SecondaryGatherOutcome> {
987
1031
  // Default 'ok'; the internal catch below flips it so a swallowed wallet
988
1032
  // error is still REPORTED as a failure (see SecondaryGatherOutcome).
@@ -998,7 +1042,11 @@ export class ConnectionManager {
998
1042
  provider.namespaceMetaData?.tvm?.detectedWallet?.jsBridgeKey
999
1043
  if (jsBridgeKey && !silentOnly && !skipFramedSecondaryConnect()) {
1000
1044
  try {
1001
- const result = await this.tonService.connect(jsBridgeKey)
1045
+ // The gap goes before the handshake only: the service first
1046
+ // resumes a stored session, which never prompts.
1047
+ const result = await this.tonService.connect(jsBridgeKey, () =>
1048
+ beforeSecondaryPrompt(leg, promptGapMs)
1049
+ )
1002
1050
  tonAccount = result.address
1003
1051
  } catch (error) {
1004
1052
  // TON connection failed or was rejected — continue without TON, but
@@ -1074,59 +1122,75 @@ export class ConnectionManager {
1074
1122
  connectedNamespace: 'eip155' | 'solana' | 'tron' | 'tvm' | 'bip122',
1075
1123
  provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
1076
1124
  availableAddresses: AvailableAddress[],
1077
- silentOnly = false
1078
- ): Promise<void> {
1125
+ silentOnly = false,
1126
+ promptGapMs = 0
1127
+ ): Promise<boolean> {
1079
1128
  // A silent gather never opens a window, so it is not tracked.
1080
1129
  const promptKey = silentOnly
1081
1130
  ? undefined
1082
1131
  : provider.namespaceMetaData.eip155?.detectedWallet?.uuid
1132
+ // Every leg runs; `prompted` is whether any of them sent a request that can
1133
+ // prompt.
1134
+ let prompted = false
1083
1135
  if (connectedNamespace !== 'eip155') {
1084
- await this.gatherNamespace(
1136
+ const legPrompted = await this.gatherNamespace(
1085
1137
  'eip155',
1086
- () =>
1138
+ leg =>
1087
1139
  this.checkAndAddEthereumAddresses(
1088
1140
  provider,
1089
1141
  availableAddresses,
1090
- silentOnly
1142
+ silentOnly,
1143
+ promptGapMs,
1144
+ leg
1091
1145
  ),
1092
1146
  promptKey
1093
1147
  )
1148
+ prompted ||= legPrompted
1094
1149
  }
1095
1150
  if (connectedNamespace !== 'solana') {
1096
- await this.gatherNamespace(
1151
+ const legPrompted = await this.gatherNamespace(
1097
1152
  'solana',
1098
- () =>
1153
+ leg =>
1099
1154
  this.checkAndAddSolanaAddresses(
1100
1155
  provider,
1101
1156
  availableAddresses,
1102
- silentOnly
1157
+ silentOnly,
1158
+ promptGapMs,
1159
+ leg
1103
1160
  ),
1104
1161
  promptKey
1105
1162
  )
1163
+ prompted ||= legPrompted
1106
1164
  }
1107
1165
  if (connectedNamespace !== 'tron') {
1108
- await this.gatherNamespace(
1166
+ const legPrompted = await this.gatherNamespace(
1109
1167
  'tron',
1110
- () =>
1168
+ leg =>
1111
1169
  this.checkAndAddTronAddresses(
1112
1170
  provider,
1113
1171
  availableAddresses,
1114
- silentOnly
1172
+ silentOnly,
1173
+ promptGapMs,
1174
+ leg
1115
1175
  ),
1116
1176
  promptKey
1117
1177
  )
1178
+ prompted ||= legPrompted
1118
1179
  }
1119
1180
  if (connectedNamespace !== 'tvm') {
1120
- await this.gatherNamespace(
1181
+ const legPrompted = await this.gatherNamespace(
1121
1182
  'tvm',
1122
- () =>
1183
+ leg =>
1123
1184
  this.checkAndAddTonAddresses(
1124
1185
  provider,
1125
1186
  availableAddresses,
1126
- silentOnly
1187
+ silentOnly,
1188
+ promptGapMs,
1189
+ leg
1127
1190
  ),
1128
1191
  promptKey
1129
1192
  )
1193
+ prompted ||= legPrompted
1130
1194
  }
1131
1195
  if (connectedNamespace !== 'bip122') {
1132
1196
  // Passive only: it never opens a window, so it is not tracked.
@@ -1134,11 +1198,13 @@ export class ConnectionManager {
1134
1198
  this.checkAndAddBitcoinAddresses(provider, availableAddresses)
1135
1199
  )
1136
1200
  }
1201
+ return prompted
1137
1202
  }
1138
1203
 
1139
1204
  /**
1140
1205
  * Run one secondary-namespace gather under its deadline, reporting the
1141
- * outcome as a `secondaryGather` step.
1206
+ * outcome as a `secondaryGather` step. Resolves whether the leg sent a
1207
+ * request that can prompt.
1142
1208
  *
1143
1209
  * Swallows a rejection as well as a timeout: the per-namespace helpers below
1144
1210
  * already catch their own wallet errors, so anything reaching here is an
@@ -1151,50 +1217,40 @@ export class ConnectionManager {
1151
1217
  */
1152
1218
  private async gatherNamespace(
1153
1219
  namespace: Namespace,
1154
- gather: () => Promise<SecondaryGatherOutcome>,
1220
+ gather: (leg: SecondaryLeg) => Promise<SecondaryGatherOutcome>,
1155
1221
  // The wallet to track the gather's request under while it is pending;
1156
1222
  // omitted for a gather that never opens a window.
1157
1223
  promptKey?: string
1158
- ): Promise<void> {
1224
+ ): Promise<boolean> {
1159
1225
  const timeoutMs = this.secondaryGatherTimeoutMs
1160
1226
  const start = Date.now()
1161
- let timedOut = false
1162
- try {
1163
- const outcome = await withDeadline(
1164
- () => this.trackPrompt(promptKey, namespace, gather()),
1227
+ const run = await runSecondaryLeg(timeoutMs, leg =>
1228
+ this.trackPrompt(promptKey, namespace, gather(leg))
1229
+ )
1230
+ const durationMs = Date.now() - start
1231
+ if (run.status === 'timedOut') {
1232
+ this.steps.report({
1233
+ step: 'secondaryGather',
1234
+ outcome: 'timedOut',
1235
+ durationMs,
1236
+ namespace,
1165
1237
  timeoutMs,
1166
- () => {
1167
- timedOut = true
1168
- this.steps.report({
1169
- step: 'secondaryGather',
1170
- outcome: 'timedOut',
1171
- durationMs: Date.now() - start,
1172
- namespace,
1173
- timeoutMs
1174
- })
1175
- }
1176
- )
1177
- if (!timedOut) {
1178
- this.steps.report({
1179
- step: 'secondaryGather',
1180
- // `withDeadline` resolves undefined only on the timeout path, which
1181
- // the `!timedOut` guard already excludes; treat a missing outcome as
1182
- // a failure rather than silently reporting success.
1183
- ...(outcome === 'ok'
1184
- ? { outcome }
1185
- : (outcome ?? { outcome: 'failed' as const })),
1186
- durationMs: Date.now() - start,
1187
- namespace
1188
- })
1189
- }
1190
- } catch (error) {
1238
+ prompted: run.prompted
1239
+ })
1240
+ } else {
1191
1241
  this.steps.report({
1192
1242
  step: 'secondaryGather',
1193
- ...gatherFailure(error),
1194
- durationMs: Date.now() - start,
1195
- namespace
1243
+ ...(run.status === 'failed'
1244
+ ? gatherFailure(run.error)
1245
+ : run.value === 'ok'
1246
+ ? { outcome: run.value }
1247
+ : run.value),
1248
+ durationMs,
1249
+ namespace,
1250
+ prompted: run.prompted
1196
1251
  })
1197
1252
  }
1253
+ return run.prompted
1198
1254
  }
1199
1255
 
1200
1256
  /**
@@ -1304,13 +1360,13 @@ export class ConnectionManager {
1304
1360
 
1305
1361
  /**
1306
1362
  * The EVM connect, asked again once if the wallet refused it because one of
1307
- * its windows is still open (ONC-2390): a secondary gather's past its
1308
- * deadline (on production's MetaMask config the connect window IS the
1309
- * Solana gather's), or one an earlier connect left open (Try Again, Link's
1310
- * return-user "Open MetaMask"). Either way the user's answer to that window
1311
- * was lost and the connect failed with -32002. Waits for the window with no
1312
- * deadline of its own, like any connect prompt: the consumer owns
1313
- * cancelling (Link's watchdog).
1363
+ * its windows is still open (ONC-2390): one an earlier connect left open
1364
+ * (Try Again, Link's return-user "Open MetaMask"), its own request or one of
1365
+ * its gathers. A cold EVM connect sends nothing before this request, so the
1366
+ * window is never its own. The user's answer to that window used to be lost
1367
+ * and the connect failed with -32002. Waits for the window with no deadline
1368
+ * of its own, like any connect prompt: the consumer owns cancelling (Link's
1369
+ * watchdog).
1314
1370
  */
1315
1371
  private async requestEthereumAccount(
1316
1372
  wallet: { uuid: string; provider: EthereumProvider },
@@ -1368,6 +1424,7 @@ export class ConnectionManager {
1368
1424
  async connectEthereum(
1369
1425
  network: Network,
1370
1426
  provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
1427
+ promptGapMs = 0,
1371
1428
  // The attempt whose pre-connect check ran before this; without one there
1372
1429
  // is no open window to wait for.
1373
1430
  attempt?: ConnectAttempt
@@ -1411,7 +1468,9 @@ export class ConnectionManager {
1411
1468
  await this.checkAndAddOtherNamespaceAddresses(
1412
1469
  'eip155',
1413
1470
  provider,
1414
- availableAddresses
1471
+ availableAddresses,
1472
+ false,
1473
+ promptGapMs
1415
1474
  )
1416
1475
 
1417
1476
  return {
@@ -1429,7 +1488,8 @@ export class ConnectionManager {
1429
1488
  */
1430
1489
  async connectSolana(
1431
1490
  network: Network,
1432
- provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider
1491
+ provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
1492
+ promptGapMs = 0
1433
1493
  ): Promise<ConnectorResult> {
1434
1494
  try {
1435
1495
  const walletUuid =
@@ -1463,7 +1523,9 @@ export class ConnectionManager {
1463
1523
  await this.checkAndAddOtherNamespaceAddresses(
1464
1524
  'solana',
1465
1525
  provider,
1466
- availableAddresses
1526
+ availableAddresses,
1527
+ false,
1528
+ promptGapMs
1467
1529
  )
1468
1530
 
1469
1531
  return {
@@ -1481,7 +1543,8 @@ export class ConnectionManager {
1481
1543
  */
1482
1544
  async connectTron(
1483
1545
  network: Network,
1484
- provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider
1546
+ provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
1547
+ promptGapMs = 0
1485
1548
  ): Promise<ConnectorResult> {
1486
1549
  try {
1487
1550
  const walletUuid = provider.namespaceMetaData?.tron?.detectedWallet?.uuid
@@ -1510,7 +1573,9 @@ export class ConnectionManager {
1510
1573
  await this.checkAndAddOtherNamespaceAddresses(
1511
1574
  'tron',
1512
1575
  provider,
1513
- availableAddresses
1576
+ availableAddresses,
1577
+ false,
1578
+ promptGapMs
1514
1579
  )
1515
1580
 
1516
1581
  return {
@@ -1528,7 +1593,8 @@ export class ConnectionManager {
1528
1593
  */
1529
1594
  async connectTon(
1530
1595
  network: Network,
1531
- provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider
1596
+ provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
1597
+ promptGapMs = 0
1532
1598
  ): Promise<ConnectorResult> {
1533
1599
  try {
1534
1600
  const jsBridgeKey =
@@ -1552,7 +1618,9 @@ export class ConnectionManager {
1552
1618
  await this.checkAndAddOtherNamespaceAddresses(
1553
1619
  'tvm',
1554
1620
  provider,
1555
- availableAddresses
1621
+ availableAddresses,
1622
+ false,
1623
+ promptGapMs
1556
1624
  )
1557
1625
 
1558
1626
  return {
@@ -1574,7 +1642,8 @@ export class ConnectionManager {
1574
1642
  async connectBitcoin(
1575
1643
  network: Network,
1576
1644
  provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
1577
- requiredAddresses?: readonly string[]
1645
+ requiredAddresses?: readonly string[],
1646
+ promptGapMs = 0
1578
1647
  ): Promise<ConnectorResult> {
1579
1648
  try {
1580
1649
  const connectResult = await this.bitcoinService.connect(
@@ -1591,7 +1660,9 @@ export class ConnectionManager {
1591
1660
  await this.checkAndAddOtherNamespaceAddresses(
1592
1661
  'bip122',
1593
1662
  provider,
1594
- availableAddresses
1663
+ availableAddresses,
1664
+ false,
1665
+ promptGapMs
1595
1666
  )
1596
1667
 
1597
1668
  return {
@@ -38,6 +38,30 @@ describe('SolanaWalletService.checkExistingConnection — allowSilentReconnect',
38
38
  expect(address).toBe('SolAddr1')
39
39
  })
40
40
 
41
+ it('calls onReconnect right before the reconnect, and only when it reconnects', async () => {
42
+ const remembered = setup({ previouslyConnected: true })
43
+ const order: string[] = []
44
+ remembered.connect.mockImplementation(async () => {
45
+ order.push('connect')
46
+ remembered.adapter.publicKey = { toBase58: () => 'SolAddr1' }
47
+ })
48
+ await remembered.service.checkExistingConnection(
49
+ remembered.adapter as unknown as SolanaAdapter,
50
+ 'wallet-1',
51
+ { onReconnect: () => order.push('onReconnect') }
52
+ )
53
+ expect(order).toEqual(['onReconnect', 'connect'])
54
+
55
+ const fresh = setup({ previouslyConnected: false })
56
+ const onReconnect = vi.fn()
57
+ await fresh.service.checkExistingConnection(
58
+ fresh.adapter as unknown as SolanaAdapter,
59
+ 'wallet-1',
60
+ { onReconnect }
61
+ )
62
+ expect(onReconnect).not.toHaveBeenCalled()
63
+ })
64
+
41
65
  it('stays purely passive when allowSilentReconnect is false (no adapter.connect)', async () => {
42
66
  const { service, adapter, connect } = setup({ previouslyConnected: true })
43
67
 
@@ -68,7 +68,11 @@ export class SolanaWalletService {
68
68
  async checkExistingConnection(
69
69
  adapter: SolanaAdapter,
70
70
  walletUuid: string,
71
- options?: { allowSilentReconnect?: boolean }
71
+ options?: {
72
+ allowSilentReconnect?: boolean
73
+ /** Runs right before the reconnect's `adapter.connect()`, which can prompt. */
74
+ onReconnect?: () => void
75
+ }
72
76
  ): Promise<string | null> {
73
77
  const allowSilentReconnect = options?.allowSilentReconnect ?? true
74
78
  try {
@@ -87,6 +91,7 @@ export class SolanaWalletService {
87
91
  const walletIsConnecting = await adapter.connecting
88
92
  if (!walletIsConnecting) {
89
93
  try {
94
+ options?.onReconnect?.()
90
95
  await adapter.connect()
91
96
 
92
97
  const base58PublicKey = await adapter.publicKey?.toBase58()
@@ -388,6 +388,75 @@ describe('TonWalletService', () => {
388
388
  expect(mockConnect).toHaveBeenCalled()
389
389
  })
390
390
 
391
+ it('awaits beforeHandshake right before a fresh handshake', async () => {
392
+ const order: string[] = []
393
+ mockOnStatusChange.mockImplementation(callback => {
394
+ setTimeout(() => callback({ account: { address: 'UQBfresh' } }), 10)
395
+ return vi.fn()
396
+ })
397
+ mockConnect.mockImplementation(() => {
398
+ order.push('handshake')
399
+ })
400
+
401
+ await service.connect('tonkeeper', async () => {
402
+ await Promise.resolve()
403
+ order.push('beforeHandshake')
404
+ })
405
+
406
+ expect(order).toEqual(['beforeHandshake', 'handshake'])
407
+ })
408
+
409
+ it('does not run beforeHandshake when a stored session is restored', async () => {
410
+ localStorage.setItem(
411
+ 'uwc-ton-injected:ton-connect-storage_bridge-connection',
412
+ JSON.stringify({
413
+ type: 'injected',
414
+ jsBridgeKey: 'tonkeeper',
415
+ nextRpcRequestId: 0
416
+ })
417
+ )
418
+ mockOnStatusChange.mockImplementation(callback => {
419
+ queueMicrotask(() =>
420
+ callback({ account: { address: '0:restoredHex' } })
421
+ )
422
+ return vi.fn()
423
+ })
424
+ const beforeHandshake = vi.fn(async () => undefined)
425
+
426
+ const result = await service.connect('tonkeeper', beforeHandshake)
427
+
428
+ expect(result.address).toBe('UQ_converted_restored')
429
+ expect(beforeHandshake).not.toHaveBeenCalled()
430
+ expect(mockConnect).not.toHaveBeenCalled()
431
+ })
432
+
433
+ it('sends no handshake and drops the SDK when beforeHandshake throws', async () => {
434
+ const abandoned = new Error('abandoned')
435
+
436
+ await expect(
437
+ service.connect('tonkeeper', () => Promise.reject(abandoned))
438
+ ).rejects.toBe(abandoned)
439
+
440
+ expect(mockConnect).not.toHaveBeenCalled()
441
+ expect(mockDisconnect).toHaveBeenCalledTimes(1)
442
+ expect(await service.checkExistingConnection()).toBeNull()
443
+ })
444
+
445
+ it('sends no handshake when disconnected while beforeHandshake runs', async () => {
446
+ let release!: () => void
447
+ const connecting = service.connect(
448
+ 'tonkeeper',
449
+ () => new Promise<void>(resolve => (release = resolve))
450
+ )
451
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'))
452
+
453
+ await service.disconnect()
454
+ release()
455
+
456
+ await expect(connecting).rejects.toThrow(/cancelled/)
457
+ expect(mockConnect).not.toHaveBeenCalled()
458
+ })
459
+
391
460
  it('ignores late timeout after successful connection (settled guard)', async () => {
392
461
  vi.useFakeTimers()
393
462
 
@@ -73,8 +73,15 @@ export class TonWalletService {
73
73
  }
74
74
  }
75
75
 
76
+ /**
77
+ * Connects the injected TON wallet: resumes a stored session silently, or
78
+ * runs a fresh handshake, which can open the wallet's prompt.
79
+ * `beforeHandshake` is awaited right before that handshake only; a throw
80
+ * from it ends the connect without one.
81
+ */
76
82
  async connect(
77
- jsBridgeKey: string
83
+ jsBridgeKey: string,
84
+ beforeHandshake?: () => Promise<void>
78
85
  ): Promise<{ address: string; publicKey?: string }> {
79
86
  const resolvedManifestUrl =
80
87
  typeof this.manifestUrl === 'function'
@@ -126,6 +133,20 @@ export class TonWalletService {
126
133
  return restored
127
134
  }
128
135
 
136
+ if (beforeHandshake) {
137
+ try {
138
+ await beforeHandshake()
139
+ } catch (error) {
140
+ await this.cleanupSdk(sdkRef)
141
+ throw error
142
+ }
143
+ // Disconnected, or superseded by a newer connect, while it ran.
144
+ if (this.connectGeneration !== generation) {
145
+ await this.cleanupSdk(sdkRef)
146
+ throw new Error('TON wallet connection was cancelled')
147
+ }
148
+ }
149
+
129
150
  // No prior session — fresh handshake (preflight cleaned any stale state).
130
151
  // Listen BEFORE connect — sdk.connect() is fire-and-forget
131
152
  const walletPromise = new Promise<{ address: string; publicKey?: string }>(