From a097eca2bf7c9d5f9dec9c46949de3575438dd7d Mon Sep 17 00:00:00 2001 From: Ulisses Ferreira Date: Tue, 17 Nov 2026 02:12:45 +0000 Subject: [PATCH] chore(solana): replace `in` and type the Solana subscription services --- oxlint-suppressions.json | 108 ------------------ .../KeyringAccountMonitor.test.ts | 44 ++++--- .../subscriptions/KeyringAccountMonitor.ts | 2 +- .../subscriptions/SignatureMonitor.test.ts | 27 +++-- .../subscriptions/SignatureMonitor.ts | 4 +- .../subscriptions/SubscriptionRepository.ts | 3 +- .../subscriptions/SubscriptionService.test.ts | 36 +++--- .../subscriptions/SubscriptionService.ts | 56 ++++++--- .../WebSocketConnectionRepository.test.ts | 3 +- .../WebSocketConnectionRepository.ts | 2 +- .../WebSocketConnectionService.test.ts | 55 ++++++--- .../WebSocketConnectionService.ts | 2 +- .../subscriptions/parseWebSocketMessage.ts | 7 +- 13 files changed, 152 insertions(+), 197 deletions(-) diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json index a3013c865..eec5bbe3f 100644 --- a/oxlint-suppressions.json +++ b/oxlint-suppressions.json @@ -791,114 +791,6 @@ "count": 1 } }, - "packages/solana-wallet-snap/src/core/services/subscriptions/KeyringAccountMonitor.test.ts": { - "typescript/no-unsafe-argument": { - "count": 2 - }, - "typescript/no-unsafe-call": { - "count": 3 - } - }, - "packages/solana-wallet-snap/src/core/services/subscriptions/KeyringAccountMonitor.ts": { - "typescript/explicit-function-return-type": { - "count": 1 - } - }, - "packages/solana-wallet-snap/src/core/services/subscriptions/SignatureMonitor.test.ts": { - "typescript/no-explicit-any": { - "count": 1 - }, - "typescript/no-unsafe-argument": { - "count": 3 - } - }, - "packages/solana-wallet-snap/src/core/services/subscriptions/SignatureMonitor.ts": { - "typescript/no-unnecessary-type-assertion": { - "count": 1 - } - }, - "packages/solana-wallet-snap/src/core/services/subscriptions/SubscriptionRepository.ts": { - "internal-snaps/no-in-operator": { - "count": 1 - } - }, - "packages/solana-wallet-snap/src/core/services/subscriptions/SubscriptionService.test.ts": { - "typescript/explicit-function-return-type": { - "count": 6 - }, - "typescript/no-explicit-any": { - "count": 3 - }, - "typescript/no-unsafe-argument": { - "count": 3 - }, - "typescript/no-unsafe-member-access": { - "count": 1 - } - }, - "packages/solana-wallet-snap/src/core/services/subscriptions/SubscriptionService.ts": { - "internal-snaps/no-in-operator": { - "count": 7 - }, - "typescript/explicit-function-return-type": { - "count": 1 - }, - "typescript/no-explicit-any": { - "count": 4 - }, - "typescript/no-unsafe-argument": { - "count": 2 - }, - "typescript/no-unsafe-member-access": { - "count": 4 - }, - "typescript/unbound-method": { - "count": 2 - } - }, - "packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionRepository.test.ts": { - "typescript/no-explicit-any": { - "count": 1 - }, - "typescript/no-unsafe-member-access": { - "count": 1 - } - }, - "packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionRepository.ts": { - "typescript/explicit-function-return-type": { - "count": 1 - } - }, - "packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionService.test.ts": { - "typescript/no-explicit-any": { - "count": 1 - }, - "typescript/no-unsafe-member-access": { - "count": 1 - }, - "vitest/no-conditional-in-test": { - "count": 3 - } - }, - "packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionService.ts": { - "typescript/restrict-template-expressions": { - "count": 1 - } - }, - "packages/solana-wallet-snap/src/core/services/subscriptions/parseWebSocketMessage.ts": { - "internal-snaps/no-in-operator": { - "count": 1 - }, - "typescript/no-explicit-any": { - "count": 1 - }, - "typescript/no-unsafe-assignment": { - "count": 3 - }, - "typescript/no-unsafe-return": { - "count": 1 - } - }, "packages/solana-wallet-snap/src/core/services/transaction-scan/TransactionScanService.test.ts": { "typescript/no-unnecessary-type-assertion": { "count": 12 diff --git a/packages/solana-wallet-snap/src/core/services/subscriptions/KeyringAccountMonitor.test.ts b/packages/solana-wallet-snap/src/core/services/subscriptions/KeyringAccountMonitor.test.ts index 6d74781dc..440b6b509 100644 --- a/packages/solana-wallet-snap/src/core/services/subscriptions/KeyringAccountMonitor.test.ts +++ b/packages/solana-wallet-snap/src/core/services/subscriptions/KeyringAccountMonitor.test.ts @@ -3,7 +3,6 @@ import type { Transaction } from '@metamask/keyring-api'; import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; import type { Address } from '@solana/kit'; import { signature } from '@solana/kit'; -import type { Mock } from 'vitest'; import type { AccountNotification, @@ -11,6 +10,7 @@ import type { ConfirmedSubscription, ProgramNotification, ProgramNotificationHandler, + SubscribeMethod, Subscription, } from '../../../entities'; import { KnownCaip19Id, Network } from '../../constants/solana'; @@ -107,13 +107,23 @@ describe('KeyringAccountMonitor', () => { getAll: vi.fn().mockResolvedValue([]), registerNotificationHandler: vi .fn() - .mockImplementation(async (method, _network, handler) => { - if (method === 'accountSubscribe') { - accountNotificationHandlers.push(handler); - } else if (method === 'programSubscribe') { - programNotificationHandlers.push(handler); - } - }), + .mockImplementation( + async ( + method: SubscribeMethod, + _network: Network, + handler: AccountNotificationHandler | ProgramNotificationHandler, + ) => { + if (method === 'accountSubscribe') { + accountNotificationHandlers.push( + handler as AccountNotificationHandler, + ); + } else if (method === 'programSubscribe') { + programNotificationHandlers.push( + handler as ProgramNotificationHandler, + ); + } + }, + ), registerConnectionRecoveryHandler: vi.fn(), } as unknown as SubscriptionService; @@ -719,9 +729,9 @@ describe('KeyringAccountMonitor', () => { const syncSpy = vi.spyOn(mockAccountsSynchronizer, 'synchronize'); // Simulate connection recovery - const recoveryHandler = ( - mockSubscriptionService.registerConnectionRecoveryHandler as Mock - ).mock.calls[0]?.[1]; + const recoveryHandler = vi.mocked( + mockSubscriptionService.registerConnectionRecoveryHandler, + ).mock.calls[0]![1]; await recoveryHandler(Network.Mainnet); expect(syncSpy).toHaveBeenCalledTimes(1); @@ -740,9 +750,9 @@ describe('KeyringAccountMonitor', () => { const syncSpy = vi.spyOn(mockAccountsSynchronizer, 'synchronize'); // Simulate connection recovery - const recoveryHandler = ( - mockSubscriptionService.registerConnectionRecoveryHandler as Mock - ).mock.calls[0]?.[1]; + const recoveryHandler = vi.mocked( + mockSubscriptionService.registerConnectionRecoveryHandler, + ).mock.calls[0]![1]; await recoveryHandler(Network.Mainnet); expect(syncSpy).toHaveBeenCalledWith(accounts); @@ -754,9 +764,9 @@ describe('KeyringAccountMonitor', () => { const syncSpy = vi.spyOn(mockAccountsSynchronizer, 'synchronize'); // Simulate connection recovery - const recoveryHandler = ( - mockSubscriptionService.registerConnectionRecoveryHandler as Mock - ).mock.calls[0]?.[1]; + const recoveryHandler = vi.mocked( + mockSubscriptionService.registerConnectionRecoveryHandler, + ).mock.calls[0]![1]; await recoveryHandler(Network.Mainnet); expect(syncSpy).not.toHaveBeenCalled(); diff --git a/packages/solana-wallet-snap/src/core/services/subscriptions/KeyringAccountMonitor.ts b/packages/solana-wallet-snap/src/core/services/subscriptions/KeyringAccountMonitor.ts index 4ac8f624a..c9995a5c1 100644 --- a/packages/solana-wallet-snap/src/core/services/subscriptions/KeyringAccountMonitor.ts +++ b/packages/solana-wallet-snap/src/core/services/subscriptions/KeyringAccountMonitor.ts @@ -175,7 +175,7 @@ export class KeyringAccountMonitor { this.#accountsSynchronizer.synchronize(accounts); const promises = accounts.flatMap((account) => { - const shouldMonitorOnNetwork = (network: Network) => + const shouldMonitorOnNetwork = (network: Network): boolean => account.scopes.includes(network); // Monitor native assets diff --git a/packages/solana-wallet-snap/src/core/services/subscriptions/SignatureMonitor.test.ts b/packages/solana-wallet-snap/src/core/services/subscriptions/SignatureMonitor.test.ts index fdc2fde7b..684defe3e 100644 --- a/packages/solana-wallet-snap/src/core/services/subscriptions/SignatureMonitor.test.ts +++ b/packages/solana-wallet-snap/src/core/services/subscriptions/SignatureMonitor.test.ts @@ -8,6 +8,7 @@ import type { ConnectionRecoveryHandler, SignatureNotification, SignatureNotificationHandler, + SubscribeMethod, Subscription, } from '../../../entities'; import { Network } from '../../constants/solana'; @@ -58,16 +59,24 @@ describe('SignatureMonitor', () => { unsubscribe: vi.fn(), registerNotificationHandler: vi .fn() - .mockImplementation(async (_method, _network, handler) => { - // This will let us capture and manually call the handler - notificationHandlers.push(handler); - }), + .mockImplementation( + async ( + _method: SubscribeMethod, + _network: Network, + handler: SignatureNotificationHandler, + ) => { + // This will let us capture and manually call the handler + notificationHandlers.push(handler); + }, + ), registerConnectionRecoveryHandler: vi .fn() - .mockImplementation(async (_network, handler) => { - // This will let us capture and manually call the handler - connectionRecoveryHandlers.push(handler); - }), + .mockImplementation( + async (_network: Network, handler: ConnectionRecoveryHandler) => { + // This will let us capture and manually call the handler + connectionRecoveryHandlers.push(handler); + }, + ), } as unknown as SubscriptionService; mockAccountService = { @@ -395,7 +404,7 @@ describe('SignatureMonitor', () => { value: [{ confirmationStatus: 'processed' }], }), }), - } as any); + } as unknown as ReturnType); await signatureMonitor.monitor( signature, diff --git a/packages/solana-wallet-snap/src/core/services/subscriptions/SignatureMonitor.ts b/packages/solana-wallet-snap/src/core/services/subscriptions/SignatureMonitor.ts index 467119575..e2c0132f9 100644 --- a/packages/solana-wallet-snap/src/core/services/subscriptions/SignatureMonitor.ts +++ b/packages/solana-wallet-snap/src/core/services/subscriptions/SignatureMonitor.ts @@ -195,9 +195,7 @@ export class SignatureMonitor { accountType: account.type, chainIdCaip: transaction.chain, transactionStatus: transaction.status, - transactionType: - transactionType ?? - (transaction.type as TransactionType | undefined), + transactionType: transactionType ?? transaction.type, }); break; default: diff --git a/packages/solana-wallet-snap/src/core/services/subscriptions/SubscriptionRepository.ts b/packages/solana-wallet-snap/src/core/services/subscriptions/SubscriptionRepository.ts index 66f3db9ee..fcf978460 100644 --- a/packages/solana-wallet-snap/src/core/services/subscriptions/SubscriptionRepository.ts +++ b/packages/solana-wallet-snap/src/core/services/subscriptions/SubscriptionRepository.ts @@ -1,4 +1,5 @@ import type { IStateManager } from '@metamask/snap-networks-utils'; +import { hasProperty } from '@metamask/utils'; import type { ConfirmedSubscription, @@ -69,7 +70,7 @@ export class SubscriptionRepository { return subscriptions.find( (subscription) => - key in subscription && + hasProperty(subscription, key) && subscription[key as keyof Subscription] === value, ); } diff --git a/packages/solana-wallet-snap/src/core/services/subscriptions/SubscriptionService.test.ts b/packages/solana-wallet-snap/src/core/services/subscriptions/SubscriptionService.test.ts index 61edcbe11..bf84f6ff5 100644 --- a/packages/solana-wallet-snap/src/core/services/subscriptions/SubscriptionService.test.ts +++ b/packages/solana-wallet-snap/src/core/services/subscriptions/SubscriptionService.test.ts @@ -45,9 +45,10 @@ const createMockConfirmationMessage = ( const createMockUnsubscriptionConfirmationMessage = ( id: string = globalThis.crypto.randomUUID(), -) => ({ +): WebSocketMessage => ({ type: 'message', id, + origin: 'some-origin', data: { type: 'text', message: JSON.stringify({ jsonrpc: '2.0', id, result: true }), @@ -57,8 +58,8 @@ const createMockUnsubscriptionConfirmationMessage = ( const createMockNotificationMessage = ( id: string = globalThis.crypto.randomUUID(), rpcSubscriptionId = 98765, - result: any = {}, -) => ({ + result: unknown = {}, +): WebSocketMessage => ({ type: 'message', id, origin: 'some-origin', @@ -73,11 +74,12 @@ const createMockNotificationMessage = ( }); const createMockFailureMessage = ( - error: any, + error: unknown, id: string = globalThis.crypto.randomUUID(), -) => ({ +): WebSocketMessage => ({ type: 'message', id, + origin: 'some-origin', data: { type: 'text', message: JSON.stringify({ @@ -91,7 +93,7 @@ const createMockFailureMessage = ( const simulateDisconnection = async ( eventEmitter: EventEmitter, connectionId: string, -) => { +): Promise => { await eventEmitter.emitSync('onWebSocketEvent', { event: { type: 'close', @@ -103,7 +105,7 @@ const simulateDisconnection = async ( const simulateReconnection = async ( eventEmitter: EventEmitter, connectionId: string, -) => { +): Promise => { await eventEmitter.emitSync('onWebSocketEvent', { event: { type: 'open', @@ -115,7 +117,7 @@ const simulateReconnection = async ( const triggerConnectionRecoveryHandlers = async ( connectionRecoveryHandlers: Map, network: Network, -) => { +): Promise => { const recoveryHandlers = connectionRecoveryHandlers.get(network) ?? []; await Promise.all( recoveryHandlers.map(async (handler) => { @@ -149,19 +151,23 @@ describe('SubscriptionService', () => { const snap = { request: vi.fn(), }; - (globalThis as any).snap = snap; + (globalThis as unknown as { snap: typeof snap }).snap = snap; mockWebSocketConnectionService = { openConnection: vi.fn(), findById: vi.fn().mockReturnValue(mockConnection), findByNetwork: vi.fn().mockReturnValue(mockConnection), // Allows to capture the connection recovery handlers to trigger them manually - onConnectionRecovery: vi.fn().mockImplementation((network, handler) => { - connectionRecoveryHandlers.set(network, [ - ...(connectionRecoveryHandlers.get(network) ?? []), - handler, - ]); - }), + onConnectionRecovery: vi + .fn() + .mockImplementation( + (network: Network, handler: ConnectionRecoveryHandler) => { + connectionRecoveryHandlers.set(network, [ + ...(connectionRecoveryHandlers.get(network) ?? []), + handler, + ]); + }, + ), handleConnectionEvent: vi.fn(), } as unknown as WebSocketConnectionService; diff --git a/packages/solana-wallet-snap/src/core/services/subscriptions/SubscriptionService.ts b/packages/solana-wallet-snap/src/core/services/subscriptions/SubscriptionService.ts index a81374251..45b514e2d 100644 --- a/packages/solana-wallet-snap/src/core/services/subscriptions/SubscriptionService.ts +++ b/packages/solana-wallet-snap/src/core/services/subscriptions/SubscriptionService.ts @@ -1,7 +1,7 @@ import type { Logger } from '@metamask/snap-networks-utils'; /* eslint-disable @typescript-eslint/no-non-null-assertion */ import type { WebSocketEvent } from '@metamask/snaps-sdk'; -import { isJsonRpcFailure } from '@metamask/utils'; +import { hasProperty, isJsonRpcFailure } from '@metamask/utils'; import type { JsonRpcFailure } from '@metamask/utils'; import type { JsonRpcRequest } from '@metamask/utils'; @@ -23,6 +23,16 @@ import { parseWebSocketMessage } from './parseWebSocketMessage'; import type { SubscriptionRepository } from './SubscriptionRepository'; import type { WebSocketConnectionService } from './WebSocketConnectionService'; +/** + * A notification handler widened to the signature used for dispatch. Handlers are + * registered per method, so the notification type always matches the handler's own + * parameter type. + */ +type DispatchableNotificationHandler = ( + notification: Notification, + subscription: Subscription, +) => Promise; + /** * Allows subscribing / unsubscribing from real-time notifications from the Solana blockchain using the [RPC WebSocket API](https://solana.com/docs/rpc/websocket). * @@ -177,7 +187,9 @@ export class SubscriptionService { const connection = await this.#connectionService.findByNetwork(network); - const sendSubscriptionMessage = async (_connectionId: string) => { + const sendSubscriptionMessage = async ( + _connectionId: string, + ): Promise => { const message: JsonRpcRequest = { jsonrpc: '2.0', id, @@ -294,7 +306,10 @@ export class SubscriptionService { if (handlers && handlers.size > 0) { const results = await Promise.allSettled( Array.from(handlers).map(async (handler) => - handler(notification as any, subscription), + (handler as DispatchableNotificationHandler)( + notification, + subscription, + ), ), ); @@ -339,13 +354,13 @@ export class SubscriptionService { * @returns True if the message is a subscription confirmation, false otherwise. */ #isSubscriptionConfirmation( - message: any, + message: object, ): message is SubscriptionConfirmation { return ( - 'jsonrpc' in message && + hasProperty(message, 'jsonrpc') && message.jsonrpc === '2.0' && - 'id' in message && - 'result' in message && + hasProperty(message, 'id') && + hasProperty(message, 'result') && typeof message.result === 'number' ); } @@ -357,12 +372,12 @@ export class SubscriptionService { * @returns True if the message is a unsubscription confirmation, false otherwise. */ #isUnsubscriptionConfirmation( - message: any, + message: object, ): message is UnsubscriptionConfirmation { return ( - 'jsonrpc' in message && - 'id' in message && - 'result' in message && + hasProperty(message, 'jsonrpc') && + hasProperty(message, 'id') && + hasProperty(message, 'result') && message.result === true ); } @@ -450,7 +465,7 @@ export class SubscriptionService { * @param response - The response to handle. */ async #handleFailure(response: JsonRpcFailure): Promise { - if ('id' in response && response.id !== undefined) { + if (hasProperty(response, 'id') && response.id !== undefined) { // This is a response to a specific subscription request, expect the error to be related to a pending subscription. const subscription = await this.#subscriptionRepository.getById( String(response.id), @@ -517,7 +532,7 @@ export class SubscriptionService { * @param obj - The object to stringify deterministically. * @returns A deterministic JSON string representation. */ - #deterministicStringify(obj: any): string { + #deterministicStringify(obj: unknown): string { if (obj === null || obj === undefined) { return JSON.stringify(obj); } @@ -528,14 +543,15 @@ export class SubscriptionService { if (Array.isArray(obj)) { return `[${obj - .map((item) => this.#deterministicStringify(item)) + .map((item: unknown) => this.#deterministicStringify(item)) .join(',')}]`; } // For objects, sort keys and recursively stringify values - const sortedKeys = Object.keys(obj).sort((a, b) => a.localeCompare(b)); + const record = obj as Record; + const sortedKeys = Object.keys(record).sort((a, b) => a.localeCompare(b)); const pairs = sortedKeys.map((key) => { - const value = this.#deterministicStringify(obj[key]); + const value = this.#deterministicStringify(record[key]); return `"${key}":${value}`; }); @@ -578,7 +594,9 @@ export class SubscriptionService { await this.#subscriptionRepository.getAll() ) .filter((subscription) => subscription.network === network) - .filter(SubscriptionService.#isNotExpired); + .filter((subscription) => + SubscriptionService.#isNotExpired(subscription), + ); const ids = subscriptionsThisNetwork.map((subscription) => subscription.id); await this.#subscriptionRepository.deleteMany(ids); @@ -601,8 +619,8 @@ export class SubscriptionService { const subscriptions = await this.#subscriptionRepository.getAll(); - const expiredSubscriptions = subscriptions.filter( - SubscriptionService.#isExpired, + const expiredSubscriptions = subscriptions.filter((subscription) => + SubscriptionService.#isExpired(subscription), ); await Promise.allSettled( diff --git a/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionRepository.test.ts b/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionRepository.test.ts index 00225b370..fd344224f 100644 --- a/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionRepository.test.ts +++ b/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionRepository.test.ts @@ -20,10 +20,9 @@ describe('WebSocketConnectionRepository', () => { repository = new WebSocketConnectionRepository(mockConfigProvider); - const snap = { + (globalThis as unknown as { snap: unknown }).snap = { request: vi.fn(), }; - (globalThis as any).snap = snap; }); describe('getAll', () => { diff --git a/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionRepository.ts b/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionRepository.ts index 0b0606de9..3693bf71b 100644 --- a/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionRepository.ts +++ b/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionRepository.ts @@ -92,7 +92,7 @@ export class WebSocketConnectionRepository { * * @param id - The ID of the connection to close. */ - async delete(id: string) { + async delete(id: string): Promise { await snap.request({ method: 'snap_closeWebSocket', params: { id }, diff --git a/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionService.test.ts b/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionService.test.ts index e5ade5916..10b0b7b7c 100644 --- a/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionService.test.ts +++ b/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionService.test.ts @@ -62,7 +62,7 @@ describe('WebSocketConnectionService', () => { vi.clearAllMocks(); vi.spyOn(Errors, 'trackError').mockResolvedValue('tracked-error-id'); - (globalThis as any).snap = { + (globalThis as unknown as { snap: unknown }).snap = { request: vi.fn(), }; @@ -493,21 +493,44 @@ describe('WebSocketConnectionService', () => { }); describe('background event scheduling', () => { + const removedBackgroundEventId = 'existing-event-id'; + const removedEventMessage = `A background event with the id of "${removedBackgroundEventId}" does not exist.`; + it.each([ - { event: 'onActive', asRpcError: false }, - { event: 'onActive', asRpcError: true }, - { event: 'onInactive', asRpcError: false }, - { event: 'onInactive', asRpcError: true }, + { + event: 'onActive', + asRpcError: false, + error: new Error(removedEventMessage), + openConnectionCalls: 2, + requestCalls: 1, + }, + { + event: 'onActive', + asRpcError: true, + error: { code: -32603, message: removedEventMessage }, + openConnectionCalls: 2, + requestCalls: 1, + }, + { + event: 'onInactive', + asRpcError: false, + error: new Error(removedEventMessage), + openConnectionCalls: 0, + requestCalls: 2, + }, + { + event: 'onInactive', + asRpcError: true, + error: { code: -32603, message: removedEventMessage }, + openConnectionCalls: 0, + requestCalls: 2, + }, ])( 'does not track an already-removed background event on $event (RPC error: $asRpcError)', - async ({ event, asRpcError }) => { - const existingEventId = 'existing-event-id'; - const message = `A background event with the id of "${existingEventId}" does not exist.`; - const error = asRpcError - ? { code: -32603, message } - : new Error(message); - - vi.spyOn(mockState, 'getKey').mockResolvedValueOnce(existingEventId); + async ({ event, error, openConnectionCalls, requestCalls }) => { + vi.spyOn(mockState, 'getKey').mockResolvedValueOnce( + removedBackgroundEventId, + ); vi.spyOn(snap, 'request') .mockRejectedValueOnce(error) .mockResolvedValueOnce('new-event-id'); @@ -523,11 +546,9 @@ describe('WebSocketConnectionService', () => { null, ); expect(service.openConnection).toHaveBeenCalledTimes( - event === 'onActive' ? 2 : 0, - ); - expect(snap.request).toHaveBeenCalledTimes( - event === 'onActive' ? 1 : 2, + openConnectionCalls, ); + expect(snap.request).toHaveBeenCalledTimes(requestCalls); }, ); diff --git a/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionService.ts b/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionService.ts index 02b61a7cc..ce7e5fdcd 100644 --- a/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionService.ts +++ b/packages/solana-wallet-snap/src/core/services/subscriptions/WebSocketConnectionService.ts @@ -278,7 +278,7 @@ export class WebSocketConnectionService { await this.#handleDisconnected(event); break; default: - this.#logger.warn(`Unknown connection event type: ${type}`); + this.#logger.warn(`Unknown connection event type: ${String(type)}`); } } diff --git a/packages/solana-wallet-snap/src/core/services/subscriptions/parseWebSocketMessage.ts b/packages/solana-wallet-snap/src/core/services/subscriptions/parseWebSocketMessage.ts index 18d2f6c0d..37eb4205e 100644 --- a/packages/solana-wallet-snap/src/core/services/subscriptions/parseWebSocketMessage.ts +++ b/packages/solana-wallet-snap/src/core/services/subscriptions/parseWebSocketMessage.ts @@ -1,4 +1,5 @@ import type { WebSocketMessage } from '@metamask/snaps-sdk'; +import { hasProperty } from '@metamask/utils'; /** * A message that we receive from the RPC WebSocket server after a subscription is confirmed. @@ -17,10 +18,10 @@ export const parseWebSocketMessage = ( event: WebSocketMessage, ): JsonRpcWebSocketMessage => { const { data } = event; - let jsonParsed: any; + let jsonParsed: unknown; // Handle SIP-20 message format - if (data && typeof data === 'object' && 'type' in data) { + if (data && typeof data === 'object' && hasProperty(data, 'type')) { // This is already a SIP-20 formatted message data if (data.type === 'text') { jsonParsed = @@ -40,5 +41,5 @@ export const parseWebSocketMessage = ( jsonParsed = typeof data === 'string' ? JSON.parse(data) : data; } - return jsonParsed; + return jsonParsed as JsonRpcWebSocketMessage; };