From b758bcb8eb0e797b0b97f5939363083caaaa219b Mon Sep 17 00:00:00 2001 From: Andrew Taran Date: Fri, 20 Nov 2026 16:27:56 +0100 Subject: [PATCH 1/2] feat(tron): report security fields on transaction events --- packages/tron-wallet-snap/CHANGELOG.md | 4 + .../clientRequest/clientRequest.test.ts | 86 +++++++- .../handlers/clientRequest/clientRequest.ts | 11 +- .../src/handlers/cronjob/cronjob.test.tsx | 138 ++++++++++++ .../src/handlers/cronjob/cronjob.tsx | 7 + .../confirmation/ConfirmationHandler.test.ts | 197 +++++++++++++++++- .../confirmation/ConfirmationHandler.ts | 24 ++- .../src/services/send/SendService.test.ts | 59 +++++- .../src/services/send/SendService.ts | 7 + .../ConfirmTransactionRequest/render.test.tsx | 159 +++++++++++++- .../ConfirmTransactionRequest/render.tsx | 38 +++- .../views/ConfirmTransactionRequest/types.ts | 18 +- .../src/validation/structs.test.ts | 80 ++++++- .../src/validation/structs.ts | 6 +- packages/tron-wallet-snap/vitest.config.ts | 8 +- 15 files changed, 793 insertions(+), 49 deletions(-) diff --git a/packages/tron-wallet-snap/CHANGELOG.md b/packages/tron-wallet-snap/CHANGELOG.md index 96adb5b9a..6986ef27f 100644 --- a/packages/tron-wallet-snap/CHANGELOG.md +++ b/packages/tron-wallet-snap/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Add security telemetry fields to the "Transaction Approved", "Transaction Rejected", "Transaction Submitted", and "Transaction Finalized" events for the send flow + ## [4.5.0] ### Added diff --git a/packages/tron-wallet-snap/src/handlers/clientRequest/clientRequest.test.ts b/packages/tron-wallet-snap/src/handlers/clientRequest/clientRequest.test.ts index f1825da61..511791a6f 100644 --- a/packages/tron-wallet-snap/src/handlers/clientRequest/clientRequest.test.ts +++ b/packages/tron-wallet-snap/src/handlers/clientRequest/clientRequest.test.ts @@ -5,7 +5,10 @@ import { } from '@metamask/keyring-api'; import { DEFAULT_METAMASK_ORIGIN } from '@metamask/snap-networks-utils'; import type { AnalyticsService } from '@metamask/snap-networks-utils'; -import { InvalidParamsError } from '@metamask/snaps-sdk'; +import { + InvalidParamsError, + UserRejectedRequestError, +} from '@metamask/snaps-sdk'; import type { JsonRpcRequest } from '@metamask/snaps-sdk'; import type { Infer } from '@metamask/superstruct'; import { BigNumber } from 'bignumber.js'; @@ -4032,6 +4035,68 @@ describe('ClientRequestHandler - confirmSend validation', () => { ); }); + it('does not sign or send the transaction when the user rejects the send', async () => { + await withClientRequestHandler( + async ({ + handler, + mockAccountsService, + mockAssetsService, + mockSendService, + mockFeeCalculatorService, + mockConfirmationHandler, + mockTransactionExpirationRefresherService, + }) => { + const request = { + jsonrpc: '2.0' as const, + id: '1', + method: ClientRequestMethod.ConfirmSend, + params: { + fromAccountId: TEST_ACCOUNT_ID, + toAddress: TEST_TO_ADDRESS, + amount: '10', + assetId: Networks[scope].nativeToken.id, + }, + }; + + mockAccountsService.findById.mockResolvedValue({ + id: TEST_ACCOUNT_ID, + address: 'TExvJsxzPyAZ2NtkrWgNKnbLkpqnFJ73DT', + entropySource: 'test-entropy', + derivationPath: [], + type: 'tron:basic', + }); + mockAssetsService.fetchAccountAssetsByIDs.mockResolvedValue([ + { + assetType: Networks[scope].nativeToken.id, + symbol: 'TRX', + decimals: 6, + uiAmount: '100', + rawAmount: '100000000', + }, + { rawAmount: '1000' }, + { rawAmount: '50000' }, + ]); + mockSendService.validateSend.mockResolvedValue({ valid: true }); + mockSendService.buildTransaction.mockResolvedValue({}); + mockFeeCalculatorService.computeFee.mockResolvedValue([]); + mockTransactionExpirationRefresherService.ensureFreshRawData.mockResolvedValue( + { expiration: 1_700_000_060_000 }, + ); + + // User rejects. + mockConfirmationHandler.confirmTransactionRequest.mockResolvedValue({ + confirmed: false, + context: {}, + }); + + await expect(handler.handle(request)).rejects.toThrow( + UserRejectedRequestError, + ); + expect(mockSendService.signAndSendTransaction).not.toHaveBeenCalled(); + }, + ); + }); + it('refreshes transaction raw data before send confirmation when validateSend returns valid', async () => { await withClientRequestHandler( async ({ @@ -4107,10 +4172,13 @@ describe('ClientRequestHandler - confirmSend validation', () => { ] as ComputeFeeResult; mockFeeCalculatorService.computeFee.mockResolvedValue(mockFees); - // User confirms. - mockConfirmationHandler.confirmTransactionRequest.mockResolvedValue( - true, - ); + // User confirms, and the confirmation context is carried along. + mockConfirmationHandler.confirmTransactionRequest.mockResolvedValue({ + confirmed: true, + context: { + securityProperties: { securityAlertResponse: 'Benign' }, + }, + }); // Transaction sent successfully. mockSendService.signAndSendTransaction.mockResolvedValue({ @@ -4156,7 +4224,13 @@ describe('ClientRequestHandler - confirmSend validation', () => { transactionRawData: freshTransactionRawData, }), ); - expect(mockSendService.signAndSendTransaction).toHaveBeenCalled(); + expect(mockSendService.signAndSendTransaction).toHaveBeenCalledWith( + expect.objectContaining({ + context: { + securityProperties: { securityAlertResponse: 'Benign' }, + }, + }), + ); // Verify the handler returns the submitted transaction. expect(result).toMatchObject({ diff --git a/packages/tron-wallet-snap/src/handlers/clientRequest/clientRequest.ts b/packages/tron-wallet-snap/src/handlers/clientRequest/clientRequest.ts index d1c48f9b3..5b96a0b13 100644 --- a/packages/tron-wallet-snap/src/handlers/clientRequest/clientRequest.ts +++ b/packages/tron-wallet-snap/src/handlers/clientRequest/clientRequest.ts @@ -730,8 +730,8 @@ export class ClientRequestHandler { * Client requests come from MetaMask's own unified send flow, so the origin * is reported as MetaMask. */ - const confirmed = await this.#confirmationHandler.confirmTransactionRequest( - { + const { confirmed, context } = + await this.#confirmationHandler.confirmTransactionRequest({ scope, fromAddress: account.address, toAddress, @@ -741,20 +741,21 @@ export class ClientRequestHandler { accountType: account.type, origin: DEFAULT_METAMASK_ORIGIN, transactionRawData: freshTransactionRawData, - }, - ); + }); if (!confirmed) { throw new UserRejectedRequestError() as unknown as Error; } /** - * Send the built transaction + * Send the built transaction. The confirmation context is passed along so + * the submitted event reports what the user saw in the confirmation. */ const result = await this.#sendService.signAndSendTransaction({ scope, fromAccountId, transaction, + context, }); // Immediately create and save a detailed pending Send transaction diff --git a/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.test.tsx b/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.test.tsx index 07a2e0a3c..583b8fcc4 100644 --- a/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.test.tsx +++ b/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.test.tsx @@ -1367,6 +1367,34 @@ describe('CronHandler', () => { ); }); + it('keeps the security verdict when rescheduling an unconfirmed transaction', async () => { + await withTrackTransactionCronHandler( + async ({ cronHandler, mockSnapClient, mockTronHttpClient }) => { + mockTronHttpClient.getTransactionInfoById.mockResolvedValue(null); + + await cronHandler.trackTransaction({ + txId: TX_ID, + scope: Network.Mainnet, + accountIds: ACCOUNT_IDS, + attempt: 0, + securityProperties: { securityAlertResponse: 'Benign' }, + }); + + expect(mockSnapClient.scheduleBackgroundEvent).toHaveBeenCalledWith({ + method: BackgroundEventMethod.TrackTransaction, + params: { + txId: TX_ID, + scope: Network.Mainnet, + accountIds: ACCOUNT_IDS, + attempt: 1, + securityProperties: { securityAlertResponse: 'Benign' }, + }, + duration: TRACK_TX_INTERVAL, + }); + }, + ); + }); + it('syncs accounts and emits finalized event when transaction confirms', async () => { await withTrackTransactionCronHandler( async ({ @@ -1408,6 +1436,88 @@ describe('CronHandler', () => { ); }); + it('validates the tracking params before tracking the transaction', async () => { + await withTrackTransactionCronHandler( + async ({ cronHandler, mockTronHttpClient }) => { + mockTronHttpClient.getTransactionInfoById.mockResolvedValue(null); + + await cronHandler.handleTrackTransaction({ + jsonrpc: '2.0', + id: 1, + method: BackgroundEventMethod.TrackTransaction, + params: { + txId: TX_ID, + scope: Network.Mainnet, + accountIds: ACCOUNT_IDS, + attempt: 0, + securityProperties: { securityAlertResponse: 'Benign' }, + }, + }); + + expect( + mockTronHttpClient.getTransactionInfoById, + ).toHaveBeenCalledWith(Network.Mainnet, TX_ID); + }, + ); + }); + + it('rejects tracking params with security fields at the top level', async () => { + await withTrackTransactionCronHandler( + async ({ cronHandler, mockTronHttpClient }) => { + await expect( + cronHandler.handleTrackTransaction({ + jsonrpc: '2.0', + id: 1, + method: BackgroundEventMethod.TrackTransaction, + params: { + txId: TX_ID, + scope: Network.Mainnet, + accountIds: ACCOUNT_IDS, + attempt: 0, + securityAlertResponse: 'Benign', + }, + }), + ).rejects.toThrow('securityAlertResponse'); + expect( + mockTronHttpClient.getTransactionInfoById, + ).not.toHaveBeenCalled(); + }, + ); + }); + + it('reports the security verdict on the finalized event', async () => { + await withTrackTransactionCronHandler( + async ({ cronHandler, mockAccountsService, mockTronHttpClient }) => { + const mockAccount = { id: ACCOUNT_ID, type: 'tron:eoa' }; + mockTronHttpClient.getTransactionInfoById.mockResolvedValue({ + blockNumber: 100, + receipt: { result: 'SUCCESS' }, + }); + mockAccountsService.findByIds.mockResolvedValue([mockAccount]); + + await cronHandler.trackTransaction({ + txId: TX_ID, + scope: Network.Mainnet, + accountIds: ACCOUNT_IDS, + attempt: 0, + transactionType: TransactionType.Send, + securityProperties: { securityAlertResponse: 'Benign' }, + }); + + expect( + mockAnalyticsService.trackTransactionFinalized, + ).toHaveBeenCalledWith({ + origin: DEFAULT_METAMASK_ORIGIN, + accountType: mockAccount.type, + chainIdCaip: Network.Mainnet, + transactionStatus: TransactionStatus.Confirmed, + transactionType: TransactionType.Send, + securityAlertResponse: 'Benign', + }); + }, + ); + }); + it('carries a swap classification through to the finalized event', async () => { await withTrackTransactionCronHandler( async ({ cronHandler, mockAccountsService, mockTronHttpClient }) => { @@ -1524,6 +1634,34 @@ describe('CronHandler', () => { ); }); + it('keeps the security verdict when retrying after a transient error', async () => { + await withTrackTransactionCronHandler( + async ({ cronHandler, mockSnapClient, mockTronHttpClient }) => { + mockTronHttpClient.getTransactionInfoById.mockRejectedValue( + new Error('Network error'), + ); + + await cronHandler.trackTransaction({ + txId: TX_ID, + scope: Network.Mainnet, + accountIds: ACCOUNT_IDS, + attempt: 0, + securityProperties: { securityAlertResponse: 'Benign' }, + }); + + expect(mockSnapClient.scheduleBackgroundEvent).toHaveBeenCalledWith( + expect.objectContaining({ + method: BackgroundEventMethod.TrackTransaction, + params: expect.objectContaining({ + attempt: 1, + securityProperties: { securityAlertResponse: 'Benign' }, + }), + }), + ); + }, + ); + }); + it('syncs accounts when an unconfirmed transaction reaches the limit', async () => { await withTrackTransactionCronHandler( async ({ diff --git a/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.tsx b/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.tsx index 823fae177..a53660770 100644 --- a/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.tsx +++ b/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.tsx @@ -6,6 +6,7 @@ import type { IStateManager, Logger, SecurityAlertsScanOption, + TransactionSecurityProperties, } from '@metamask/snap-networks-utils'; import type { JsonRpcRequest } from '@metamask/snaps-sdk'; @@ -771,6 +772,7 @@ export class CronHandler { * @param params.accountIds - Account IDs to sync after confirmation (first account is always the sender) * @param params.attempt - Current attempt number (for retry logic) * @param params.transactionType - Classification resolved at submit time, carried so the finalized event reports the same flow + * @param params.securityProperties - Security verdict fields from the confirmation, if any */ async trackTransaction({ txId, @@ -778,12 +780,14 @@ export class CronHandler { accountIds, attempt = 0, transactionType, + securityProperties, }: { txId: string; scope: Network; accountIds: string[]; attempt: number; transactionType?: TransactionType; + securityProperties?: TransactionSecurityProperties; }): Promise { this.#logger.info( `[Attempt ${attempt + 1}] Tracking transaction ${txId} on ${scope}...`, @@ -822,6 +826,7 @@ export class CronHandler { accountIds, attempt: attempt + 1, ...(transactionType === undefined ? {} : { transactionType }), + ...(securityProperties === undefined ? {} : { securityProperties }), }, duration: TRACK_TX_INTERVAL, }); @@ -859,6 +864,7 @@ export class CronHandler { chainIdCaip: scope, transactionStatus, transactionType, + ...securityProperties, }); } catch (error) { this.#logger.error( @@ -884,6 +890,7 @@ export class CronHandler { accountIds, attempt: attempt + 1, ...(transactionType === undefined ? {} : { transactionType }), + ...(securityProperties === undefined ? {} : { securityProperties }), }, duration: TRACK_TX_INTERVAL, }); diff --git a/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.test.ts b/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.test.ts index 002f57e6b..ac18b2e5d 100644 --- a/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.test.ts +++ b/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.test.ts @@ -19,6 +19,7 @@ import * as ConfirmSignMessageRender from '../../ui/confirmation/views/ConfirmSi import * as ConfirmSignTransactionComponent from '../../ui/confirmation/views/ConfirmSignTransaction/ConfirmSignTransaction'; import * as ConfirmSignTransactionRender from '../../ui/confirmation/views/ConfirmSignTransaction/render'; import * as ConfirmTransactionRequestRender from '../../ui/confirmation/views/ConfirmTransactionRequest/render'; +import type { ConfirmTransactionRequestResult } from '../../ui/confirmation/views/ConfirmTransactionRequest/types'; import { mockLogger } from '../../utils/mockLogger'; import type { AssetsService } from '../assets/AssetsService'; import { AssetFetchError } from '../assets/errors'; @@ -194,6 +195,22 @@ async function withConfirmationHandler( }); } +/** + * Builds the outcome the ConfirmTransactionRequest render resolves to. + * + * @param overrides - Fields to override on the default outcome. + * @returns The render outcome. + */ +function buildConfirmTransactionRequestResult( + overrides: Partial = {}, +): ConfirmTransactionRequestResult { + return { + result: true, + context: {}, + ...overrides, + }; +} + describe('ConfirmationHandler', () => { beforeEach(() => { vi.spyOn( @@ -208,7 +225,7 @@ describe('ConfirmationHandler', () => { .mockResolvedValue(undefined as never); mockRenderConfirmTransactionRequest = vi .spyOn(ConfirmTransactionRequestRender, 'render') - .mockResolvedValue(undefined as never); + .mockResolvedValue(buildConfirmTransactionRequestResult()); mockGetIconUrlForKnownAsset = vi .spyOn(KnownAssetIcon, 'getIconUrlForKnownAsset') .mockReturnValue('mock-icon-url'); @@ -468,11 +485,16 @@ describe('ConfirmationHandler', () => { it('returns true and tracks approval when user confirms', async () => { await withConfirmationHandler(async ({ handler }) => { - mockRenderConfirmTransactionRequest.mockResolvedValue(true); + mockRenderConfirmTransactionRequest.mockResolvedValue( + buildConfirmTransactionRequestResult(), + ); const result = await handler.confirmTransactionRequest(defaultParams); - expect(result).toBe(true); + expect(result).toStrictEqual({ + confirmed: true, + context: {}, + }); expect(mockAnalyticsService.trackTransactionAdded).toHaveBeenCalledWith( { origin: DEFAULT_METAMASK_ORIGIN, @@ -495,13 +517,39 @@ describe('ConfirmationHandler', () => { }); }); + it('returns the confirmation security properties with the result', async () => { + await withConfirmationHandler(async ({ handler }) => { + mockRenderConfirmTransactionRequest.mockResolvedValue( + buildConfirmTransactionRequestResult({ + context: { + securityProperties: { securityAlertResponse: 'Benign' }, + }, + }), + ); + + const result = await handler.confirmTransactionRequest(defaultParams); + + expect(result).toStrictEqual({ + confirmed: true, + context: { + securityProperties: { securityAlertResponse: 'Benign' }, + }, + }); + }); + }); + it('returns false and tracks rejection when user rejects', async () => { await withConfirmationHandler(async ({ handler }) => { - mockRenderConfirmTransactionRequest.mockResolvedValue(null); + mockRenderConfirmTransactionRequest.mockResolvedValue( + buildConfirmTransactionRequestResult({ result: null }), + ); const result = await handler.confirmTransactionRequest(defaultParams); - expect(result).toBe(false); + expect(result).toStrictEqual({ + confirmed: false, + context: {}, + }); expect( mockAnalyticsService.trackTransactionRejected, ).toHaveBeenCalledWith({ @@ -519,7 +567,9 @@ describe('ConfirmationHandler', () => { it('passes the raw origin and transactionRawData to render', async () => { await withConfirmationHandler( async ({ handler, mockSnapClient, mockState }) => { - mockRenderConfirmTransactionRequest.mockResolvedValue(true); + mockRenderConfirmTransactionRequest.mockResolvedValue( + buildConfirmTransactionRequestResult(), + ); await handler.confirmTransactionRequest({ ...defaultParams, @@ -541,7 +591,9 @@ describe('ConfirmationHandler', () => { it('passes the raw MetaMask origin to render so the scan can recognize it', async () => { await withConfirmationHandler( async ({ handler, mockSnapClient, mockState }) => { - mockRenderConfirmTransactionRequest.mockResolvedValue(true); + mockRenderConfirmTransactionRequest.mockResolvedValue( + buildConfirmTransactionRequestResult(), + ); await handler.confirmTransactionRequest({ ...defaultParams, @@ -557,9 +609,109 @@ describe('ConfirmationHandler', () => { ); }); + it('spreads the security properties of the outcome into Approved', async () => { + await withConfirmationHandler(async ({ handler }) => { + mockRenderConfirmTransactionRequest.mockResolvedValue( + buildConfirmTransactionRequestResult({ + context: { + securityProperties: { + securityAlertResponse: 'Warning', + securityAlertReason: 'transfer_farming', + }, + }, + }), + ); + + await handler.confirmTransactionRequest(defaultParams); + + expect( + mockAnalyticsService.trackTransactionApproved, + ).toHaveBeenCalledWith({ + origin: DEFAULT_METAMASK_ORIGIN, + accountType: 'tron:eoa', + chainIdCaip: Network.Mainnet, + transactionType: TransactionType.Send, + securityAlertResponse: 'Warning', + securityAlertReason: 'transfer_farming', + }); + }); + }); + + it('spreads the security properties of the outcome into Rejected', async () => { + await withConfirmationHandler(async ({ handler }) => { + mockRenderConfirmTransactionRequest.mockResolvedValue( + buildConfirmTransactionRequestResult({ + result: false, + context: { + securityProperties: { + securityAlertResponse: 'Malicious', + securityAlertReason: 'known_attacker', + }, + }, + }), + ); + + await handler.confirmTransactionRequest(defaultParams); + + expect( + mockAnalyticsService.trackTransactionRejected, + ).toHaveBeenCalledWith({ + origin: DEFAULT_METAMASK_ORIGIN, + accountType: 'tron:eoa', + chainIdCaip: Network.Mainnet, + transactionType: TransactionType.Send, + securityAlertResponse: 'Malicious', + securityAlertReason: 'known_attacker', + }); + }); + }); + + it('does not report a reason for a benign outcome on Approved', async () => { + await withConfirmationHandler(async ({ handler }) => { + mockRenderConfirmTransactionRequest.mockResolvedValue( + buildConfirmTransactionRequestResult({ + context: { + securityProperties: { securityAlertResponse: 'Benign' }, + }, + }), + ); + + await handler.confirmTransactionRequest(defaultParams); + + expect( + mockAnalyticsService.trackTransactionApproved, + ).toHaveBeenCalledWith({ + origin: DEFAULT_METAMASK_ORIGIN, + accountType: 'tron:eoa', + chainIdCaip: Network.Mainnet, + transactionType: TransactionType.Send, + securityAlertResponse: 'Benign', + }); + }); + }); + + it('reports no security fields when the outcome has none', async () => { + await withConfirmationHandler(async ({ handler }) => { + mockRenderConfirmTransactionRequest.mockResolvedValue( + buildConfirmTransactionRequestResult({ + context: {}, + }), + ); + + await handler.confirmTransactionRequest(defaultParams); + + expect( + vi.mocked(mockAnalyticsService.trackTransactionApproved).mock + .calls[0]?.[0], + ).not.toHaveProperty('securityAlertResponse'); + }); + }); + it('clears the interface ID after render completes', async () => { await withConfirmationHandler(async ({ handler, mockState }) => { - mockRenderConfirmTransactionRequest.mockResolvedValue(true); + mockRenderConfirmTransactionRequest.mockResolvedValue( + buildConfirmTransactionRequestResult(), + ); await handler.confirmTransactionRequest(defaultParams); @@ -572,12 +724,14 @@ describe('ConfirmationHandler', () => { it('logs error but does not throw when clearing interface ID fails', async () => { await withConfirmationHandler(async ({ handler, mockState }) => { - mockRenderConfirmTransactionRequest.mockResolvedValue(true); + mockRenderConfirmTransactionRequest.mockResolvedValue( + buildConfirmTransactionRequestResult(), + ); mockState.setKey.mockRejectedValue(new Error('state write failed')); const result = await handler.confirmTransactionRequest(defaultParams); - expect(result).toBe(true); + expect(result.confirmed).toBe(true); expect(mockState.setKey).toHaveBeenCalledWith( 'mapInterfaceNameToId.confirmTransaction', null, @@ -590,7 +744,9 @@ describe('ConfirmationHandler', () => { async ({ handler, mockSnapClient, mockState }) => { const error = new Error('state write failed'); - mockRenderConfirmTransactionRequest.mockResolvedValue(true); + mockRenderConfirmTransactionRequest.mockResolvedValue( + buildConfirmTransactionRequestResult(), + ); mockState.setKey.mockRejectedValue(error); await handler.confirmTransactionRequest(defaultParams); @@ -629,6 +785,25 @@ describe('ConfirmationHandler', () => { }, }; + it('rejects a request with an unhandled method', async () => { + await withConfirmationHandler(async ({ handler }) => { + await expect( + handler.handleKeyringRequest({ + request: { + ...request, + request: { + ...request.request, + method: 'tron_unknownMethod' as never, + }, + }, + account: mockAccount, + }), + ).rejects.toThrow( + 'Unhandled keyring request method: tron_unknownMethod', + ); + }); + }); + it('passes deserialized raw data when rendering signTransaction confirmation', async () => { await withConfirmationHandler(async ({ handler, mockTronWeb }) => { mockTronWeb.utils.deserializeTx.deserializeTransaction.mockReturnValue( diff --git a/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.ts b/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.ts index f531e0f36..3342d133b 100644 --- a/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.ts +++ b/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.ts @@ -26,6 +26,7 @@ import { render as renderConfirmSignTransaction } from '../../ui/confirmation/vi import { CONFIRM_SIGN_TRANSACTION_INTERFACE_NAME } from '../../ui/confirmation/views/ConfirmSignTransaction/types'; import type { ConfirmSignTransactionContext } from '../../ui/confirmation/views/ConfirmSignTransaction/types'; import { render as renderConfirmTransactionRequest } from '../../ui/confirmation/views/ConfirmTransactionRequest/render'; +import type { ConfirmTransactionRequestResult } from '../../ui/confirmation/views/ConfirmTransactionRequest/types'; import { CONFIRM_TRANSACTION_INTERFACE_NAME } from '../../ui/confirmation/views/ConfirmTransactionRequest/types'; import { resolveTransactionType } from '../../utils/transactionType'; import { SignTransactionRequestStruct } from '../../validation/structs'; @@ -194,7 +195,10 @@ export class ConfirmationHandler { accountType: string; origin: string; transactionRawData: TronwebTypes.Transaction['raw_data']; - }): Promise { + }): Promise<{ + confirmed: boolean; + context: ConfirmTransactionRequestResult['context']; + }> { const trackingProperties = { origin, accountType, @@ -209,7 +213,7 @@ export class ConfirmationHandler { // Track Transaction Added event await this.#analyticsService.trackTransactionAdded(trackingProperties); - const result = await renderConfirmTransactionRequest( + const { result, context } = await renderConfirmTransactionRequest( this.#snapClient, this.#state, { @@ -232,14 +236,22 @@ export class ConfirmationHandler { await this.#clearInterfaceId(CONFIRM_TRANSACTION_INTERFACE_NAME); - // Track Transaction Rejected event if user rejects + const propertiesToReport = { + ...trackingProperties, + ...context.securityProperties, + }; + if (result === true) { - await this.#analyticsService.trackTransactionApproved(trackingProperties); + await this.#analyticsService.trackTransactionApproved(propertiesToReport); } else { - await this.#analyticsService.trackTransactionRejected(trackingProperties); + // Track Transaction Rejected event if user rejects + await this.#analyticsService.trackTransactionRejected(propertiesToReport); } - return result === true; + return { + confirmed: result === true, + context, + }; } /** diff --git a/packages/tron-wallet-snap/src/services/send/SendService.test.ts b/packages/tron-wallet-snap/src/services/send/SendService.test.ts index 54c53839f..0b21e4c67 100644 --- a/packages/tron-wallet-snap/src/services/send/SendService.test.ts +++ b/packages/tron-wallet-snap/src/services/send/SendService.test.ts @@ -49,6 +49,7 @@ describe('SendService', () => { let mockTronWebFactory: any; let mockFeeCalculatorService: any; let mockSnapClient: any; + let mockScheduleBackgroundEvent: Mock; let mockTronWeb: any; let mockTransactionExpirationRefresherService: any; @@ -149,8 +150,9 @@ describe('SendService', () => { computeFee: vi.fn(), }; + mockScheduleBackgroundEvent = vi.fn(); mockSnapClient = { - scheduleBackgroundEvent: vi.fn(), + scheduleBackgroundEvent: mockScheduleBackgroundEvent, }; mockTransactionExpirationRefresherService = { @@ -223,6 +225,57 @@ describe('SendService', () => { }); }); + it('tracks the security properties with the submitted event', async () => { + await sendService.signAndSendTransaction({ + scope: Network.Mainnet, + fromAccountId: TEST_ACCOUNT_ID, + transaction: createMockTransaction(), + context: { + securityProperties: { + securityAlertResponse: 'Benign', + }, + }, + }); + + expect( + mockAnalyticsService.trackTransactionSubmitted, + ).toHaveBeenCalledWith({ + origin: DEFAULT_METAMASK_ORIGIN, + accountType: 'tron:eoa', + chainIdCaip: Network.Mainnet, + transactionType: TransactionType.Send, + securityAlertResponse: 'Benign', + }); + }); + + it('schedules tracking with the security properties nested under securityProperties', async () => { + await sendService.signAndSendTransaction({ + scope: Network.Mainnet, + fromAccountId: TEST_ACCOUNT_ID, + transaction: createMockTransaction(), + context: { + securityProperties: { + securityAlertResponse: 'Benign', + }, + }, + }); + + expect(mockScheduleBackgroundEvent).toHaveBeenCalledWith({ + method: BackgroundEventMethod.TrackTransaction, + params: { + txId: 'broadcast-tx-id', + scope: Network.Mainnet, + accountIds: [TEST_ACCOUNT_ID], + attempt: 0, + transactionType: TransactionType.Send, + securityProperties: { + securityAlertResponse: 'Benign', + }, + }, + duration: TRACK_TX_INTERVAL, + }); + }); + it('classifies a unified TRC20 send as send rather than unknown', async () => { const transaction = createMockTrc20Transaction(); @@ -276,6 +329,7 @@ describe('SendService', () => { let mockTronWebFactory: any; let mockFeeCalculatorService: any; let mockSnapClient: any; + let mockScheduleBackgroundEvent: Mock; let mockTronWeb: any; let mockTransactionExpirationRefresherService: { ensureFreshMetadata: Mock; @@ -415,8 +469,9 @@ describe('SendService', () => { computeFee: vi.fn(), }; + mockScheduleBackgroundEvent = vi.fn(); mockSnapClient = { - scheduleBackgroundEvent: vi.fn(), + scheduleBackgroundEvent: mockScheduleBackgroundEvent, }; mockTransactionExpirationRefresherService = { diff --git a/packages/tron-wallet-snap/src/services/send/SendService.ts b/packages/tron-wallet-snap/src/services/send/SendService.ts index 3afa29a80..153711a7c 100644 --- a/packages/tron-wallet-snap/src/services/send/SendService.ts +++ b/packages/tron-wallet-snap/src/services/send/SendService.ts @@ -10,6 +10,7 @@ import { Networks, TRACK_TX_INTERVAL, ZERO } from '../../constants'; import type { AssetEntity } from '../../entities/assets'; import { SendErrorCodes } from '../../handlers/clientRequest/types'; import { BackgroundEventMethod } from '../../handlers/cronjob/cronjob'; +import type { ConfirmTransactionRequestResult } from '../../ui/confirmation/views/ConfirmTransactionRequest/types'; import { isSuccessfulBroadcast, throwOnTransientBroadcastFailure, @@ -389,6 +390,7 @@ export class SendService { fromAccountId, transaction, origin = DEFAULT_METAMASK_ORIGIN, + context, }: { scope: Network; fromAccountId: string; @@ -397,6 +399,7 @@ export class SendService { | TronwebTypes.Transaction | TronwebTypes.Transaction; origin?: string; + context?: ConfirmTransactionRequestResult['context']; // TODO: Replace `any` with type // eslint-disable-next-line @typescript-eslint/no-explicit-any }): Promise> { @@ -449,11 +452,14 @@ export class SendService { } const txId = result.txid ?? freshTransaction.txID; + const securityProperties = context?.securityProperties; + await this.#analyticsService.trackTransactionSubmitted({ origin, accountType: account.type, chainIdCaip: scope, transactionType, + ...securityProperties, }); await this.#snapClient.scheduleBackgroundEvent({ @@ -464,6 +470,7 @@ export class SendService { accountIds: [fromAccountId], attempt: 0, transactionType, + ...(securityProperties ? { securityProperties } : {}), }, duration: TRACK_TX_INTERVAL, }); diff --git a/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmTransactionRequest/render.test.tsx b/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmTransactionRequest/render.test.tsx index 85a49ccb2..af14f73a4 100644 --- a/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmTransactionRequest/render.test.tsx +++ b/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmTransactionRequest/render.test.tsx @@ -9,7 +9,7 @@ import { extractScanParametersFromTransactionData, } from '../../../../clients/security-alerts-api/utils'; import type { SnapClient } from '../../../../clients/snap/SnapClient'; -import { Network } from '../../../../constants'; +import { KnownCaip19Id, Network, TokenMetadata } from '../../../../constants'; import snapContext from '../../../../context'; import type { AssetEntity } from '../../../../entities/assets'; import { BackgroundEventMethod } from '../../../../handlers/cronjob/cronjob'; @@ -393,9 +393,9 @@ describe('ConfirmTransactionRequest render', () => { new Error('Failed to load'), ); - const result = await callRender(); + const outcome = await callRender(); - expect(result).toBe(true); + expect(outcome.result).toBe(true); expect(mockTransactionScanService.scanTransaction).toHaveBeenCalled(); }, ); @@ -480,12 +480,161 @@ describe('ConfirmTransactionRequest render', () => { await withRender(async ({ callRender, mockSnapClient }) => { mockSnapClient.showDialog.mockResolvedValue(true); - const result = await callRender(); + const outcome = await callRender(); - expect(result).toBe(true); + expect(outcome.result).toBe(true); }); }); + it('returns the security verdict shown in the dialog', async () => { + await withRender(async ({ callRender }) => { + const outcome = await callRender(); + + expect(outcome).toStrictEqual({ + result: true, + context: { + securityProperties: { securityAlertResponse: 'Benign' }, + }, + }); + }); + }); + + it('marks token prices as fetched when external pricing is disabled', async () => { + await withRender(async ({ callRender, mockSnapClient }) => { + mockSnapClient.getPreferences.mockResolvedValue({ + ...defaultPreferences, + useExternalPricingData: false, + }); + + await callRender(); + + expect(mockSnapClient.updateInterface).toHaveBeenCalledWith( + 'interface-id-123', + expect.anything(), + expect.objectContaining({ + tokenPricesFetchStatus: FetchStatus.Fetched, + }), + ); + }); + }); + + it('reports no security fields when only simulation is enabled', async () => { + await withRender(async ({ callRender, mockSnapClient }) => { + mockSnapClient.getPreferences.mockResolvedValue({ + ...defaultPreferences, + useSecurityAlerts: false, + simulateOnChainActions: true, + }); + + const outcome = await callRender(); + + expect(outcome.context.securityProperties).toBeUndefined(); + }); + }); + + it('reports an error verdict without a description when the scan throws', async () => { + await withRender(async ({ callRender, mockTransactionScanService }) => { + mockTransactionScanService.scanTransaction.mockRejectedValue( + new Error('Scan failed'), + ); + + const outcome = await callRender(); + + expect(outcome).toStrictEqual({ + result: true, + context: { + securityProperties: { + securityAlertResponse: 'Error', + securityAlertReason: 'Error', + }, + }, + }); + }); + }); + + it('reports an error verdict without a description when the scan returns no result', async () => { + await withRender(async ({ callRender, mockTransactionScanService }) => { + mockTransactionScanService.scanTransaction.mockResolvedValue(null); + + const outcome = await callRender(); + + expect(outcome.context.securityProperties).toStrictEqual({ + securityAlertResponse: 'Error', + securityAlertReason: 'Error', + }); + }); + }); + + it('resolves the icon URL for each fee asset', async () => { + await withRender(async ({ callRender, mockSnapClient }) => { + await callRender({ + fees: [ + { + type: 'base', + asset: { + unit: 'TRX', + type: KnownCaip19Id.TrxMainnet, + amount: '0.02', + fungible: true, + }, + }, + ] as never, + }); + + const [, context] = mockSnapClient.createInterface.mock + .calls[0] as unknown as [ + unknown, + { fees: { asset: { iconUrl?: string } }[] }, + ]; + expect(context.fees[0]?.asset.iconUrl).toBe( + TokenMetadata[KnownCaip19Id.TrxMainnet].iconUrl, + ); + }); + }); + + it('reports no security fields for an unsupported contract type, even when the scan returns a verdict', async () => { + await withRender( + async ({ callRender, mockSnapClient, mockTransactionScanService }) => { + mockSnapClient.getPreferences.mockResolvedValue({ + ...defaultPreferences, + useSecurityAlerts: true, + }); + const trc10RawData = { + ...defaultTransactionRawData, + contract: [ + { + ...defaultTransactionRawData.contract[0], + type: TronwebTypes.ContractType.TransferAssetContract, + }, + ], + } as TronwebTypes.Transaction['raw_data']; + + const outcome = await callRender({ transactionRawData: trc10RawData }); + + expect( + mockTransactionScanService.scanTransaction, + ).toHaveBeenCalledTimes(1); + expect(outcome.context.securityProperties).toBeUndefined(); + }, + ); + }); + + it('reports no security fields when the scan service is missing', async () => { + await withRender( + { hasTransactionScanService: false }, + async ({ callRender, mockSnapClient }) => { + mockSnapClient.getPreferences.mockResolvedValue({ + ...defaultPreferences, + useSecurityAlerts: true, + }); + + const outcome = await callRender(); + + expect(outcome.context.securityProperties).toBeUndefined(); + }, + ); + }); + it('stores interface ID in state for background refresh', async () => { await withRender(async ({ callRender, mockState }) => { await callRender(); diff --git a/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmTransactionRequest/render.tsx b/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmTransactionRequest/render.tsx index f15e78ad7..90b3d0efb 100644 --- a/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmTransactionRequest/render.tsx +++ b/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmTransactionRequest/render.tsx @@ -1,12 +1,16 @@ -import { DEFAULT_METAMASK_ORIGIN } from '@metamask/snap-networks-utils'; +import { + DEFAULT_METAMASK_ORIGIN, + getTransactionSecurityProperties, +} from '@metamask/snap-networks-utils'; import type { ExtendedKeyringAccount, IStateManager, SecurityAlertsScanOption, } from '@metamask/snap-networks-utils'; -import type { DialogResult, Json } from '@metamask/snaps-sdk'; +import type { Json } from '@metamask/snaps-sdk'; import type { Types as TronwebTypes } from 'tronweb'; +import { isContractTypeSupported } from '../../../../clients/security-alerts-api/utils'; import type { SnapClient } from '../../../../clients/snap/SnapClient'; import { Network } from '../../../../constants'; import snapContext from '../../../../context'; @@ -20,7 +24,10 @@ import { assertTransactionStructure } from '../../../../validation/transaction'; import { getIconUrlForKnownAsset } from '../../utils/getIconUrlForKnownAsset'; import { ConfirmTransactionRequest } from './ConfirmTransactionRequest'; import { CONFIRM_TRANSACTION_INTERFACE_NAME } from './types'; -import type { ConfirmTransactionRequestContext } from './types'; +import type { + ConfirmTransactionRequestContext, + ConfirmTransactionRequestResult, +} from './types'; export const DEFAULT_CONFIRMATION_CONTEXT: ConfirmTransactionRequestContext = { scope: Network.Mainnet, @@ -75,7 +82,7 @@ export const DEFAULT_CONFIRMATION_CONTEXT: ConfirmTransactionRequestContext = { * @param incomingContext.origin - The origin string to display. * @param incomingContext.accountType - The account type for analytics. * @param incomingContext.transactionRawData - The raw transaction data for security scanning. - * @returns A dialog result with the user's decision. + * @returns The user's decision and context data. */ export async function render( snapClient: SnapClient, @@ -91,7 +98,7 @@ export async function render( accountType: string; transactionRawData: TronwebTypes.Transaction['raw_data']; }, -): Promise { +): Promise { const { transactionScanService } = snapContext; const { transactionRawData } = incomingContext; @@ -211,7 +218,24 @@ export async function render( }); } - // 7. Return the dialog promise immediately (don't await it!) + // 7. Wait for the user's decision, then return it with the security properties + // of the scan that was shown. // Cleanup happens in the background refresh handler when it detects the interface is gone - return dialogPromise; + const result = await dialogPromise; + + const validationRequested = securityScanEnabled && useSecurityAlerts; + + // Without validation, or for a contract type the service skips, no response is + // stored, so there is no security data to report. + const securityProperties = + validationRequested && isContractTypeSupported(transactionRawData) + ? getTransactionSecurityProperties(context.scan) + : undefined; + + return { + result, + context: { + securityProperties, + }, + }; } diff --git a/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmTransactionRequest/types.ts b/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmTransactionRequest/types.ts index 5e5a57d5a..fe18437e4 100644 --- a/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmTransactionRequest/types.ts +++ b/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmTransactionRequest/types.ts @@ -1,4 +1,5 @@ -import type { Json } from '@metamask/snaps-sdk'; +import type { TransactionSecurityProperties } from '@metamask/snap-networks-utils'; +import type { DialogResult, Json } from '@metamask/snaps-sdk'; import type { SpotPrices } from '../../../../clients/price-api/types'; import type { Network } from '../../../../constants'; @@ -28,3 +29,18 @@ export type ConfirmTransactionRequestContext = { transactionRawData: Json; accountType: string; }; + +/** + * The user's decision in the ConfirmTransactionRequest dialog, with context data. + */ +export type ConfirmTransactionRequestResult = { + /** The dialog result. `true` when the user confirmed. */ + result: DialogResult; + context: { + /** + * The security properties of the scan shown in the dialog, ready to report. + * `undefined` when the dialog produced no security data. + */ + securityProperties?: TransactionSecurityProperties; + }; +}; diff --git a/packages/tron-wallet-snap/src/validation/structs.test.ts b/packages/tron-wallet-snap/src/validation/structs.test.ts index 60228d0f3..56f384c29 100644 --- a/packages/tron-wallet-snap/src/validation/structs.test.ts +++ b/packages/tron-wallet-snap/src/validation/structs.test.ts @@ -1,7 +1,13 @@ /* eslint-disable vitest/require-to-throw-message */ import { assert, is } from '@metamask/superstruct'; -import { Base58Struct, Base64Struct } from './structs'; +import { Network } from '../constants'; +import { + Base58Struct, + Base64Struct, + PrivateKeyHexStruct, + TrackTransactionParamsStruct, +} from './structs'; describe('structs', () => { describe('Base58Struct', () => { @@ -113,4 +119,76 @@ describe('structs', () => { }); }); }); + + describe('non-string values', () => { + it('rejects non-string Base58 and private key values', () => { + expect(is(123, Base58Struct)).toBe(false); + expect(is(123, PrivateKeyHexStruct)).toBe(false); + }); + }); + + describe('TrackTransactionParamsStruct', () => { + const params = { + txId: 'tx-id', + scope: Network.Mainnet, + accountIds: ['account-id'], + attempt: 0, + }; + + it('accepts params without security properties', () => { + expect(is(params, TrackTransactionParamsStruct)).toBe(true); + }); + + it('accepts security properties nested under securityProperties', () => { + expect( + is( + { + ...params, + securityProperties: { + securityAlertResponse: 'Warning', + securityAlertReason: 'Malicious', + securityAlertDescription: 'Known scam address', + }, + }, + TrackTransactionParamsStruct, + ), + ).toBe(true); + }); + + it('rejects security fields sent at the top level', () => { + expect( + is( + { ...params, securityAlertResponse: 'Benign' }, + TrackTransactionParamsStruct, + ), + ).toBe(false); + }); + + it('accepts the loading and not-applicable verdicts', () => { + expect( + is( + { + ...params, + securityProperties: { + securityAlertResponse: 'Loading', + securityAlertReason: 'NotApplicable', + }, + }, + TrackTransactionParamsStruct, + ), + ).toBe(true); + }); + + it('rejects an unknown security verdict', () => { + expect( + is( + { + ...params, + securityProperties: { securityAlertResponse: 'Unknown' }, + }, + TrackTransactionParamsStruct, + ), + ).toBe(false); + }); + }); }); diff --git a/packages/tron-wallet-snap/src/validation/structs.ts b/packages/tron-wallet-snap/src/validation/structs.ts index 99ba8f0ef..6047c325d 100644 --- a/packages/tron-wallet-snap/src/validation/structs.ts +++ b/packages/tron-wallet-snap/src/validation/structs.ts @@ -6,7 +6,10 @@ import { TrxAccountType, } from '@metamask/keyring-api'; import { ExportAccountOptionsStruct } from '@metamask/keyring-api/v2'; -import { UuidStruct } from '@metamask/snap-networks-utils'; +import { + TransactionSecurityPropertiesStruct, + UuidStruct, +} from '@metamask/snap-networks-utils'; import type { Infer, Struct } from '@metamask/superstruct'; import { array, @@ -86,6 +89,7 @@ export const TrackTransactionParamsStruct = object({ accountIds: array(string()), attempt: integer(), transactionType: optional(enums(Object.values(TransactionType))), + securityProperties: optional(TransactionSecurityPropertiesStruct), }); /** diff --git a/packages/tron-wallet-snap/vitest.config.ts b/packages/tron-wallet-snap/vitest.config.ts index a4bdcade9..b8f41546f 100644 --- a/packages/tron-wallet-snap/vitest.config.ts +++ b/packages/tron-wallet-snap/vitest.config.ts @@ -37,10 +37,10 @@ export default mergeConfig( coverage: { exclude: ['src/utils/logger.ts'], thresholds: { - branches: 77.31, - functions: 86.5, - lines: 87.63, - statements: 87.55, + branches: 78.06, + functions: 86.9, + lines: 87.95, + statements: 87.86, }, }, }, From 84eee933fb11b18eec29a0d3167ed9ea9aefba2b Mon Sep 17 00:00:00 2001 From: Andrew Taran Date: Fri, 20 Nov 2026 16:27:56 +0100 Subject: [PATCH 2/2] test(tron): cover sign confirmation when the price fetch fails --- packages/tron-wallet-snap/CHANGELOG.md | 2 +- .../ConfirmSignTransaction/render.test.tsx | 50 +++++++++++++++++++ packages/tron-wallet-snap/vitest.config.ts | 6 +-- 3 files changed, 54 insertions(+), 4 deletions(-) diff --git a/packages/tron-wallet-snap/CHANGELOG.md b/packages/tron-wallet-snap/CHANGELOG.md index 6986ef27f..5f8f57011 100644 --- a/packages/tron-wallet-snap/CHANGELOG.md +++ b/packages/tron-wallet-snap/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Add security telemetry fields to the "Transaction Approved", "Transaction Rejected", "Transaction Submitted", and "Transaction Finalized" events for the send flow +- Add security telemetry fields to the "Transaction Approved", "Transaction Rejected", "Transaction Submitted", and "Transaction Finalized" events for the send flow ([#660](https://github.com/MetaMask/internal-snaps/pull/660)) ## [4.5.0] diff --git a/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmSignTransaction/render.test.tsx b/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmSignTransaction/render.test.tsx index e0dab9972..70f7b0d5e 100644 --- a/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmSignTransaction/render.test.tsx +++ b/packages/tron-wallet-snap/src/ui/confirmation/views/ConfirmSignTransaction/render.test.tsx @@ -1,5 +1,6 @@ import type { FeeType } from '@metamask/keyring-api'; import { bytesToBase64, bytesToHex, stringToBytes } from '@metamask/utils'; +import type { Types as TronwebTypes } from 'tronweb'; import type { Mocked, Mock } from 'vitest'; import type { SnapClient } from '../../../../clients/snap/SnapClient'; @@ -764,6 +765,55 @@ describe('ConfirmSignTransaction render', () => { }); }); + it('renders without token prices when the price fetch fails', async () => { + await withSnapContext(async ({ mockSnapClient, mockPriceApiClient }) => { + mockPriceApiClient.getMultipleSpotPrices.mockRejectedValue( + new Error('price API down'), + ); + + const request: TronWalletKeyringRequest = { + id: '00000000-0000-4000-8000-00000000000a', + origin: 'https://test.com', + account: mockAccount.id, + scope: Network.Mainnet, + request: { + method: TronMultichainMethod.SignTransaction, + params: { + address: mockAccount.address, + transaction: { + rawDataHex: toHex('transaction'), + type: 'TransferContract', + }, + }, + }, + }; + + const mockRawData = { + contract: [], + }; + + // A failed price fetch falls back to empty prices, so render still completes. + expect( + await render( + request, + mockAccount, + mockRawData as unknown as TronwebTypes.Transaction['raw_data'], + ), + ).toBe(true); + expect(mockPriceApiClient.getMultipleSpotPrices).toHaveBeenCalled(); + + const finalContext = mockSnapClient.updateInterface.mock.calls.at( + -1, + )?.[2] as { + tokenPrices: Record; + tokenPricesFetchStatus: string; + }; + + expect(finalContext.tokenPrices).toStrictEqual({}); + expect(finalContext.tokenPricesFetchStatus).toBe(FetchStatus.Fetched); + }); + }); + it('falls back to an error state when updating the interface fails', async () => { await withSnapContext(async ({ mockSnapClient }) => { mockSnapClient.updateInterface.mockImplementationOnce(async () => { diff --git a/packages/tron-wallet-snap/vitest.config.ts b/packages/tron-wallet-snap/vitest.config.ts index b8f41546f..1a0902d4a 100644 --- a/packages/tron-wallet-snap/vitest.config.ts +++ b/packages/tron-wallet-snap/vitest.config.ts @@ -38,9 +38,9 @@ export default mergeConfig( exclude: ['src/utils/logger.ts'], thresholds: { branches: 78.06, - functions: 86.9, - lines: 87.95, - statements: 87.86, + functions: 87.1, + lines: 87.98, + statements: 87.89, }, }, },