Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/tron-wallet-snap/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 ([#660](https://github.com/MetaMask/internal-snaps/pull/660))

## [4.5.0]

### Added
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 ({
Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -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({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down
138 changes: 138 additions & 0 deletions packages/tron-wallet-snap/src/handlers/cronjob/cronjob.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 ({
Expand Down Expand Up @@ -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 }) => {
Expand Down Expand Up @@ -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 ({
Expand Down
7 changes: 7 additions & 0 deletions packages/tron-wallet-snap/src/handlers/cronjob/cronjob.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
IStateManager,
Logger,
SecurityAlertsScanOption,
TransactionSecurityProperties,
} from '@metamask/snap-networks-utils';
import type { JsonRpcRequest } from '@metamask/snaps-sdk';

Expand Down Expand Up @@ -771,19 +772,22 @@ 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,
scope,
accountIds,
attempt = 0,
transactionType,
securityProperties,
}: {
txId: string;
scope: Network;
accountIds: string[];
attempt: number;
transactionType?: TransactionType;
securityProperties?: TransactionSecurityProperties;
}): Promise<void> {
this.#logger.info(
`[Attempt ${attempt + 1}] Tracking transaction ${txId} on ${scope}...`,
Expand Down Expand Up @@ -822,6 +826,7 @@ export class CronHandler {
accountIds,
attempt: attempt + 1,
...(transactionType === undefined ? {} : { transactionType }),
...(securityProperties === undefined ? {} : { securityProperties }),
},
duration: TRACK_TX_INTERVAL,
});
Expand Down Expand Up @@ -859,6 +864,7 @@ export class CronHandler {
chainIdCaip: scope,
transactionStatus,
transactionType,
...securityProperties,
});
} catch (error) {
this.#logger.error(
Expand All @@ -884,6 +890,7 @@ export class CronHandler {
accountIds,
attempt: attempt + 1,
...(transactionType === undefined ? {} : { transactionType }),
...(securityProperties === undefined ? {} : { securityProperties }),
},
duration: TRACK_TX_INTERVAL,
});
Expand Down
Loading