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
3 changes: 0 additions & 3 deletions eslint-suppressions.json
Original file line number Diff line number Diff line change
Expand Up @@ -229,9 +229,6 @@
"packages/solana-wallet-snap/src/core/handlers/onCronjob/backgroundEvents/refreshConfirmationEstimation.test.tsx": {
"@typescript-eslint/explicit-function-return-type": {
"count": 2
},
"@typescript-eslint/no-explicit-any": {
"count": 1
}
},
"packages/solana-wallet-snap/src/core/handlers/onCronjob/backgroundEvents/refreshConfirmationEstimation.tsx": {
Expand Down
1 change: 1 addition & 0 deletions packages/solana-wallet-snap/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed

- **BREAKING:** Preserve dapp-origin `signTransaction` and `signAndSendTransaction` payloads by signing the decoded transaction directly ([#156](https://github.com/MetaMask/internal-snaps/pull/156))
- Prevent signing dapp transactions with expired blockhashes, and refresh the blockhash for MetaMask-originated transactions before signing. ([#183](https://github.com/MetaMask/internal-snaps/pull/183))

## [6.0.0]

Expand Down
3 changes: 3 additions & 0 deletions packages/solana-wallet-snap/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,9 @@
"transactionScan.errors.slippageToleranceExceeded": {
"message": "The transaction was reverted because the slippage tolerance was exceeded."
},
"transactionScan.errors.transactionBlockhashExpired": {
"message": "Please go back and try again"
},
"transactionScan.errors.unknownError": {
"message": "An unknown error occurred."
}
Expand Down
1 change: 1 addition & 0 deletions packages/solana-wallet-snap/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,5 +92,6 @@
"transactionScan.errors.accountAlreadyInUse": "An account with the same address already exists.",
"transactionScan.errors.insufficientSol": "Account does not have enough SOL to perform the operation.",
"transactionScan.errors.slippageToleranceExceeded": "The transaction was reverted because the slippage tolerance was exceeded.",
"transactionScan.errors.transactionBlockhashExpired": "Please go back and try again",
"transactionScan.errors.unknownError": "An unknown error occurred."
}
2 changes: 1 addition & 1 deletion packages/solana-wallet-snap/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/MetaMask/internal-snaps.git"
},
"source": {
"shasum": "lKgpeQgMXQzAgQ8GpHxIQ0ot/jc+D5HIZhrccB9fUjI=",
"shasum": "oXoiahUrkV7oLuS2LwK44vux9N9FxF3/9x696z1Pdcg=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
import { SolMethod } from '@metamask/keyring-api';
import type { JsonRpcParams, JsonRpcRequest } from '@metamask/utils';

import { transactionScanService, state } from '../../../../snapContext';
import { Network } from '../../../constants/solana';
import { METAMASK_ORIGIN, Network } from '../../../constants/solana';
import { serialize } from '../../../serialization/serialize';
import { EXPIRED_TRANSACTION_SCAN } from '../../../services/transaction-scan/buildExpiredScanResult';
import { isTransactionBlockhashExpired } from '../../../services/transaction-scan/isTransactionBlockhashExpired';
import { trackError } from '../../../utils/errors';
import { getInterfaceContext, updateInterface } from '../../../utils/interface';
import { refreshConfirmationEstimation } from './refreshConfirmationEstimation';

jest.mock(
'../../../services/transaction-scan/isTransactionBlockhashExpired',
() => ({
isTransactionBlockhashExpired: jest.fn().mockResolvedValue(false),
}),
);

jest.mock('../../../utils/errors', () => ({
trackError: jest.fn().mockResolvedValue('tracked-error-id'),
}));
Expand All @@ -29,6 +39,9 @@ jest.mock(
);

jest.mock('../../../../snapContext', () => ({
connection: {
getRpc: jest.fn(),
},
state: {
getKey: jest.fn(),
},
Expand All @@ -38,6 +51,8 @@ jest.mock('../../../../snapContext', () => ({
}));

const setupTest = () => {
jest.clearAllMocks();

const interfaceContext = {
account: {
address: 'BLw3RweJmfbTapJRgnPRvd962YDjFYAnVGd1p5hmZ5tP',
Expand All @@ -58,9 +73,34 @@ const setupTest = () => {
(getInterfaceContext as jest.Mock).mockResolvedValue(interfaceContext);
(updateInterface as jest.Mock).mockResolvedValue(undefined);
(serialize as jest.Mock).mockImplementation((value) => value);
jest.mocked(isTransactionBlockhashExpired).mockResolvedValue(false);

return interfaceContext;
};

describe('refreshConfirmationEstimation', () => {
it('disables confirmation with an expired scan result for an invalid blockhash', async () => {
setupTest();

(transactionScanService.scanTransaction as jest.Mock).mockResolvedValue({
status: 'SUCCESS',
});
jest.mocked(isTransactionBlockhashExpired).mockResolvedValue(true);

await refreshConfirmationEstimation({
request: {} as JsonRpcRequest<JsonRpcParams>,
});

expect(updateInterface).toHaveBeenCalledWith(
'interface-id',
null,
expect.objectContaining({
scan: EXPIRED_TRANSACTION_SCAN,
scanFetchStatus: 'fetched',
}),
);
});

it('tracks refresh failures and restores the fetched state', async () => {
setupTest();

Expand All @@ -70,7 +110,9 @@ describe('refreshConfirmationEstimation', () => {
error,
);

await refreshConfirmationEstimation({ request: {} as any });
await refreshConfirmationEstimation({
request: {} as JsonRpcRequest<JsonRpcParams>,
});

expect(trackError).toHaveBeenCalledWith(error);
expect(updateInterface).toHaveBeenLastCalledWith(
Expand All @@ -81,4 +123,74 @@ describe('refreshConfirmationEstimation', () => {
}),
);
});

it('checks blockhash expiry when simulation is disabled', async () => {
const interfaceContext = setupTest();

interfaceContext.preferences = {
simulateOnChainActions: false,
};
(getInterfaceContext as jest.Mock).mockResolvedValue(interfaceContext);
jest.mocked(isTransactionBlockhashExpired).mockResolvedValue(true);

await refreshConfirmationEstimation({
request: {} as JsonRpcRequest<JsonRpcParams>,
});

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: METAMASK_ORIGIN,
};
(getInterfaceContext as jest.Mock).mockResolvedValue(interfaceContext);

await refreshConfirmationEstimation({
request: {} as JsonRpcRequest<JsonRpcParams>,
});

expect(isTransactionBlockhashExpired).not.toHaveBeenCalled();
});

it('preserves the existing scan while checking a valid blockhash without simulation', async () => {
const existingScan = { status: 'SUCCESS' };
const interfaceContext = {
...setupTest(),
preferences: { simulateOnChainActions: false },
scan: existingScan,
};

(getInterfaceContext as jest.Mock).mockResolvedValue(interfaceContext);

await refreshConfirmationEstimation({
request: {} as JsonRpcRequest<JsonRpcParams>,
});

expect(transactionScanService.scanTransaction).not.toHaveBeenCalled();
expect(updateInterface).toHaveBeenNthCalledWith(
1,
'interface-id',
null,
expect.objectContaining({ scanFetchStatus: 'fetching' }),
);
expect(updateInterface).toHaveBeenLastCalledWith(
'interface-id',
null,
expect.objectContaining({
scan: existingScan,
scanFetchStatus: 'fetched',
}),
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,24 @@ import type { OnCronjobHandler } from '@metamask/snaps-sdk';

import { ConfirmTransactionRequest } from '../../../../features/confirmation/views/ConfirmTransactionRequest/ConfirmTransactionRequest';
import type { ConfirmTransactionRequestContext } from '../../../../features/confirmation/views/ConfirmTransactionRequest/types';
import { state, transactionScanService } from '../../../../snapContext';
import {
connection,
state,
transactionScanService,
} from '../../../../snapContext';
import { METAMASK_ORIGIN } from '../../../constants/solana';
import { serialize } from '../../../serialization/serialize';
import type { UnencryptedStateValue } from '../../../services/state/State';
import { EXPIRED_TRANSACTION_SCAN } from '../../../services/transaction-scan/buildExpiredScanResult';
import { isTransactionBlockhashExpired } from '../../../services/transaction-scan/isTransactionBlockhashExpired';
import { trackError } from '../../../utils/errors';
import {
CONFIRM_SIGN_AND_SEND_TRANSACTION_INTERFACE_NAME,
getInterfaceContext,
updateInterface,
} from '../../../utils/interface';
import baseLogger from '../../../utils/logger';
import { ScheduleBackgroundEventMethod } from './ScheduleBackgroundEventMethod';

export const refreshConfirmationEstimation: OnCronjobHandler = async () => {
const logger = baseLogger.withPrefix('[refreshConfirmationEstimation]');
Expand Down Expand Up @@ -58,9 +66,12 @@ export const refreshConfirmationEstimation: OnCronjobHandler = async () => {
// Skip transaction simulation if the preference is disabled
if (!interfaceContext.preferences?.simulateOnChainActions) {
logger.info(`Transaction simulation is disabled in preferences`);
return;
}

// MetaMask-originated transactions receive a fresh blockhash before signing.
const shouldSkipBlockhashCheck =
interfaceContext.origin === METAMASK_ORIGIN;

const fetchingConfirmationContext = {
...interfaceContext,
scanFetchStatus: 'fetching',
Expand All @@ -74,15 +85,23 @@ export const refreshConfirmationEstimation: OnCronjobHandler = async () => {
fetchingConfirmationContext,
);

const [scan, updatedInterfaceContextFinal] = await Promise.all([
transactionScanService.scanTransaction({
method: interfaceContext.method,
accountAddress: interfaceContext.account.address,
transaction: interfaceContext.transaction,
scope: interfaceContext.scope,
origin: interfaceContext.origin,
account: interfaceContext.account,
}),
const [scan, isExpired, updatedInterfaceContextFinal] = await Promise.all([
interfaceContext.preferences?.simulateOnChainActions
? transactionScanService.scanTransaction({
method: interfaceContext.method,
accountAddress: interfaceContext.account.address,
transaction: interfaceContext.transaction,
scope: interfaceContext.scope,
origin: interfaceContext.origin,
account: interfaceContext.account,
})
: Promise.resolve(interfaceContext.scan),
shouldSkipBlockhashCheck
? Promise.resolve(false)
: isTransactionBlockhashExpired(
interfaceContext.transaction,
connection.getRpc(interfaceContext.scope),
),
Comment on lines +101 to +104

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is highly unlikely a Dapp would send already expired transaction.

getInterfaceContext<ConfirmTransactionRequestContext>(
confirmationInterfaceId,
),
Expand All @@ -100,9 +119,12 @@ export const refreshConfirmationEstimation: OnCronjobHandler = async () => {
const updatedInterfaceContext = {
...updatedInterfaceContextFinal,
scanFetchStatus: 'fetched' as const,
scan,
scan: isExpired ? EXPIRED_TRANSACTION_SCAN : scan,
};
logger.info(`New scan fetched`);

if (interfaceContext.preferences?.simulateOnChainActions) {
logger.info(`New scan fetched`);
}

await updateInterface(
confirmationInterfaceId,
Expand All @@ -119,7 +141,9 @@ export const refreshConfirmationEstimation: OnCronjobHandler = async () => {
method: 'snap_scheduleBackgroundEvent',
params: {
duration: 'PT20S',
request: { method: 'refreshConfirmationEstimation' },
request: {
method: ScheduleBackgroundEventMethod.RefreshConfirmationEstimation,
},
},
});
} catch (error) {
Expand Down
Loading