@meshconnect/uwc-injected-connector 0.27.4 → 0.27.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.
@@ -11,6 +11,7 @@ import type {
11
11
  } from '@meshconnect/uwc-types'
12
12
  import { withDeadline } from '../utils/with-deadline'
13
13
  import { createStepReporter, type StepReporter } from '../utils/step-reporter'
14
+ import type { EthereumProvider } from '../eip6963-discovery'
14
15
  import type { EthereumWalletService } from './ethereum/ethereum-wallet-service'
15
16
  import type { SolanaWalletService } from './solana/solana-wallet-service'
16
17
  import type { TronWalletService } from './tron/tron-wallet-service'
@@ -21,7 +22,7 @@ import {
21
22
  pinIncludes
22
23
  } from './bitcoin/bitcoin-wallet-service'
23
24
  import { assertBitcoinNetwork } from '@meshconnect/uwc-bitcoin'
24
- import { parseError } from '../utils/error-utils'
25
+ import { isRequestAlreadyPending, parseError } from '../utils/error-utils'
25
26
  import {
26
27
  gatherFailure,
27
28
  type SecondaryGatherFailure
@@ -297,6 +298,25 @@ export interface ConnectionManagerOptions {
297
298
  */
298
299
  export const DEFAULT_SECONDARY_GATHER_TIMEOUT_MS = 15_000
299
300
 
301
+ /**
302
+ * A wallet request that may have a window open in the wallet (ONC-2390).
303
+ * `settled` never rejects.
304
+ */
305
+ interface OpenPrompt {
306
+ namespace: Namespace
307
+ settled: Promise<void>
308
+ }
309
+
310
+ /**
311
+ * One connect attempt, from its pre-connect check to its primary request
312
+ * (ONC-2390). A superseded attempt keeps running after a newer one starts
313
+ * (core only stops awaiting it), so it carries its generation and can tell
314
+ * when it is no longer live.
315
+ */
316
+ export interface ConnectAttempt {
317
+ readonly generation: number
318
+ }
319
+
300
320
  /**
301
321
  * What a per-namespace secondary gather actually did, as reported UP to
302
322
  * `gatherNamespace` for step telemetry.
@@ -337,6 +357,18 @@ export class ConnectionManager {
337
357
  | undefined
338
358
  private readonly steps: StepReporter
339
359
  private readonly secondaryGatherTimeoutMs: number
360
+ /**
361
+ * Bumped by every new connect attempt ({@link beginAttempt}) and by
362
+ * {@link disconnect}: an attempt whose generation no longer matches is no
363
+ * longer live.
364
+ */
365
+ private attemptGeneration = 0
366
+ /**
367
+ * Requests still pending in each wallet (keyed by its EIP-6963 uuid), from
368
+ * any attempt: while one is open, MetaMask refuses every other request with
369
+ * -32002 "already pending" (ONC-2390).
370
+ */
371
+ private readonly openPrompts = new Map<string, Set<OpenPrompt>>()
340
372
 
341
373
  constructor(
342
374
  private ethereumService: EthereumWalletService,
@@ -1044,35 +1076,60 @@ export class ConnectionManager {
1044
1076
  availableAddresses: AvailableAddress[],
1045
1077
  silentOnly = false
1046
1078
  ): Promise<void> {
1079
+ // A silent gather never opens a window, so it is not tracked.
1080
+ const promptKey = silentOnly
1081
+ ? undefined
1082
+ : provider.namespaceMetaData.eip155?.detectedWallet?.uuid
1047
1083
  if (connectedNamespace !== 'eip155') {
1048
- await this.gatherNamespace('eip155', () =>
1049
- this.checkAndAddEthereumAddresses(
1050
- provider,
1051
- availableAddresses,
1052
- silentOnly
1053
- )
1084
+ await this.gatherNamespace(
1085
+ 'eip155',
1086
+ () =>
1087
+ this.checkAndAddEthereumAddresses(
1088
+ provider,
1089
+ availableAddresses,
1090
+ silentOnly
1091
+ ),
1092
+ promptKey
1054
1093
  )
1055
1094
  }
1056
1095
  if (connectedNamespace !== 'solana') {
1057
- await this.gatherNamespace('solana', () =>
1058
- this.checkAndAddSolanaAddresses(
1059
- provider,
1060
- availableAddresses,
1061
- silentOnly
1062
- )
1096
+ await this.gatherNamespace(
1097
+ 'solana',
1098
+ () =>
1099
+ this.checkAndAddSolanaAddresses(
1100
+ provider,
1101
+ availableAddresses,
1102
+ silentOnly
1103
+ ),
1104
+ promptKey
1063
1105
  )
1064
1106
  }
1065
1107
  if (connectedNamespace !== 'tron') {
1066
- await this.gatherNamespace('tron', () =>
1067
- this.checkAndAddTronAddresses(provider, availableAddresses, silentOnly)
1108
+ await this.gatherNamespace(
1109
+ 'tron',
1110
+ () =>
1111
+ this.checkAndAddTronAddresses(
1112
+ provider,
1113
+ availableAddresses,
1114
+ silentOnly
1115
+ ),
1116
+ promptKey
1068
1117
  )
1069
1118
  }
1070
1119
  if (connectedNamespace !== 'tvm') {
1071
- await this.gatherNamespace('tvm', () =>
1072
- this.checkAndAddTonAddresses(provider, availableAddresses, silentOnly)
1120
+ await this.gatherNamespace(
1121
+ 'tvm',
1122
+ () =>
1123
+ this.checkAndAddTonAddresses(
1124
+ provider,
1125
+ availableAddresses,
1126
+ silentOnly
1127
+ ),
1128
+ promptKey
1073
1129
  )
1074
1130
  }
1075
1131
  if (connectedNamespace !== 'bip122') {
1132
+ // Passive only: it never opens a window, so it is not tracked.
1076
1133
  await this.gatherNamespace('bip122', () =>
1077
1134
  this.checkAndAddBitcoinAddresses(provider, availableAddresses)
1078
1135
  )
@@ -1094,22 +1151,29 @@ export class ConnectionManager {
1094
1151
  */
1095
1152
  private async gatherNamespace(
1096
1153
  namespace: Namespace,
1097
- gather: () => Promise<SecondaryGatherOutcome>
1154
+ gather: () => Promise<SecondaryGatherOutcome>,
1155
+ // The wallet to track the gather's request under while it is pending;
1156
+ // omitted for a gather that never opens a window.
1157
+ promptKey?: string
1098
1158
  ): Promise<void> {
1099
1159
  const timeoutMs = this.secondaryGatherTimeoutMs
1100
1160
  const start = Date.now()
1101
1161
  let timedOut = false
1102
1162
  try {
1103
- const outcome = await withDeadline(gather, timeoutMs, () => {
1104
- timedOut = true
1105
- this.steps.report({
1106
- step: 'secondaryGather',
1107
- outcome: 'timedOut',
1108
- durationMs: Date.now() - start,
1109
- namespace,
1110
- timeoutMs
1111
- })
1112
- })
1163
+ const outcome = await withDeadline(
1164
+ () => this.trackPrompt(promptKey, namespace, gather()),
1165
+ 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
+ )
1113
1177
  if (!timedOut) {
1114
1178
  this.steps.report({
1115
1179
  step: 'secondaryGather',
@@ -1206,12 +1270,107 @@ export class ConnectionManager {
1206
1270
  return addresses
1207
1271
  }
1208
1272
 
1273
+ /** Start a connect attempt; any earlier one stops being live. */
1274
+ beginAttempt(): ConnectAttempt {
1275
+ this.attemptGeneration++
1276
+ return { generation: this.attemptGeneration }
1277
+ }
1278
+
1279
+ /** Track `request` as open in the wallet until it settles; returns it. */
1280
+ private trackPrompt<T>(
1281
+ key: string | undefined,
1282
+ namespace: Namespace,
1283
+ request: Promise<T>
1284
+ ): Promise<T> {
1285
+ if (!key) return request
1286
+ const prompts = this.openPrompts.get(key) ?? new Set<OpenPrompt>()
1287
+ this.openPrompts.set(key, prompts)
1288
+ const prompt: OpenPrompt = {
1289
+ namespace,
1290
+ settled: request.then(
1291
+ () => undefined,
1292
+ () => undefined
1293
+ )
1294
+ }
1295
+ prompts.add(prompt)
1296
+ void prompt.settled.then(() => {
1297
+ prompts.delete(prompt)
1298
+ if (prompts.size === 0 && this.openPrompts.get(key) === prompts) {
1299
+ this.openPrompts.delete(key)
1300
+ }
1301
+ })
1302
+ return request
1303
+ }
1304
+
1305
+ /**
1306
+ * 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).
1314
+ */
1315
+ private async requestEthereumAccount(
1316
+ wallet: { uuid: string; provider: EthereumProvider },
1317
+ attempt: ConnectAttempt | undefined
1318
+ ): Promise<string> {
1319
+ const isLive = () =>
1320
+ attempt === undefined || attempt.generation === this.attemptGeneration
1321
+ // Disconnected or superseded before its primary request: sending it
1322
+ // would open a prompt nobody waits for, or one that refuses the newer
1323
+ // attempt's.
1324
+ if (!isLive()) {
1325
+ throw new DOMException(
1326
+ 'Superseded by a newer connection attempt',
1327
+ 'AbortError'
1328
+ )
1329
+ }
1330
+ const connect = () =>
1331
+ this.trackPrompt(
1332
+ wallet.uuid,
1333
+ 'eip155',
1334
+ this.ethereumService.connect(wallet.provider, wallet.uuid, info =>
1335
+ this.steps.report(info)
1336
+ )
1337
+ )
1338
+ // Taken when the request is sent: its refusal can arrive after the user
1339
+ // answered the window that caused it (a slow bridge).
1340
+ const open = [...(this.openPrompts.get(wallet.uuid) ?? [])]
1341
+ try {
1342
+ return await connect()
1343
+ } catch (error) {
1344
+ if (!attempt || open.length === 0 || !isRequestAlreadyPending(error)) {
1345
+ throw error
1346
+ }
1347
+ const start = Date.now()
1348
+ await Promise.all(open.map(prompt => prompt.settled))
1349
+ // Disconnected, or superseded by a newer attempt, while waiting: asking
1350
+ // now could open a prompt nobody is waiting for.
1351
+ const live = isLive()
1352
+ for (const { namespace } of open) {
1353
+ this.steps.report({
1354
+ step: 'awaitOpenPrompt',
1355
+ outcome: live ? 'ok' : 'skipped',
1356
+ durationMs: Date.now() - start,
1357
+ namespace
1358
+ })
1359
+ }
1360
+ if (!live) throw error
1361
+ return await connect()
1362
+ }
1363
+ }
1364
+
1209
1365
  /**
1210
1366
  * Connect to Ethereum wallet
1211
1367
  */
1212
1368
  async connectEthereum(
1213
1369
  network: Network,
1214
- provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider
1370
+ provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
1371
+ // The attempt whose pre-connect check ran before this; without one there
1372
+ // is no open window to wait for.
1373
+ attempt?: ConnectAttempt
1215
1374
  ): Promise<ConnectorResult> {
1216
1375
  try {
1217
1376
  // Provider detection is reported as its own step (ONC-183): both throws
@@ -1237,11 +1396,7 @@ export class ConnectionManager {
1237
1396
  }
1238
1397
  )
1239
1398
 
1240
- const address = await this.ethereumService.connect(
1241
- wallet.provider,
1242
- wallet.uuid,
1243
- info => this.steps.report(info)
1244
- )
1399
+ const address = await this.requestEthereumAccount(wallet, attempt)
1245
1400
  this.currentNetworkId = network.id
1246
1401
 
1247
1402
  const availableAddresses: AvailableAddress[] = []
@@ -1621,6 +1776,7 @@ export class ConnectionManager {
1621
1776
  * Disconnect all
1622
1777
  */
1623
1778
  async disconnect(): Promise<void> {
1779
+ this.attemptGeneration++
1624
1780
  this.ethereumService.disconnect()
1625
1781
  this.solanaService.disconnect()
1626
1782
  this.tronService.disconnect()
@@ -4,7 +4,8 @@ import { WalletConnectorError } from '@meshconnect/uwc-types'
4
4
  import {
5
5
  parseError,
6
6
  extractTonSdkErrorMessage,
7
- classifyWalletError
7
+ classifyWalletError,
8
+ isRequestAlreadyPending
8
9
  } from './error-utils'
9
10
 
10
11
  // Capture the thrown error explicitly — parseError is `never`, and a bare
@@ -250,3 +251,56 @@ describe('extractTonSdkErrorMessage', () => {
250
251
  expect(extractTonSdkErrorMessage(42)).toBe('')
251
252
  })
252
253
  })
254
+
255
+ describe('isRequestAlreadyPending', () => {
256
+ it.each([
257
+ [
258
+ 'MetaMask -32002',
259
+ {
260
+ code: -32002,
261
+ message:
262
+ "Request of type 'wallet_requestPermissions' already pending for origin https://link.example. Please wait."
263
+ }
264
+ ],
265
+ [
266
+ 'the message alone (embedded mode)',
267
+ new Error("Request of type 'wallet_requestPermissions' already pending")
268
+ ],
269
+ [
270
+ "Trust Wallet's text",
271
+ { message: 'PUBLIC_requestAccounts already pending' }
272
+ ]
273
+ ])('matches %s', (_, error) => {
274
+ expect(isRequestAlreadyPending(error)).toBe(true)
275
+ })
276
+
277
+ it.each([
278
+ ['a user rejection', { code: 4001, message: 'User rejected the request.' }],
279
+ ['a code in another form', { code: '-32002', message: 'Request failed' }],
280
+ // EIP-1474's -32002 is "resource unavailable": only MetaMask uses it for an
281
+ // open window. Phantom's in-app browser sends it for something else
282
+ // (CUS-173), which waiting would only turn into a hang.
283
+ [
284
+ "Phantom's -32002 resource error",
285
+ { code: -32002, message: 'Requested resource not available.' }
286
+ ],
287
+ ['-32002 with no message', { code: -32002 }],
288
+ ['a bare string', 'already pending'],
289
+ ['null', null],
290
+ ['undefined', undefined]
291
+ ])('does not match %s', (_, error) => {
292
+ expect(isRequestAlreadyPending(error)).toBe(false)
293
+ })
294
+
295
+ it('does not throw on an error whose fields cannot be read', () => {
296
+ const unreadable = new Proxy(
297
+ {},
298
+ {
299
+ get() {
300
+ throw new Error('denied')
301
+ }
302
+ }
303
+ )
304
+ expect(isRequestAlreadyPending(unreadable)).toBe(false)
305
+ })
306
+ })
@@ -159,3 +159,20 @@ export function classifyWalletError(error: unknown): WalletError {
159
159
 
160
160
  return walletError
161
161
  }
162
+
163
+ /**
164
+ * True when a wallet refused a request because an earlier one is still open
165
+ * in it: MetaMask's -32002 "Request of type '…' already pending", Trust
166
+ * Wallet's "PUBLIC_requestAccounts already pending". Matched on the message,
167
+ * which both send direct and embedded (the bridge keeps only the message):
168
+ * -32002 alone is EIP-1474's "resource unavailable", and Phantom's in-app
169
+ * browser sends it for an error no open window explains.
170
+ */
171
+ export function isRequestAlreadyPending(error: unknown): boolean {
172
+ try {
173
+ const { message } = (error ?? {}) as { message?: unknown }
174
+ return typeof message === 'string' && /already pending/i.test(message)
175
+ } catch {
176
+ return false
177
+ }
178
+ }