diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json index 7a5989182..939c3ed55 100644 --- a/oxlint-suppressions.json +++ b/oxlint-suppressions.json @@ -826,7 +826,7 @@ }, "packages/solana-wallet-snap/src/core/services/transaction-scan/TransactionScanService.ts": { "internal-snaps/no-in-operator": { - "count": 2 + "count": 1 }, "typescript/no-unsafe-assignment": { "count": 1 @@ -1209,6 +1209,16 @@ "count": 2 } }, + "packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/SecurityScanAlert.tsx": { + "typescript/no-unsafe-return": { + "count": 2 + } + }, + "packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/TransactionFailureAlert.tsx": { + "typescript/no-unsafe-return": { + "count": 1 + } + }, "packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/events.tsx": { "typescript/no-unsafe-argument": { "count": 1 diff --git a/packages/solana-wallet-snap/CHANGELOG.md b/packages/solana-wallet-snap/CHANGELOG.md index c57b4ded9..aed543aa2 100644 --- a/packages/solana-wallet-snap/CHANGELOG.md +++ b/packages/solana-wallet-snap/CHANGELOG.md @@ -25,6 +25,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- Align Solana transaction security alerts with the shared transaction warning contract ([#617](https://github.com/MetaMask/internal-snaps/pull/617)) - Update Solana confirmation copy to match the shared wording ([#614](https://github.com/MetaMask/internal-snaps/pull/614)) - Report Solana RPC, Price API, Token API, NFT API and Security Alerts API outages through the shared fetch policy ([#583](https://github.com/MetaMask/internal-snaps/pull/583)) - Slow or failing requests now emit `Snap Service Degraded` and `Snap Service Unavailable` Segment events, and give-ups are sent to Sentry without URLs, request params or response data. diff --git a/packages/solana-wallet-snap/src/core/handlers/onCronjob/backgroundEvents/refreshConfirmationEstimation.test.tsx b/packages/solana-wallet-snap/src/core/handlers/onCronjob/backgroundEvents/refreshConfirmationEstimation.test.tsx index 422fe07b7..47379f384 100644 --- a/packages/solana-wallet-snap/src/core/handlers/onCronjob/backgroundEvents/refreshConfirmationEstimation.test.tsx +++ b/packages/solana-wallet-snap/src/core/handlers/onCronjob/backgroundEvents/refreshConfirmationEstimation.test.tsx @@ -19,9 +19,8 @@ import { state, } from '../../../../snapContext'; import { Network } from '../../../constants/solana'; -import { EXPIRED_TRANSACTION_SCAN } from '../../../services/transaction-scan/buildExpiredScanResult'; -import { isTransactionBlockhashExpired } from '../../../services/transaction-scan/isTransactionBlockhashExpired'; -import * as BlockhashExpired from '../../../services/transaction-scan/isTransactionBlockhashExpired'; +import { isTransactionBlockhashExpired } from '../../../services/confirmation/isTransactionBlockhashExpired'; +import * as BlockhashExpired from '../../../services/confirmation/isTransactionBlockhashExpired'; import * as Errors from '../../../utils/errors'; import { trackError } from '../../../utils/errors'; import { @@ -81,7 +80,7 @@ describe('refreshConfirmationEstimation', () => { vi.spyOn(Errors, 'trackError').mockResolvedValue('tracked-error-id'); }); - it('disables confirmation with an expired scan result for an invalid blockhash', async () => { + it('stores local expiry separately without replacing the API scan', async () => { setupTest(); (transactionScanService.scanTransaction as Mock).mockResolvedValue({ @@ -97,36 +96,74 @@ describe('refreshConfirmationEstimation', () => { 'interface-id', null, expect.objectContaining({ - scan: EXPIRED_TRANSACTION_SCAN, + transactionExpired: true, + scan: { status: 'SUCCESS' }, scanFetchStatus: 'fetched', }), ); }); - it('persists local expiry as transactionExpired', async () => { + it('tracks unexpected refresh failures and restores the fetched state', async () => { setupTest(); - (transactionScanService.scanTransaction as Mock).mockResolvedValue({ - status: 'SUCCESS', - }); - vi.mocked(isTransactionBlockhashExpired).mockResolvedValue(true); + const error = new Error('Scan failed'); + + (transactionScanService.scanTransaction as Mock).mockRejectedValue(error); await refreshConfirmationEstimation({ request: {} as JsonRpcRequest, }); + expect(trackError).toHaveBeenCalledWith(error); expect(updateInterface).toHaveBeenLastCalledWith( 'interface-id', null, expect.objectContaining({ - scan: EXPIRED_TRANSACTION_SCAN, scanFetchStatus: 'fetched', + }), + ); + }); + + it('checks blockhash expiry when simulation is disabled', async () => { + const interfaceContext = setupTest(); + + interfaceContext.preferences = { + simulateOnChainActions: false, + }; + (getInterfaceContext as Mock).mockResolvedValue(interfaceContext); + vi.mocked(isTransactionBlockhashExpired).mockResolvedValue(true); + + await refreshConfirmationEstimation({ + request: {} as JsonRpcRequest, + }); + + expect(transactionScanService.scanTransaction).not.toHaveBeenCalled(); + expect(isTransactionBlockhashExpired).toHaveBeenCalled(); + expect(updateInterface).toHaveBeenCalledWith( + 'interface-id', + null, + expect.objectContaining({ transactionExpired: true, + scanFetchStatus: 'fetched', }), ); }); - it('keeps a known local expiry when the next scan fails', async () => { + it('does not check blockhash expiry for MetaMask-origin transactions', async () => { + const interfaceContext = { + ...setupTest(), + origin: DEFAULT_METAMASK_ORIGIN, + }; + (getInterfaceContext as Mock).mockResolvedValue(interfaceContext); + + await refreshConfirmationEstimation({ + request: {} as JsonRpcRequest, + }); + + expect(isTransactionBlockhashExpired).not.toHaveBeenCalled(); + }); + + it('keeps a known local expiry when the next scan and expiry RPC are unavailable', async () => { const interfaceContext = { ...setupTest(), transactionExpired: true }; (getInterfaceContext as Mock).mockResolvedValue(interfaceContext); (transactionScanService.scanTransaction as Mock).mockResolvedValue(null); @@ -140,9 +177,121 @@ describe('refreshConfirmationEstimation', () => { 'interface-id', null, expect.objectContaining({ - scan: EXPIRED_TRANSACTION_SCAN, - scanFetchStatus: 'fetched', transactionExpired: true, + scanFetchStatus: 'error', + }), + ); + }); + + it('preserves a newly detected expiry when the scan is unavailable', async () => { + setupTest(); + (transactionScanService.scanTransaction as Mock).mockResolvedValue(null); + vi.mocked(isTransactionBlockhashExpired).mockResolvedValue(true); + + await refreshConfirmationEstimation({ + request: {} as JsonRpcRequest, + }); + + expect(updateInterface).toHaveBeenLastCalledWith( + 'interface-id', + null, + expect.objectContaining({ + transactionExpired: true, + scanFetchStatus: 'error', + }), + ); + }); + + it('re-scans validation-only and preserves the scan result without a fetching state when simulation is disabled', async () => { + const existingScan = { status: 'SUCCESS' }; + const interfaceContext = { + ...setupTest(), + preferences: { simulateOnChainActions: false, useSecurityAlerts: true }, + scan: existingScan, + }; + + (getInterfaceContext as Mock).mockResolvedValue(interfaceContext); + (transactionScanService.scanTransaction as Mock).mockResolvedValue({ + status: 'SUCCESS', + }); + + await refreshConfirmationEstimation({ + request: {} as JsonRpcRequest, + }); + + expect(transactionScanService.scanTransaction).toHaveBeenCalledTimes(1); + expect(transactionScanService.scanTransaction).toHaveBeenCalledWith( + expect.objectContaining({ options: ['validation'] }), + ); + expect(updateInterface).not.toHaveBeenCalledWith( + 'interface-id', + null, + expect.objectContaining({ scanFetchStatus: 'fetching' }), + ); + expect(updateInterface).toHaveBeenLastCalledWith( + 'interface-id', + null, + expect.objectContaining({ + scan: { status: 'SUCCESS' }, + scanFetchStatus: 'fetched', + }), + ); + }); + + it('re-scans with preference-respecting options when simulation is enabled', async () => { + setupTest(); + + (transactionScanService.scanTransaction as Mock).mockResolvedValue({ + status: 'SUCCESS', + }); + + await refreshConfirmationEstimation({ + request: {} as JsonRpcRequest, + }); + + expect(transactionScanService.scanTransaction).toHaveBeenCalledWith( + expect.objectContaining({ options: ['simulation'] }), + ); + }); + + it('never sets the fetching state while re-scanning so confirm stays enabled', async () => { + setupTest(); + + (transactionScanService.scanTransaction as Mock).mockImplementation( + () => + new Promise((resolve) => { + // The scan is in flight while the pre-scan interface update happens. + setTimeout(() => resolve({ status: 'SUCCESS' }), 50); + }), + ); + + await refreshConfirmationEstimation({ + request: {} as JsonRpcRequest, + }); + + expect(updateInterface).not.toHaveBeenCalledWith( + 'interface-id', + null, + expect.objectContaining({ scanFetchStatus: 'fetching' }), + ); + expect(updateInterface).toHaveBeenCalledTimes(1); + }); + + it('marks the scan as errored without blocking confirm when the re-scan fails', async () => { + setupTest(); + + (transactionScanService.scanTransaction as Mock).mockResolvedValue(null); + + await refreshConfirmationEstimation({ + request: {} as JsonRpcRequest, + }); + + expect(updateInterface).toHaveBeenLastCalledWith( + 'interface-id', + null, + expect.objectContaining({ + scan: null, + scanFetchStatus: 'error', }), ); }); @@ -171,7 +320,7 @@ describe('refreshConfirmationEstimation', () => { null, expect.objectContaining({ scan: maliciousScan, - scanFetchStatus: 'fetched', + scanFetchStatus: 'error', }), ); }); @@ -200,11 +349,11 @@ describe('refreshConfirmationEstimation', () => { scan: maliciousScan, }); (transactionScanService.scanTransaction as Mock).mockResolvedValue({ - status: 'SUCCESS', + status: 'ERROR', estimatedChanges: { assets: refreshedAssets }, validation: { type: null, reason: null }, error: null, - validationError: null, + validationError: { type: 'validation', code: null, message: null }, }); await refreshConfirmationEstimation({ @@ -215,10 +364,13 @@ describe('refreshConfirmationEstimation', () => { 'interface-id', null, expect.objectContaining({ - scan: expect.objectContaining({ + scan: { + status: 'ERROR', estimatedChanges: { assets: refreshedAssets }, validation: maliciousScan.validation, - }), + error: null, + validationError: null, + }, }), ); }); @@ -252,59 +404,6 @@ describe('refreshConfirmationEstimation', () => { ); }); - it('does not set a fetching state during a background re-scan', async () => { - setupTest(); - (transactionScanService.scanTransaction as Mock).mockResolvedValue({ - status: 'SUCCESS', - }); - - await refreshConfirmationEstimation({ - request: {} as JsonRpcRequest, - }); - - expect(transactionScanService.scanTransaction).toHaveBeenCalled(); - expect(updateInterface).not.toHaveBeenCalledWith( - 'interface-id', - null, - expect.objectContaining({ scanFetchStatus: 'fetching' }), - ); - expect(updateInterface).toHaveBeenLastCalledWith( - 'interface-id', - null, - expect.objectContaining({ scanFetchStatus: 'fetched' }), - ); - }); - - it('applies the re-scan result only after the interface lock is released', async () => { - setupTest(); - (transactionScanService.scanTransaction as Mock).mockResolvedValue({ - status: 'SUCCESS', - }); - - let releaseLock!: () => void; - const heldLock = withInterfaceLock('interface-id', async () => { - await new Promise((resolve) => { - releaseLock = resolve; - }); - }); - - const refresh = refreshConfirmationEstimation({ - request: {} as JsonRpcRequest, - }); - await new Promise((resolve) => setTimeout(resolve, 10)); - - expect(updateInterface).not.toHaveBeenCalled(); - - releaseLock(); - await Promise.all([heldLock, refresh]); - - expect(updateInterface).toHaveBeenCalledWith( - 'interface-id', - null, - expect.objectContaining({ scanFetchStatus: 'fetched' }), - ); - }); - it('does not confirm an expired transaction after a refresh persists the expiry', async () => { setupTest(); (transactionScanService.scanTransaction as Mock).mockResolvedValue({ @@ -333,93 +432,33 @@ describe('refreshConfirmationEstimation', () => { expect(resolveSpy).not.toHaveBeenCalled(); }); - it('tracks refresh failures and restores the fetched state', async () => { + it('applies the re-scan result only after the interface lock is released', async () => { setupTest(); - - const error = new Error('Scan failed'); - - (transactionScanService.scanTransaction as Mock).mockRejectedValue(error); - - await refreshConfirmationEstimation({ - request: {} as JsonRpcRequest, + (transactionScanService.scanTransaction as Mock).mockResolvedValue({ + status: 'SUCCESS', }); - expect(trackError).toHaveBeenCalledWith(error); - expect(updateInterface).toHaveBeenLastCalledWith( - 'interface-id', - null, - expect.objectContaining({ - scanFetchStatus: 'fetched', - }), - ); - }); - - it('checks blockhash expiry when simulation is disabled', async () => { - const interfaceContext = setupTest(); - - interfaceContext.preferences = { - simulateOnChainActions: false, - }; - (getInterfaceContext as Mock).mockResolvedValue(interfaceContext); - vi.mocked(isTransactionBlockhashExpired).mockResolvedValue(true); - - await refreshConfirmationEstimation({ - request: {} as JsonRpcRequest, + let releaseLock!: () => void; + const heldLock = withInterfaceLock('interface-id', async () => { + await new Promise((resolve) => { + releaseLock = resolve; + }); }); - expect(transactionScanService.scanTransaction).not.toHaveBeenCalled(); - expect(isTransactionBlockhashExpired).toHaveBeenCalled(); - expect(updateInterface).toHaveBeenCalledWith( - 'interface-id', - null, - expect.objectContaining({ - scan: EXPIRED_TRANSACTION_SCAN, - scanFetchStatus: 'fetched', - }), - ); - }); - - it('does not check blockhash expiry for MetaMask-origin transactions', async () => { - const interfaceContext = { - ...setupTest(), - origin: DEFAULT_METAMASK_ORIGIN, - }; - (getInterfaceContext as Mock).mockResolvedValue(interfaceContext); - - await refreshConfirmationEstimation({ + const refresh = refreshConfirmationEstimation({ request: {} as JsonRpcRequest, }); + await new Promise((resolve) => setTimeout(resolve, 10)); - expect(isTransactionBlockhashExpired).not.toHaveBeenCalled(); - }); - - it('preserves the existing scan without a fetching state while checking a valid blockhash without simulation', async () => { - const existingScan = { status: 'SUCCESS' }; - const interfaceContext = { - ...setupTest(), - preferences: { simulateOnChainActions: false, useSecurityAlerts: true }, - scan: existingScan, - }; - - (getInterfaceContext as Mock).mockResolvedValue(interfaceContext); + expect(updateInterface).not.toHaveBeenCalled(); - await refreshConfirmationEstimation({ - request: {} as JsonRpcRequest, - }); + releaseLock(); + await Promise.all([heldLock, refresh]); - expect(transactionScanService.scanTransaction).not.toHaveBeenCalled(); - expect(updateInterface).not.toHaveBeenCalledWith( - 'interface-id', - null, - expect.objectContaining({ scanFetchStatus: 'fetching' }), - ); - expect(updateInterface).toHaveBeenLastCalledWith( + expect(updateInterface).toHaveBeenCalledWith( 'interface-id', null, - expect.objectContaining({ - scan: existingScan, - scanFetchStatus: 'fetched', - }), + expect.objectContaining({ scanFetchStatus: 'fetched' }), ); }); }); diff --git a/packages/solana-wallet-snap/src/core/handlers/onCronjob/backgroundEvents/refreshConfirmationEstimation.tsx b/packages/solana-wallet-snap/src/core/handlers/onCronjob/backgroundEvents/refreshConfirmationEstimation.tsx index 2abab7275..0e0871c73 100644 --- a/packages/solana-wallet-snap/src/core/handlers/onCronjob/backgroundEvents/refreshConfirmationEstimation.tsx +++ b/packages/solana-wallet-snap/src/core/handlers/onCronjob/backgroundEvents/refreshConfirmationEstimation.tsx @@ -1,4 +1,5 @@ import { DEFAULT_METAMASK_ORIGIN } from '@metamask/snap-networks-utils'; +import type { SecurityAlertsScanOption } from '@metamask/snap-networks-utils'; import type { OnCronjobHandler } from '@metamask/snaps-sdk'; import { ConfirmTransactionRequest } from '../../../../features/confirmation/views/ConfirmTransactionRequest/ConfirmTransactionRequest'; @@ -9,9 +10,8 @@ import { state, transactionScanService, } from '../../../../snapContext'; +import { isTransactionBlockhashExpired } from '../../../services/confirmation/isTransactionBlockhashExpired'; import type { UnencryptedStateValue } from '../../../services/state/stateTypes'; -import { EXPIRED_TRANSACTION_SCAN } from '../../../services/transaction-scan/buildExpiredScanResult'; -import { isTransactionBlockhashExpired } from '../../../services/transaction-scan/isTransactionBlockhashExpired'; import type { TransactionScanResult } from '../../../services/transaction-scan/types'; import { trackError } from '../../../utils/errors'; import { @@ -24,9 +24,10 @@ import baseLogger from '../../../utils/logger'; import { ScheduleBackgroundEventMethod } from './ScheduleBackgroundEventMethod'; /** - * Returns the scan to store after a refresh. The simulation data always comes - * from the refresh, but a refresh without a validation verdict keeps the latest - * verdict, so a known malicious verdict is not lost. + * Returns the scan to store after a refresh. A refresh without a validation + * verdict keeps the latest verdict, so a known malicious verdict is not lost. + * The refresh's validation error is dropped in that case, so the known verdict + * is shown instead of an unavailable notice. * * @param latestScan - The scan stored before this refresh. * @param refreshedScan - The scan produced by this refresh. @@ -39,7 +40,11 @@ function keepKnownVerdict( const knownValidation = latestScan?.validation; if (!refreshedScan.validation?.type && knownValidation?.type) { - return { ...refreshedScan, validation: knownValidation }; + return { + ...refreshedScan, + validation: knownValidation, + validationError: null, + }; } return refreshedScan; @@ -87,22 +92,31 @@ export const refreshConfirmationEstimation: OnCronjobHandler = async () => { return; } - const shouldScan = Boolean( - interfaceContext.preferences?.simulateOnChainActions, - ); + // Re-scan with the same options the initial scan used, per preference: + // simulation only when simulation is enabled, validation only when + // security alerts are enabled. + const options: SecurityAlertsScanOption[] = []; + if (interfaceContext.preferences?.simulateOnChainActions) { + options.push('simulation'); + } + if (interfaceContext.preferences?.useSecurityAlerts) { + options.push('validation'); + } + const shouldScan = options.length > 0; // MetaMask-originated transactions receive a fresh blockhash before signing. const shouldSkipBlockhashCheck = interfaceContext.origin === DEFAULT_METAMASK_ORIGIN; - // Background refreshes never set `fetching`. Only the initial load does, so - // Confirm and an open acknowledgement stay usable while a refresh runs. + // Background re-scans never surface the scan-in-progress state: per the + // transaction warning contract, they must never disable confirm. The + // interface is only updated once the re-scan settles. if (!shouldScan) { logger.info(`Transaction simulation is disabled in preferences`); } - // The scan and expiry check run outside the interface lock because they can - // take a while. Only the read-merge-write below runs under the lock. + // The scan and expiry check run outside the interface lock because they + // can take a while. Only the read-merge-write below runs under the lock. const [scan, isExpired] = await Promise.all([ shouldScan ? transactionScanService.scanTransaction({ @@ -112,8 +126,9 @@ export const refreshConfirmationEstimation: OnCronjobHandler = async () => { scope: interfaceContext.scope, origin: interfaceContext.origin, account: interfaceContext.account, + options, }) - : Promise.resolve(undefined), + : Promise.resolve(null), shouldSkipBlockhashCheck ? Promise.resolve(false) : isTransactionBlockhashExpired( @@ -122,8 +137,9 @@ export const refreshConfirmationEstimation: OnCronjobHandler = async () => { ), ]); - // Merge the result into the latest context under the lock, so a handler's - // update made while the scan was pending is kept. + // Read and write the latest context under the lock. A handler, such as the + // user opening acknowledgement, may update the interface while the scan is + // running. Writing a context captured before the scan would overwrite it. const isUpdated = await withInterfaceLock( confirmationInterfaceId, async () => { @@ -140,27 +156,21 @@ export const refreshConfirmationEstimation: OnCronjobHandler = async () => { return false; } - // Local expiry is sticky: once detected, neither a later check nor a - // failed scan clears it. - const transactionExpired = - isExpired || latestInterfaceContext.transactionExpired === true; - - // Keep the latest scan unless this refresh produced one. A failed refresh - // returns null, so it keeps the latest scan too. Local expiry takes - // precedence, so its blocking state stays in place. - let updatedScan = latestInterfaceContext.scan; - if (scan) { - updatedScan = keepKnownVerdict(latestInterfaceContext.scan, scan); - } - if (transactionExpired) { - updatedScan = EXPIRED_TRANSACTION_SCAN; - } + // Retain estimates after an outage, but do not reuse a stale execution + // failure as a blocker. Local expiry remains independent and cannot be + // cleared by a later failed scan or inconclusive blockhash check. + const scanFailed = shouldScan && scan === null; const updatedInterfaceContext = { ...latestInterfaceContext, - scanFetchStatus: 'fetched' as const, - scan: updatedScan, - transactionExpired, + scanFetchStatus: scanFailed + ? ('error' as const) + : ('fetched' as const), + scan: scan + ? keepKnownVerdict(latestInterfaceContext.scan, scan) + : (latestInterfaceContext.scan ?? null), + transactionExpired: + isExpired || latestInterfaceContext.transactionExpired === true, }; if (shouldScan) { @@ -199,7 +209,8 @@ export const refreshConfirmationEstimation: OnCronjobHandler = async () => { await trackError(error); // Roll back under the lock so a handler's concurrent update is not - // overwritten. Nothing is rolled back if the UI was closed. + // overwritten. Check if context exists in case the UI was closed, in which + // case there is nothing to roll back. const isRolledBack = await withInterfaceLock( confirmationInterfaceId, async () => { @@ -213,7 +224,7 @@ export const refreshConfirmationEstimation: OnCronjobHandler = async () => { return false; } - const rolledBackConfirmationContext = { + const fetchingConfirmationContext = { ...fetchedInterfaceContext, scanFetchStatus: 'fetched', } as ConfirmTransactionRequestContext; @@ -221,9 +232,9 @@ export const refreshConfirmationEstimation: OnCronjobHandler = async () => { await updateInterface( confirmationInterfaceId, , - rolledBackConfirmationContext, + fetchingConfirmationContext, ); return true; diff --git a/packages/solana-wallet-snap/src/core/services/__mocks__/scanResponses.ts b/packages/solana-wallet-snap/src/core/services/__mocks__/scanResponses.ts index dbcfb6387..156b323cc 100644 --- a/packages/solana-wallet-snap/src/core/services/__mocks__/scanResponses.ts +++ b/packages/solana-wallet-snap/src/core/services/__mocks__/scanResponses.ts @@ -445,4 +445,5 @@ export const MOCK_SCAN_TRANSACTION_RESPONSE: TransactionScanResult & { }, validation: { type: 'Benign', reason: 'exposure_farming' }, error: null, + validationError: null, }; diff --git a/packages/solana-wallet-snap/src/core/services/transaction-scan/isTransactionBlockhashExpired.test.ts b/packages/solana-wallet-snap/src/core/services/confirmation/isTransactionBlockhashExpired.test.ts similarity index 100% rename from packages/solana-wallet-snap/src/core/services/transaction-scan/isTransactionBlockhashExpired.test.ts rename to packages/solana-wallet-snap/src/core/services/confirmation/isTransactionBlockhashExpired.test.ts diff --git a/packages/solana-wallet-snap/src/core/services/transaction-scan/isTransactionBlockhashExpired.ts b/packages/solana-wallet-snap/src/core/services/confirmation/isTransactionBlockhashExpired.ts similarity index 100% rename from packages/solana-wallet-snap/src/core/services/transaction-scan/isTransactionBlockhashExpired.ts rename to packages/solana-wallet-snap/src/core/services/confirmation/isTransactionBlockhashExpired.ts diff --git a/packages/solana-wallet-snap/src/core/services/transaction-scan/TransactionScanService.test.ts b/packages/solana-wallet-snap/src/core/services/transaction-scan/TransactionScanService.test.ts index 4737b3025..3dc3edde2 100644 --- a/packages/solana-wallet-snap/src/core/services/transaction-scan/TransactionScanService.test.ts +++ b/packages/solana-wallet-snap/src/core/services/transaction-scan/TransactionScanService.test.ts @@ -14,6 +14,7 @@ import type { SecurityAlertSimulationValidationResponse } from '../../clients/se import { Network } from '../../constants/solana'; import { MOCK_SOLANA_KEYRING_ACCOUNT_0 } from '../../test/mocks/solana-keyring-accounts'; import { TransactionScanService } from './TransactionScanService'; +import type { TransactionScanError, TransactionScanStatus } from './types'; describe('TransactionScan', () => { let transactionScanService: TransactionScanService; @@ -50,12 +51,418 @@ describe('TransactionScan', () => { }); describe('scanTransaction', () => { + it.each<{ + name: string; + response: SecurityAlertSimulationValidationResponse; + options: ('simulation' | 'validation')[]; + status: TransactionScanStatus; + error: TransactionScanError | null; + validationError?: TransactionScanError | null; + estimatedChanges?: unknown; + }>([ + { + name: 'an API error classified as an execution failure', + estimatedChanges: null, + response: { + status: 'ERROR', + error_details: { type: 'ApiError', message: 'Unavailable' }, + }, + options: ['simulation', 'validation'], + status: 'ERROR', + error: { + type: 'simulation', + code: null, + message: 'Unavailable', + }, + validationError: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + }, + { + name: 'an overall error with a verdict and no error details', + response: { + status: 'ERROR', + error: 'Request timed out', + result: { + simulation: {}, + validation: { result_type: 'Benign' }, + }, + }, + options: ['simulation', 'validation'], + status: 'ERROR', + error: null, + validationError: { + type: 'response', + code: null, + message: 'Request timed out', + }, + }, + { + name: 'an overall error without execution details', + estimatedChanges: null, + response: { status: 'ERROR' }, + options: ['simulation', 'validation'], + status: 'ERROR', + error: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + validationError: { type: 'response', code: null, message: null }, + }, + { + name: 'a validation error with a successful simulation', + response: { + status: 'SUCCESS', + result: { simulation: {}, validation: { result_type: 'Error' } }, + }, + options: ['simulation', 'validation'], + status: 'ERROR', + error: null, + validationError: { type: 'validation', code: null, message: null }, + }, + { + name: 'no requested results', + estimatedChanges: null, + response: { + status: 'SUCCESS', + result: { simulation: null, validation: null }, + }, + options: ['simulation', 'validation'], + status: 'ERROR', + error: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + validationError: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + }, + { + name: 'a missing result object', + estimatedChanges: null, + response: { status: 'SUCCESS' }, + options: ['simulation', 'validation'], + status: 'ERROR', + error: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + validationError: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + }, + { + name: 'a present validation section without a verdict', + response: { status: 'SUCCESS', result: { validation: {} } }, + options: ['validation'], + status: 'ERROR', + error: null, + validationError: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + }, + { + name: 'simulation only when requested', + response: { + status: 'SUCCESS', + result: { simulation: {}, validation: null }, + }, + options: ['simulation'], + status: 'SUCCESS', + error: null, + }, + { + name: 'validation only when requested', + response: { + status: 'SUCCESS', + result: { simulation: null, validation: { result_type: 'Benign' } }, + }, + options: ['validation'], + status: 'SUCCESS', + error: null, + }, + { + name: 'a missing verdict next to a successful simulation', + response: { + status: 'SUCCESS', + result: { simulation: {}, validation: null }, + }, + options: ['simulation', 'validation'], + status: 'ERROR', + error: null, + validationError: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + }, + { + name: 'a security verdict without requested simulation estimates', + response: { + status: 'SUCCESS', + result: { simulation: null, validation: { result_type: 'Benign' } }, + }, + options: ['simulation', 'validation'], + status: 'SUCCESS', + estimatedChanges: null, + error: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + }, + { + name: 'a missing simulation when only simulation was requested', + estimatedChanges: null, + response: { + status: 'SUCCESS', + result: { simulation: null, validation: null }, + }, + options: ['simulation'], + status: 'SUCCESS', + error: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + validationError: null, + }, + { + name: 'an unrequested result with the requested result missing', + response: { + status: 'SUCCESS', + result: { simulation: {}, validation: null }, + }, + options: ['validation'], + status: 'ERROR', + error: null, + validationError: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + }, + { + name: 'a transaction error with a null code', + estimatedChanges: null, + response: { + status: 'ERROR', + error_details: { + type: 'TransactionError', + message: 'Insufficient funds', + transaction_index: 0, + code: null, + }, + }, + options: ['simulation', 'validation'], + status: 'ERROR', + error: { + type: 'simulation', + code: null, + message: 'Insufficient funds', + }, + validationError: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + }, + { + name: 'an execution failure', + estimatedChanges: null, + response: { + status: 'ERROR', + error_details: { + type: 'TransactionError', + message: 'Insufficient funds', + transaction_index: 0, + code: 'ResultWithNegativeLamports', + }, + }, + options: ['simulation', 'validation'], + status: 'ERROR', + error: { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: 'Insufficient funds', + }, + validationError: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + }, + { + name: 'an execution failure with a successful security verdict', + response: { + status: 'ERROR', + error_details: { + type: 'TransactionError', + message: 'Insufficient funds', + transaction_index: 0, + code: 'ResultWithNegativeLamports', + }, + result: { + simulation: {}, + validation: { result_type: 'Benign' }, + }, + }, + options: ['simulation', 'validation'], + status: 'SUCCESS', + error: { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: 'Insufficient funds', + }, + validationError: null, + estimatedChanges: null, + }, + { + name: 'an instruction failure', + estimatedChanges: null, + response: { + status: 'ERROR', + error_details: { + type: 'InstructionError', + message: 'Failed instruction', + transaction_index: 0, + instruction_index: 0, + program_account: null, + }, + }, + options: ['simulation', 'validation'], + status: 'ERROR', + error: { + type: 'simulation', + code: null, + message: 'Failed instruction', + }, + validationError: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + }, + ])( + 'classifies $name independently of transaction validity', + async ({ + response, + options, + status, + error, + validationError = null, + estimatedChanges = expect.objectContaining({ + assets: expect.any(Array), + }), + }) => { + vi.mocked( + mockSecurityAlertsApiClient.scanTransaction, + ).mockResolvedValue(response); + + const scan = await transactionScanService.scanTransaction({ + method: 'signAndSendTransaction', + accountAddress: MOCK_SOLANA_KEYRING_ACCOUNT_0.address, + transaction: 'transaction', + scope: Network.Mainnet, + origin: 'metamask', + options, + }); + + expect(scan).toMatchObject({ + status, + error, + validationError, + }); + expect(scan).not.toHaveProperty('unavailable'); + expect(scan?.estimatedChanges).toStrictEqual(estimatedChanges); + }, + ); + + it('keeps simulated asset changes when only the security verdict fails', async () => { + vi.mocked(mockSecurityAlertsApiClient.scanTransaction).mockResolvedValue({ + status: 'SUCCESS', + result: { + simulation: { + account_summary: { + account_assets_diff: [ + { + asset_type: 'NativeToken', + asset: { type: 'NativeToken', decimals: 9, logo: null }, + in: { usd_price: 10, summary: null, value: 1, raw_value: 1 }, + out: null, + }, + ], + }, + }, + validation: { + result_type: 'Error', + reason: 'Validation unavailable', + }, + }, + }); + + const scan = await transactionScanService.scanTransaction({ + method: 'signAndSendTransaction', + accountAddress: MOCK_SOLANA_KEYRING_ACCOUNT_0.address, + transaction: 'transaction', + scope: Network.Mainnet, + origin: 'metamask', + options: ['simulation', 'validation'], + }); + + expect(scan).toMatchObject({ + status: 'ERROR', + validationError: { type: 'validation' }, + estimatedChanges: { + assets: [expect.objectContaining({ type: 'in', value: 1 })], + }, + }); + }); + + it('keeps the shared estimates container when only validation was requested', async () => { + vi.mocked(mockSecurityAlertsApiClient.scanTransaction).mockResolvedValue({ + status: 'SUCCESS', + result: { simulation: null, validation: { result_type: 'Benign' } }, + }); + + const result = await transactionScanService.scanTransaction({ + method: 'signAndSendTransaction', + accountAddress: MOCK_SOLANA_KEYRING_ACCOUNT_0.address, + transaction: 'transaction', + scope: Network.Mainnet, + origin: 'metamask', + options: ['validation'], + }); + + expect(result).not.toBeNull(); + expect(result?.estimatedChanges).toStrictEqual({ assets: [] }); + expect(Object.keys(result as object).sort()).toStrictEqual([ + 'error', + 'estimatedChanges', + 'status', + 'validation', + 'validationError', + ]); + }); + it('scans a transaction', async () => { vi.spyOn( mockSecurityAlertsApiClient, 'scanTransaction', ).mockResolvedValue({ status: 'SUCCESS', + result: { simulation: {}, validation: { result_type: 'Benign' } }, } as SecurityAlertSimulationValidationResponse); const result = await transactionScanService.scanTransaction({ @@ -71,6 +478,46 @@ describe('TransactionScan', () => { }); }); + it('preserves a failed security verdict alongside the classified simulation error', async () => { + vi.mocked(mockSecurityAlertsApiClient.scanTransaction).mockResolvedValue({ + status: 'ERROR', + result: { + validation: { + result_type: 'Error', + reason: 'Validation unavailable', + }, + }, + error_details: { + type: 'TransactionError', + message: 'Insufficient funds', + transaction_index: 0, + code: 'ResultWithNegativeLamports', + }, + }); + + const result = await transactionScanService.scanTransaction({ + method: 'signAndSendTransaction', + accountAddress: MOCK_SOLANA_KEYRING_ACCOUNT_0.address, + transaction: 'transaction', + scope: Network.Mainnet, + origin: 'metamask', + }); + + expect(result).toMatchObject({ + error: { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: 'Insufficient funds', + }, + validationError: { + type: 'validation', + code: 'Validation unavailable', + message: 'Validation unavailable', + }, + validation: { type: 'Error', reason: 'Validation unavailable' }, + }); + }); + it('returns null if the scan fails', async () => { const error = new Error('Scan failed'); vi.spyOn( @@ -229,7 +676,7 @@ describe('TransactionScan', () => { }); }); - it('maps asset diffs and error details', async () => { + it('hides asset diffs when the simulation failed', async () => { vi.spyOn( mockSecurityAlertsApiClient, 'scanTransaction', @@ -304,7 +751,99 @@ describe('TransactionScan', () => { }); expect(result).toMatchObject({ - status: SecurityAlertsScanStatus.ERROR, + status: SecurityAlertsScanStatus.SUCCESS, + estimatedChanges: null, + error: { + type: 'simulation', + code: '0x1', + message: 'failed', + }, + }); + }); + + it('maps asset diffs when the simulation succeeded', async () => { + vi.spyOn( + mockSecurityAlertsApiClient, + 'scanTransaction', + ).mockResolvedValue({ + status: SecurityAlertsScanStatus.SUCCESS, + encoding: 'base58', + error: null, + error_details: null, + request_id: 'test-request-id', + result: { + validation: { + result_type: SecurityAlertResponse.Benign, + reason: '', + features: [], + }, + simulation: { + account_summary: { + account_assets_diff: [ + { + asset_type: 'NativeToken', + asset: { + type: 'NativeToken', + decimals: 9, + logo: null, + }, + in: { + usd_price: 10, + summary: null, + value: 1, + raw_value: 1, + }, + out: null, + }, + { + asset_type: 'TOKEN', + asset: { + type: 'TOKEN', + address: 'mint', + symbol: 'USDC', + name: 'USD Coin', + logo: 'https://example.com/usdc.png', + decimals: 6, + }, + in: null, + out: { + usd_price: 20, + summary: null, + value: 2, + raw_value: 2, + }, + }, + { + asset_type: 'TOKEN', + asset: { + type: 'TOKEN', + address: 'mint-2', + decimals: 6, + logo: null, + }, + in: null, + out: null, + }, + ], + account_delegations: [], + account_ownerships_diff: [], + total_usd_diff: { in: 0, out: 0, total: 0 }, + }, + }, + }, + }); + + const result = await transactionScanService.scanTransaction({ + method: 'method', + accountAddress: 'accountAddress', + transaction: 'transaction', + scope: Network.Mainnet, + origin: 'https://metamask.io', + }); + + expect(result).toMatchObject({ + status: SecurityAlertsScanStatus.SUCCESS, + error: null, estimatedChanges: { assets: [ { @@ -323,12 +862,16 @@ describe('TransactionScan', () => { value: 2, price: 20, }, + { + type: 'out', + symbol: 'TOKEN', + name: 'TOKEN', + logo: null, + value: null, + price: null, + }, ], }, - error: { - type: 'TransactionError', - code: '0x1', - }, }); }); @@ -382,6 +925,64 @@ describe('TransactionScan', () => { }); }); + it('does not track a security scan when only simulation was requested', async () => { + vi.spyOn( + mockSecurityAlertsApiClient, + 'scanTransaction', + ).mockResolvedValue({ + status: SecurityAlertsScanStatus.SUCCESS, + encoding: 'base58', + error: null, + error_details: null, + request_id: 'test-request-id', + result: { + simulation: { + account_summary: { + account_assets_diff: [], + account_delegations: [], + account_ownerships_diff: [], + total_usd_diff: { in: 0, out: 0, total: 0 }, + }, + }, + }, + }); + + await transactionScanService.scanTransaction({ + method: 'method', + accountAddress: 'accountAddress', + transaction: 'transaction', + scope: Network.Mainnet, + origin: 'https://metamask.io', + account: MOCK_SOLANA_KEYRING_ACCOUNT_0, + options: ['simulation'], + }); + + expect( + mockAnalyticsService.trackSecurityScanCompleted, + ).not.toHaveBeenCalled(); + }); + + it('does not track a failed security scan when only simulation was requested', async () => { + vi.spyOn( + mockSecurityAlertsApiClient, + 'scanTransaction', + ).mockRejectedValue(new Error('network error')); + + await transactionScanService.scanTransaction({ + method: 'method', + accountAddress: 'accountAddress', + transaction: 'transaction', + scope: Network.Mainnet, + origin: 'https://metamask.io', + account: MOCK_SOLANA_KEYRING_ACCOUNT_0, + options: ['simulation'], + }); + + expect( + mockAnalyticsService.trackSecurityScanCompleted, + ).not.toHaveBeenCalled(); + }); + it('does not track analytics without an account', async () => { vi.spyOn( mockSecurityAlertsApiClient, diff --git a/packages/solana-wallet-snap/src/core/services/transaction-scan/TransactionScanService.ts b/packages/solana-wallet-snap/src/core/services/transaction-scan/TransactionScanService.ts index a6fa0e802..755779911 100644 --- a/packages/solana-wallet-snap/src/core/services/transaction-scan/TransactionScanService.ts +++ b/packages/solana-wallet-snap/src/core/services/transaction-scan/TransactionScanService.ts @@ -19,7 +19,7 @@ import type { SolanaScanRequestBody, } from '../../clients/security-alerts-api/structs'; import { Network } from '../../constants/solana'; -import type { TransactionScanResult } from './types'; +import type { TransactionScanError, TransactionScanResult } from './types'; /** * The Security Alerts API chain identifier for each Solana scope. @@ -31,6 +31,38 @@ const SCOPE_TO_CHAIN: Record = { [Network.Localnet]: 'localnet', }; +/** + * Whether the response reports an execution failure, meaning the transaction + * would not succeed on chain. + * + * @param result - The validated API response. + * @returns True when the response reports an execution failure. + */ +function isExecutionFailure( + result: SecurityAlertSimulationValidationResponse, +): boolean { + const type = result.error_details?.type; + return ( + result.status === 'ERROR' && + (type === 'TransactionError' || + type === 'InstructionError' || + type === 'ApiError') + ); +} + +/** + * The error for a requested result that the response did not return. + * + * @returns The response error. + */ +function emptyResponseError(): TransactionScanError { + return { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }; +} + export class TransactionScanService extends BaseTransactionScanService { /** * Scans a transaction. @@ -91,12 +123,16 @@ export class TransactionScanService extends BaseTransactionScanService { assert(result, SecurityAlertResponseStruct, 'Solana scan response body'); - const scan = this.#mapScan(result); + const scan = this.#mapScan(result, options); - await this.trackScanCompleted( - { origin, scope, accountType: account?.type }, - scan, - ); + // Only a requested security validation is a security scan. A + // simulation-only request must not be reported as one. + if (options.includes('validation')) { + await this.trackScanCompleted( + { origin, scope, accountType: account?.type }, + scan, + ); + } // Logo URLs are passed directly to Image component - no conversion needed return scan; @@ -104,7 +140,13 @@ export class TransactionScanService extends BaseTransactionScanService { await this.trackError(error); this.logger.error(error); - await this.trackScanFailed({ origin, scope, accountType: account?.type }); + if (options.includes('validation')) { + await this.trackScanFailed({ + origin, + scope, + accountType: account?.type, + }); + } return null; } @@ -129,39 +171,112 @@ export class TransactionScanService extends BaseTransactionScanService { #mapScan( result: SecurityAlertSimulationValidationResponse, + options: SecurityAlertsScanOption[], ): TransactionScanResult { + const simulationError = this.#mapSimulationError(result, options); + const validationError = this.#mapValidationError(result, options); + const simulation = result.result?.simulation; + const assetDiff = simulation?.account_summary?.account_assets_diff ?? []; + // Status reports only the security scan. A missing simulation is a + // simulation error, so the security verdict still stands. The estimate + // depends only on the simulation: it is null when the simulation failed, so + // the UI reports "not available" rather than "no changes". + return { - status: - result.status === 'SUCCESS' || result.status === 'ERROR' - ? result.status - : 'ERROR', - estimatedChanges: { - assets: - result.result?.simulation?.account_summary?.account_assets_diff?.map( - (asset) => ({ - type: asset.in ? 'in' : 'out', - symbol: asset.asset.symbol ?? asset.asset_type, - name: asset.asset.name ?? asset.asset_type, - logo: asset.asset.logo ?? null, - value: asset.in?.value ?? asset.out?.value ?? null, - price: asset.in?.usd_price ?? asset.out?.usd_price ?? null, - }), - ) ?? [], - }, + status: validationError ? 'ERROR' : 'SUCCESS', + estimatedChanges: + simulationError === null + ? { + assets: assetDiff.map((asset) => ({ + type: asset.in ? 'in' : 'out', + symbol: asset.asset.symbol ?? asset.asset_type, + name: asset.asset.name ?? asset.asset_type, + logo: asset.asset.logo ?? null, + value: asset.in?.value ?? asset.out?.value ?? null, + price: asset.in?.usd_price ?? asset.out?.usd_price ?? null, + })), + } + : null, validation: { type: result.result?.validation?.result_type ?? null, reason: result.result?.validation?.reason ?? null, }, - error: result?.error_details - ? { - type: - 'type' in result.error_details ? result.error_details.type : null, - code: - ('code' in result.error_details - ? result.error_details.code - : null) ?? null, - } - : null, + error: simulationError, + validationError, }; } + + /** + * Classifies a simulation failure: an execution failure, or a requested + * simulation that returned no result. An execution failure is not gated on + * `options`, because the error describes the response itself, as in Stellar's + * `simulationError`. + * + * @param result - The validated API response. + * @param options - The requested scan sections. + * @returns The simulation error, or null when the simulation succeeded. + */ + #mapSimulationError( + result: SecurityAlertSimulationValidationResponse, + options: SecurityAlertsScanOption[], + ): TransactionScanError | null { + const details = result.error_details; + if (details && isExecutionFailure(result)) { + return { + type: 'simulation', + code: 'code' in details && details.code ? details.code : null, + message: details.message, + }; + } + + if (options.includes('simulation') && !result.result?.simulation) { + return emptyResponseError(); + } + + return null; + } + + /** + * Classifies a failure of the security scan itself: a validation `Error`, an + * overall response error, or requested results that are missing. Execution + * failures are classified by `#mapSimulationError`, so a failed simulation + * and a failed validation are reported separately. + * + * @param result - The validated API response. + * @param options - The requested scan sections. + * @returns The validation error, or null when the scan itself succeeded. + */ + #mapValidationError( + result: SecurityAlertSimulationValidationResponse, + options: SecurityAlertsScanOption[], + ): TransactionScanError | null { + const details = result.error_details; + const validation = result.result?.validation; + + if (options.includes('validation') && validation?.result_type === 'Error') { + return { + type: 'validation', + code: validation.reason ?? null, + message: validation.reason ?? null, + }; + } + + if (result.status === 'ERROR' && !isExecutionFailure(result)) { + // An ERROR response that `isExecutionFailure` does not classify, such as + // one without `error_details`. Without this branch it would be reported + // as a success when the verdict is present. + return { + type: 'response', + code: details?.type ?? null, + message: details?.message ?? result.error ?? null, + }; + } + + // A requested validation without a verdict means the security scan failed. + if (options.includes('validation') && !validation?.result_type) { + return emptyResponseError(); + } + + return null; + } } diff --git a/packages/solana-wallet-snap/src/core/services/transaction-scan/buildExpiredScanResult.ts b/packages/solana-wallet-snap/src/core/services/transaction-scan/buildExpiredScanResult.ts deleted file mode 100644 index 8647d3187..000000000 --- a/packages/solana-wallet-snap/src/core/services/transaction-scan/buildExpiredScanResult.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { TransactionScanResult } from './types'; - -export const TRANSACTION_BLOCKHASH_EXPIRED = 'TransactionBlockhashExpired'; - -/** A failed scan result used when a transaction's recent blockhash has expired. */ -export const EXPIRED_TRANSACTION_SCAN: TransactionScanResult = { - status: 'ERROR', - estimatedChanges: { assets: [] }, - validation: { type: 'Benign', reason: null }, - error: { - type: null, - code: TRANSACTION_BLOCKHASH_EXPIRED, - }, -}; diff --git a/packages/solana-wallet-snap/src/core/services/transaction-scan/types.ts b/packages/solana-wallet-snap/src/core/services/transaction-scan/types.ts index e3ee1af70..333aa1a45 100644 --- a/packages/solana-wallet-snap/src/core/services/transaction-scan/types.ts +++ b/packages/solana-wallet-snap/src/core/services/transaction-scan/types.ts @@ -19,13 +19,25 @@ export type TransactionScanValidation = { }; export type TransactionScanError = { - type: string | null; + type: 'simulation' | 'validation' | 'response' | null; code: string | null; + message: string | null; }; export type TransactionScanResult = { + /** `ERROR` when the security scan failed (see `validationError`). */ status: TransactionScanStatus; - estimatedChanges: TransactionScanEstimatedChanges; + /** Null when the simulation failed or is missing. */ + estimatedChanges: TransactionScanEstimatedChanges | null; validation: TransactionScanValidation; + /** + * Simulation failure: an execution failure, or a requested simulation with no + * result. + */ error: TransactionScanError | null; + /** + * Failure of the security scan itself: a validation error, an overall + * response error, or requested results that are missing. + */ + validationError: TransactionScanError | null; }; diff --git a/packages/solana-wallet-snap/src/core/utils/interface.test.ts b/packages/solana-wallet-snap/src/core/utils/interface.test.ts index cb296f9ed..d931b2301 100644 --- a/packages/solana-wallet-snap/src/core/utils/interface.test.ts +++ b/packages/solana-wallet-snap/src/core/utils/interface.test.ts @@ -1,4 +1,23 @@ -import { withInterfaceLock } from './interface'; +import { + endTrace, + listEntropySources, + scheduleBackgroundEvent, + startTrace, + withInterfaceLock, +} from './interface'; + +const setupSnapRequest = (): { mockSnapRequest: ReturnType } => { + vi.clearAllMocks(); + + const mockSnapRequest = vi.fn(); + Object.assign(globalThis, { + snap: { + request: mockSnapRequest, + }, + }); + + return { mockSnapRequest }; +}; describe('withInterfaceLock', () => { it('serializes work for one interface while allowing another to proceed', async () => { @@ -41,3 +60,102 @@ describe('withInterfaceLock', () => { expect(await withInterfaceLock('one', async () => 'value')).toBe('value'); }); }); + +describe('scheduleBackgroundEvent', () => { + it('schedules the event with the given duration and empty params by default', async () => { + const { mockSnapRequest } = setupSnapRequest(); + mockSnapRequest.mockResolvedValueOnce('event-id'); + + expect( + await scheduleBackgroundEvent({ + method: 'refreshConfirmationEstimation', + duration: 'PT20S', + }), + ).toBe('event-id'); + + expect(mockSnapRequest).toHaveBeenCalledWith({ + method: 'snap_scheduleBackgroundEvent', + params: { + duration: 'PT20S', + request: { + method: 'refreshConfirmationEstimation', + params: {}, + }, + }, + }); + }); + + it('passes the given params to the background event', async () => { + const { mockSnapRequest } = setupSnapRequest(); + + await scheduleBackgroundEvent({ + method: 'onTransactionAdded', + params: { interfaceId: 'interface-id' }, + duration: 'PT1S', + }); + + expect(mockSnapRequest).toHaveBeenCalledWith({ + method: 'snap_scheduleBackgroundEvent', + params: { + duration: 'PT1S', + request: { + method: 'onTransactionAdded', + params: { interfaceId: 'interface-id' }, + }, + }, + }); + }); +}); + +describe('listEntropySources', () => { + it('returns the entropy sources from the snap', async () => { + const { mockSnapRequest } = setupSnapRequest(); + const sources = [{ id: 'primary', primary: true, name: 'Primary' }]; + mockSnapRequest.mockResolvedValueOnce(sources); + + expect(await listEntropySources()).toStrictEqual(sources); + expect(mockSnapRequest).toHaveBeenCalledWith({ + method: 'snap_listEntropySources', + }); + }); +}); + +describe('startTrace', () => { + it('returns the trace ID from the snap', async () => { + const { mockSnapRequest } = setupSnapRequest(); + mockSnapRequest.mockResolvedValueOnce(7); + + expect(await startTrace('trace-name')).toBe(7); + expect(mockSnapRequest).toHaveBeenCalledWith({ + method: 'snap_startTrace', + params: { name: 'trace-name' }, + }); + }); + + it('returns null when the snap rejects the trace', async () => { + const { mockSnapRequest } = setupSnapRequest(); + mockSnapRequest.mockRejectedValueOnce(new Error('unsupported')); + + expect(await startTrace('trace-name')).toBeNull(); + }); +}); + +describe('endTrace', () => { + it('ends the trace with the snap', async () => { + const { mockSnapRequest } = setupSnapRequest(); + mockSnapRequest.mockResolvedValueOnce('ended'); + + expect(await endTrace('trace-name')).toBe('ended'); + expect(mockSnapRequest).toHaveBeenCalledWith({ + method: 'snap_endTrace', + params: { name: 'trace-name' }, + }); + }); + + it('returns null when the snap rejects the end of the trace', async () => { + const { mockSnapRequest } = setupSnapRequest(); + mockSnapRequest.mockRejectedValueOnce(new Error('unknown trace')); + + expect(await endTrace('trace-name')).toBeNull(); + }); +}); diff --git a/packages/solana-wallet-snap/src/features/confirmation/components/EstimatedChanges/EstimatedChanges.test.tsx b/packages/solana-wallet-snap/src/features/confirmation/components/EstimatedChanges/EstimatedChanges.test.tsx index 3dafac4e8..da6387019 100644 --- a/packages/solana-wallet-snap/src/features/confirmation/components/EstimatedChanges/EstimatedChanges.test.tsx +++ b/packages/solana-wallet-snap/src/features/confirmation/components/EstimatedChanges/EstimatedChanges.test.tsx @@ -19,7 +19,6 @@ const render = ( JSON.stringify( EstimatedChanges({ changes: { assets: [sol] }, - scanStatus: 'SUCCESS', scanFetchStatus: 'fetched', preferences, ...props, @@ -57,17 +56,9 @@ describe('EstimatedChanges', () => { ); }); - it('renders not available when the scan result is an error', () => { - const serialized = render({ changes: null, scanStatus: 'ERROR' }); - - expect(serialized).toContain('Not available'); - expect(serialized).not.toContain('No changes'); - }); - it.each([ { scanFetchStatus: 'fetching' }, { scanFetchStatus: 'error' }, - { scanStatus: 'ERROR' }, ] as const)('keeps previously estimated rows visible for %o', (props) => { const serialized = render(props); @@ -76,7 +67,14 @@ describe('EstimatedChanges', () => { expect(serialized).not.toContain('Not available'); }); - it('renders no changes when there are no estimated changes', () => { - expect(render({ changes: null })).toContain('No changes'); + it('renders no changes when simulation returned an empty asset diff', () => { + expect(render({ changes: { assets: [] } })).toContain('No changes'); + }); + + it('renders not available when simulation did not return a result', () => { + const serialized = render({ changes: null }); + + expect(serialized).toContain('Not available'); + expect(serialized).not.toContain('No changes'); }); }); diff --git a/packages/solana-wallet-snap/src/features/confirmation/components/EstimatedChanges/EstimatedChanges.tsx b/packages/solana-wallet-snap/src/features/confirmation/components/EstimatedChanges/EstimatedChanges.tsx index 6d8f108f4..35fed4d7d 100644 --- a/packages/solana-wallet-snap/src/features/confirmation/components/EstimatedChanges/EstimatedChanges.tsx +++ b/packages/solana-wallet-snap/src/features/confirmation/components/EstimatedChanges/EstimatedChanges.tsx @@ -1,10 +1,7 @@ import { EstimatedChanges as SharedEstimatedChanges } from '@metamask/snap-networks-utils'; import type { SnapComponent } from '@metamask/snaps-sdk/jsx'; -import type { - TransactionScanEstimatedChanges, - TransactionScanStatus, -} from '../../../../core/services/transaction-scan/types'; +import type { TransactionScanEstimatedChanges } from '../../../../core/services/transaction-scan/types'; import type { FetchStatus, Preferences } from '../../../../core/types/snap'; import { formatCryptoBalance } from '../../../../core/utils/formatCryptoBalance'; import { formatFiat } from '../../../../core/utils/formatFiat'; @@ -12,7 +9,6 @@ import { i18n } from '../../../../core/utils/i18n'; type EstimatedChangesProps = { changes: TransactionScanEstimatedChanges | null; - scanStatus: TransactionScanStatus | null; preferences: Preferences; scanFetchStatus: FetchStatus; }; @@ -21,7 +17,6 @@ export const EstimatedChanges: SnapComponent = ({ changes, preferences, scanFetchStatus, - scanStatus, }) => { const translate = i18n(preferences.locale); const { locale, currency } = preferences; @@ -49,7 +44,7 @@ export const EstimatedChanges: SnapComponent = ({ noChanges: translate('confirmation.estimatedChanges.noChanges'), }} isFetching={scanFetchStatus === 'fetching'} - isUnavailable={scanFetchStatus === 'error' || scanStatus === 'ERROR'} + isUnavailable={scanFetchStatus === 'error' || changes === null} /> ); }; diff --git a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmSignIn/ConfirmSignIn.tsx b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmSignIn/ConfirmSignIn.tsx index 7e124d484..38646334d 100644 --- a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmSignIn/ConfirmSignIn.tsx +++ b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmSignIn/ConfirmSignIn.tsx @@ -94,7 +94,6 @@ export const ConfirmSignIn: SnapComponent = ({ {preferences.simulateOnChainActions ? ( diff --git a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/ConfirmTransactionRequest.test.tsx b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/ConfirmTransactionRequest.test.tsx index 99dfc377c..95bc818d8 100644 --- a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/ConfirmTransactionRequest.test.tsx +++ b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/ConfirmTransactionRequest.test.tsx @@ -49,6 +49,7 @@ const scan = ( estimatedChanges: { assets: [] }, validation: { type: 'Benign', reason: null }, error: null, + validationError: null, ...overrides, }); @@ -75,16 +76,23 @@ describe('ConfirmTransactionRequest', () => { it('renders the API error banner when the scan request fails', () => { const serialized = render({ scanFetchStatus: 'error' }); - expect(serialized).toContain('"severity":"danger"'); + expect(serialized).toContain('"severity":"info"'); + expect(serialized).toContain('Security check unavailable'); expect(serialized).toContain( - "Because of an error, we couldn't check for security alerts.", + "We couldn't complete this safety check. Only continue if you trust this site and/or every address involved.", ); + expect(serialized).not.toContain('"disabled":true'); }); it('renders the simulation error banner with the translated reason', () => { const serialized = render({ + preferences: { ...context.preferences, simulateOnChainActions: true }, scan: scan({ - error: { type: 'simulation', code: 'ResultWithNegativeLamports' }, + error: { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: null, + }, validation: { type: 'Malicious', reason: null }, }), }); @@ -94,13 +102,11 @@ describe('ConfirmTransactionRequest', () => { expect(serialized).toContain( 'Account does not have enough SOL to perform the operation.', ); - expect(serialized).not.toContain('This is a deceptive request'); + expect(serialized).toContain('This is a deceptive request'); + expect(serialized.match(/"type":"Banner"/gu)).toHaveLength(2); }); - it.each([ - ['Malicious', 'danger'], - ['Warning', 'warning'], - ] as const)( + it.each([['Malicious', 'danger']] as const)( 'renders the security banner for a %s validation', (type, severity) => { const serialized = render({ @@ -109,10 +115,23 @@ describe('ConfirmTransactionRequest', () => { expect(serialized).toContain(`"severity":"${severity}"`); expect(serialized).toContain('This is a deceptive request'); + expect(serialized).toContain('See details'); expect(serialized).toContain('Powered by'); }, ); + it('renders the soft warning copy for a warning validation', () => { + const serialized = render({ + scan: scan({ validation: { type: 'Warning', reason: null } }), + }); + + expect(serialized).toContain('"severity":"warning"'); + expect(serialized).toContain('This request may be risky'); + expect(serialized).toContain('See details'); + expect(serialized).toContain('Powered by'); + expect(serialized).not.toContain('This is a deceptive request'); + }); + it('renders a destructive Confirm that opens acknowledgement for a malicious validation', () => { const serialized = render({ scan: scan({ validation: { type: 'Malicious', reason: null } }), @@ -138,10 +157,329 @@ describe('ConfirmTransactionRequest', () => { expect(serialized).toContain('confirm-sign-and-send-transaction-confirm'); }); + it('keeps malicious acknowledgement available despite a remote execution failure', () => { + const serialized = render({ + scan: scan({ + status: 'ERROR', + error: { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: null, + }, + validation: { type: 'Malicious', reason: null }, + }), + }); + + expect(serialized).toContain(MaliciousAcknowledgementFormNames.Review); + expect(serialized).toContain('"variant":"destructive"'); + expect(serialized).not.toContain('"disabled":true'); + }); + + it('shows the execution-failure warning while allowing normal confirmation', () => { + const serialized = render({ + preferences: { ...context.preferences, simulateOnChainActions: true }, + scan: scan({ + status: 'ERROR', + error: { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: null, + }, + }), + }); + + expect(serialized).toContain('This transaction is expected to fail.'); + expect(serialized).toContain( + 'Account does not have enough SOL to perform the operation.', + ); + expect(serialized).toContain('"severity":"warning"'); + expect(serialized).toContain('confirm-sign-and-send-transaction-confirm'); + expect(serialized).not.toContain('"disabled":true'); + }); + it('renders no banner for a benign validation', () => { expect(render({ scan: scan({}) })).not.toContain('"type":"Banner"'); }); + it.each(['validation', 'response'] as const)( + 'shows an info banner and enables confirmation for a %s error', + (type) => { + const serialized = render({ + scan: scan({ + status: 'ERROR', + validationError: { + type, + code: 'empty', + message: 'No scan results returned', + }, + }), + }); + + expect(serialized).toContain('Security check unavailable'); + expect(serialized).toContain('"severity":"info"'); + expect(serialized).not.toContain('expected to fail'); + expect(serialized).not.toContain('"disabled":true'); + }, + ); + + it('keeps missing simulation estimates unavailable without hiding a successful security verdict', () => { + const serialized = render({ + preferences: { ...context.preferences, simulateOnChainActions: true }, + scan: scan({ + status: 'SUCCESS', + estimatedChanges: null, + validation: { type: 'Warning', reason: null }, + }), + }); + + expect(serialized).toContain('This request may be risky'); + expect(serialized).toContain('Not available'); + expect(serialized).not.toContain('No changes'); + expect(serialized).not.toContain('Security check unavailable'); + expect(serialized).not.toContain('"disabled":true'); + }); + + it('does not let a retained execution failure block confirmation after a scan outage', () => { + const serialized = render({ + scanFetchStatus: 'error', + scan: scan({ + status: 'ERROR', + error: { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: null, + }, + }), + }); + + expect(serialized).toContain('Security check unavailable'); + expect(serialized).not.toContain('expected to fail'); + expect(serialized).not.toContain('"disabled":true'); + }); + + it.each(['fetched', 'error'] as const)( + 'shows only the local expiry banner independently of a %s scan', + (scanFetchStatus) => { + const serialized = render({ + scanFetchStatus, + transactionExpired: true, + scan: scan({}), + }); + + expect(serialized).toContain('This transaction is expected to fail.'); + expect(serialized).toContain( + 'This transaction has expired. Close this request and try again.', + ); + expect(serialized).toContain('"disabled":true'); + expect(serialized).not.toContain('Security check unavailable'); + expect(serialized.match(/"type":"Banner"/gu)).toHaveLength(1); + expect(serialized).toContain('"severity":"danger"'); + }, + ); + + it.each([ + ['Malicious', 'This is a deceptive request'], + ['Warning', 'This request may be risky'], + ])( + 'shows only the local expiry banner over a %s security banner', + (type, title) => { + const serialized = render({ + transactionExpired: true, + scan: scan({ validation: { type, reason: null } }), + }); + + expect(serialized).not.toContain(title); + expect(serialized).toContain( + 'This transaction has expired. Close this request and try again.', + ); + expect(serialized).toContain('"severity":"danger"'); + expect(serialized.match(/"type":"Banner"/gu)).toHaveLength(1); + expect(serialized).toContain('"disabled":true'); + expect(serialized).not.toContain( + MaliciousAcknowledgementFormNames.Review, + ); + }, + ); + + it('keeps the warning security verdict alongside a remote execution failure', () => { + const serialized = render({ + preferences: { ...context.preferences, simulateOnChainActions: true }, + scan: scan({ + status: 'ERROR', + validation: { type: 'Warning', reason: null }, + error: { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: null, + }, + }), + }); + + expect(serialized).toContain('This request may be risky'); + expect(serialized).toContain( + 'Account does not have enough SOL to perform the operation.', + ); + expect(serialized.match(/"type":"Banner"/gu)).toHaveLength(2); + expect(serialized).not.toContain('"disabled":true'); + }); + + it('shows the malicious verdict and a simulation failure side by side when not expired', () => { + const serialized = render({ + preferences: { ...context.preferences, simulateOnChainActions: true }, + scan: scan({ + status: 'ERROR', + validation: { type: 'Malicious', reason: null }, + error: { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: null, + }, + }), + }); + + expect(serialized).toContain('This is a deceptive request'); + expect(serialized).toContain( + 'Account does not have enough SOL to perform the operation.', + ); + expect(serialized.match(/"type":"Banner"/gu)).toHaveLength(2); + expect(serialized).toContain(MaliciousAcknowledgementFormNames.Review); + }); + + it('shows security unavailability and a reported execution failure independently', () => { + const serialized = render({ + preferences: { ...context.preferences, simulateOnChainActions: true }, + scan: scan({ + status: 'ERROR', + validation: { type: 'Error', reason: null }, + validationError: { + type: 'validation', + code: null, + message: null, + }, + error: { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: null, + }, + }), + }); + + expect(serialized).toContain('Security check unavailable'); + expect(serialized).toContain( + 'Account does not have enough SOL to perform the operation.', + ); + expect(serialized).toContain('"severity":"info"'); + expect(serialized).toContain('"severity":"warning"'); + expect(serialized.match(/"type":"Banner"/gu)).toHaveLength(2); + expect(serialized).not.toContain('"disabled":true'); + }); + + it('shows the simulation error and the unavailable security check side by side', () => { + const serialized = render({ + preferences: { ...context.preferences, simulateOnChainActions: true }, + scan: scan({ + status: 'ERROR', + error: { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: null, + }, + validationError: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + }), + }); + + expect(serialized).toContain('Security check unavailable'); + expect(serialized).toContain( + 'Account does not have enough SOL to perform the operation.', + ); + expect(serialized.match(/"type":"Banner"/gu)).toHaveLength(2); + expect(serialized).not.toContain('"disabled":true'); + }); + + it('hides the unavailable security check when security alerts are disabled', () => { + const serialized = render({ + preferences: { + ...context.preferences, + useSecurityAlerts: false, + simulateOnChainActions: true, + }, + scan: scan({ + status: 'ERROR', + validationError: { + type: 'response', + code: 'empty', + message: 'No scan results returned', + }, + }), + }); + + expect(serialized).not.toContain('Security check unavailable'); + expect(serialized).not.toContain('"type":"Banner"'); + }); + + it('hides a failed scan request when security alerts are disabled', () => { + const serialized = render({ + scanFetchStatus: 'error', + preferences: { + ...context.preferences, + useSecurityAlerts: false, + simulateOnChainActions: true, + }, + }); + + expect(serialized).not.toContain('Security check unavailable'); + }); + + it('hides the security verdict when disabled without hiding the execution warning', () => { + const serialized = render({ + preferences: { + ...context.preferences, + useSecurityAlerts: false, + simulateOnChainActions: true, + }, + scan: scan({ + status: 'ERROR', + validation: { type: 'Malicious', reason: null }, + error: { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: null, + }, + }), + }); + + expect(serialized).not.toContain('This is a deceptive request'); + expect(serialized).toContain( + 'Account does not have enough SOL to perform the operation.', + ); + expect(serialized.match(/"type":"Banner"/gu)).toHaveLength(1); + expect(serialized).not.toContain( + MaliciousAcknowledgementFormNames.Review, + ); + expect(serialized).not.toContain('"disabled":true'); + }); + + it('shows local expiry even with all scan preferences disabled', () => { + const serialized = render({ + transactionExpired: true, + preferences: { + ...context.preferences, + useSecurityAlerts: false, + simulateOnChainActions: false, + }, + }); + + expect(serialized).toContain( + 'This transaction has expired. Close this request and try again.', + ); + expect(serialized).toContain('"disabled":true'); + expect(serialized).toContain('"severity":"danger"'); + }); + it('renders no banner when security alerts are disabled and the scan succeeded', () => { const serialized = render({ preferences: { ...context.preferences, useSecurityAlerts: false }, @@ -150,6 +488,19 @@ describe('ConfirmTransactionRequest', () => { expect(serialized).not.toContain('"type":"Banner"'); }); + + it('renders no banner when all scan preferences are disabled', () => { + const serialized = render({ + preferences: { + ...context.preferences, + useSecurityAlerts: false, + simulateOnChainActions: false, + }, + scanFetchStatus: 'error', + }); + + expect(serialized).not.toContain('"type":"Banner"'); + }); }); describe('malicious acknowledgement', () => { diff --git a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/ConfirmTransactionRequest.tsx b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/ConfirmTransactionRequest.tsx index 8c04a9421..f0a7d6d8c 100644 --- a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/ConfirmTransactionRequest.tsx +++ b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/ConfirmTransactionRequest.tsx @@ -5,7 +5,6 @@ import { MaliciousAcknowledgementFormNames, MaliciousAcknowledgementScreen, requiresMaliciousAcknowledgement, - TransactionAlert, } from '@metamask/snap-networks-utils'; import { Box, Container } from '@metamask/snaps-sdk/jsx'; @@ -15,7 +14,8 @@ import { Advanced } from '../../components/Advanced/Advanced'; import { EstimatedChanges } from '../../components/EstimatedChanges/EstimatedChanges'; import { TransactionDetails } from '../../components/TransactionDetails/TransactionDetails'; import { ConfirmSignAndSendTransactionFormNames } from './events'; -import { getErrorMessage } from './getErrorMessage'; +import { SecurityScanAlert } from './SecurityScanAlert'; +import { TransactionFailureAlert } from './TransactionFailureAlert'; import type { ConfirmTransactionRequestContext } from './types'; import { shouldDisableConfirmation } from './utils'; @@ -45,70 +45,46 @@ export const ConfirmTransactionRequest = ({ const { nativeToken } = Networks[context.scope]; const nativePrice = context.tokenPrices[nativeToken.caip19Id]?.price ?? null; - const isScanError = context.scan?.status === 'ERROR'; - const shouldDisableConfirmButton = shouldDisableConfirmation({ scanFetchStatus: context.scanFetchStatus, transactionExpired: context.transactionExpired, }); - // A malicious verdict opens the acknowledgement screen from the confirm - // button. The API can return any `result_type` string; the shared helper - // only treats `Malicious` as malicious. + // Local expiry is the blocking alert, so it is shown alone. Otherwise the + // security verdict and the simulation failure render side by side. + const isBlockedByExpiry = context.transactionExpired === true; + + // A blocking state takes priority over the acknowledgement swap: the shared + // footer falls back to the disabled "Confirm" button so the user can never + // enter the acknowledgement flow for a transaction that is no longer valid. + // The API can return any `result_type` string. The shared helper only checks + // for `Malicious`, so unrecognized values are never treated as malicious. const requiresAcknowledgement = requiresMaliciousAcknowledgement( context.preferences.useSecurityAlerts, context.scan?.validation?.type as SecurityAlertResponse | null | undefined, ); - const shouldShowAlert = context.preferences.useSecurityAlerts || isScanError; - const scanError = context.scan?.error; - return ( - {shouldShowAlert ? ( - - ) : null} + )} + {context.preferences.simulateOnChainActions ? ( { + it.each([ + { scanFetchStatus: 'error' as const }, + { scanFetchStatus: 'fetching' as const }, + ])('passes runtime UI validation for %j', (props) => { + expect(() => + assertJSXElement( + SecurityScanAlert({ + scan: null, + preferences: { locale: 'en', useSecurityAlerts: true } as Preferences, + ...props, + }), + ), + ).not.toThrow(); + }); + + it('shows the malicious verdict, not the unavailable notice, when a refresh failed after a malicious scan', () => { + const text = JSON.stringify( + SecurityScanAlert({ + scan: maliciousScan, + scanFetchStatus: 'error', + preferences, + }), + ); + + expect(text).toContain(MALICIOUS_TITLE); + expect(text).not.toContain(UNAVAILABLE_TITLE); + }); + + it('shows the unavailable notice when the scan failed and there is no verdict', () => { + const text = JSON.stringify( + SecurityScanAlert({ + scan: null, + scanFetchStatus: 'error', + preferences, + }), + ); + + expect(text).toContain(UNAVAILABLE_TITLE); + expect(text).not.toContain(MALICIOUS_TITLE); + }); + + it('shows the unavailable notice when the security scan itself failed', () => { + const text = JSON.stringify( + SecurityScanAlert({ + scan: { + ...maliciousScan, + validation: { type: null, reason: null }, + validationError: { type: 'validation', code: null, message: null }, + }, + scanFetchStatus: 'fetched', + preferences, + }), + ); + + expect(text).toContain(UNAVAILABLE_TITLE); + }); +}); diff --git a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/SecurityScanAlert.tsx b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/SecurityScanAlert.tsx new file mode 100644 index 000000000..32e3ae8ed --- /dev/null +++ b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/SecurityScanAlert.tsx @@ -0,0 +1,88 @@ +import { TransactionAlert } from '@metamask/snap-networks-utils'; +import type { ComponentOrElement } from '@metamask/snaps-sdk'; +import { Banner, Text as SnapText } from '@metamask/snaps-sdk/jsx'; + +import type { TransactionScanResult } from '../../../../core/services/transaction-scan/types'; +import type { FetchStatus, Preferences } from '../../../../core/types/snap'; +import { i18n } from '../../../../core/utils/i18n'; + +type SecurityScanAlertProps = { + scan: TransactionScanResult | null; + scanFetchStatus: FetchStatus; + preferences: Preferences; +}; + +/** + * Renders scan availability and security verdicts independently of transaction + * execution failures and local expiry. + * + * @param props - The scan and preference state. + * @param props.scan - The most recent scan result. + * @param props.scanFetchStatus - The latest request status. + * @param props.preferences - The user's preferences. + * @returns The security alert, or null. + */ +export const SecurityScanAlert = ({ + scan, + scanFetchStatus, + preferences, +}: SecurityScanAlertProps): ComponentOrElement | null => { + const translate = i18n(preferences.locale); + + if (!preferences.useSecurityAlerts && !preferences.simulateOnChainActions) { + return null; + } + + const isFetching = scanFetchStatus === 'fetching'; + // The security check is unavailable when the scan request failed or the + // security scan itself failed. A kept malicious verdict takes priority, so a + // failed background refresh never downgrades it. Execution failures are shown + // by TransactionFailureAlert, so they never stand in for this notice. + const unavailable = + (scanFetchStatus === 'error' || Boolean(scan?.validationError)) && + scan?.validation?.type !== 'Malicious'; + + if (!isFetching && preferences.useSecurityAlerts && unavailable) { + return ( + + + {translate('confirmation.securityScanUnavailableMessage')} + + + ); + } + + return ( + + ); +}; diff --git a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/TransactionFailureAlert.test.tsx b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/TransactionFailureAlert.test.tsx new file mode 100644 index 000000000..9a9221c5e --- /dev/null +++ b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/TransactionFailureAlert.test.tsx @@ -0,0 +1,97 @@ +import { assertJSXElement } from '@metamask/snaps-sdk/jsx'; + +import type { TransactionScanResult } from '../../../../core/services/transaction-scan/types'; +import type { Preferences } from '../../../../core/types/snap'; +import { TransactionFailureAlert } from './TransactionFailureAlert'; + +describe('TransactionFailureAlert', () => { + it.each([ + { scan: null, transactionExpired: true }, + { + scan: { + status: 'ERROR', + estimatedChanges: { assets: [] }, + validation: { type: 'Malicious', reason: null }, + error: { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: null, + }, + validationError: null, + } as TransactionScanResult, + }, + ])('passes runtime UI validation for %j', (props) => { + expect(() => + assertJSXElement( + TransactionFailureAlert({ + scanFetchStatus: 'fetched', + preferences: { + locale: 'en', + useSecurityAlerts: true, + simulateOnChainActions: true, + } as Preferences, + ...props, + }), + ), + ).not.toThrow(); + }); + + it('renders a danger banner for a local expiry', () => { + const serialized = JSON.stringify( + TransactionFailureAlert({ + scan: null, + scanFetchStatus: 'fetched', + transactionExpired: true, + preferences: { locale: 'en', useSecurityAlerts: true } as Preferences, + }), + ); + + expect(serialized).toContain('"severity":"danger"'); + }); + + it('hides a simulation failure when only security alerts are enabled', () => { + expect( + TransactionFailureAlert({ + scan: { + status: 'ERROR', + estimatedChanges: null, + validation: { type: 'Benign', reason: null }, + error: { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: null, + }, + validationError: null, + }, + scanFetchStatus: 'fetched', + preferences: { locale: 'en', useSecurityAlerts: true } as Preferences, + }), + ).toBeNull(); + }); + + it('renders a warning banner for a simulation failure', () => { + const serialized = JSON.stringify( + TransactionFailureAlert({ + scan: { + status: 'ERROR', + estimatedChanges: { assets: [] }, + validation: { type: 'Benign', reason: null }, + error: { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: null, + }, + validationError: null, + }, + scanFetchStatus: 'fetched', + preferences: { + locale: 'en', + useSecurityAlerts: true, + simulateOnChainActions: true, + } as Preferences, + }), + ); + + expect(serialized).toContain('"severity":"warning"'); + }); +}); diff --git a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/TransactionFailureAlert.tsx b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/TransactionFailureAlert.tsx new file mode 100644 index 000000000..acc4ce52e --- /dev/null +++ b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/TransactionFailureAlert.tsx @@ -0,0 +1,63 @@ +import type { ComponentOrElement } from '@metamask/snaps-sdk'; +import { Banner, Text as SnapText } from '@metamask/snaps-sdk/jsx'; + +import type { TransactionScanResult } from '../../../../core/services/transaction-scan/types'; +import type { FetchStatus, Preferences } from '../../../../core/types/snap'; +import { i18n } from '../../../../core/utils/i18n'; +import { getErrorMessage } from './getErrorMessage'; + +type TransactionFailureAlertProps = { + scan: TransactionScanResult | null; + scanFetchStatus: FetchStatus; + transactionExpired?: boolean; + preferences: Preferences; +}; + +/** + * Renders a transaction-failure banner without hiding security alerts. Local + * expiry takes priority over remote execution details, is a danger banner, and + * does not depend on scanning preferences. A simulation failure is a warning. + * + * @param props - The transaction failure and preference state. + * @param props.scan - The most recent scan result. + * @param props.scanFetchStatus - The latest request status. + * @param props.transactionExpired - Whether a local check detected expiry. + * @param props.preferences - The user's preferences. + * @returns The transaction-failure warning, or null. + */ +export const TransactionFailureAlert = ({ + scan, + scanFetchStatus, + transactionExpired = false, + preferences, +}: TransactionFailureAlertProps): ComponentOrElement | null => { + const translate = i18n(preferences.locale); + + const error = + scanFetchStatus === 'fetched' && + scan?.error?.type === 'simulation' && + preferences.simulateOnChainActions + ? scan?.error + : null; + + let message: string; + + if (transactionExpired) { + message = translate('confirmation.txnError.expired'); + } else if (error) { + message = translate('confirmation.simulationErrorSubtitle', { + reason: getErrorMessage(error, preferences), + }); + } else { + return null; + } + + return ( + + {message} + + ); +}; diff --git a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/events.test.tsx b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/events.test.tsx index 43ddf2cee..27766f0e2 100644 --- a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/events.test.tsx +++ b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/events.test.tsx @@ -201,7 +201,9 @@ describe('confirm transaction request events', () => { error: { type: 'simulation', code: 'ResultWithNegativeLamports', + message: null, }, + validationError: null, }, }); @@ -244,7 +246,9 @@ describe('confirm transaction request events', () => { error: { type: 'simulation', code: 'ResultWithNegativeLamports', + message: null, }, + validationError: null, }, }); diff --git a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/getErrorMessage.test.ts b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/getErrorMessage.test.ts new file mode 100644 index 000000000..7620c625e --- /dev/null +++ b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/getErrorMessage.test.ts @@ -0,0 +1,59 @@ +import type { Preferences } from '../../../../core/types/snap'; +import { getErrorMessage } from './getErrorMessage'; + +const preferences = { locale: 'en' } as Preferences; + +describe('getErrorMessage', () => { + it('returns the translated copy for a mapped error code', () => { + expect( + getErrorMessage( + { + type: 'simulation', + code: 'ResultWithNegativeLamports', + message: 'raw message', + }, + preferences, + ), + ).toBe('Account does not have enough SOL to perform the operation.'); + }); + + it('returns the API message for an unmapped error code', () => { + expect( + getErrorMessage( + { + type: 'simulation', + code: 'UnmappedCode', + message: 'Program failed to complete', + }, + preferences, + ), + ).toBe('Program failed to complete'); + }); + + it('returns the API message when there is no error code', () => { + expect( + getErrorMessage( + { type: 'simulation', code: null, message: 'Program failed' }, + preferences, + ), + ).toBe('Program failed'); + }); + + it('returns the unknown error copy for an unmapped code without a message', () => { + expect( + getErrorMessage( + { type: 'simulation', code: 'UnmappedCode', message: null }, + preferences, + ), + ).toBe('An unknown error occurred.'); + }); + + it('returns the unknown error copy when there is neither a code nor a message', () => { + expect( + getErrorMessage( + { type: 'simulation', code: null, message: null }, + preferences, + ), + ).toBe('An unknown error occurred.'); + }); +}); diff --git a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/getErrorMessage.ts b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/getErrorMessage.ts index a35430e55..22d7f57b1 100644 --- a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/getErrorMessage.ts +++ b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/getErrorMessage.ts @@ -1,4 +1,3 @@ -import { TRANSACTION_BLOCKHASH_EXPIRED } from '../../../../core/services/transaction-scan/buildExpiredScanResult'; import type { TransactionScanError } from '../../../../core/services/transaction-scan/types'; import type { Preferences } from '../../../../core/types/snap'; import { i18n } from '../../../../core/utils/i18n'; @@ -12,7 +11,7 @@ const ERROR_MESSAGES: Record = { SlippageToleranceExceeded: 'transactionScan.errors.slippageToleranceExceeded', // Jupiter ExceededDesiredSlippageLimit: 'transactionScan.errors.slippageToleranceExceeded', // Raydium - [TRANSACTION_BLOCKHASH_EXPIRED]: + TransactionBlockhashExpired: 'transactionScan.errors.transactionBlockhashExpired', }; @@ -21,17 +20,21 @@ const ERROR_MESSAGES: Record = { * * @param error - The error of the transaction scan. * @param preferences - The user preferences containing locale information. - * @returns A user-friendly error message, or the original error code if no mapping exists. + * @returns The translated copy for a mapped error code, otherwise the API + * message, otherwise the unknown error copy. */ export function getErrorMessage( error: TransactionScanError, preferences: Preferences, ): string { const translate = i18n(preferences.locale); - const { code } = error; + const { code, message } = error; - const translationKey = - (code && ERROR_MESSAGES[code]) ?? 'transactionScan.errors.unknownError'; + const translationKey = code ? ERROR_MESSAGES[code] : undefined; - return translate(translationKey as keyof typeof translate); + if (translationKey) { + return translate(translationKey as keyof typeof translate); + } + + return message ?? translate('transactionScan.errors.unknownError'); } diff --git a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/render.test.tsx b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/render.test.tsx index c3a8b0030..f3244663f 100644 --- a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/render.test.tsx +++ b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/render.test.tsx @@ -369,6 +369,8 @@ describe('render tracking', () => { return { render, + createInterface, + getPreferences, trackError, calculateFee, extractDestinationAddress, @@ -381,6 +383,57 @@ describe('render tracking', () => { }; }; + it.each([ + [false, false, false, 'fetched', 0], + [false, false, true, 'fetched', 0], + [true, false, false, 'fetching', 1], + [false, true, false, 'fetching', 1], + [true, true, false, 'fetching', 1], + ] as const)( + 'initializes security=%s simulation=%s expiry=%s with scan state %s', + async ( + useSecurityAlerts, + simulateOnChainActions, + transactionExpired, + scanFetchStatus, + expectedScanCalls, + ) => { + const { + render, + createInterface, + getPreferences, + transactionScanService, + } = await setupTest(); + getPreferences.mockResolvedValue({ + locale: 'en', + currency: 'usd', + useExternalPricingData: false, + useSecurityAlerts, + simulateOnChainActions, + }); + transactionScanService.scanTransaction.mockResolvedValue({ + status: 'SUCCESS', + estimatedChanges: { assets: [] }, + validation: { type: 'Benign', reason: null }, + error: null, + }); + + await render({ + ...DEFAULT_CONFIRMATION_CONTEXT, + networkImage: null, + transactionExpired, + }); + + expect(createInterface).toHaveBeenCalledWith( + null, + expect.objectContaining({ scanFetchStatus, transactionExpired }), + ); + expect(transactionScanService.scanTransaction).toHaveBeenCalledTimes( + expectedScanCalls, + ); + }, + ); + it('tracks confirmation fallbacks', async () => { const { render, diff --git a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/render.tsx b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/render.tsx index 447df3ba4..97f2f0954 100644 --- a/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/render.tsx +++ b/packages/solana-wallet-snap/src/features/confirmation/views/ConfirmTransactionRequest/render.tsx @@ -212,6 +212,10 @@ export async function render(incomingContext: Context) { simulateOnChainActions, } = context.preferences; + if (!useSecurityAlerts && !simulateOnChainActions) { + context.scanFetchStatus = 'fetched'; + } + const id = await createInterface( , context, @@ -303,7 +307,7 @@ export async function render(incomingContext: Context) { } if (simulateOnChainActions || useSecurityAlerts) { - const transactionScanPromise = transactionScanService + await transactionScanService .scanTransaction({ method: updatedContext2.method, accountAddress: updatedContext2.account?.address ?? '', @@ -315,14 +319,7 @@ export async function render(incomingContext: Context) { .then(async (scan) => { updatedContext2.scan = scan; updatedContext2.scanFetchStatus = scan ? 'fetched' : 'error'; - }) - .catch(async (error) => { - await trackError(error); - updatedContext2.scan = null; - updatedContext2.scanFetchStatus = 'error'; }); - - await Promise.all([transactionScanPromise]); } else { updatedContext2.scanFetchStatus = 'fetched'; updatedContext2.scan = null; diff --git a/packages/solana-wallet-snap/vitest.config.ts b/packages/solana-wallet-snap/vitest.config.ts index f0bb573a8..5412dbf95 100644 --- a/packages/solana-wallet-snap/vitest.config.ts +++ b/packages/solana-wallet-snap/vitest.config.ts @@ -47,10 +47,10 @@ export default mergeConfig( coverage: { exclude: ['src/core/utils/logger.ts'], thresholds: { - branches: 72.12, - functions: 81.01, - lines: 85.43, - statements: 85.48, + branches: 77.31, + functions: 84.61, + lines: 87.78, + statements: 87.83, }, }, },