Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Change visibility of AmountRow in contract interaction #29131

Merged
merged 7 commits into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { SimulationErrorCode } from '@metamask/transaction-controller';
import { Hex } from '@metamask/utils';
import {
getMockConfirmState,
getMockConfirmStateForTransaction,
Expand Down Expand Up @@ -44,21 +44,96 @@ describe('<TransactionDetails />', () => {
expect(container).toMatchSnapshot();
});

it('renders component for transaction details with amount', () => {
const simulationDataMock = {
error: { code: SimulationErrorCode.Disabled },
tokenBalanceChanges: [],
};
const contractInteraction = genUnapprovedContractInteractionConfirmation({
simulationData: simulationDataMock,
chainId: CHAIN_IDS.GOERLI,
describe('AmountRow', () => {
describe('should be in the document', () => {
it('when showAdvancedDetails is true', () => {
const contractInteraction =
genUnapprovedContractInteractionConfirmation({
chainId: CHAIN_IDS.GOERLI,
});
const state = getMockConfirmStateForTransaction(contractInteraction, {
metamask: {
preferences: {
showConfirmationAdvancedDetails: true,
},
},
});
const mockStore = configureMockStore(middleware)(state);
const { getByTestId } = renderWithConfirmContextProvider(
<TransactionDetails />,
mockStore,
);
expect(
getByTestId('transaction-details-amount-row'),
).toBeInTheDocument();
});

it('when value and simulated native balance mismatch', () => {
// Transaction value is set to 0x3782dace9d900000 below mock
const simulationDataMock = {
tokenBalanceChanges: [],
nativeBalanceChange: {
difference: '0x1' as Hex,
isDecrease: false,
previousBalance: '0x2' as Hex,
newBalance: '0x1' as Hex,
},
};
const contractInteraction =
genUnapprovedContractInteractionConfirmation({
simulationData: simulationDataMock,
chainId: CHAIN_IDS.GOERLI,
});
const state = getMockConfirmStateForTransaction(contractInteraction, {
metamask: {
preferences: {
// Intentionally setting to false to test the condition
showConfirmationAdvancedDetails: false,
},
},
});
const mockStore = configureMockStore(middleware)(state);
const { getByTestId } = renderWithConfirmContextProvider(
<TransactionDetails />,
mockStore,
);
expect(
getByTestId('transaction-details-amount-row'),
).toBeInTheDocument();
});
});

it('should not be in the document when value and simulated native balance mismatch is within threshold', () => {
// Transaction value is set to 0x3782dace9d900000 below mock
const simulationDataMock = {
tokenBalanceChanges: [],
nativeBalanceChange: {
difference: '0x3782dace9d900000' as Hex,
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you use decimal test number constants and convert them to hex using a util, so the numbers are human readable?

Copy link
Member Author

Choose a reason for hiding this comment

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

Make sense, done in 9a6e27a

isDecrease: true,
previousBalance: '0x3782dace9d900001' as Hex,
newBalance: '0x0000000000000001' as Hex,
},
};
const contractInteraction = genUnapprovedContractInteractionConfirmation({
simulationData: simulationDataMock,
chainId: CHAIN_IDS.GOERLI,
});
const state = getMockConfirmStateForTransaction(contractInteraction, {
metamask: {
preferences: {
// Intentionally setting to false to test the condition
showConfirmationAdvancedDetails: false,
},
},
});
const mockStore = configureMockStore(middleware)(state);
const { queryByTestId } = renderWithConfirmContextProvider(
<TransactionDetails />,
mockStore,
);
expect(
queryByTestId('transaction-details-amount-row'),
).not.toBeInTheDocument();
});
const state = getMockConfirmStateForTransaction(contractInteraction);
const mockStore = configureMockStore(middleware)(state);
const { getByTestId } = renderWithConfirmContextProvider(
<TransactionDetails />,
mockStore,
);
expect(getByTestId('transaction-details-amount-row')).toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { TransactionMeta } from '@metamask/transaction-controller';
import { isValidAddress } from 'ethereumjs-util';
import React from 'react';
import React, { useMemo } from 'react';
import { useSelector } from 'react-redux';
import {
ConfirmInfoRow,
Expand All @@ -20,6 +20,7 @@ import { ConfirmInfoRowCurrency } from '../../../../../../../components/app/conf
import { PRIMARY } from '../../../../../../../helpers/constants/common';
import { useUserPreferencedCurrency } from '../../../../../../../hooks/useUserPreferencedCurrency';
import { HEX_ZERO } from '../constants';
import { hasValueAndNativeBalanceMismatch as checkValueAndNativeBalanceMismatch } from '../../utils';
import { SigningInWithRow } from '../sign-in-with-row/sign-in-with-row';

export const OriginRow = () => {
Expand Down Expand Up @@ -99,9 +100,8 @@ const AmountRow = () => {
const { currency } = useUserPreferencedCurrency(PRIMARY);

const value = currentConfirmation?.txParams?.value;
const simulationData = currentConfirmation?.simulationData;

if (!value || value === HEX_ZERO || !simulationData?.error) {
if (!value || value === HEX_ZERO) {
return null;
}

Expand Down Expand Up @@ -150,6 +150,11 @@ export const TransactionDetails = () => {
const showAdvancedDetails = useSelector(
selectConfirmationAdvancedDetailsOpen,
);
const { currentConfirmation } = useConfirmContext<TransactionMeta>();
const hasValueAndNativeBalanceMismatch = useMemo(
() => checkValueAndNativeBalanceMismatch(currentConfirmation),
[currentConfirmation],
);

return (
<>
Expand All @@ -159,7 +164,9 @@ export const TransactionDetails = () => {
{showAdvancedDetails && <MethodDataRow />}
<SigningInWithRow />
</ConfirmInfoSection>
<AmountRow />
{(showAdvancedDetails || hasValueAndNativeBalanceMismatch) && (
<AmountRow />
)}
<PaymasterRow />
</>
);
Expand Down
83 changes: 83 additions & 0 deletions ui/pages/confirmations/components/confirm/info/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { TransactionMeta } from '@metamask/transaction-controller';
import type { Hex } from '@metamask/utils';
import { remove0x } from '@metamask/utils';
import { BN } from 'bn.js';
import { DecodedTransactionDataResponse } from '../../../../../../shared/types/transaction-decode';
import {
BackgroundColor,
TextColor,
} from '../../../../../helpers/constants/design-system';

const VALUE_COMPARISON_PERCENT_THRESHOLD = 5;

export function getIsRevokeSetApprovalForAll(
value: DecodedTransactionDataResponse | undefined,
): boolean {
Expand All @@ -27,3 +33,80 @@ export const getAmountColors = (credit?: boolean, debit?: boolean) => {
}
return { color, backgroundColor };
};

Copy link
Contributor

Choose a reason for hiding this comment

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

Perhaps it would be good to add unit tests to these util methods

/**
* Calculate the absolute percentage change between two values.
*
* @param originalValue - The first value.
* @param newValue - The second value.
* @returns The percentage change from the first value to the second value.
* If the original value is zero and the new value is not, returns 100.
*/
export function getPercentageChange(
originalValue: InstanceType<typeof BN>,
newValue: InstanceType<typeof BN>,
): number {
const precisionFactor = new BN(10).pow(new BN(18));
const originalValuePrecision = originalValue.mul(precisionFactor);
const newValuePrecision = newValue.mul(precisionFactor);

const difference = newValuePrecision.sub(originalValuePrecision);

if (difference.isZero()) {
return 0;
}

if (originalValuePrecision.isZero() && !newValuePrecision.isZero()) {
return 100;
}

return difference.muln(100).div(originalValuePrecision).abs().toNumber();
}

/**
* Determine if the percentage change between two values is within a threshold.
*
* @param originalValue - The original value.
* @param newValue - The new value.
* @param newNegative - Whether the new value is negative.
* @returns Whether the percentage change between the two values is within a threshold.
*/
function percentageChangeWithinThreshold(
originalValue: Hex,
newValue: Hex,
newNegative?: boolean,
): boolean {
const originalValueBN = new BN(remove0x(originalValue), 'hex');
let newValueBN = new BN(remove0x(newValue), 'hex');

if (newNegative) {
newValueBN = newValueBN.neg();
}

return (
getPercentageChange(originalValueBN, newValueBN) <=
VALUE_COMPARISON_PERCENT_THRESHOLD
);
}

/**
* Determine if a transaction has a value and simulation native balance mismatch.
*
* @param transactionMeta - The transaction metadata.
* @returns Whether the transaction has a value and simulation native balance mismatch.
*/
export function hasValueAndNativeBalanceMismatch(
transactionMeta: TransactionMeta,
): boolean {
const value = transactionMeta?.txParams?.value ?? '0x0';
const nativeBalanceChange =
transactionMeta?.simulationData?.nativeBalanceChange;
Copy link
Contributor

Choose a reason for hiding this comment

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

It will be nice to test cover util methods also

const simulatedNativeBalanceDifference =
nativeBalanceChange?.difference ?? '0x0';

return !percentageChangeWithinThreshold(
value as Hex,
simulatedNativeBalanceDifference,
nativeBalanceChange?.isDecrease === false,
);
}
Loading