Skip to content
Merged
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
1 change: 1 addition & 0 deletions components/Assets/__tests__/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export const spendFixture: SpendModeFigures = {
borrowApy: '5.57%',
borrowedProgress: 0.175,
segmentValue: { cash: '$228.40', credit: '$1,650.00', smart: '$1,650.00' },
availableUsd: 1650,
hasPosition: true,
canBorrow: true,
showsBorrowPosition: true,
Expand Down
23 changes: 18 additions & 5 deletions components/Card/NewCardDetails/SpendMode/useSpendModeFigures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ export interface SpendModeFigures {

/** The figure under each segment name in the control. */
segmentValue: Record<SpendMode, string>;
/**
* What the home Available to spend tile shows for the mode in force, in dollars, before it is
* formatted: the cash balance in Cash, the credit left in Credit, the larger of the two in Smart.
*
* For anything that has to quote the tile's number rather than work out one of its own (the
* declined-payment banner and receipt). Null while the tile is loading or reads "—".
*/
availableUsd: number | null;

/** Whether there is a loan at all. What gates the Repay button. */
hasPosition: boolean;
Expand Down Expand Up @@ -172,6 +180,13 @@ export const useSpendModeFigures = (): SpendModeFigures => {
// The tile's own placeholder, on the figures that count Base and nowhere else: `isLoading`
// also holds the Assets screen's Fuse-only credit line, which has nothing to wait for.
const unknownWithoutBase = isBaseCreditUnavailable ? '—' : undefined;
const isLoading =
isRegistrationLoading || isBalanceLoading || isBaseAccessLoading || isBaseCreditLoading;
// The tile's figure for the mode in force, by the same rules as the labels below.
const smartMicro = cashMicro > spendableHeadroom ? cashMicro : spendableHeadroom;
const availableMicro =
mode === 'cash' ? cashMicro : mode === 'credit' ? spendableHeadroom : smartMicro;
const isAvailableKnown = !isLoading && (mode === 'cash' || !unknownWithoutBase);

return {
mode,
Expand Down Expand Up @@ -201,10 +216,9 @@ export const useSpendModeFigures = (): SpendModeFigures => {
// takes exactly one path, so the most Smart can fund is the larger of the two; the
// two figures also overlap heavily, both deriving from the same balance, so adding
// them would quote money the Safe does not have.
smart:
unknownWithoutBase ??
formatMicroUsd(cashMicro > spendableHeadroom ? cashMicro : spendableHeadroom),
smart: unknownWithoutBase ?? formatMicroUsd(smartMicro),
},
availableUsd: isAvailableKnown ? Number(availableMicro) / Number(ONE_USD) : null,

hasPosition: debt > 0n,
canBorrow,
Expand All @@ -215,8 +229,7 @@ export const useSpendModeFigures = (): SpendModeFigures => {
fullyPriced: position?.fullyPriced ?? true,

// Base too, so the tile doesn't land on the Fuse figure and then jump to the whole line.
isLoading:
isRegistrationLoading || isBalanceLoading || isBaseAccessLoading || isBaseCreditLoading,
isLoading,
};
}, [
mode,
Expand Down
145 changes: 144 additions & 1 deletion hooks/__tests__/useDeclinedPaymentPrompt.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';

import { DeclinedPaymentPrompt, useDeclinedPaymentPrompt } from '@/hooks/useDeclinedPaymentPrompt';
import { useDeclineSpendable } from '@/hooks/useDeclineSpendable';
import { CardTransactionCategory } from '@/lib/types';

const { act, create } = jest.requireActual('react-test-renderer');
Expand All @@ -13,8 +14,26 @@ let mockDisplayCurrency: any;
jest.mock('@/hooks/useCardTransactions', () => ({
useCardTransactions: () => ({ data: mockTransactions }),
}));
let mockSpendableLoading: boolean;
const mockRefetchSpendable = jest.fn();
jest.mock('@/hooks/useCardSpendable', () => ({
useCardSpendable: () => ({ data: mockSpendable }),
useCardSpendable: () => ({
data: mockSpendable,
isLoading: mockSpendableLoading,
refetch: mockRefetchSpendable,
}),
}));
let mockBalancesRefresh: any;
const mockRefetchBalances = jest.fn();
jest.mock('@/hooks/useBalances', () => ({
useBalancesRefresh: (options: any) => {
mockBalancesRefresh = options;
return { refetch: mockRefetchBalances };
},
}));
let mockTile: { availableUsd: number | null; isLoading: boolean };
jest.mock('@/components/Card/NewCardDetails/SpendMode/useSpendModeFigures', () => ({
useSpendModeFigures: () => mockTile,
}));
jest.mock('@/hooks/useCardSpendRegistration', () => ({
useCardSpendRegistration: () => mockRegistration,
Expand Down Expand Up @@ -59,9 +78,14 @@ describe('useDeclinedPaymentPrompt', () => {
beforeEach(() => {
jest.useFakeTimers({ now: NOW });
mockSpendable = { available: { amount: '0', currency: 'usd' } };
mockSpendableLoading = false;
mockRefetchSpendable.mockReset();
mockRefetchBalances.mockReset();
mockRegistration = { registration: {}, mode: 'cash', isRegistered: true };
mockBaseCredit = { base: {}, readsBase: false, isBaseGateReady: true };
mockDisplayCurrency = { inEuros: false };
// The tile cannot say unless a test gives it a number: the hook's own figures stand.
mockTile = { availableUsd: null, isLoading: false };
});

afterEach(() => {
Expand Down Expand Up @@ -167,4 +191,123 @@ describe('useDeclinedPaymentPrompt', () => {

expect(prompt).toBeNull();
});

describe("the Available to spend tile's number (T-174)", () => {
beforeEach(() => {
mockTransactions = { pages: [{ data: [declined(new Date(NOW.getTime() - 2 * HOUR_MS))] }] };
// Cash only, as the backend counts it.
mockSpendable = { available: { amount: '5', currency: 'usd' } };
});

it('is what the banner quotes, not the cash-only figure', () => {
mockTile = { availableUsd: 12.5, isLoading: false };

act(() => {
root = create(<Probe />);
});

expect(prompt?.available).toEqual({ amount: 12.5, currency: 'USD' });
});

it('is what the banner quotes in Credit mode, in the main currency', () => {
// On its own the hook would say the larger single line, $11. The tile reads $43.40.
mockRegistration = {
...mockRegistration,
mode: 'credit',
position: { availableToBorrowUsd: 11_000_000n },
};
mockBaseCredit = {
...mockBaseCredit,
readsBase: true,
base: { data: { availableToBorrowUsd: 5_000_000n } },
};
mockDisplayCurrency = { inEuros: true, usdPerEur: 1.1657 };
mockTransactions = {
pages: [{ data: [{ ...declined(new Date(NOW.getTime() - HOUR_MS)), amount: '110.96' }] }],
};
mockTile = { availableUsd: 43.4, isLoading: false };

act(() => {
root = create(<Probe />);
});
expect(prompt?.available).toEqual({ amount: 37.23, currency: 'EUR' });

mockTile = { availableUsd: 111, isLoading: false };
act(() => root.update(<Probe />));
expect(prompt).toBeNull();
});

it('hides the banner once it covers the payment', () => {
mockTile = { availableUsd: 20, isLoading: false };

act(() => {
root = create(<Probe />);
});

expect(prompt).toBeNull();
});

it('waits for the tile rather than show one number and then another', () => {
mockTile = { availableUsd: null, isLoading: true };

act(() => {
root = create(<Probe />);
});

expect(prompt).toBeNull();
});

it('still quotes the tile, in dollars, when the backend cash read failed', () => {
mockSpendable = undefined;
mockTile = { availableUsd: 12.5, isLoading: false };

act(() => {
root = create(<Probe />);
});

expect(prompt?.available).toEqual({ amount: 12.5, currency: 'USD' });
});

it('waits for the backend cash read while it is still loading', () => {
mockSpendable = undefined;
mockSpendableLoading = true;
mockTile = { availableUsd: 12.5, isLoading: false };

act(() => {
root = create(<Probe />);
});

expect(prompt).toBeNull();
});

it("re-reads the tile's balances with the receipt's poll and its refresh", async () => {
let refetchCash: (() => Promise<unknown>) | undefined;
const Receipt = () => {
const { refetchCash: current } = useDeclineSpendable({ refetchInterval: 15_000 });
React.useEffect(() => {
refetchCash = current;
}, [current]);
return null;
};

act(() => {
root = create(<Receipt />);
});
expect(mockBalancesRefresh).toEqual({ enabled: true, refetchInterval: 15_000 });

await refetchCash?.();
expect(mockRefetchSpendable).toHaveBeenCalledTimes(1);
expect(mockRefetchBalances).toHaveBeenCalledTimes(1);
});

it('falls back to the cash figure when the tile cannot say', () => {
mockTile = { availableUsd: null, isLoading: false };

act(() => {
root = create(<Probe />);
});

expect(prompt?.available).toEqual({ amount: 5, currency: 'USD' });
});
});
});
25 changes: 25 additions & 0 deletions hooks/useBalances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1222,3 +1222,28 @@ export const useBalancesPolling = (): void => {
notifyOnChangeProps: [],
});
};

/**
* A faster re-read of the same balances for a screen that is waiting on a top-up: the declined
* receipt, whose Cash figure is the Available to spend tile's and so comes from these balances.
* The app-wide timer above can be a minute apart; this one runs at the screen's own pace, and only
* while that screen asks. Renders nothing. `refetch` reads them at once.
*/
export const useBalancesRefresh = ({
enabled = true,
refetchInterval,
}: { enabled?: boolean; refetchInterval?: number } = {}) => {
const { user } = useUser();
const options = tokenBalancesQueryOptions(user?.safeAddress);

const { refetch } = useQuery({
...options,
...balancesObserverOptions,
enabled: options.enabled && enabled && !!refetchInterval,
refetchInterval,
refetchIntervalInBackground: false,
notifyOnChangeProps: [],
});

return { refetch };
};
72 changes: 63 additions & 9 deletions hooks/useDeclineSpendable.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,27 @@
import { useCallback } from 'react';

import { useSpendModeFigures } from '@/components/Card/NewCardDetails/SpendMode/useSpendModeFigures';
import { ONE_USD } from '@/constants/cardSpendModule';
import { useBalancesRefresh } from '@/hooks/useBalances';
import { useCardCreditPositions } from '@/hooks/useCardCreditPositions';
import { useCardSpendable } from '@/hooks/useCardSpendable';
import { useCardSpendRegistration } from '@/hooks/useCardSpendRegistration';
import { useCardDisplayCurrency } from '@/hooks/useMainCurrency';
import { declinedPaymentFigures } from '@/lib/utils/cardCurrency';
import { declinedPaymentFigures, withTileAvailable } from '@/lib/utils/cardCurrency';

import type { CardTransaction } from '@/lib/types';
import type { CardSpendableResponse, CardTransaction } from '@/lib/types';

/** Live spending power for the declined receipt and its Home banner. */
/**
* Live spending power for the declined receipt and its Home banner.
*
* What is available is the home Available to spend tile's own number, so the banner under the tile
* and the receipt it opens quote the figure the tile shows — and neither says a payment is short
* when the tile covers it. Nothing while the tile is still loading, so they do not show one number
* and then another. When the tile cannot say (it reads "—"), the figures worked out here stand.
*
* The tile's cash comes from the token balances, not from the backend's spendable read, so the
* poll and `refetchCash` re-read both: a top-up shows on the receipt at the poll's pace.
*/
export const useDeclineSpendable = ({
enabled = true,
refetchInterval,
Expand All @@ -18,13 +30,23 @@ export const useDeclineSpendable = ({
useCardSpendRegistration({
refetchInterval: enabled ? refetchInterval : undefined,
});
const { data: cash, refetch: refetchCash } = useCardSpendable({ enabled, refetchInterval });
const {
data: cash,
isLoading: isCashLoading,
refetch: refetchSpendable,
} = useCardSpendable({ enabled, refetchInterval });
const { refetch: refetchBalances } = useBalancesRefresh({ enabled, refetchInterval });
const refetchCash = useCallback(
() => Promise.all([refetchSpendable(), refetchBalances()]),
[refetchSpendable, refetchBalances],
);
const hasMode = enabled && !!registration;
const { base, readsBase, isBaseGateReady } = useCardCreditPositions({
enabled: hasMode && mode !== 'cash',
refetchInterval,
});
const { inEuros, usdPerEur } = useCardDisplayCurrency();
const { inEuros, usdPerEur, toDisplayAmount } = useCardDisplayCurrency();
const { availableUsd: tileUsd, isLoading: isTileLoading } = useSpendModeFigures();

// One card authorization draws credit from one instance, subject to its remaining limits.
const fuseMicroUsd =
Expand All @@ -40,14 +62,46 @@ export const useDeclineSpendable = ({
const figuresFor = useCallback(
(transaction: CardTransaction) => {
if (!enabled || (!hasMode && isLoading)) return declinedPaymentFigures(transaction);
if (!hasMode || mode === 'cash') return declinedPaymentFigures(transaction, cash);
const displayUsdPerEur = inEuros ? usdPerEur : undefined;
if (tileUsd === null) {
if (isTileLoading) return declinedPaymentFigures(transaction);
if (!hasMode || mode === 'cash') return declinedPaymentFigures(transaction, cash);
return declinedPaymentFigures(transaction, cash, { mode, availableUsd, displayUsdPerEur });
}
if (!hasMode || mode === 'cash') {
// Still being read: wait for the card's own quote rather than show dollars and then euros.
if (!cash && isCashLoading) return declinedPaymentFigures(transaction);
// The read failed: the tile's number still stands, in dollars, with no card quote.
const known: CardSpendableResponse = cash ?? {
available: { amount: '0', currency: 'usd' },
};
const tileCash = withTileAvailable(known, {
usd: tileUsd,
eur: inEuros ? toDisplayAmount(tileUsd) : undefined,
});
return declinedPaymentFigures(transaction, tileCash);
}
return declinedPaymentFigures(transaction, cash, {
mode,
availableUsd,
displayUsdPerEur: inEuros ? usdPerEur : undefined,
availableUsd: tileUsd,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
displayUsdPerEur,
isTileFigure: true,
});
},
[enabled, hasMode, isLoading, mode, cash, availableUsd, inEuros, usdPerEur],
[
enabled,
hasMode,
isLoading,
mode,
cash,
isCashLoading,
availableUsd,
inEuros,
usdPerEur,
toDisplayAmount,
tileUsd,
isTileLoading,
],
);

return { mode, figuresFor, refetchCash };
Expand Down
5 changes: 4 additions & 1 deletion hooks/useDeclinedPaymentPrompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ export interface DeclinedPaymentPrompt {
/** Card transaction id — what the banner's "Fix it" opens. */
transactionId: string;
payment: Money;
/** What the card can spend now, live — less than {@link payment}, or there is no banner. */
/**
* What the card can spend now, live — the Available to spend tile's own number. Less than
* {@link payment}, or there is no banner.
*/
available: Money;
merchantName?: string;
}
Expand Down
Loading
Loading