Skip to content

Commit d644099

Browse files
feat: use last selected payment detail instead of deducing from approval amount (#37409)
<!-- 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? --> Fix subscription crypto approval screen loading flicker by using lastSelectedPaymentDetail instead of deducting from transaction approval amount [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/MetaMask/metamask-extension/pull/37409?quickstart=1) ## **Changelog** <!-- If this PR is not End-User-Facing and should not show up in the CHANGELOG, you can choose to either: 1. Write `CHANGELOG entry: null` 2. Label with `no-changelog` If this PR is End-User-Facing, please write a short User-Facing description in the past tense like: `CHANGELOG entry: Added a new tab for users to see their NFTs` `CHANGELOG entry: Fixed a bug that was causing some NFTs to flicker` (This helps the Release Engineer do their job more quickly and accurately) --> CHANGELOG entry: fix subscription crypto approval screen loading flicker ## **Related issues** Fixes: ## **Manual testing steps** 1. Go to shield plan screen 2. Select crypto payment method 3. Crypto approval transaction confirm screen should only show loading once ## **Screenshots/Recordings** <!-- If applicable, add screenshots and/or recordings to visualize the before and after of your change. --> ### **Before** <!-- [screenshots/recordings] --> ### **After** <!-- [screenshots/recordings] --> ## **Pre-merge author checklist** - [x] I've followed [MetaMask Contributor Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Extension Coding Standards](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/CODING_GUIDELINES.md). - [x] I've completed the PR template to the best of my ability - [x] I’ve included tests if applicable - [x] I’ve documented my code using [JSDoc](https://jsdoc.app/) format if applicable - [x] I’ve applied the right labels on the PR (see [labeling guidelines](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/LABELING_GUIDELINES.md)). Not required for external contributors. ## **Pre-merge reviewer checklist** - [x] I've manually tested the PR (e.g. pull and build branch, run the app, test code being changed). - [x] 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. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > Use cached last-selected payment method to render Shield crypto approval pricing and token, removing the deduction-from-approval logic and updating tests. > > - **Confirmations UI (Shield crypto approval)**: > - Derives `productPrice` and token info from cached `lastSelectedPaymentMethod` and pricing (`useSubscriptionPricing`, `useSubscriptionProductPlans`, `useSubscriptionPaymentMethods`). > - Computes `approvalAmount` via decoded data + asset `decimals`, simplifies loading state, and passes `productPrice`/`tokenSymbol` to child components. > - **Hooks**: > - Removes `useShieldSubscriptionPricingFromTokenApproval` and associated imports/logic from `useSubscriptionPricing`. > - **Tests**: > - Updates `shield-subscription-approve.test.tsx` to mock pricing and `lastSelectedPaymentMethod`; verifies monthly pricing/trial and UI sections. > - Cleans up `useSubscriptionPricing.test.ts` by removing tests for the deleted hook; retains tests for pricing, product plans, and payment methods. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 55fb0b6. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Chaitanya Potti <[email protected]>
1 parent 03691d8 commit d644099

File tree

4 files changed

+108
-226
lines changed

4 files changed

+108
-226
lines changed

ui/hooks/subscription/useSubscriptionPricing.test.ts

Lines changed: 0 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,12 @@ import {
66
ProductType,
77
PaymentType,
88
} from '@metamask/subscription-controller';
9-
import {
10-
TransactionMeta,
11-
TransactionStatus,
12-
} from '@metamask/transaction-controller';
139
import { renderHookWithProvider } from '../../../test/lib/render-helpers';
1410
import baseMockState from '../../../test/data/mock-state.json';
1511
import {
1612
useSubscriptionPricing,
1713
useSubscriptionProductPlans,
1814
useSubscriptionPaymentMethods,
19-
useShieldSubscriptionPricingFromTokenApproval,
2015
} from './useSubscriptionPricing';
2116

2217
const mockSubscriptionPricing: PricingResponse = {
@@ -186,101 +181,4 @@ describe('useSubscriptionPricing', () => {
186181
expect(result.current).toBeUndefined();
187182
});
188183
});
189-
190-
describe('useShieldSubscriptionPricingFromTokenApproval', () => {
191-
const mockTransactionMeta: TransactionMeta = {
192-
id: 'test-tx-id',
193-
chainId: '0x1',
194-
networkClientId: 'mainnet',
195-
status: TransactionStatus.unapproved,
196-
time: Date.now(),
197-
txParams: {
198-
from: '0x1234567890123456789012345678901234567890',
199-
to: '0x0000000000000000000000000000000000000000',
200-
},
201-
};
202-
203-
it('should return monthly plan when approval amount matches monthly', async () => {
204-
const { result } = renderHookWithProvider(
205-
() =>
206-
useShieldSubscriptionPricingFromTokenApproval({
207-
transactionMeta: mockTransactionMeta,
208-
decodedApprovalAmount: '120000000',
209-
}),
210-
mockState,
211-
);
212-
213-
// Wait for async operation to complete
214-
await new Promise((resolve) => setTimeout(resolve, 100));
215-
216-
expect(result.current.productPrice).toEqual({
217-
interval: RECURRING_INTERVALS.month,
218-
unitAmount: 120000000,
219-
unitDecimals: 6,
220-
currency: 'usd',
221-
trialPeriodDays: 7,
222-
minBillingCycles: 1,
223-
});
224-
expect(result.current.selectedTokenPrice).toEqual(
225-
mockSubscriptionPricing?.paymentMethods?.find(
226-
(paymentMethod) => paymentMethod.type === PAYMENT_TYPES.byCrypto,
227-
)?.chains?.[0]?.tokens?.[0],
228-
);
229-
});
230-
231-
it('should return yearly plan when approval amount matches yearly', async () => {
232-
const { result } = renderHookWithProvider(
233-
() =>
234-
useShieldSubscriptionPricingFromTokenApproval({
235-
transactionMeta: mockTransactionMeta,
236-
decodedApprovalAmount: '100000000',
237-
}),
238-
mockState,
239-
);
240-
241-
// Wait for async operation to complete
242-
await new Promise((resolve) => setTimeout(resolve, 100));
243-
244-
expect(result.current.productPrice).toEqual({
245-
interval: RECURRING_INTERVALS.year,
246-
unitAmount: 100000000,
247-
unitDecimals: 6,
248-
currency: 'usd',
249-
trialPeriodDays: 7,
250-
minBillingCycles: 1,
251-
});
252-
});
253-
254-
it('should return undefined when approval amount does not match any plan', async () => {
255-
const { result } = renderHookWithProvider(
256-
() =>
257-
useShieldSubscriptionPricingFromTokenApproval({
258-
transactionMeta: mockTransactionMeta,
259-
decodedApprovalAmount: '99999999',
260-
}),
261-
mockState,
262-
);
263-
264-
// Wait for async operation to complete
265-
await new Promise((resolve) => setTimeout(resolve, 100));
266-
267-
expect(result.current.productPrice).toBeUndefined();
268-
});
269-
270-
it('should return undefined when transaction meta is not provided', async () => {
271-
const { result } = renderHookWithProvider(
272-
() =>
273-
useShieldSubscriptionPricingFromTokenApproval({
274-
transactionMeta: undefined,
275-
decodedApprovalAmount: '120000000',
276-
}),
277-
mockState,
278-
);
279-
280-
// Wait for async operation to complete
281-
await new Promise((resolve) => setTimeout(resolve, 100));
282-
283-
expect(result.current.productPrice).toBeUndefined();
284-
});
285-
});
286184
});

ui/hooks/subscription/useSubscriptionPricing.ts

Lines changed: 0 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,14 @@ import { useDispatch, useSelector } from 'react-redux';
33
import log from 'loglevel';
44
import {
55
ChainPaymentInfo,
6-
PAYMENT_TYPES,
76
PaymentType,
87
PricingPaymentMethod,
98
PricingResponse,
10-
PRODUCT_TYPES,
119
ProductPrice,
1210
ProductType,
13-
RECURRING_INTERVALS,
1411
TokenPaymentInfo,
1512
} from '@metamask/subscription-controller';
1613
import { Hex } from '@metamask/utils';
17-
import { TransactionMeta } from '@metamask/transaction-controller';
1814
import { getSubscriptionPricing } from '../../selectors/subscription';
1915
import {
2016
getSubscriptionCryptoApprovalAmount,
@@ -214,83 +210,3 @@ export const useSubscriptionPaymentMethods = (
214210
[pricing, paymentType],
215211
);
216212
};
217-
218-
/**
219-
* Use this hook to get the shield subscription price derived from transaction data.
220-
*
221-
* @param params - The parameters for the hook.
222-
* @param params.transactionMeta - The transaction meta.
223-
* @param params.decodedApprovalAmount - The decoded approval amount.
224-
* @returns The product price.
225-
*/
226-
export const useShieldSubscriptionPricingFromTokenApproval = ({
227-
transactionMeta,
228-
decodedApprovalAmount,
229-
}: {
230-
transactionMeta?: TransactionMeta;
231-
decodedApprovalAmount?: string;
232-
}) => {
233-
const { subscriptionPricing } = useSubscriptionPricing(); // shouldn't refetch pricing here since we are using the cached pricing from shield plan screen to compare price amount
234-
const pricingPlans = useSubscriptionProductPlans(
235-
PRODUCT_TYPES.SHIELD,
236-
subscriptionPricing,
237-
);
238-
const cryptoPaymentMethod = useSubscriptionPaymentMethods(
239-
PAYMENT_TYPES.byCrypto,
240-
subscriptionPricing,
241-
);
242-
const selectedTokenPrice = useMemo(() => {
243-
return cryptoPaymentMethod?.chains
244-
?.find(
245-
(chain) =>
246-
chain.chainId.toLowerCase() ===
247-
transactionMeta?.chainId.toLowerCase(),
248-
)
249-
?.tokens.find(
250-
(token) =>
251-
token.address.toLowerCase() ===
252-
transactionMeta?.txParams?.to?.toLowerCase(),
253-
);
254-
}, [cryptoPaymentMethod, transactionMeta]);
255-
256-
// need to do async here since `getSubscriptionCryptoApprovalAmount` make call to background script
257-
const { value: productPrice, pending } = useAsyncResult(async (): Promise<
258-
ProductPrice | undefined
259-
> => {
260-
if (selectedTokenPrice) {
261-
const params = {
262-
chainId: transactionMeta?.chainId as Hex,
263-
paymentTokenAddress: selectedTokenPrice.address as Hex,
264-
productType: PRODUCT_TYPES.SHIELD,
265-
};
266-
// Get all intervals from RECURRING_INTERVALS
267-
const intervals = Object.values(RECURRING_INTERVALS);
268-
269-
// Fetch approval amounts for all intervals
270-
const approvalAmounts = await Promise.all(
271-
intervals.map((interval) =>
272-
getSubscriptionCryptoApprovalAmount({
273-
...params,
274-
interval,
275-
}),
276-
),
277-
);
278-
279-
// Find the matching plan by comparing approval amounts
280-
for (let i = 0; i < approvalAmounts.length; i++) {
281-
if (approvalAmounts[i]?.approveAmount === decodedApprovalAmount) {
282-
return pricingPlans?.find((plan) => plan.interval === intervals[i]);
283-
}
284-
}
285-
}
286-
287-
return undefined;
288-
}, [
289-
transactionMeta,
290-
selectedTokenPrice,
291-
decodedApprovalAmount,
292-
pricingPlans,
293-
]);
294-
295-
return { productPrice, pending, selectedTokenPrice };
296-
};

ui/pages/confirmations/components/confirm/info/shield-subscription-approve/shield-subscription-approve.test.tsx

Lines changed: 64 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
import React from 'react';
22
import configureMockStore from 'redux-mock-store';
3-
import { ProductPrice } from '@metamask/subscription-controller';
3+
import {
4+
CachedLastSelectedPaymentMethod,
5+
PAYMENT_TYPES,
6+
PricingResponse,
7+
PRODUCT_TYPES,
8+
RECURRING_INTERVALS,
9+
} from '@metamask/subscription-controller';
410
import { getMockApproveConfirmState } from '../../../../../../../test/data/confirmations/helper';
511
import { renderWithConfirmContextProvider } from '../../../../../../../test/lib/confirmations/render-helpers';
612
import { tEn } from '../../../../../../../test/lib/i18n-helpers';
@@ -63,26 +69,67 @@ jest.mock('../../../../../../store/actions', () => ({
6369
}),
6470
}));
6571

66-
jest.mock('../../../../../../hooks/subscription/useSubscriptionPricing', () => {
67-
const mockProductPrice: ProductPrice = {
68-
interval: 'month',
69-
minBillingCycles: 12,
70-
unitAmount: 8000000,
71-
unitDecimals: 6,
72-
currency: 'usd',
73-
trialPeriodDays: 14,
74-
};
75-
return {
76-
useShieldSubscriptionPricingFromTokenApproval: jest.fn(() => ({
77-
productPrice: mockProductPrice,
78-
pending: false,
79-
})),
80-
};
81-
});
72+
const mockSubscriptionPricing: PricingResponse = {
73+
products: [
74+
{
75+
name: PRODUCT_TYPES.SHIELD,
76+
prices: [
77+
{
78+
interval: RECURRING_INTERVALS.month,
79+
unitAmount: 8_000_000,
80+
unitDecimals: 6,
81+
currency: 'usd',
82+
trialPeriodDays: 14,
83+
minBillingCycles: 12,
84+
},
85+
{
86+
interval: RECURRING_INTERVALS.year,
87+
unitAmount: 100_000_000,
88+
unitDecimals: 6,
89+
currency: 'usd',
90+
trialPeriodDays: 14,
91+
minBillingCycles: 1,
92+
},
93+
],
94+
},
95+
],
96+
paymentMethods: [
97+
{
98+
type: PAYMENT_TYPES.byCrypto,
99+
chains: [
100+
{
101+
chainId: '0x1',
102+
paymentAddress: '0x1234567890123456789012345678901234567890',
103+
tokens: [
104+
{
105+
address: '0x0000000000000000000000000000000000000000',
106+
symbol: 'usdc',
107+
decimals: 6,
108+
conversionRate: { usd: '1' },
109+
},
110+
],
111+
},
112+
],
113+
},
114+
],
115+
};
116+
117+
const mockLastUsedPaymentDetail: CachedLastSelectedPaymentMethod = {
118+
plan: RECURRING_INTERVALS.month,
119+
paymentTokenAddress: '0x1234567890123456789012345678901234567890',
120+
type: PAYMENT_TYPES.byCrypto,
121+
};
82122

83123
describe('ShieldSubscriptionApproveInfo', () => {
84124
it('renders correctly', () => {
85125
const state = getMockApproveConfirmState();
126+
// @ts-expect-error - mock state
127+
state.metamask.lastSelectedPaymentMethod = {
128+
[PRODUCT_TYPES.SHIELD]: mockLastUsedPaymentDetail,
129+
};
130+
// @ts-expect-error - mock state
131+
state.metamask.pricing = mockSubscriptionPricing;
132+
86133
const mockStore = configureMockStore([])(state);
87134
const { getByText } = renderWithConfirmContextProvider(
88135
<ShieldSubscriptionApproveInfo />,

0 commit comments

Comments
 (0)