@meshconnect/uwc-injected-connector 0.20.3 → 0.22.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 (62) hide show
  1. package/dist/eip6963-discovery.d.ts +13 -0
  2. package/dist/eip6963-discovery.d.ts.map +1 -1
  3. package/dist/eip6963-discovery.js +12 -3
  4. package/dist/eip6963-discovery.js.map +1 -1
  5. package/dist/injected-connector.d.ts +39 -2
  6. package/dist/injected-connector.d.ts.map +1 -1
  7. package/dist/injected-connector.js +170 -19
  8. package/dist/injected-connector.js.map +1 -1
  9. package/dist/services/connection-manager.d.ts +84 -5
  10. package/dist/services/connection-manager.d.ts.map +1 -1
  11. package/dist/services/connection-manager.js +172 -30
  12. package/dist/services/connection-manager.js.map +1 -1
  13. package/dist/services/ethereum/ethereum-transaction-builder.d.ts.map +1 -1
  14. package/dist/services/ethereum/ethereum-transaction-builder.js +3 -2
  15. package/dist/services/ethereum/ethereum-transaction-builder.js.map +1 -1
  16. package/dist/services/ethereum/ethereum-wallet-service.d.ts +86 -7
  17. package/dist/services/ethereum/ethereum-wallet-service.d.ts.map +1 -1
  18. package/dist/services/ethereum/ethereum-wallet-service.js +201 -28
  19. package/dist/services/ethereum/ethereum-wallet-service.js.map +1 -1
  20. package/dist/services/solana/solana-wallet-service.d.ts +57 -0
  21. package/dist/services/solana/solana-wallet-service.d.ts.map +1 -1
  22. package/dist/services/solana/solana-wallet-service.js +118 -0
  23. package/dist/services/solana/solana-wallet-service.js.map +1 -1
  24. package/dist/services/ton/ton-wallet-service.d.ts +9 -0
  25. package/dist/services/ton/ton-wallet-service.d.ts.map +1 -1
  26. package/dist/services/ton/ton-wallet-service.js +15 -0
  27. package/dist/services/ton/ton-wallet-service.js.map +1 -1
  28. package/dist/services/tron/tron-wallet-service.d.ts +11 -0
  29. package/dist/services/tron/tron-wallet-service.d.ts.map +1 -1
  30. package/dist/services/tron/tron-wallet-service.js +21 -0
  31. package/dist/services/tron/tron-wallet-service.js.map +1 -1
  32. package/dist/utils/step-reporter.d.ts +33 -0
  33. package/dist/utils/step-reporter.d.ts.map +1 -0
  34. package/dist/utils/step-reporter.js +54 -0
  35. package/dist/utils/step-reporter.js.map +1 -0
  36. package/dist/utils/with-deadline.d.ts +30 -0
  37. package/dist/utils/with-deadline.d.ts.map +1 -0
  38. package/dist/utils/with-deadline.js +67 -0
  39. package/dist/utils/with-deadline.js.map +1 -0
  40. package/package.json +6 -6
  41. package/src/eip6963-discovery.test.ts +111 -2
  42. package/src/eip6963-discovery.ts +28 -4
  43. package/src/injected-connector.test.ts +574 -16
  44. package/src/injected-connector.ts +210 -23
  45. package/src/services/connection-manager.test.ts +338 -1
  46. package/src/services/connection-manager.ts +236 -41
  47. package/src/services/ethereum/ethereum-transaction-builder.test.ts +97 -0
  48. package/src/services/ethereum/ethereum-transaction-builder.ts +3 -2
  49. package/src/services/ethereum/ethereum-wallet-service.test.ts +495 -17
  50. package/src/services/ethereum/ethereum-wallet-service.ts +248 -32
  51. package/src/services/solana/solana-wallet-service.lifecycle.test.ts +156 -6
  52. package/src/services/solana/solana-wallet-service.reconnect.test.ts +175 -0
  53. package/src/services/solana/solana-wallet-service.ts +132 -0
  54. package/src/services/ton/ton-wallet-service.test.ts +25 -0
  55. package/src/services/ton/ton-wallet-service.ts +15 -0
  56. package/src/services/tron/tron-wallet-service.test.ts +45 -0
  57. package/src/services/tron/tron-wallet-service.ts +20 -0
  58. package/src/signSolanaTransactionBytes.test.ts +1 -1
  59. package/src/utils/step-reporter.test.ts +56 -0
  60. package/src/utils/step-reporter.ts +83 -0
  61. package/src/utils/with-deadline.test.ts +80 -0
  62. package/src/utils/with-deadline.ts +67 -0
@@ -0,0 +1,175 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { SolanaWalletService } from './solana-wallet-service'
3
+ import { StorageService } from '../storage-service'
4
+ import type { WalletStandardInfo } from '../../wallet-standard-discovery'
5
+
6
+ function serviceWithPrivateState(overrides: {
7
+ connectedAdapter?: unknown
8
+ connectedWalletUuid?: string | null
9
+ }) {
10
+ const service = new SolanaWalletService(new StorageService())
11
+ const priv = service as unknown as {
12
+ connectedAdapter: unknown
13
+ connectedWalletUuid: string | null
14
+ }
15
+ if ('connectedAdapter' in overrides) {
16
+ priv.connectedAdapter = overrides.connectedAdapter
17
+ }
18
+ if ('connectedWalletUuid' in overrides) {
19
+ priv.connectedWalletUuid = overrides.connectedWalletUuid ?? null
20
+ }
21
+ return service
22
+ }
23
+
24
+ describe('SolanaWalletService.ensureConnectedAdapter', () => {
25
+ it('returns true (NOT the adapter) without touching discovery when already connected (happy path, no-op)', async () => {
26
+ // Regression guard: ensureConnectedAdapter must return a BOOLEAN, never the
27
+ // adapter — in bridge mode the adapter is a Comlink proxy, and `await`ing it
28
+ // forces Comlink to clone the (unserializable) adapter. Callers read it
29
+ // synchronously via getConnectedAdapter() instead.
30
+ const adapter = { publicKey: { toBase58: async () => 'addr' } }
31
+ const service = serviceWithPrivateState({
32
+ connectedAdapter: adapter,
33
+ connectedWalletUuid: 'uuid-1'
34
+ })
35
+ const discoverySpy = vi.spyOn(service, 'initializeDiscovery')
36
+
37
+ const result = await service.ensureConnectedAdapter()
38
+
39
+ expect(result).toBe(true)
40
+ expect(service.getConnectedAdapter()).toBe(adapter)
41
+ expect(discoverySpy).not.toHaveBeenCalled()
42
+ })
43
+
44
+ it('returns false when there is no connected adapter and no remembered wallet uuid', async () => {
45
+ const service = serviceWithPrivateState({
46
+ connectedAdapter: null,
47
+ connectedWalletUuid: null
48
+ })
49
+
50
+ expect(await service.ensureConnectedAdapter()).toBe(false)
51
+ })
52
+
53
+ it('rebuilds via discovery + findWalletByUuid + checkExistingConnection when the adapter was cleared but the wallet uuid is remembered', async () => {
54
+ const service = serviceWithPrivateState({
55
+ connectedAdapter: null,
56
+ connectedWalletUuid: 'uuid-1'
57
+ })
58
+ const rebuiltAdapter = { publicKey: { toBase58: async () => 'addr' } }
59
+ const walletInfo = {
60
+ uuid: 'uuid-1',
61
+ adapter: rebuiltAdapter
62
+ } as unknown as WalletStandardInfo
63
+
64
+ vi.spyOn(service, 'initializeDiscovery').mockResolvedValue(undefined)
65
+ vi.spyOn(service, 'findWalletByUuid').mockReturnValue(walletInfo)
66
+ const checkSpy = vi
67
+ .spyOn(service, 'checkExistingConnection')
68
+ .mockResolvedValue('SoLaNaAddr_NEW')
69
+
70
+ const result = await service.ensureConnectedAdapter()
71
+
72
+ expect(checkSpy).toHaveBeenCalledWith(rebuiltAdapter, 'uuid-1')
73
+ expect(result).toBe(true)
74
+ expect(service.getConnectedAdapter()).toBe(rebuiltAdapter)
75
+ expect(service.getAccount()).toBe('SoLaNaAddr_NEW')
76
+ })
77
+
78
+ it('returns false when findWalletByUuid finds nothing', async () => {
79
+ const service = serviceWithPrivateState({
80
+ connectedAdapter: null,
81
+ connectedWalletUuid: 'uuid-1'
82
+ })
83
+ vi.spyOn(service, 'initializeDiscovery').mockResolvedValue(undefined)
84
+ vi.spyOn(service, 'findWalletByUuid').mockReturnValue(undefined)
85
+
86
+ expect(await service.ensureConnectedAdapter()).toBe(false)
87
+ })
88
+
89
+ it('returns false when checkExistingConnection yields no address (not previously authorized / silent reconnect unsupported)', async () => {
90
+ const service = serviceWithPrivateState({
91
+ connectedAdapter: null,
92
+ connectedWalletUuid: 'uuid-1'
93
+ })
94
+ const walletInfo = {
95
+ uuid: 'uuid-1',
96
+ adapter: { publicKey: null }
97
+ } as unknown as WalletStandardInfo
98
+ vi.spyOn(service, 'initializeDiscovery').mockResolvedValue(undefined)
99
+ vi.spyOn(service, 'findWalletByUuid').mockReturnValue(walletInfo)
100
+ vi.spyOn(service, 'checkExistingConnection').mockResolvedValue(null)
101
+
102
+ expect(await service.ensureConnectedAdapter()).toBe(false)
103
+ })
104
+
105
+ it('never throws: returns false when discovery/rebuild helpers throw', async () => {
106
+ const service = serviceWithPrivateState({
107
+ connectedAdapter: null,
108
+ connectedWalletUuid: 'uuid-1'
109
+ })
110
+ vi.spyOn(service, 'initializeDiscovery').mockRejectedValue(
111
+ new Error('discovery failed')
112
+ )
113
+
114
+ await expect(service.ensureConnectedAdapter()).resolves.toBe(false)
115
+ })
116
+ })
117
+
118
+ describe('SolanaWalletService — connectedWalletUuid bookkeeping', () => {
119
+ it('is set on connect()', async () => {
120
+ const service = new SolanaWalletService(new StorageService())
121
+ const adapter = {
122
+ connect: vi.fn().mockResolvedValue(undefined),
123
+ publicKey: { toBase58: async () => 'addr' }
124
+ } as any
125
+
126
+ await service.connect(adapter, 'uuid-42')
127
+
128
+ expect(
129
+ (service as unknown as { connectedWalletUuid: string | null })
130
+ .connectedWalletUuid
131
+ ).toBe('uuid-42')
132
+ })
133
+
134
+ it('is set on setConnectionState(...) when adapter+account+walletUuid are all provided', () => {
135
+ const service = new SolanaWalletService(new StorageService())
136
+ const adapter = { publicKey: { toBase58: async () => 'addr' } } as any
137
+
138
+ service.setConnectionState(adapter, 'addr', 'uuid-7')
139
+
140
+ expect(
141
+ (service as unknown as { connectedWalletUuid: string | null })
142
+ .connectedWalletUuid
143
+ ).toBe('uuid-7')
144
+ })
145
+
146
+ it('is not set on setConnectionState(...) when walletUuid is omitted', () => {
147
+ const service = new SolanaWalletService(new StorageService())
148
+ const adapter = { publicKey: { toBase58: async () => 'addr' } } as any
149
+
150
+ service.setConnectionState(adapter, 'addr')
151
+
152
+ expect(
153
+ (service as unknown as { connectedWalletUuid: string | null })
154
+ .connectedWalletUuid
155
+ ).toBeNull()
156
+ })
157
+
158
+ it('is cleared on disconnect()', async () => {
159
+ const service = new SolanaWalletService(new StorageService())
160
+ const adapter = {
161
+ connect: vi.fn().mockResolvedValue(undefined),
162
+ publicKey: { toBase58: async () => 'addr' }
163
+ } as any
164
+ await service.connect(adapter, 'uuid-42')
165
+
166
+ service.disconnect()
167
+
168
+ expect(
169
+ (service as unknown as { connectedWalletUuid: string | null })
170
+ .connectedWalletUuid
171
+ ).toBeNull()
172
+ expect(service.getConnectedAdapter()).toBeNull()
173
+ expect(service.getAccount()).toBeNull()
174
+ })
175
+ })
@@ -19,6 +19,7 @@ export class SolanaWalletService {
19
19
  private detectedWallets: WalletStandardInfo[] = []
20
20
  private connectedAdapter: SolanaAdapter | null = null
21
21
  private account: string | null = null
22
+ private connectedWalletUuid: string | null = null
22
23
  private storageService: StorageService
23
24
 
24
25
  constructor(storageService: StorageService) {
@@ -117,6 +118,7 @@ export class SolanaWalletService {
117
118
 
118
119
  this.connectedAdapter = adapter
119
120
  this.account = address
121
+ this.connectedWalletUuid = walletUuid
120
122
 
121
123
  // Store this wallet as connected
122
124
  this.storageService.storeSolanaWalletUUID(walletUuid)
@@ -156,6 +158,7 @@ export class SolanaWalletService {
156
158
 
157
159
  // Store wallet UUID if provided and connected
158
160
  if (adapter && account && walletUuid) {
161
+ this.connectedWalletUuid = walletUuid
159
162
  this.storageService.storeSolanaWalletUUID(walletUuid)
160
163
  }
161
164
  }
@@ -167,6 +170,26 @@ export class SolanaWalletService {
167
170
  return this.account
168
171
  }
169
172
 
173
+ /**
174
+ * The LIVE public key of the connected adapter, read at call time from
175
+ * `adapter.publicKey?.toBase58()`. Unlike `getAccount()`'s connect-time
176
+ * cache, this reflects an in-wallet account switch (in bridged mode the
177
+ * publicKey is a live Comlink proxy whose `toBase58()` is async, so this
178
+ * awaits it), letting the signMessage flow claim the account that ACTUALLY
179
+ * signs. Returns null when there is no connected adapter or it exposes no
180
+ * public key; the caller decides whether to throw.
181
+ */
182
+ async getLiveAccount(): Promise<string | null> {
183
+ const adapter = this.connectedAdapter
184
+ if (!adapter) return null
185
+ try {
186
+ const base58 = await adapter.publicKey?.toBase58()
187
+ return base58 ?? null
188
+ } catch {
189
+ return null
190
+ }
191
+ }
192
+
170
193
  /**
171
194
  * Get connected adapter
172
195
  */
@@ -174,6 +197,39 @@ export class SolanaWalletService {
174
197
  return this.connectedAdapter
175
198
  }
176
199
 
200
+ /**
201
+ * (Re)bind the connected adapter if the reference was cleared (e.g. a re-auth
202
+ * teardown after an in-wallet account switch) but the wallet is still
203
+ * authorized. Silent: uses the no-prompt `checkExistingConnection` path, so
204
+ * signing after a switch never surfaces an extra approval popup.
205
+ *
206
+ * Returns a BOOLEAN, never the adapter itself: in bridge mode the adapter is
207
+ * a Comlink proxy, and `await`ing that proxy value (as callers would with
208
+ * `const a = await ensureConnectedAdapter()`) makes the Promise machinery
209
+ * follow its thenable and forces Comlink to structured-clone the
210
+ * (unserializable) adapter → "Unserializable return value". Callers must read
211
+ * the adapter SYNCHRONOUSLY via `getConnectedAdapter()` AFTER awaiting this,
212
+ * so the proxy's methods are called remotely but the proxy is never awaited.
213
+ */
214
+ async ensureConnectedAdapter(): Promise<boolean> {
215
+ if (this.connectedAdapter) return true
216
+ if (!this.connectedWalletUuid) return false
217
+ try {
218
+ await this.initializeDiscovery()
219
+ const wallet = this.findWalletByUuid(this.connectedWalletUuid)
220
+ if (!wallet?.adapter) return false
221
+ const address = await this.checkExistingConnection(
222
+ wallet.adapter,
223
+ this.connectedWalletUuid
224
+ )
225
+ if (!address) return false
226
+ this.setConnectionState(wallet.adapter, address, this.connectedWalletUuid)
227
+ return this.connectedAdapter != null
228
+ } catch {
229
+ return false
230
+ }
231
+ }
232
+
177
233
  /**
178
234
  * Subscribe to the connected wallet-standard adapter's lifecycle. Only the
179
235
  * adapter's typed `disconnect` event is forwarded (`WalletAdapterEvents` doesn't
@@ -208,11 +264,87 @@ export class SolanaWalletService {
208
264
  }
209
265
  }
210
266
 
267
+ /**
268
+ * Subscribe to the connected Solana adapter's account changes (direct mode
269
+ * only). `StandardWalletAdapter` re-emits `'connect'` with the new
270
+ * `PublicKey` whenever the underlying Wallet-Standard wallet reports a
271
+ * `change` to its accounts (e.g. the user switches accounts in Phantom),
272
+ * and emits `'disconnect'` when the account goes away entirely. We forward
273
+ * `[address]` on connect and `[]` on disconnect — core reads `[]` as a
274
+ * namespace disconnect.
275
+ *
276
+ * Bridge guard: in the production iframe the adapter published to this
277
+ * service is a Comlink proxy (no real `.on`/`.off`), so a direct
278
+ * subscription is impossible here. Instead, relay through
279
+ * `window.__uwcSubscribeSolanaWalletEvent` (installed by
280
+ * `@meshconnect/uwc-bridge-child`, only present in bridge mode), which asks
281
+ * the PARENT frame — where the live adapter actually lives — to subscribe
282
+ * on our behalf. Falls back to `undefined` (polling remains the fallback)
283
+ * when the global or a connected wallet id isn't available, e.g. an older
284
+ * bridge-parent that predates this capability.
285
+ */
286
+ onAccountsChanged(
287
+ listener: (accounts: string[]) => void
288
+ ): (() => void) | undefined {
289
+ if (
290
+ typeof window !== 'undefined' &&
291
+ (window as unknown as { UWCBridgeChildInitialized?: boolean })
292
+ .UWCBridgeChildInitialized === true
293
+ ) {
294
+ return this.subscribeAccountsChangedViaBridge(listener)
295
+ }
296
+
297
+ const adapter = this.connectedAdapter
298
+ if (!adapter || typeof adapter.on !== 'function') return undefined
299
+
300
+ const onConnect = (publicKey: { toBase58(): string } | null) => {
301
+ const address = publicKey?.toBase58?.()
302
+ listener(address ? [address] : [])
303
+ }
304
+ const onDisconnect = () => listener([])
305
+ adapter.on('connect', onConnect)
306
+ adapter.on('disconnect', onDisconnect)
307
+ return () => {
308
+ adapter.off('connect', onConnect)
309
+ adapter.off('disconnect', onDisconnect)
310
+ }
311
+ }
312
+
313
+ /**
314
+ * Bridge half of `onAccountsChanged`. `walletId` is
315
+ * `connectedWalletUuid` — the SAME id BridgeParent's
316
+ * `walletStandardWallets[].uuid` publishes (name+chain based, not a real
317
+ * UUID; see `generateWalletId` in `wallet-standard-discovery.ts`), which
318
+ * this service captured at connect time. The bridge global forwards a
319
+ * plain `string | null` address (never a `PublicKey`); we map it to the
320
+ * `[address]` / `[]` shape `onAccountsChanged`'s direct-mode branch already
321
+ * uses (core reads `[]` as a namespace disconnect).
322
+ */
323
+ private subscribeAccountsChangedViaBridge(
324
+ listener: (accounts: string[]) => void
325
+ ): (() => void) | undefined {
326
+ const walletId = this.connectedWalletUuid
327
+ const bridgeSubscribe = (
328
+ window as unknown as {
329
+ __uwcSubscribeSolanaWalletEvent?: (
330
+ walletId: string,
331
+ callback: (address: string | null) => void
332
+ ) => () => void
333
+ }
334
+ ).__uwcSubscribeSolanaWalletEvent
335
+ if (!walletId || !bridgeSubscribe) return undefined
336
+
337
+ return bridgeSubscribe(walletId, address => {
338
+ listener(address ? [address] : [])
339
+ })
340
+ }
341
+
211
342
  /**
212
343
  * Disconnect (clear state only, don't actually disconnect from wallet)
213
344
  */
214
345
  disconnect(): void {
215
346
  this.connectedAdapter = null
216
347
  this.account = null
348
+ this.connectedWalletUuid = null
217
349
  }
218
350
  }
@@ -656,6 +656,31 @@ describe('TonWalletService', () => {
656
656
  })
657
657
  })
658
658
 
659
+ describe('getAccount — live signer address', () => {
660
+ it('returns the LIVE SDK account after an in-wallet switch, not the stale connect-time cache', async () => {
661
+ await connectService(service)
662
+ // connect-time cache is 'UQBconnected'
663
+ expect(service.getAccount()).toBe('UQBconnected')
664
+
665
+ // Simulate an in-wallet account switch: the live SDK account now points
666
+ // at a DIFFERENT raw address B. The connect-time cache is untouched.
667
+ getLastSdkInstance().account = { address: '0:switched_to_b_9999' }
668
+
669
+ // getAccount() must reflect the LIVE account (friendly form of B), not
670
+ // the stale 'UQBconnected'. This is the address the tvm signMessage
671
+ // branch claims to the backend, so it must equal the actual signer.
672
+ expect(service.getAccount()).toBe('UQ_converted_switched')
673
+ expect(service.getAccount()).not.toBe('UQBconnected')
674
+ })
675
+
676
+ it('falls back to the cached address when the SDK has no live account', async () => {
677
+ await connectService(service)
678
+ // No sdk.account set (mock leaves it null) — fall back to the cache.
679
+ expect(getLastSdkInstance().account).toBeNull()
680
+ expect(service.getAccount()).toBe('UQBconnected')
681
+ })
682
+ })
683
+
659
684
  describe('disconnect', () => {
660
685
  it('clears all connection state', async () => {
661
686
  mockOnStatusChange.mockImplementation(callback => {
@@ -247,7 +247,22 @@ export class TonWalletService {
247
247
  .map(networkId => ({ address, networkId: networkId as NetworkId }))
248
248
  }
249
249
 
250
+ /**
251
+ * The current signer address. Prefers the LIVE SDK account (which reflects an
252
+ * in-wallet account switch) over the connect-time cache, converting the raw
253
+ * SDK address to the user-friendly form the connect handshake returned. The
254
+ * tvm signMessage branch claims this to the backend, so it MUST equal the
255
+ * account that actually signs — a stale cache would surface as an invalid
256
+ * signature after a switch. Falls back to the cache when no live SDK account
257
+ * is available (e.g. state seeded via setConnectionState without an SDK).
258
+ */
250
259
  getAccount(): string | null {
260
+ const liveRawAddress = this.sdkInstance?.account?.address
261
+ if (liveRawAddress) {
262
+ return this.toUserFriendlyAddress
263
+ ? toFriendlyAddress(liveRawAddress, this.toUserFriendlyAddress)
264
+ : liveRawAddress
265
+ }
251
266
  return this.connectedAddress
252
267
  }
253
268
 
@@ -301,6 +301,51 @@ describe('TronWalletService', () => {
301
301
  })
302
302
  })
303
303
 
304
+ describe('getLiveAccount — live signer address', () => {
305
+ it('returns the LIVE default address after an in-wallet switch, not the connect-time cache', async () => {
306
+ const provider = createMockProvider({ address: 'TTronAddr_A_OLD' })
307
+ await service.connect(provider)
308
+ expect(service.getAccount()).toBe('TTronAddr_A_OLD')
309
+
310
+ // Simulate an in-wallet account switch: the live tronWeb defaultAddress
311
+ // now reports B. The connect-time cache is untouched.
312
+ provider.tronWeb.defaultAddress = {
313
+ base58: 'TTronAddr_B_NEW',
314
+ hex: '0x5678'
315
+ }
316
+
317
+ expect(await service.getLiveAccount()).toBe('TTronAddr_B_NEW')
318
+ expect(await service.getLiveAccount()).not.toBe('TTronAddr_A_OLD')
319
+ })
320
+
321
+ it('reads the LIVE address via getDefaultAddress for bridge providers', async () => {
322
+ const provider = {
323
+ ready: true,
324
+ request: vi.fn(),
325
+ tronWeb: {
326
+ getDefaultAddress: vi
327
+ .fn()
328
+ .mockResolvedValue({ base58: 'TTronAddr_B_NEW', hex: '0x5678' })
329
+ }
330
+ } as any
331
+ service.setConnectionState(provider, 'TTronAddr_A_OLD')
332
+
333
+ expect(await service.getLiveAccount()).toBe('TTronAddr_B_NEW')
334
+ expect(provider.tronWeb.getDefaultAddress).toHaveBeenCalled()
335
+ })
336
+
337
+ it('returns null when there is no connected provider', async () => {
338
+ expect(await service.getLiveAccount()).toBeNull()
339
+ })
340
+
341
+ it('returns null when the provider exposes no default address', async () => {
342
+ const provider = createMockProvider()
343
+ provider.tronWeb.defaultAddress = { base58: false, hex: false }
344
+ service.setConnectionState(provider, 'TTronAddr_A_OLD')
345
+ expect(await service.getLiveAccount()).toBeNull()
346
+ })
347
+ })
348
+
304
349
  describe('disconnect', () => {
305
350
  it('should clear connection state', async () => {
306
351
  const provider = createMockProvider({ address: 'TAddr' })
@@ -136,6 +136,26 @@ export class TronWalletService {
136
136
  return this.account
137
137
  }
138
138
 
139
+ /**
140
+ * The LIVE default address of the connected Tron provider, resolved at call
141
+ * time from `tronWeb` (bridge providers via async `getDefaultAddress()`,
142
+ * native via `defaultAddress.base58`). Unlike `getAccount()`'s connect-time
143
+ * cache, this reflects an in-wallet account switch, letting the signMessage
144
+ * flow claim the account that ACTUALLY signs (`signMessageV2` signs with the
145
+ * wallet's current default address). Returns null when there is no connected
146
+ * provider or it exposes no address, or the lookup fails; the caller decides
147
+ * whether to throw.
148
+ */
149
+ async getLiveAccount(): Promise<string | null> {
150
+ const provider = this.connectedProvider
151
+ if (!provider) return null
152
+ try {
153
+ return await this.resolveAddress(provider.tronWeb)
154
+ } catch {
155
+ return null
156
+ }
157
+ }
158
+
139
159
  /**
140
160
  * Get connected provider
141
161
  */
@@ -20,7 +20,7 @@ vi.mock('@meshconnect/uwc-bridge-child', () => ({
20
20
  }))
21
21
 
22
22
  // SolanaWalletService needs fine-grained control — we mock at the module level
23
- // and override getConnectedAdapter per test.
23
+ // and override ensureConnectedAdapter per test.
24
24
  vi.mock('./services/solana/solana-wallet-service')
25
25
 
26
26
  // Build a minimal valid serialized VersionedTransaction for deserialize tests.
@@ -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
+ }