@meshconnect/uwc-injected-connector 0.16.6 → 0.17.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.
@@ -0,0 +1,340 @@
1
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
2
+
3
+ // Mock @solana/wallet-adapter-base with a minimal base class (mirrors
4
+ // BaseWalletAdapter.test.ts in uwc-bridge-parent).
5
+ vi.mock('@solana/wallet-adapter-base', () => {
6
+ class MockBaseMessageSignerWalletAdapter {
7
+ _evtListeners: Record<string, ((...args: any[]) => void)[]> = {}
8
+ get connected() {
9
+ return !!(this as any)._publicKey
10
+ }
11
+ emit(event: string, ...args: any[]) {
12
+ for (const fn of this._evtListeners[event] || []) fn(...args)
13
+ return true
14
+ }
15
+ on(event: string, fn: (...args: any[]) => void) {
16
+ if (!this._evtListeners[event]) this._evtListeners[event] = []
17
+ this._evtListeners[event]!.push(fn)
18
+ return this
19
+ }
20
+ off(event: string, fn: (...args: any[]) => void) {
21
+ if (this._evtListeners[event]) {
22
+ this._evtListeners[event] = this._evtListeners[event]!.filter(
23
+ f => f !== fn
24
+ )
25
+ }
26
+ return this
27
+ }
28
+ async prepareTransaction(tx: any) {
29
+ return tx
30
+ }
31
+ }
32
+ const err = (name: string) =>
33
+ class extends Error {
34
+ override name = name
35
+ constructor(msg?: string) {
36
+ super(msg || name)
37
+ }
38
+ }
39
+ return {
40
+ BaseMessageSignerWalletAdapter: MockBaseMessageSignerWalletAdapter,
41
+ isVersionedTransaction: vi.fn(() => false),
42
+ scopePollingDetectionStrategy: vi.fn(),
43
+ WalletAccountError: err('WalletAccountError'),
44
+ WalletConnectionError: err('WalletConnectionError'),
45
+ WalletDisconnectedError: err('WalletDisconnectedError'),
46
+ WalletDisconnectionError: err('WalletDisconnectionError'),
47
+ WalletError: class extends Error {},
48
+ WalletNotConnectedError: err('WalletNotConnectedError'),
49
+ WalletNotReadyError: err('WalletNotReadyError'),
50
+ WalletPublicKeyError: err('WalletPublicKeyError'),
51
+ WalletReadyState: {
52
+ Installed: 'Installed',
53
+ NotDetected: 'NotDetected',
54
+ Loadable: 'Loadable',
55
+ Unsupported: 'Unsupported'
56
+ },
57
+ WalletSendTransactionError: err('WalletSendTransactionError'),
58
+ WalletSignTransactionError: err('WalletSignTransactionError'),
59
+ WalletSignMessageError: err('WalletSignMessageError')
60
+ }
61
+ })
62
+
63
+ vi.mock('@solana/web3.js', () => ({
64
+ PublicKey: class {
65
+ constructor(public _bytes: any) {}
66
+ toBase58() {
67
+ return 'mockBase58'
68
+ }
69
+ toBytes() {
70
+ return this._bytes
71
+ }
72
+ }
73
+ }))
74
+
75
+ const INJECTED_ID = 'coinbaseSolana'
76
+ const WALLET_NAME = 'Base Wallet'
77
+
78
+ describe('LegacyInjectedSolanaWalletAdapter (generic, metadata-driven)', () => {
79
+ let mockWallet: any
80
+
81
+ beforeEach(() => {
82
+ vi.clearAllMocks()
83
+ mockWallet = {
84
+ publicKey: { toBytes: () => new Uint8Array([1, 2, 3]) },
85
+ connect: vi.fn().mockResolvedValue(undefined),
86
+ disconnect: vi.fn().mockResolvedValue(undefined),
87
+ signTransaction: vi.fn(async (tx: any) => tx),
88
+ signAllTransactions: vi.fn(async (txs: any) => txs),
89
+ signAndSendTransaction: vi
90
+ .fn()
91
+ .mockResolvedValue({ signature: 'mockSig' }),
92
+ signMessage: vi
93
+ .fn()
94
+ .mockResolvedValue({ signature: new Uint8Array([4, 5, 6]) }),
95
+ on: vi.fn(),
96
+ off: vi.fn()
97
+ }
98
+ })
99
+
100
+ afterEach(() => {
101
+ delete (window as any)[INJECTED_ID]
102
+ delete (window as any).nested
103
+ vi.restoreAllMocks()
104
+ })
105
+
106
+ async function createInstalledAdapter(injectedId = INJECTED_ID) {
107
+ const { LegacyInjectedSolanaWalletAdapter } =
108
+ await import('./legacy-injected-solana-adapter')
109
+ // Place the provider at the (possibly nested) injectedId path.
110
+ if (injectedId.includes('.')) {
111
+ const [head, tail] = injectedId.split('.')
112
+ ;(window as any)[head!] = { [tail!]: mockWallet }
113
+ } else {
114
+ ;(window as any)[injectedId] = mockWallet
115
+ }
116
+ // Provider present at construction → the adapter is Installed synchronously,
117
+ // no polling tick required.
118
+ return new LegacyInjectedSolanaWalletAdapter(injectedId, WALLET_NAME)
119
+ }
120
+
121
+ describe('provider resolution helpers', () => {
122
+ it('getInjectedSolanaProvider returns undefined when absent', async () => {
123
+ const { getInjectedSolanaProvider } =
124
+ await import('./legacy-injected-solana-adapter')
125
+ expect(getInjectedSolanaProvider(INJECTED_ID)).toBeUndefined()
126
+ })
127
+
128
+ it('getInjectedSolanaProvider returns the provider when present + valid', async () => {
129
+ const { getInjectedSolanaProvider } =
130
+ await import('./legacy-injected-solana-adapter')
131
+ ;(window as any)[INJECTED_ID] = mockWallet
132
+ expect(getInjectedSolanaProvider(INJECTED_ID)).toBe(mockWallet)
133
+ })
134
+
135
+ it('getInjectedSolanaProvider rejects a global that is not a Solana provider', async () => {
136
+ const { getInjectedSolanaProvider } =
137
+ await import('./legacy-injected-solana-adapter')
138
+ ;(window as any)[INJECTED_ID] = { foo: 'bar' } // no connect/signTransaction
139
+ expect(getInjectedSolanaProvider(INJECTED_ID)).toBeUndefined()
140
+ })
141
+
142
+ it('resolves a dot-nested injectedId path', async () => {
143
+ const { getInjectedSolanaProvider } =
144
+ await import('./legacy-injected-solana-adapter')
145
+ ;(window as any).nested = { solana: mockWallet }
146
+ expect(getInjectedSolanaProvider('nested.solana')).toBe(mockWallet)
147
+ })
148
+
149
+ it('isLegacyInjectedSolanaProvider requires the full invoked method surface', async () => {
150
+ const { isLegacyInjectedSolanaProvider } =
151
+ await import('./legacy-injected-solana-adapter')
152
+ // mockWallet implements connect/disconnect/on/off/sign* → valid
153
+ expect(isLegacyInjectedSolanaProvider(mockWallet)).toBe(true)
154
+ expect(isLegacyInjectedSolanaProvider({ connect: () => {} })).toBe(false)
155
+ // Partial provider (connect + signTransaction only) is now rejected — it
156
+ // would throw at disconnect/signMessage/lifecycle time otherwise.
157
+ expect(
158
+ isLegacyInjectedSolanaProvider({
159
+ connect: () => {},
160
+ signTransaction: () => {}
161
+ })
162
+ ).toBe(false)
163
+ // Missing just one method (off) → rejected.
164
+ const missingOff = { ...mockWallet }
165
+ delete missingOff.off
166
+ expect(isLegacyInjectedSolanaProvider(missingOff)).toBe(false)
167
+ expect(isLegacyInjectedSolanaProvider(null)).toBe(false)
168
+ })
169
+ })
170
+
171
+ describe('constructor', () => {
172
+ it('uses the name passed in (no hardcoded wallet name)', async () => {
173
+ const { LegacyInjectedSolanaWalletAdapter } =
174
+ await import('./legacy-injected-solana-adapter')
175
+ const adapter = new LegacyInjectedSolanaWalletAdapter(
176
+ INJECTED_ID,
177
+ 'Some Other Wallet'
178
+ )
179
+ expect(adapter.name).toBe('Some Other Wallet')
180
+ expect(adapter.publicKey).toBeNull()
181
+ expect(adapter.readyState).toBe('NotDetected')
182
+ expect(adapter.supportedTransactionVersions).toEqual(
183
+ new Set(['legacy', 0])
184
+ )
185
+ })
186
+
187
+ it('is Installed synchronously when the provider is already present (no poll tick)', async () => {
188
+ const { scopePollingDetectionStrategy } =
189
+ await import('@solana/wallet-adapter-base')
190
+ const { LegacyInjectedSolanaWalletAdapter } =
191
+ await import('./legacy-injected-solana-adapter')
192
+ // Provider present before construction (the discovery path guarantees this):
193
+ // readyState must be Installed immediately so the synchronous auto-reconnect
194
+ // connect() doesn't race the first polling tick and throw WalletNotReadyError.
195
+ ;(window as any)[INJECTED_ID] = mockWallet
196
+ const adapter = new LegacyInjectedSolanaWalletAdapter(
197
+ INJECTED_ID,
198
+ WALLET_NAME
199
+ )
200
+ expect(adapter.readyState).toBe('Installed')
201
+ expect(scopePollingDetectionStrategy).not.toHaveBeenCalled()
202
+ })
203
+
204
+ it('flips readyState to Installed only once its injectedId global appears', async () => {
205
+ const { scopePollingDetectionStrategy } =
206
+ await import('@solana/wallet-adapter-base')
207
+ const { LegacyInjectedSolanaWalletAdapter } =
208
+ await import('./legacy-injected-solana-adapter')
209
+ const adapter = new LegacyInjectedSolanaWalletAdapter(
210
+ INJECTED_ID,
211
+ WALLET_NAME
212
+ )
213
+ const mock = vi.mocked(scopePollingDetectionStrategy).mock
214
+ const cb = mock.calls[mock.calls.length - 1]![0] as () => boolean
215
+ expect(cb()).toBe(false)
216
+ ;(window as any)[INJECTED_ID] = mockWallet
217
+ expect(cb()).toBe(true)
218
+ expect(adapter.readyState).toBe('Installed')
219
+ })
220
+ })
221
+
222
+ describe('connect', () => {
223
+ it('throws when not installed', async () => {
224
+ const { LegacyInjectedSolanaWalletAdapter } =
225
+ await import('./legacy-injected-solana-adapter')
226
+ const adapter = new LegacyInjectedSolanaWalletAdapter(
227
+ INJECTED_ID,
228
+ WALLET_NAME
229
+ )
230
+ await expect(adapter.connect()).rejects.toThrow()
231
+ expect(mockWallet.connect).not.toHaveBeenCalled()
232
+ })
233
+
234
+ it('connects and exposes the publicKey', async () => {
235
+ const adapter = await createInstalledAdapter()
236
+ await adapter.connect()
237
+ expect(mockWallet.connect).toHaveBeenCalled()
238
+ expect(adapter.publicKey?.toBase58()).toBe('mockBase58')
239
+ })
240
+
241
+ it('resolves the provider at a nested injectedId', async () => {
242
+ const adapter = await createInstalledAdapter('nested.solana')
243
+ await adapter.connect()
244
+ expect(mockWallet.connect).toHaveBeenCalled()
245
+ expect(adapter.publicKey).not.toBeNull()
246
+ })
247
+
248
+ it('wraps a provider connect rejection', async () => {
249
+ mockWallet.connect.mockRejectedValue(new Error('user rejected'))
250
+ const adapter = await createInstalledAdapter()
251
+ await expect(adapter.connect()).rejects.toThrow()
252
+ expect(adapter.publicKey).toBeNull()
253
+ })
254
+
255
+ it('throws when the provider returns no publicKey', async () => {
256
+ mockWallet.publicKey = null
257
+ const adapter = await createInstalledAdapter()
258
+ await expect(adapter.connect()).rejects.toThrow()
259
+ })
260
+
261
+ it('is idempotent while connected', async () => {
262
+ const adapter = await createInstalledAdapter()
263
+ await adapter.connect()
264
+ await adapter.connect()
265
+ expect(mockWallet.connect).toHaveBeenCalledTimes(1)
266
+ })
267
+
268
+ it('a concurrent connect() early-returns without clearing the in-flight connecting state', async () => {
269
+ const adapter = await createInstalledAdapter()
270
+ let resolveConnect!: () => void
271
+ mockWallet.connect.mockReturnValue(
272
+ new Promise<void>(r => {
273
+ resolveConnect = r
274
+ })
275
+ )
276
+
277
+ const inflight = adapter.connect()
278
+ expect(adapter.connecting).toBe(true)
279
+
280
+ // Second call while the first is in flight must early-return and NOT reset
281
+ // the shared connecting state (pre-fix the finally flipped it to false).
282
+ await adapter.connect()
283
+ expect(adapter.connecting).toBe(true)
284
+
285
+ resolveConnect()
286
+ await inflight
287
+ expect(adapter.connecting).toBe(false)
288
+ expect(mockWallet.connect).toHaveBeenCalledTimes(1)
289
+ })
290
+ })
291
+
292
+ describe('disconnect + signing', () => {
293
+ it('clears state and emits disconnect', async () => {
294
+ const adapter = await createInstalledAdapter()
295
+ await adapter.connect()
296
+ const handler = vi.fn()
297
+ adapter.on('disconnect', handler)
298
+ await adapter.disconnect()
299
+ expect(adapter.publicKey).toBeNull()
300
+ expect(mockWallet.disconnect).toHaveBeenCalled()
301
+ expect(handler).toHaveBeenCalled()
302
+ })
303
+
304
+ it('signTransaction throws when not connected', async () => {
305
+ const { LegacyInjectedSolanaWalletAdapter } =
306
+ await import('./legacy-injected-solana-adapter')
307
+ const adapter = new LegacyInjectedSolanaWalletAdapter(
308
+ INJECTED_ID,
309
+ WALLET_NAME
310
+ )
311
+ await expect(adapter.signTransaction({} as any)).rejects.toThrow()
312
+ })
313
+
314
+ it('signTransaction delegates to the provider', async () => {
315
+ const adapter = await createInstalledAdapter()
316
+ await adapter.connect()
317
+ const tx = { id: 1 } as any
318
+ await adapter.signTransaction(tx)
319
+ expect(mockWallet.signTransaction).toHaveBeenCalledWith(tx)
320
+ })
321
+
322
+ it('signMessage returns the provider signature', async () => {
323
+ const adapter = await createInstalledAdapter()
324
+ await adapter.connect()
325
+ const sig = await adapter.signMessage(new Uint8Array([1]))
326
+ expect(sig).toEqual(new Uint8Array([4, 5, 6]))
327
+ })
328
+
329
+ it('sendTransaction returns the provider signature', async () => {
330
+ const adapter = await createInstalledAdapter()
331
+ await adapter.connect()
332
+ const result = await adapter.sendTransaction(
333
+ {} as any,
334
+ { commitment: 'confirmed' } as any
335
+ )
336
+ expect(mockWallet.signAndSendTransaction).toHaveBeenCalled()
337
+ expect(result).toBe('mockSig')
338
+ })
339
+ })
340
+ })
@@ -0,0 +1,370 @@
1
+ /**
2
+ * Generic legacy injected-Solana adapter.
3
+ *
4
+ * WHY THIS EXISTS (MFS-805): some wallets' in-app dApp browsers expose their
5
+ * Solana provider ONLY via a legacy `window[injectedId]` global and never
6
+ * register with the Wallet Standard registry (`getWallets()`) — so UWC's
7
+ * registry-only Solana discovery misses them and connect hangs. The first case
8
+ * is Coinbase/Base Wallet Legacy mode (`window.coinbaseSolana`), but this is
9
+ * wallet-agnostic: the global key comes from `SolanaMetadata.injectedId`, exactly
10
+ * like the EVM (`eip155.injectedId`) and TRON (`tron.injectedId`) legacy paths.
11
+ *
12
+ * The provider shape is the de-facto injected-Solana interface (connect +
13
+ * sign*), the same one `@solana/wallet-standard-wallet-adapter-base` wraps.
14
+ */
15
+ import type {
16
+ EventEmitter,
17
+ SendTransactionOptions,
18
+ WalletName
19
+ } from '@solana/wallet-adapter-base'
20
+ import {
21
+ BaseMessageSignerWalletAdapter,
22
+ isVersionedTransaction,
23
+ scopePollingDetectionStrategy,
24
+ WalletAccountError,
25
+ WalletConnectionError,
26
+ WalletDisconnectedError,
27
+ WalletDisconnectionError,
28
+ WalletError,
29
+ WalletNotConnectedError,
30
+ WalletNotReadyError,
31
+ WalletPublicKeyError,
32
+ WalletReadyState,
33
+ WalletSendTransactionError,
34
+ WalletSignTransactionError,
35
+ WalletSignMessageError
36
+ } from '@solana/wallet-adapter-base'
37
+ import type {
38
+ Connection,
39
+ SendOptions,
40
+ Transaction,
41
+ VersionedTransaction,
42
+ TransactionSignature,
43
+ TransactionVersion
44
+ } from '@solana/web3.js'
45
+ import { PublicKey } from '@solana/web3.js'
46
+
47
+ interface LegacyInjectedSolanaEvents {
48
+ connect(...args: unknown[]): unknown
49
+ disconnect(...args: unknown[]): unknown
50
+ }
51
+
52
+ /**
53
+ * De-facto shape of a legacy injected-Solana provider. Only the members UWC
54
+ * relies on are declared.
55
+ */
56
+ export interface LegacyInjectedSolanaProvider extends EventEmitter<LegacyInjectedSolanaEvents> {
57
+ publicKey?: PublicKey
58
+ signTransaction<T extends Transaction | VersionedTransaction>(
59
+ transaction: T
60
+ ): Promise<T>
61
+ signAllTransactions<T extends Transaction | VersionedTransaction>(
62
+ transactions: T[]
63
+ ): Promise<T[]>
64
+ signAndSendTransaction<T extends Transaction | VersionedTransaction>(
65
+ transaction: T,
66
+ options?: SendOptions
67
+ ): Promise<{ signature: TransactionSignature }>
68
+ signMessage(message: Uint8Array): Promise<{ signature: Uint8Array }>
69
+ connect(): Promise<void>
70
+ disconnect(): Promise<void>
71
+ }
72
+
73
+ /**
74
+ * Resolve a (possibly dot-nested) `injectedId` path on `window`, without
75
+ * throwing in non-browser / SSR contexts. Mirrors the TRON discovery resolver.
76
+ */
77
+ export function resolveInjectedProperty(injectedId: string): unknown {
78
+ if (typeof window === 'undefined') return undefined
79
+ return injectedId
80
+ .split('.')
81
+ .reduce<unknown>(
82
+ (acc, part) =>
83
+ acc == null ? undefined : (acc as Record<string, unknown>)[part],
84
+ window as unknown as Record<string, unknown>
85
+ )
86
+ }
87
+
88
+ /**
89
+ * Duck-type check: a legacy injected-Solana provider must expose every method
90
+ * the adapter invokes. Checking the full surface (not just `connect` +
91
+ * `signTransaction`) keeps discovery from surfacing a partial/unrelated global
92
+ * that would then throw at connect/sign/lifecycle time.
93
+ */
94
+ export function isLegacyInjectedSolanaProvider(
95
+ value: unknown
96
+ ): value is LegacyInjectedSolanaProvider {
97
+ if (!value || typeof value !== 'object') return false
98
+ const p = value as Record<string, unknown>
99
+ const required = [
100
+ 'connect',
101
+ 'disconnect',
102
+ 'on',
103
+ 'off',
104
+ 'signTransaction',
105
+ 'signAllTransactions',
106
+ 'signMessage',
107
+ 'signAndSendTransaction'
108
+ ]
109
+ return required.every(method => typeof p[method] === 'function')
110
+ }
111
+
112
+ /**
113
+ * Read the legacy injected-Solana provider at `injectedId`, or undefined.
114
+ */
115
+ export function getInjectedSolanaProvider(
116
+ injectedId: string
117
+ ): LegacyInjectedSolanaProvider | undefined {
118
+ const provider = resolveInjectedProperty(injectedId)
119
+ return isLegacyInjectedSolanaProvider(provider) ? provider : undefined
120
+ }
121
+
122
+ export class LegacyInjectedSolanaWalletAdapter extends BaseMessageSignerWalletAdapter {
123
+ readonly name: WalletName
124
+ // The adapter's own url/icon are unused by the Link UI (it renders its own
125
+ // catalog metadata); the wallet-adapter contract just requires strings.
126
+ url = ''
127
+ icon = ''
128
+ supportedTransactionVersions: ReadonlySet<TransactionVersion> = new Set([
129
+ 'legacy',
130
+ 0
131
+ ])
132
+
133
+ private readonly _injectedId: string
134
+ private _connecting = false
135
+ private _wallet: LegacyInjectedSolanaProvider | null = null
136
+ private _publicKey: PublicKey | null = null
137
+ private _readyState: WalletReadyState =
138
+ typeof window === 'undefined' || typeof document === 'undefined'
139
+ ? WalletReadyState.Unsupported
140
+ : WalletReadyState.NotDetected
141
+
142
+ constructor(injectedId: string, name: string) {
143
+ super()
144
+ this._injectedId = injectedId
145
+ this.name = name as WalletName
146
+
147
+ if (this._readyState !== WalletReadyState.Unsupported) {
148
+ // Discovery only constructs this adapter after confirming the provider
149
+ // exists, so mark `Installed` synchronously — otherwise `connect()` (which
150
+ // hard-requires `Installed`) can race the first polling tick on the
151
+ // auto-reconnect path and throw `WalletNotReadyError`. Fall back to
152
+ // polling only when the provider isn't present yet.
153
+ if (getInjectedSolanaProvider(this._injectedId)) {
154
+ this._readyState = WalletReadyState.Installed
155
+ } else {
156
+ scopePollingDetectionStrategy(() => {
157
+ if (getInjectedSolanaProvider(this._injectedId)) {
158
+ this._readyState = WalletReadyState.Installed
159
+ this.emit('readyStateChange', this._readyState)
160
+ return true
161
+ }
162
+ return false
163
+ })
164
+ }
165
+ }
166
+ }
167
+
168
+ get publicKey() {
169
+ return this._publicKey
170
+ }
171
+
172
+ get connecting() {
173
+ return this._connecting
174
+ }
175
+
176
+ get readyState() {
177
+ return this._readyState
178
+ }
179
+
180
+ async connect(): Promise<void> {
181
+ // Guard OUTSIDE the try: a concurrent connect() must early-return without
182
+ // hitting the `finally` below, which would otherwise clear `_connecting` for
183
+ // the still-in-flight first call and allow re-entrancy.
184
+ if (this.connected || this.connecting) return
185
+
186
+ this._connecting = true
187
+ try {
188
+ if (this._readyState !== WalletReadyState.Installed)
189
+ throw new WalletNotReadyError()
190
+
191
+ const wallet = getInjectedSolanaProvider(this._injectedId)
192
+ if (!wallet) throw new WalletNotReadyError()
193
+
194
+ try {
195
+ await wallet.connect()
196
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
197
+ } catch (error: any) {
198
+ throw new WalletConnectionError(error?.message, error)
199
+ }
200
+
201
+ if (!wallet.publicKey) throw new WalletAccountError()
202
+
203
+ let publicKey: PublicKey
204
+ try {
205
+ publicKey = new PublicKey(wallet.publicKey.toBytes())
206
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
207
+ } catch (error: any) {
208
+ throw new WalletPublicKeyError(error?.message, error)
209
+ }
210
+
211
+ // Assign state BEFORE subscribing: if the provider fires `disconnect`
212
+ // synchronously during registration, `_disconnected` must see `_wallet`
213
+ // set so it can tear down cleanly.
214
+ this._wallet = wallet
215
+ this._publicKey = publicKey
216
+
217
+ wallet.on('disconnect', this._disconnected)
218
+
219
+ this.emit('connect', publicKey)
220
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
221
+ } catch (error: any) {
222
+ this.emit('error', error)
223
+ throw error
224
+ } finally {
225
+ this._connecting = false
226
+ }
227
+ }
228
+
229
+ async disconnect(): Promise<void> {
230
+ const wallet = this._wallet
231
+ if (wallet) {
232
+ wallet.off('disconnect', this._disconnected)
233
+
234
+ this._wallet = null
235
+ this._publicKey = null
236
+
237
+ try {
238
+ await wallet.disconnect()
239
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
240
+ } catch (error: any) {
241
+ this.emit('error', new WalletDisconnectionError(error?.message, error))
242
+ }
243
+ }
244
+
245
+ this.emit('disconnect')
246
+ }
247
+
248
+ override async sendTransaction<T extends Transaction | VersionedTransaction>(
249
+ transaction: T,
250
+ connection: Connection,
251
+ options: SendTransactionOptions = {}
252
+ ): Promise<TransactionSignature> {
253
+ try {
254
+ const wallet = this._wallet
255
+ if (!wallet) throw new WalletNotConnectedError()
256
+
257
+ try {
258
+ const { signers, ...sendOptions } = options
259
+
260
+ if (isVersionedTransaction(transaction)) {
261
+ if (signers?.length) transaction.sign(signers)
262
+ } else {
263
+ if (!(transaction as Transaction).recentBlockhash) {
264
+ transaction = (await this.prepareTransaction(
265
+ transaction,
266
+ connection,
267
+ sendOptions
268
+ )) as T
269
+ }
270
+
271
+ if (signers?.length)
272
+ (transaction as Transaction).partialSign(...signers)
273
+ }
274
+
275
+ if (!sendOptions.preflightCommitment && connection.commitment) {
276
+ sendOptions.preflightCommitment = connection.commitment
277
+ }
278
+
279
+ const { signature } = await wallet.signAndSendTransaction(
280
+ transaction,
281
+ sendOptions
282
+ )
283
+ return signature
284
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
285
+ } catch (error: any) {
286
+ if (error instanceof WalletError) throw error
287
+ throw new WalletSendTransactionError(error?.message, error)
288
+ }
289
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
290
+ } catch (error: any) {
291
+ this.emit('error', error)
292
+ throw error
293
+ }
294
+ }
295
+
296
+ async signTransaction<T extends Transaction | VersionedTransaction>(
297
+ transaction: T
298
+ ): Promise<T> {
299
+ try {
300
+ const wallet = this._wallet
301
+ if (!wallet) throw new WalletNotConnectedError()
302
+
303
+ try {
304
+ return ((await wallet.signTransaction(transaction)) as T) || transaction
305
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
306
+ } catch (error: any) {
307
+ throw new WalletSignTransactionError(error?.message, error)
308
+ }
309
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
310
+ } catch (error: any) {
311
+ this.emit('error', error)
312
+ throw error
313
+ }
314
+ }
315
+
316
+ override async signAllTransactions<
317
+ T extends Transaction | VersionedTransaction
318
+ >(transactions: T[]): Promise<T[]> {
319
+ try {
320
+ const wallet = this._wallet
321
+ if (!wallet) throw new WalletNotConnectedError()
322
+
323
+ try {
324
+ return (
325
+ ((await wallet.signAllTransactions(transactions)) as T[]) ||
326
+ transactions
327
+ )
328
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
329
+ } catch (error: any) {
330
+ throw new WalletSignTransactionError(error?.message, error)
331
+ }
332
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
333
+ } catch (error: any) {
334
+ this.emit('error', error)
335
+ throw error
336
+ }
337
+ }
338
+
339
+ async signMessage(message: Uint8Array): Promise<Uint8Array> {
340
+ try {
341
+ const wallet = this._wallet
342
+ if (!wallet) throw new WalletNotConnectedError()
343
+
344
+ try {
345
+ const { signature } = await wallet.signMessage(message)
346
+ return signature
347
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
348
+ } catch (error: any) {
349
+ throw new WalletSignMessageError(error?.message, error)
350
+ }
351
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
352
+ } catch (error: any) {
353
+ this.emit('error', error)
354
+ throw error
355
+ }
356
+ }
357
+
358
+ private _disconnected = () => {
359
+ const wallet = this._wallet
360
+ if (wallet) {
361
+ wallet.off('disconnect', this._disconnected)
362
+
363
+ this._wallet = null
364
+ this._publicKey = null
365
+
366
+ this.emit('error', new WalletDisconnectedError())
367
+ this.emit('disconnect')
368
+ }
369
+ }
370
+ }