Skip to content

Commit

Permalink
feat: Add first time interaction warning (#28435)
Browse files Browse the repository at this point in the history
<!--
Please submit this PR as a draft initially.
Do not mark it as "Ready for review" until the template has been
completely filled out, and PR status checks have passed at least once.
-->

## **Description**

<!--
Write a short description of the changes included in this pull request,
also include relevant motivation and context. Have in mind the following
questions:
1. What is the reason for the change?
2. What is the improvement/solution?
-->

This PR implements first time interaction feature where it shows an
alert if you interact with the address for the first time.
Information of the first time interaction is fetched in the transaction
controller when the transaction is added to the state.

Core PR: MetaMask/core#4895

[![Open in GitHub
Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/MetaMask/metamask-extension/pull/28435?quickstart=1)

## **Related issues**

Fixes: MetaMask/MetaMask-planning#3040

## **Manual testing steps**

1. Go to test dapp
2. Use send legacy transaction - make sure you interact here with your
account for the first time
3. See warning

## **Screenshots/Recordings**

<!-- If applicable, add screenshots and/or recordings to visualize the
before and after of your change. -->

### **Before**

<!-- [screenshots/recordings] -->

### **After**

![Screenshot 2024-11-13 at 11 51
14](https://github.com/user-attachments/assets/6cc1f481-788c-4945-b190-1448c5a03141)

![Screenshot 2024-11-13 at 11 51
19](https://github.com/user-attachments/assets/98413caa-ef43-4877-a37d-ea0a6da1397f)


## **Pre-merge author checklist**

- [ ] I've followed [MetaMask Contributor
Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask
Extension Coding
Standards](https://github.com/MetaMask/metamask-extension/blob/develop/.github/guidelines/CODING_GUIDELINES.md).
- [ ] I've completed the PR template to the best of my ability
- [ ] I’ve included tests if applicable
- [ ] I’ve documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [ ] I’ve applied the right labels on the PR (see [labeling
guidelines](https://github.com/MetaMask/metamask-extension/blob/develop/.github/guidelines/LABELING_GUIDELINES.md)).
Not required for external contributors.

## **Pre-merge reviewer checklist**

- [ ] I've manually tested the PR (e.g. pull and build branch, run the
app, test code being changed).
- [ ] I confirm that this PR addresses all acceptance criteria described
in the ticket it closes and includes the necessary testing evidence such
as recordings and or screenshots.
  • Loading branch information
OGPoyraz authored Nov 26, 2024
1 parent 1bf2e7a commit 608caf6
Show file tree
Hide file tree
Showing 13 changed files with 198 additions and 23 deletions.
8 changes: 7 additions & 1 deletion app/_locales/en/messages.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions app/scripts/metamask-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -1940,6 +1940,8 @@ export default class MetamaskController extends EventEmitter {
queryEntireHistory: false,
updateTransactions: false,
},
isFirstTimeInteractionEnabled: () =>
this.preferencesController.state.securityAlertsEnabled,
isMultichainEnabled: process.env.TRANSACTION_MULTICHAIN,
isSimulationEnabled: () =>
this.preferencesController.state.useTransactionSimulations,
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@
"@metamask/snaps-sdk": "^6.12.0",
"@metamask/snaps-utils": "^8.6.0",
"@metamask/solana-wallet-snap": "^0.1.9",
"@metamask/transaction-controller": "^40.0.0",
"@metamask/transaction-controller": "^40.1.0",
"@metamask/user-operation-controller": "^13.0.0",
"@metamask/utils": "^10.0.1",
"@ngraveio/bc-ur": "^1.1.12",
Expand Down
1 change: 1 addition & 0 deletions ui/components/app/confirm/info/row/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export const TEST_ADDRESS = '0x5CfE73b6021E818B776b421B1c4Db2474086a7e1';

export enum RowAlertKey {
EstimatedFee = 'estimatedFee',
FirstTimeInteraction = 'firstTimeInteraction',
SigningInWith = 'signingInWith',
RequestFrom = 'requestFrom',
Resimulation = 'resimulation',
Expand Down
3 changes: 2 additions & 1 deletion ui/components/app/confirm/info/row/row.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export enum ConfirmInfoRowVariant {

export type ConfirmInfoRowProps = {
label: string;
children: React.ReactNode | string;
children?: React.ReactNode | string;
tooltip?: string;
variant?: ConfirmInfoRowVariant;
style?: React.CSSProperties;
Expand Down Expand Up @@ -169,6 +169,7 @@ export const ConfirmInfoRow: React.FC<ConfirmInfoRowProps> = ({
</Box>
</Box>
{expanded &&
children &&
(typeof children === 'string' ? (
<Text marginRight={copyEnabled ? 3 : 0} color={TextColor.inherit}>
{children}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,10 @@ exports[`<TransactionFlowSection /> renders correctly 1`] = `
/>
<div
class="mm-box confirm-info-row mm-box--margin-top-2 mm-box--margin-bottom-2 mm-box--padding-right-2 mm-box--padding-left-2 mm-box--display-flex mm-box--flex-direction-row mm-box--flex-wrap-wrap mm-box--justify-content-space-between mm-box--align-items-flex-start mm-box--color-text-default mm-box--rounded-lg"
style="overflow-wrap: anywhere; min-height: 24px; position: relative; flex-direction: column; align-items: flex-start;"
style="overflow-wrap: anywhere; min-height: 24px; position: relative; background: transparent; flex-direction: column;"
>
<div
class="mm-box mm-box--display-flex mm-box--flex-direction-row mm-box--justify-content-center mm-box--align-items-flex-start"
class="mm-box mm-box--display-flex mm-box--flex-direction-row mm-box--justify-content-center mm-box--align-items-flex-start mm-box--color-text-default"
>
<div
class="mm-box mm-box--display-flex mm-box--align-items-center"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@ import {
IconColor,
JustifyContent,
} from '../../../../../../helpers/constants/design-system';
import {
ConfirmInfoRow,
ConfirmInfoRowAddress,
} from '../../../../../../components/app/confirm/info/row';
import { ConfirmInfoRowAddress } from '../../../../../../components/app/confirm/info/row';
import { ConfirmInfoAlertRow } from '../../../../../../components/app/confirm/info/row/alert-row/alert-row';
import { RowAlertKey } from '../../../../../../components/app/confirm/info/row/constants';
import { useI18nContext } from '../../../../../../hooks/useI18nContext';
Expand Down Expand Up @@ -61,7 +58,9 @@ export const TransactionFlowSection = () => {
alertKey={RowAlertKey.SigningInWith}
label={t('from')}
ownerId={transactionMeta.id}
style={{ flexDirection: FlexDirection.Column }}
style={{
flexDirection: FlexDirection.Column,
}}
>
<Box marginTop={1}>
<ConfirmInfoRowAddress
Expand All @@ -77,11 +76,12 @@ export const TransactionFlowSection = () => {
color={IconColor.iconMuted}
/>
{recipientAddress && (
<ConfirmInfoRow
<ConfirmInfoAlertRow
alertKey={RowAlertKey.FirstTimeInteraction}
label={t('to')}
ownerId={transactionMeta.id}
style={{
flexDirection: FlexDirection.Column,
alignItems: AlignItems.flexStart,
}}
>
<Box marginTop={1}>
Expand All @@ -90,7 +90,7 @@ export const TransactionFlowSection = () => {
chainId={chainId}
/>
</Box>
</ConfirmInfoRow>
</ConfirmInfoAlertRow>
)}
</Box>
</ConfirmInfoSection>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,7 @@ const HeaderWithAlert = ({ transactionId }: { transactionId: string }) => {
paddingLeft: 0,
paddingRight: 0,
}}
>
{/* Intentional fragment */}
<></>
</ConfirmInfoAlertRow>
/>
);
};

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import { ApprovalType } from '@metamask/controller-utils';
import {
TransactionMeta,
TransactionStatus,
TransactionType,
} from '@metamask/transaction-controller';

import { getMockConfirmState } from '../../../../../../test/data/confirmations/helper';
import { renderHookWithConfirmContextProvider } from '../../../../../../test/lib/confirmations/render-helpers';
import { Severity } from '../../../../../helpers/constants/design-system';
import { RowAlertKey } from '../../../../../components/app/confirm/info/row/constants';
import { genUnapprovedContractInteractionConfirmation } from '../../../../../../test/data/confirmations/contract-interaction';
import { useFirstTimeInteractionAlert } from './useFirstTimeInteractionAlert';

const ACCOUNT_ADDRESS = '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc';
const TRANSACTION_ID_MOCK = '123-456';

const CONFIRMATION_MOCK = genUnapprovedContractInteractionConfirmation({
chainId: '0x5',
}) as TransactionMeta;

const TRANSACTION_META_MOCK = {
id: TRANSACTION_ID_MOCK,
chainId: '0x5',
status: TransactionStatus.submitted,
type: TransactionType.contractInteraction,
txParams: {
from: ACCOUNT_ADDRESS,
},
time: new Date().getTime() - 10000,
firstTimeInteraction: true,
} as TransactionMeta;

function runHook({
currentConfirmation,
transactions = [],
}: {
currentConfirmation?: TransactionMeta;
transactions?: TransactionMeta[];
} = {}) {
let pendingApprovals = {};
if (currentConfirmation) {
pendingApprovals = {
[currentConfirmation.id as string]: {
id: currentConfirmation.id,
type: ApprovalType.Transaction,
},
};
transactions.push(currentConfirmation);
}
const state = getMockConfirmState({
metamask: {
pendingApprovals,
transactions,
},
});
const response = renderHookWithConfirmContextProvider(
useFirstTimeInteractionAlert,
state,
);

return response.result.current;
}

describe('useFirstTimeInteractionAlert', () => {
beforeEach(() => {
jest.resetAllMocks();
});

it('returns no alerts if no confirmation', () => {
expect(runHook()).toEqual([]);
});

it('returns no alerts if no transactions', () => {
expect(
runHook({
currentConfirmation: CONFIRMATION_MOCK,
transactions: [],
}),
).toEqual([]);
});

it('returns no alerts if firstTimeInteraction is false', () => {
const notFirstTimeConfirmation = {
...TRANSACTION_META_MOCK,
firstTimeInteraction: false,
};
expect(
runHook({
currentConfirmation: notFirstTimeConfirmation,
}),
).toEqual([]);
});

it('returns no alerts if firstTimeInteraction is undefined', () => {
const notFirstTimeConfirmation = {
...TRANSACTION_META_MOCK,
firstTimeInteraction: undefined,
};
expect(
runHook({
currentConfirmation: notFirstTimeConfirmation,
}),
).toEqual([]);
});

it('returns alert if isFirstTimeInteraction is true', () => {
const firstTimeConfirmation = {
...CONFIRMATION_MOCK,
isFirstTimeInteraction: true,
};
const alerts = runHook({
currentConfirmation: firstTimeConfirmation,
});

expect(alerts).toEqual([
{
actions: [],
field: RowAlertKey.FirstTimeInteraction,
isBlocking: false,
key: 'firstTimeInteractionTitle',
message:
"You're interacting with this address for the first time. Make sure that it's correct before you continue.",
reason: '1st interaction',
severity: Severity.Warning,
},
]);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useMemo } from 'react';
import { TransactionMeta } from '@metamask/transaction-controller';

import { Alert } from '../../../../../ducks/confirm-alerts/confirm-alerts';
import { useI18nContext } from '../../../../../hooks/useI18nContext';
import { Severity } from '../../../../../helpers/constants/design-system';
import { RowAlertKey } from '../../../../../components/app/confirm/info/row/constants';
import { useConfirmContext } from '../../../context/confirm';

export function useFirstTimeInteractionAlert(): Alert[] {
const t = useI18nContext();
const { currentConfirmation } = useConfirmContext<TransactionMeta>();

const { isFirstTimeInteraction } = currentConfirmation ?? {};

return useMemo(() => {
// If isFirstTimeInteraction is undefined that means it's either disabled or error in accounts API
// If it's false that means account relationship found
if (!isFirstTimeInteraction) {
return [];
}

return [
{
actions: [],
field: RowAlertKey.FirstTimeInteraction,
isBlocking: false,
key: 'firstTimeInteractionTitle',
message: t('alertMessageFirstTimeInteraction'),
reason: t('alertReasonFirstTimeInteraction'),
severity: Severity.Warning,
},
];
}, [isFirstTimeInteraction, t]);
}
4 changes: 4 additions & 0 deletions ui/pages/confirmations/hooks/useConfirmationAlerts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { useNoGasPriceAlerts } from './alerts/transactions/useNoGasPriceAlerts';
import { usePendingTransactionAlerts } from './alerts/transactions/usePendingTransactionAlerts';
import { useQueuedConfirmationsAlerts } from './alerts/transactions/useQueuedConfirmationsAlerts';
import { useResimulationAlert } from './alerts/transactions/useResimulationAlert';
import { useFirstTimeInteractionAlert } from './alerts/transactions/useFirstTimeInteractionAlert';
///: BEGIN:ONLY_INCLUDE_IF(build-main,build-beta,build-flask)
import { useSigningOrSubmittingAlerts } from './alerts/transactions/useSigningOrSubmittingAlerts';
///: END:ONLY_INCLUDE_IF
Expand All @@ -37,6 +38,7 @@ function useTransactionAlerts(): Alert[] {
const noGasPriceAlerts = useNoGasPriceAlerts();
const pendingTransactionAlerts = usePendingTransactionAlerts();
const resimulationAlert = useResimulationAlert();
const firstTimeInteractionAlert = useFirstTimeInteractionAlert();
///: BEGIN:ONLY_INCLUDE_IF(build-main,build-beta,build-flask)
const signingOrSubmittingAlerts = useSigningOrSubmittingAlerts();
///: END:ONLY_INCLUDE_IF
Expand All @@ -52,6 +54,7 @@ function useTransactionAlerts(): Alert[] {
...noGasPriceAlerts,
...pendingTransactionAlerts,
...resimulationAlert,
...firstTimeInteractionAlert,
///: BEGIN:ONLY_INCLUDE_IF(build-main,build-beta,build-flask)
...signingOrSubmittingAlerts,
///: END:ONLY_INCLUDE_IF
Expand All @@ -66,6 +69,7 @@ function useTransactionAlerts(): Alert[] {
noGasPriceAlerts,
pendingTransactionAlerts,
resimulationAlert,
firstTimeInteractionAlert,
///: BEGIN:ONLY_INCLUDE_IF(build-main,build-beta,build-flask)
signingOrSubmittingAlerts,
///: END:ONLY_INCLUDE_IF
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ exports[`Security Tab should match snapshot 1`] = `
>
<span>
This feature alerts you to malicious activity by actively reviewing transaction and signature requests.
This feature alerts you to malicious or unusual activity by actively reviewing transaction and signature requests.
<a
href="https://support.metamask.io/privacy-and-security/how-to-turn-on-security-alerts/"
rel="noreferrer"
Expand Down
10 changes: 5 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6738,9 +6738,9 @@ __metadata:
languageName: node
linkType: hard

"@metamask/transaction-controller@npm:^40.0.0":
version: 40.0.0
resolution: "@metamask/transaction-controller@npm:40.0.0"
"@metamask/transaction-controller@npm:^40.1.0":
version: 40.1.0
resolution: "@metamask/transaction-controller@npm:40.1.0"
dependencies:
"@ethereumjs/common": "npm:^3.2.0"
"@ethereumjs/tx": "npm:^4.2.0"
Expand All @@ -6767,7 +6767,7 @@ __metadata:
"@metamask/approval-controller": ^7.0.0
"@metamask/gas-fee-controller": ^22.0.0
"@metamask/network-controller": ^22.0.0
checksum: 10/1325f5d264e4351dfeee664bba601d873b2204eb82ccb840ab7934fa27f48e31c5f47a60f0a4b4baa94b41ac801121c498bb28102a65cbe59a0456630d4e0138
checksum: 10/1057af5b0da2d51e46e7568fc0e7fdbe6aed34a013cf56a5a35ad694cbedcb726a5823bbe70b980d1dc9560138acf9d82ac5f0e06f7d17e11b46abacd466dc42
languageName: node
linkType: hard

Expand Down Expand Up @@ -26891,7 +26891,7 @@ __metadata:
"@metamask/solana-wallet-snap": "npm:^0.1.9"
"@metamask/test-bundler": "npm:^1.0.0"
"@metamask/test-dapp": "npm:8.13.0"
"@metamask/transaction-controller": "npm:^40.0.0"
"@metamask/transaction-controller": "npm:^40.1.0"
"@metamask/user-operation-controller": "npm:^13.0.0"
"@metamask/utils": "npm:^10.0.1"
"@ngraveio/bc-ur": "npm:^1.1.12"
Expand Down

0 comments on commit 608caf6

Please sign in to comment.