@meshconnect/uwc-injected-connector 0.21.0 → 0.22.1

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 (35) hide show
  1. package/dist/injected-connector.d.ts +18 -1
  2. package/dist/injected-connector.d.ts.map +1 -1
  3. package/dist/injected-connector.js +45 -4
  4. package/dist/injected-connector.js.map +1 -1
  5. package/dist/services/connection-manager.d.ts +67 -1
  6. package/dist/services/connection-manager.d.ts.map +1 -1
  7. package/dist/services/connection-manager.js +130 -18
  8. package/dist/services/connection-manager.js.map +1 -1
  9. package/dist/services/ethereum/ethereum-transaction-builder.d.ts.map +1 -1
  10. package/dist/services/ethereum/ethereum-transaction-builder.js +3 -2
  11. package/dist/services/ethereum/ethereum-transaction-builder.js.map +1 -1
  12. package/dist/services/ethereum/ethereum-wallet-service.d.ts +10 -3
  13. package/dist/services/ethereum/ethereum-wallet-service.d.ts.map +1 -1
  14. package/dist/services/ethereum/ethereum-wallet-service.js +15 -7
  15. package/dist/services/ethereum/ethereum-wallet-service.js.map +1 -1
  16. package/dist/utils/step-reporter.d.ts +33 -0
  17. package/dist/utils/step-reporter.d.ts.map +1 -0
  18. package/dist/utils/step-reporter.js +54 -0
  19. package/dist/utils/step-reporter.js.map +1 -0
  20. package/dist/utils/with-deadline.d.ts +30 -0
  21. package/dist/utils/with-deadline.d.ts.map +1 -0
  22. package/dist/utils/with-deadline.js +67 -0
  23. package/dist/utils/with-deadline.js.map +1 -0
  24. package/package.json +5 -5
  25. package/src/injected-connector.test.ts +97 -0
  26. package/src/injected-connector.ts +68 -5
  27. package/src/services/connection-manager.test.ts +234 -0
  28. package/src/services/connection-manager.ts +187 -28
  29. package/src/services/ethereum/ethereum-transaction-builder.test.ts +97 -0
  30. package/src/services/ethereum/ethereum-transaction-builder.ts +3 -2
  31. package/src/services/ethereum/ethereum-wallet-service.ts +28 -8
  32. package/src/utils/step-reporter.test.ts +56 -0
  33. package/src/utils/step-reporter.ts +83 -0
  34. package/src/utils/with-deadline.test.ts +80 -0
  35. package/src/utils/with-deadline.ts +67 -0
@@ -6,8 +6,11 @@ import type {
6
6
  ConnectorResult,
7
7
  SwitchNetworkResult,
8
8
  AvailableAddress,
9
- SolanaMetadata
9
+ SolanaMetadata,
10
+ WalletStepInfo
10
11
  } from '@meshconnect/uwc-types'
12
+ import { withDeadline } from '../utils/with-deadline'
13
+ import { createStepReporter, type StepReporter } from '../utils/step-reporter'
11
14
  import { EthereumWalletService } from './ethereum/ethereum-wallet-service'
12
15
  import { SolanaWalletService } from './solana/solana-wallet-service'
13
16
  import { TronWalletService } from './tron/tron-wallet-service'
@@ -223,8 +226,53 @@ export interface ConnectionManagerOptions {
223
226
  onWalletConnectionsReleased?:
224
227
  | ((info: { namespaces: Namespace[] }) => void)
225
228
  | undefined
229
+ /**
230
+ * Step-level telemetry sink (ONC-183) — see {@link WalletStepInfo}. Invoked
231
+ * once per named phase of a connect. Unlike the dedup'd sinks above this
232
+ * fires EVERY time: the point is per-attempt timing, so suppressing repeats
233
+ * would erase exactly the signal (a retry that hangs where the first didn't).
234
+ */
235
+ onConnectStep?: ((info: WalletStepInfo) => void) | undefined
236
+ /**
237
+ * Per-namespace deadline (ms) for a best-effort SECONDARY address gather —
238
+ * see {@link ConnectionManager.checkAndAddOtherNamespaceAddresses}. `0`
239
+ * disables the bound (pre-ONC-183 behaviour).
240
+ */
241
+ secondaryGatherTimeoutMs?: number | undefined
226
242
  }
227
243
 
244
+ /**
245
+ * Default per-namespace cap for a secondary address gather (ONC-183).
246
+ *
247
+ * These run AFTER the user has already authorized the target namespace, and a
248
+ * wallet that never answers one of them used to hold the entire connect open
249
+ * indefinitely — the dominant "connected but hung" class (MetaMask's Solana
250
+ * Snap prompt being the motivating case: EVM approved, Snap prompt abandoned,
251
+ * `connect()` pending forever).
252
+ *
253
+ * 15s is deliberately generous relative to the ~19s MEDIAN for a whole connect:
254
+ * this bounds one supplementary leg, not the user-facing approval, and the cost
255
+ * of firing early is a missing secondary address (the session still connects on
256
+ * the namespace the user asked for) while the cost of firing late is nil. Tune
257
+ * from the `walletStep` p99 once it has run in prod.
258
+ */
259
+ export const DEFAULT_SECONDARY_GATHER_TIMEOUT_MS = 15_000
260
+
261
+ /**
262
+ * What a per-namespace secondary gather actually did, as reported UP to
263
+ * `gatherNamespace` for step telemetry.
264
+ *
265
+ * Necessary because each `checkAndAdd*Addresses` helper CATCHES its own wallet
266
+ * errors internally — that is the best-effort contract and it predates this
267
+ * telemetry. So the helper resolving normally does NOT mean the gather worked:
268
+ * a declined Solana Snap prompt is swallowed and resolves exactly like a clean
269
+ * no-op. Reporting `ok` off "the promise resolved" therefore mislabelled every
270
+ * user-declined secondary prompt as a success (ONC-183 review). The helpers
271
+ * return this instead so a swallowed failure is still reported as one, while
272
+ * the swallow keeps the connect alive.
273
+ */
274
+ export type SecondaryGatherOutcome = 'ok' | 'failed'
275
+
228
276
  export class ConnectionManager {
229
277
  private currentNetworkId: string | null = null
230
278
 
@@ -248,6 +296,8 @@ export class ConnectionManager {
248
296
  private readonly onWalletConnectionsReleased?:
249
297
  | ((info: { namespaces: Namespace[] }) => void)
250
298
  | undefined
299
+ private readonly steps: StepReporter
300
+ private readonly secondaryGatherTimeoutMs: number
251
301
 
252
302
  constructor(
253
303
  private ethereumService: EthereumWalletService,
@@ -262,6 +312,9 @@ export class ConnectionManager {
262
312
  this.onSecondarySolanaConnectGathered =
263
313
  options.onSecondarySolanaConnectGathered
264
314
  this.onWalletConnectionsReleased = options.onWalletConnectionsReleased
315
+ this.steps = createStepReporter(options.onConnectStep)
316
+ this.secondaryGatherTimeoutMs =
317
+ options.secondaryGatherTimeoutMs ?? DEFAULT_SECONDARY_GATHER_TIMEOUT_MS
265
318
  }
266
319
 
267
320
  /** Report a gathered legacy-injectedId Solana address, once per injectedId x source. */
@@ -418,8 +471,11 @@ export class ConnectionManager {
418
471
  if (walletUuid) {
419
472
  const wallet = this.ethereumService.findWalletByUuid(walletUuid)
420
473
  if (wallet?.provider) {
421
- const accounts = await this.ethereumService.checkExistingConnection(
422
- wallet.provider
474
+ const accounts = await this.steps.track(
475
+ 'existingConnectionCheck',
476
+ 'eip155',
477
+ () =>
478
+ this.ethereumService.checkExistingConnection(wallet.provider)
423
479
  )
424
480
  if (accounts && accounts.length > 0) {
425
481
  currentAddress = accounts[0] || null
@@ -562,7 +618,10 @@ export class ConnectionManager {
562
618
  private async checkAndAddEthereumAddresses(
563
619
  provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
564
620
  availableAddresses: AvailableAddress[]
565
- ): Promise<void> {
621
+ ): Promise<SecondaryGatherOutcome> {
622
+ // Default 'ok'; the internal catch below flips it so a swallowed wallet
623
+ // error is still REPORTED as a failure (see SecondaryGatherOutcome).
624
+ let outcome: SecondaryGatherOutcome = 'ok'
566
625
  let ethAccount = this.ethereumService.getAccount()
567
626
 
568
627
  // If not connected, try to check existing connection
@@ -597,7 +656,9 @@ export class ConnectionManager {
597
656
  }
598
657
  } catch {
599
658
  // EVM unavailable or the user declined the connect prompt —
600
- // continue without it (same as the Solana/Tron/TON gathers).
659
+ // continue without it (same as the Solana/Tron/TON gathers), but
660
+ // record it so the step telemetry doesn't report this as 'ok'.
661
+ outcome = 'failed'
601
662
  }
602
663
  }
603
664
  }
@@ -611,6 +672,7 @@ export class ConnectionManager {
611
672
  )
612
673
  availableAddresses.push(...ethAddresses)
613
674
  }
675
+ return outcome
614
676
  }
615
677
 
616
678
  /**
@@ -619,7 +681,10 @@ export class ConnectionManager {
619
681
  private async checkAndAddSolanaAddresses(
620
682
  provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
621
683
  availableAddresses: AvailableAddress[]
622
- ): Promise<void> {
684
+ ): Promise<SecondaryGatherOutcome> {
685
+ // Default 'ok'; the internal catch below flips it so a swallowed wallet
686
+ // error is still REPORTED as a failure (see SecondaryGatherOutcome).
687
+ let outcome: SecondaryGatherOutcome = 'ok'
623
688
  let solanaAccount = this.solanaService.getAccount()
624
689
 
625
690
  // If not connected, try to check existing connection
@@ -686,7 +751,10 @@ export class ConnectionManager {
686
751
  )
687
752
  }
688
753
  } catch {
689
- // Solana namespace not available — continue without it
754
+ // Solana namespace not available (or the user declined the Snap
755
+ // prompt) — continue without it, but record the failure so the
756
+ // step telemetry doesn't report this as 'ok'.
757
+ outcome = 'failed'
690
758
  }
691
759
  }
692
760
  }
@@ -700,6 +768,7 @@ export class ConnectionManager {
700
768
  )
701
769
  availableAddresses.push(...solanaAddresses)
702
770
  }
771
+ return outcome
703
772
  }
704
773
 
705
774
  /**
@@ -708,7 +777,10 @@ export class ConnectionManager {
708
777
  private async checkAndAddTronAddresses(
709
778
  provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
710
779
  availableAddresses: AvailableAddress[]
711
- ): Promise<void> {
780
+ ): Promise<SecondaryGatherOutcome> {
781
+ // Default 'ok'; the internal catch below flips it so a swallowed wallet
782
+ // error is still REPORTED as a failure (see SecondaryGatherOutcome).
783
+ let outcome: SecondaryGatherOutcome = 'ok'
712
784
  let tronAccount = this.tronService.getAccount()
713
785
 
714
786
  // If not connected, try to check existing connection
@@ -731,7 +803,9 @@ export class ConnectionManager {
731
803
  this.tronService.setConnectionState(tronWallet.provider, address)
732
804
  }
733
805
  } catch {
734
- // Tron namespace not available — continue without it
806
+ // Tron namespace not available — continue without it, but record
807
+ // the failure so the step telemetry doesn't report this as 'ok'.
808
+ outcome = 'failed'
735
809
  }
736
810
  }
737
811
  }
@@ -745,6 +819,7 @@ export class ConnectionManager {
745
819
  )
746
820
  availableAddresses.push(...tronAddresses)
747
821
  }
822
+ return outcome
748
823
  }
749
824
 
750
825
  /**
@@ -755,7 +830,10 @@ export class ConnectionManager {
755
830
  private async checkAndAddTonAddresses(
756
831
  provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider,
757
832
  availableAddresses: AvailableAddress[]
758
- ): Promise<void> {
833
+ ): Promise<SecondaryGatherOutcome> {
834
+ // Default 'ok'; the internal catch below flips it so a swallowed wallet
835
+ // error is still REPORTED as a failure (see SecondaryGatherOutcome).
836
+ let outcome: SecondaryGatherOutcome = 'ok'
759
837
  let tonAccount = this.tonService.getAccount()
760
838
 
761
839
  if (!tonAccount) {
@@ -770,7 +848,9 @@ export class ConnectionManager {
770
848
  const result = await this.tonService.connect(jsBridgeKey)
771
849
  tonAccount = result.address
772
850
  } catch {
773
- // TON connection failed or was rejected — continue without TON
851
+ // TON connection failed or was rejected — continue without TON, but
852
+ // record the failure so the step telemetry doesn't report it as 'ok'.
853
+ outcome = 'failed'
774
854
  }
775
855
  }
776
856
  }
@@ -782,11 +862,19 @@ export class ConnectionManager {
782
862
  )
783
863
  availableAddresses.push(...tonAddresses)
784
864
  }
865
+ return outcome
785
866
  }
786
867
 
787
868
  /**
788
869
  * After connecting one namespace, check and add addresses for all OTHER namespaces.
789
870
  * E.g. after connecting Ethereum, also gather Solana, Tron, and TON addresses.
871
+ *
872
+ * Every leg is BEST-EFFORT and individually deadline-bounded (ONC-183). These
873
+ * run after the user has already authorized the target namespace, so a leg
874
+ * that never answers must cost its own address — not the whole connect. Each
875
+ * leg gets its OWN budget rather than one shared across all four: a shared
876
+ * budget would let a slow first leg silently starve the rest, turning one
877
+ * wallet's slowness into three missing addresses.
790
878
  */
791
879
  private async checkAndAddOtherNamespaceAddresses(
792
880
  connectedNamespace: 'eip155' | 'solana' | 'tron' | 'tvm',
@@ -794,16 +882,76 @@ export class ConnectionManager {
794
882
  availableAddresses: AvailableAddress[]
795
883
  ): Promise<void> {
796
884
  if (connectedNamespace !== 'eip155') {
797
- await this.checkAndAddEthereumAddresses(provider, availableAddresses)
885
+ await this.gatherNamespace('eip155', () =>
886
+ this.checkAndAddEthereumAddresses(provider, availableAddresses)
887
+ )
798
888
  }
799
889
  if (connectedNamespace !== 'solana') {
800
- await this.checkAndAddSolanaAddresses(provider, availableAddresses)
890
+ await this.gatherNamespace('solana', () =>
891
+ this.checkAndAddSolanaAddresses(provider, availableAddresses)
892
+ )
801
893
  }
802
894
  if (connectedNamespace !== 'tron') {
803
- await this.checkAndAddTronAddresses(provider, availableAddresses)
895
+ await this.gatherNamespace('tron', () =>
896
+ this.checkAndAddTronAddresses(provider, availableAddresses)
897
+ )
804
898
  }
805
899
  if (connectedNamespace !== 'tvm') {
806
- await this.checkAndAddTonAddresses(provider, availableAddresses)
900
+ await this.gatherNamespace('tvm', () =>
901
+ this.checkAndAddTonAddresses(provider, availableAddresses)
902
+ )
903
+ }
904
+ }
905
+
906
+ /**
907
+ * Run one secondary-namespace gather under its deadline, reporting the
908
+ * outcome as a `secondaryGather` step.
909
+ *
910
+ * Swallows a rejection as well as a timeout: the per-namespace helpers below
911
+ * already catch their own wallet errors, so anything reaching here is an
912
+ * unexpected throw — and dropping one namespace's address is still the right
913
+ * degradation for a gather the user never asked for.
914
+ *
915
+ * The reported outcome comes from the helper's own
916
+ * {@link SecondaryGatherOutcome}, NOT from "did the promise resolve" — see
917
+ * that type for why those two are not the same thing.
918
+ */
919
+ private async gatherNamespace(
920
+ namespace: Namespace,
921
+ gather: () => Promise<SecondaryGatherOutcome>
922
+ ): Promise<void> {
923
+ const timeoutMs = this.secondaryGatherTimeoutMs
924
+ const start = Date.now()
925
+ let timedOut = false
926
+ try {
927
+ const outcome = await withDeadline(gather, timeoutMs, () => {
928
+ timedOut = true
929
+ this.steps.report({
930
+ step: 'secondaryGather',
931
+ outcome: 'timedOut',
932
+ durationMs: Date.now() - start,
933
+ namespace,
934
+ timeoutMs
935
+ })
936
+ })
937
+ if (!timedOut) {
938
+ this.steps.report({
939
+ step: 'secondaryGather',
940
+ // `withDeadline` resolves undefined only on the timeout path, which
941
+ // the `!timedOut` guard already excludes; treat a missing outcome as
942
+ // a failure rather than silently reporting success.
943
+ outcome: outcome ?? 'failed',
944
+ durationMs: Date.now() - start,
945
+ namespace
946
+ })
947
+ }
948
+ } catch {
949
+ this.steps.report({
950
+ step: 'secondaryGather',
951
+ outcome: 'failed',
952
+ durationMs: Date.now() - start,
953
+ namespace
954
+ })
807
955
  }
808
956
  }
809
957
 
@@ -874,22 +1022,33 @@ export class ConnectionManager {
874
1022
  provider: ExtensionInjectedProvider | IntegratedBrowserInjectedProvider
875
1023
  ): Promise<ConnectorResult> {
876
1024
  try {
877
- const walletUuid =
878
- provider.namespaceMetaData?.eip155?.detectedWallet?.uuid
879
- if (!walletUuid) {
880
- throw new Error(
881
- `${provider.namespaceMetaData.eip155?.eip155Name || provider.namespaceMetaData.eip155?.injectedId} wallet eip155 provider was not detected`
882
- )
883
- }
884
-
885
- const wallet = this.ethereumService.findWalletByUuid(walletUuid)
886
- if (!wallet || !wallet.provider) {
887
- throw new Error(`Wallet provider not found for UUID: ${walletUuid}`)
888
- }
1025
+ // Provider detection is reported as its own step (ONC-183): both throws
1026
+ // below are "the wallet was never found", a failure class that is
1027
+ // indistinguishable from "the wallet never answered" once it collapses
1028
+ // into a single `walletFailed` terminal — and unlike a wallet hang it is
1029
+ // retryable without re-prompting the user.
1030
+ const wallet = await this.steps.track(
1031
+ 'providerDetection',
1032
+ 'eip155',
1033
+ () => {
1034
+ const uuid = provider.namespaceMetaData?.eip155?.detectedWallet?.uuid
1035
+ if (!uuid) {
1036
+ throw new Error(
1037
+ `${provider.namespaceMetaData.eip155?.eip155Name || provider.namespaceMetaData.eip155?.injectedId} wallet eip155 provider was not detected`
1038
+ )
1039
+ }
1040
+ const detected = this.ethereumService.findWalletByUuid(uuid)
1041
+ if (!detected || !detected.provider) {
1042
+ throw new Error(`Wallet provider not found for UUID: ${uuid}`)
1043
+ }
1044
+ return Promise.resolve({ uuid, provider: detected.provider })
1045
+ }
1046
+ )
889
1047
 
890
1048
  const address = await this.ethereumService.connect(
891
1049
  wallet.provider,
892
- walletUuid
1050
+ wallet.uuid,
1051
+ info => this.steps.report(info)
893
1052
  )
894
1053
  this.currentNetworkId = network.id
895
1054
 
@@ -249,4 +249,101 @@ describe('EthereumTransactionBuilder', () => {
249
249
  expect(result.maxPriorityFeePerGas).toBe(BigInt(2000000000))
250
250
  })
251
251
  })
252
+
253
+ describe('value normalization', () => {
254
+ const oneEth = 1000000000000000000n
255
+ const from = '0x1234567890123456789012345678901234567890'
256
+ const to = '0x0987654321098765432109876543210987654321'
257
+ const cases: [string, bigint | string][] = [
258
+ ['bigint', oneEth],
259
+ ['decimal string', '1000000000000000000'],
260
+ ['hex string', '0xde0b6b3a7640000']
261
+ ]
262
+
263
+ it.each(cases)(
264
+ 'contract-call value as %s normalizes to bigint',
265
+ async (_l, value) => {
266
+ const result = await builder.getContractTransaction({
267
+ from,
268
+ contractAddress: to,
269
+ abi: [
270
+ {
271
+ inputs: [],
272
+ name: 'deposit',
273
+ outputs: [],
274
+ stateMutability: 'payable',
275
+ type: 'function'
276
+ }
277
+ ],
278
+ functionName: 'deposit',
279
+ args: [],
280
+ value
281
+ })
282
+ expect(result.value).toBe(oneEth)
283
+ }
284
+ )
285
+
286
+ it.each(cases)(
287
+ 'data-transfer value as %s normalizes to bigint',
288
+ async (_l, value) => {
289
+ const result = await builder.getDataTransaction({
290
+ from,
291
+ to,
292
+ data: '0x',
293
+ chainId: '1',
294
+ value
295
+ })
296
+ expect(result.value).toBe(oneEth)
297
+ }
298
+ )
299
+
300
+ it('defaults a missing value to 0n', async () => {
301
+ const result = await builder.getDataTransaction({
302
+ from,
303
+ to,
304
+ data: '0x',
305
+ chainId: '1'
306
+ })
307
+ expect(result.value).toBe(0n)
308
+ })
309
+
310
+ it.each(['', ' ', 'abc', '1.5', '0x'])(
311
+ 'rejects an invalid data-transfer value %j instead of coercing to 0',
312
+ async value => {
313
+ await expect(
314
+ builder.getDataTransaction({
315
+ from,
316
+ to,
317
+ data: '0x',
318
+ chainId: '1',
319
+ value
320
+ })
321
+ ).rejects.toThrow(/Invalid EVM value/)
322
+ }
323
+ )
324
+
325
+ it.each(['', ' ', 'abc', '1.5', '0x'])(
326
+ 'rejects an invalid contract-call value %j instead of coercing to 0',
327
+ async value => {
328
+ await expect(
329
+ builder.getContractTransaction({
330
+ from,
331
+ contractAddress: to,
332
+ abi: [
333
+ {
334
+ inputs: [],
335
+ name: 'deposit',
336
+ outputs: [],
337
+ stateMutability: 'payable',
338
+ type: 'function'
339
+ }
340
+ ],
341
+ functionName: 'deposit',
342
+ args: [],
343
+ value
344
+ })
345
+ ).rejects.toThrow(/Invalid EVM value/)
346
+ }
347
+ )
348
+ })
252
349
  })
@@ -6,6 +6,7 @@ import type {
6
6
  EVMTransactionParams,
7
7
  EVMDataTransferRequest
8
8
  } from '@meshconnect/uwc-types'
9
+ import { toEvmValueBigInt } from '@meshconnect/uwc-types'
9
10
  import { parseError } from '../../utils/error-utils'
10
11
 
11
12
  /**
@@ -25,7 +26,7 @@ export class EthereumTransactionBuilder {
25
26
  const txRequest: EVMTransactionParams = {
26
27
  to: request.contractAddress,
27
28
  data,
28
- value: request.value ?? 0n,
29
+ value: toEvmValueBigInt(request.value),
29
30
  ...this.formatGasConfig(request.gasConfig)
30
31
  }
31
32
  return txRequest
@@ -55,7 +56,7 @@ export class EthereumTransactionBuilder {
55
56
  const txRequest: EVMTransactionParams = {
56
57
  to: request.to,
57
58
  data: request.data,
58
- value: request.value ?? 0n,
59
+ value: toEvmValueBigInt(request.value),
59
60
  ...this.formatGasConfig(request.gasConfig)
60
61
  }
61
62
 
@@ -5,7 +5,9 @@ import type {
5
5
  EVMCapabilityStatus,
6
6
  Network,
7
7
  WalletMetadata,
8
- WalletLifecycleEvent
8
+ WalletLifecycleEvent,
9
+ WalletStepInfo,
10
+ WalletStepName
9
11
  } from '@meshconnect/uwc-types'
10
12
  import type {
11
13
  EthereumProvider,
@@ -14,6 +16,7 @@ import type {
14
16
  } from '../../eip6963-discovery'
15
17
  import { getAvailableWallets as getEIP6963Wallets } from '../../eip6963-discovery'
16
18
  import { supportedNetworks } from '@meshconnect/uwc-constants'
19
+ import { createStepReporter } from '../../utils/step-reporter'
17
20
 
18
21
  /**
19
22
  * Normalize an EIP-1193 `chainChanged` payload (hex `'0x1'`, decimal string, or a
@@ -101,11 +104,28 @@ export class EthereumWalletService {
101
104
 
102
105
  /**
103
106
  * Connect to wallet
107
+ *
108
+ * `onStep` (optional) reports the two wallet round-trips separately (ONC-183)
109
+ * — `eth_requestAccounts` is the user-facing approval, `eth_chainId` is a
110
+ * follow-on read against an already-granted permission, and they fail for
111
+ * different reasons (an abandoned prompt vs. a provider that granted accounts
112
+ * then went unresponsive, the bridge-mode case). Rolled together they were
113
+ * one opaque duration.
104
114
  */
105
- async connect(provider: EthereumProvider, uuid?: string): Promise<string> {
106
- const accounts = await provider.request({
107
- method: 'eth_requestAccounts'
108
- })
115
+ async connect(
116
+ provider: EthereumProvider,
117
+ uuid?: string,
118
+ onStep?: (info: WalletStepInfo) => void
119
+ ): Promise<string> {
120
+ // Shared reporter (ONC-183 review) rather than a fourth hand-rolled copy of
121
+ // the time-and-report shape — see `createStepReporter`.
122
+ const steps = createStepReporter(onStep)
123
+ const track = <T>(step: WalletStepName, request: () => Promise<T>) =>
124
+ steps.track(step, 'eip155', request)
125
+
126
+ const accounts = await track('primaryConnect', () =>
127
+ provider.request({ method: 'eth_requestAccounts' })
128
+ )
109
129
 
110
130
  if (!accounts || accounts.length === 0) {
111
131
  throw new Error('No accounts returned from wallet')
@@ -118,9 +138,9 @@ export class EthereumWalletService {
118
138
  this.account = address
119
139
 
120
140
  // Request chain ID to ensure we're connected
121
- await provider.request({
122
- method: 'eth_chainId'
123
- })
141
+ await track('chainIdRead', () =>
142
+ provider.request({ method: 'eth_chainId' })
143
+ )
124
144
 
125
145
  return address
126
146
  }
@@ -0,0 +1,56 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { createStepReporter } from './step-reporter'
3
+
4
+ describe('createStepReporter', () => {
5
+ it('reports ok with a duration on success and returns the value', async () => {
6
+ const sink = vi.fn()
7
+ const r = createStepReporter(sink)
8
+ await expect(
9
+ r.track('primaryConnect', 'eip155', async () => 'v')
10
+ ).resolves.toBe('v')
11
+ expect(sink).toHaveBeenCalledWith(
12
+ expect.objectContaining({
13
+ step: 'primaryConnect',
14
+ outcome: 'ok',
15
+ namespace: 'eip155'
16
+ })
17
+ )
18
+ expect(typeof sink.mock.calls[0]![0].durationMs).toBe('number')
19
+ })
20
+
21
+ it('reports failed AND rethrows — a failed step’s duration is the point', async () => {
22
+ const sink = vi.fn()
23
+ const r = createStepReporter(sink)
24
+ await expect(
25
+ r.track('providerDetection', 'eip155', async () => {
26
+ throw new Error('nope')
27
+ })
28
+ ).rejects.toThrow('nope')
29
+ expect(sink).toHaveBeenCalledWith(
30
+ expect.objectContaining({ step: 'providerDetection', outcome: 'failed' })
31
+ )
32
+ })
33
+
34
+ it('never lets a throwing sink break the operation', async () => {
35
+ const r = createStepReporter(() => {
36
+ throw new Error('sink exploded')
37
+ })
38
+ await expect(
39
+ r.track('chainIdRead', 'eip155', async () => 'ok')
40
+ ).resolves.toBe('ok')
41
+ expect(() =>
42
+ r.report({ step: 'chainIdRead', outcome: 'ok', durationMs: 1 })
43
+ ).not.toThrow()
44
+ })
45
+
46
+ it('degrades to a plain call with no sink wired', async () => {
47
+ const r = createStepReporter(undefined)
48
+ expect(r.enabled).toBe(false)
49
+ await expect(r.track('chainIdRead', 'eip155', async () => 7)).resolves.toBe(
50
+ 7
51
+ )
52
+ expect(() =>
53
+ r.report({ step: 'chainIdRead', outcome: 'ok', durationMs: 1 })
54
+ ).not.toThrow()
55
+ })
56
+ })
@@ -0,0 +1,83 @@
1
+ import type {
2
+ Namespace,
3
+ WalletStepInfo,
4
+ WalletStepName
5
+ } from '@meshconnect/uwc-types'
6
+
7
+ /** Sink for step records; supplied by the consumer via `onConnectStep`. */
8
+ export type StepSink = (info: WalletStepInfo) => void
9
+
10
+ export interface StepReporter {
11
+ /**
12
+ * Emit a step record. Never throws — a consumer's telemetry sink must not be
13
+ * able to fail a wallet operation.
14
+ */
15
+ report(info: WalletStepInfo): void
16
+ /**
17
+ * Time `operation` and report it as `step`. Reports on BOTH paths, because a
18
+ * failed step's duration is exactly what triage needs; the operation's own
19
+ * error propagates unchanged.
20
+ */
21
+ track<T>(
22
+ step: WalletStepName,
23
+ namespace: Namespace | undefined,
24
+ operation: () => Promise<T>
25
+ ): Promise<T>
26
+ /** Whether a sink is actually wired — lets callers skip building payloads. */
27
+ readonly enabled: boolean
28
+ }
29
+
30
+ /**
31
+ * One time-and-report implementation for every step emit site (ONC-183 review).
32
+ *
33
+ * Previously `ConnectionManager.trackStep`, the inline block in
34
+ * `InjectedConnector.enrichWithTron`, and the local `track` in
35
+ * `EthereumWalletService.connect` were three hand-rolled copies of the same
36
+ * shape, plus a `reportStep` duplicated across two classes — and the Tron copy
37
+ * was the only one with no test. Collapsing them means the swallow-the-sink and
38
+ * report-on-both-paths guarantees are asserted once and hold everywhere.
39
+ *
40
+ * `sink` may be undefined (no consumer observer): `track` then degrades to a
41
+ * plain call with no timing overhead, and `report` is a no-op.
42
+ */
43
+ export function createStepReporter(sink: StepSink | undefined): StepReporter {
44
+ const report = (info: WalletStepInfo): void => {
45
+ if (!sink) return
46
+ try {
47
+ sink(info)
48
+ } catch {
49
+ // A telemetry sink must never break a wallet operation.
50
+ }
51
+ }
52
+
53
+ return {
54
+ enabled: !!sink,
55
+ report,
56
+ async track<T>(
57
+ step: WalletStepName,
58
+ namespace: Namespace | undefined,
59
+ operation: () => Promise<T>
60
+ ): Promise<T> {
61
+ if (!sink) return await operation()
62
+ const start = Date.now()
63
+ try {
64
+ const result = await operation()
65
+ report({
66
+ step,
67
+ outcome: 'ok',
68
+ durationMs: Date.now() - start,
69
+ namespace
70
+ })
71
+ return result
72
+ } catch (error) {
73
+ report({
74
+ step,
75
+ outcome: 'failed',
76
+ durationMs: Date.now() - start,
77
+ namespace
78
+ })
79
+ throw error
80
+ }
81
+ }
82
+ }
83
+ }