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
77 changes: 51 additions & 26 deletions components/Card/RainSunset/RainClosingWithdraw.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import Toast from 'react-native-toast-message';
import { Image } from 'expo-image';
import { useRouter } from 'expo-router';
import { useQueryClient } from '@tanstack/react-query';
import { formatUnits } from 'viem';

import PageLayout from '@/components/PageLayout';
import RenderTokenIcon from '@/components/RenderTokenIcon';
Expand All @@ -29,9 +28,11 @@ import { showFailureSheet } from '@/lib/errors';
import getTokenIcon from '@/lib/getTokenIcon';
import { isCancelledByUser } from '@/lib/utils/passkeyErrors';
import {
closingWithdrawalPlan,
floorCents,
formatClosingBalance,
formatClosingDate,
formatTokenUnits,
remainderCents,
tokenWithdrawal,
unitsToCents,
Expand Down Expand Up @@ -76,6 +77,11 @@ type Phase =
* reason to leave anything on it. Each token is its own collateral withdrawal —
* today's `useWithdrawRainCollateral`, one `withdrawAsset` per token — so a card
* holding two tokens asks for the passkey twice, and the screen says so.
*
* The amounts shown are what the withdrawal will move (`closingWithdrawalPlan`),
* never the card's whole collateral: the part of it set aside for card payments
* already made stays on the card, and the screen says how much that is. Showing
* the collateral put "Withdraw $11.14" on a card with $0.24 to withdraw.
*/
export function RainClosingWithdraw() {
const router = useRouter();
Expand All @@ -93,7 +99,15 @@ export function RainClosingWithdraw() {
),
[collateral],
);
const totalUsd = tokens.reduce((sum, token) => sum + token.balanceUsd, 0);
// What the withdrawal will move under the card's spending power, and what
// that leaves on the card; the rows, the total and the button all read this.
const plan = useMemo(
() => closingWithdrawalPlan(tokens, collateral?.spendingPowerUsd),
[tokens, collateral?.spendingPowerUsd],
);
const movable = plan.rows.filter(row => row.units > 0n);
const totalUsd = Number(plan.movableCents) / 100;
const heldUsd = Number(plan.heldCents) / 100;
const closesOn = formatClosingDate(sunset?.closesAt);
// No answer at all is not an empty card: say so and offer to read it again.
const unreadable = !collateral && isError;
Expand Down Expand Up @@ -200,9 +214,10 @@ export function RainClosingWithdraw() {
};

if (phase.kind === 'done' && phase.leftUsd > 0) {
// Rain capped the withdrawal below the card balance (it still holds some
// against pending payments). Say what moved and what did not, and lead
// back to the review, which shows what is still on the card.
// Rain capped the withdrawal below the card's collateral: the rest is set
// aside, nearly always for card payments already made. Say what moved and
// what did not, without promising the rest, and offer the review, which
// re-reads the card.
return (
<PageLayout desktopOnly scrollable={false}>
<View className="mx-auto w-full max-w-lg flex-1 px-6">
Expand All @@ -216,19 +231,20 @@ export function RainClosingWithdraw() {
{formatClosingBalance(phase.usd)} is in your wallet
</Text>
<Text className="text-center text-[16px] leading-[22px] text-white/70">
{formatClosingBalance(phase.leftUsd)} is still on your card, held for pending
payments. Withdraw it once they settle.
{formatClosingBalance(phase.leftUsd)} is still on your card. It is set aside, usually
for card payments you already made, and can’t be withdrawn.
</Text>
</View>
<View className="pb-6 pt-3">
<Button onPress={goToCard} className="mb-2 h-[54px] rounded-full bg-white">
<Text className="text-[17px] font-semibold text-black">Done</Text>
</Button>
<Button
variant="ghost"
onPress={() => setPhase({ kind: 'review' })}
className="mb-2 h-[54px] rounded-full bg-white"
className="h-[54px] rounded-full"
>
<Text className="text-[17px] font-semibold text-black">Withdraw the rest</Text>
</Button>
<Button variant="ghost" onPress={goToCard} className="h-[54px] rounded-full">
<Text className="text-[17px] font-semibold text-white">Done</Text>
<Text className="text-[17px] font-semibold text-white">Check card balance</Text>
</Button>
</View>
</View>
Expand Down Expand Up @@ -284,10 +300,18 @@ export function RainClosingWithdraw() {
}

const withdrawing = phase.kind === 'withdrawing';
// One passkey confirmation per token that actually moves.
const confirmations =
tokens.length > 1
? `You'll confirm with your passkey, once for each of the ${tokens.length} tokens.`
movable.length > 1
? `You'll confirm with your passkey, once for each of the ${movable.length} tokens.`
: "You'll confirm with your passkey.";
// The collateral past the cap: named, so the total above is not read as an error.
const held =
heldUsd > 0
? movable.length > 0
? `Another ${formatClosingBalance(heldUsd)} on your card is set aside, usually for card payments you already made, and can’t be withdrawn.`
: `The ${formatClosingBalance(heldUsd)} on your card is set aside, usually for card payments you already made, and can’t be withdrawn.`
: null;
const stays = closesOn
? ` Your card keeps working until ${closesOn.long}.`
: ' Your card keeps working until it closes.';
Expand Down Expand Up @@ -318,29 +342,28 @@ export function RainClosingWithdraw() {
{formatClosingBalance(totalUsd)}
</Text>
)}
<Text className="text-[14px] text-white/50">All of it moves to your wallet</Text>
{movable.length > 0 || !held ? (
<Text className="text-[14px] text-white/50">All of it moves to your wallet</Text>
) : null}
</View>

{tokens.length > 0 ? (
{movable.length > 0 ? (
<View style={styles.section}>
<Text className="text-[15px] font-medium text-white/60">From your card</Text>
<View style={styles.list}>
{tokens.map((token, index) => (
{movable.map(({ token, index, units, cents }, position) => (
<View key={`${token.chainId}:${token.tokenAddress}`}>
{index > 0 ? <View style={styles.divider} /> : null}
{position > 0 ? <View style={styles.divider} /> : null}
<View style={styles.row}>
<TokenLogoPop symbol={token.symbol} index={index} />
<TokenLogoPop symbol={token.symbol} index={position} />
<View style={styles.rowText}>
<Text className="text-[16px] font-medium text-white">{token.symbol}</Text>
<Text className="text-[13px] text-white/50">
{Number(
formatUnits(BigInt(token.rawBalance || '0'), token.decimals),
).toFixed(2)}{' '}
{token.symbol}
{formatTokenUnits(units, token.decimals)} {token.symbol}
</Text>
</View>
<Text className="text-[16px] font-medium text-white">
{formatClosingBalance(token.balanceUsd)}
{formatClosingBalance(Number(cents) / 100)}
</Text>
{withdrawing && phase.step === index ? (
<ActivityIndicator color="#94F27F" style={styles.rowSpinner} />
Expand All @@ -367,6 +390,8 @@ export function RainClosingWithdraw() {
</View>
</View>

{held ? <Text className="text-[14px] leading-[20px] text-white/50">{held}</Text> : null}

<Text className="text-[14px] leading-[20px] text-white/50">
{confirmations}
{stays}
Expand All @@ -377,7 +402,7 @@ export function RainClosingWithdraw() {
<Button
variant="brand"
className="h-[54px] rounded-full"
disabled={withdrawing || isLoading || (!unreadable && tokens.length === 0)}
disabled={withdrawing || isLoading || (!unreadable && movable.length === 0)}
onPress={() => (unreadable ? void refetch() : void withdrawAll())}
>
{withdrawing ? (
Expand All @@ -386,7 +411,7 @@ export function RainClosingWithdraw() {
<Text className="text-[17px] font-semibold text-black">
{unreadable
? 'Try again'
: tokens.length === 0 && !isLoading
: movable.length === 0 && !isLoading
? 'Nothing to withdraw'
: `Withdraw ${formatClosingBalance(totalUsd)}`}
</Text>
Expand Down
6 changes: 6 additions & 0 deletions components/tabBar/NewCustomTabBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ const HIDDEN_TAB_ROUTES = new Set(['settings', 'sumsub-kyc']);
* - `spend-order`, `collateral-order`: the card's order editors; the bar covers their Save
* button and the bottom band a lifted row auto-scrolls the page in.
* - `credit`: the card's Credit page; the bar covers its loan actions and the end of the page.
* - `closing-withdraw`: the closing card's withdraw screen; the bar covers its Withdraw
* button, so the balance cannot be moved off the card.
* - `new-card`: the move to the new card; the bar covers "Not now" and the lower edge of the
* button above it. Same pinned footer as `closing-withdraw`.
* - `ai-api`, `ai-api-key`, `ai-api-setup`: the AI API screens end in their own
* full-width buttons, which the bar would sit on.
* - `refer/*`: the referral v4 screens pin their share bar to the bottom edge.
Expand All @@ -93,6 +97,8 @@ const HIDDEN_NESTED_ROUTES = new Set([
'spend-order',
'collateral-order',
'credit',
'closing-withdraw',
'new-card',
'ai-api',
'ai-api-key',
'ai-api-setup',
Expand Down
16 changes: 9 additions & 7 deletions hooks/useRainSunset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,20 @@ import { useQuery } from '@tanstack/react-query';
import { useCardStatus } from '@/hooks/useCardStatus';
import { getCardCollateralAvailable } from '@/lib/api';
import { withRefreshToken } from '@/lib/utils';
import { rainSunsetOf } from '@/lib/utils/rainSunset';
import { closingCardBalanceUsd, rainSunsetOf } from '@/lib/utils/rainSunset';

export const RAIN_SUNSET_BALANCE_KEY = 'rainSunsetBalance';

/**
* Rain sunset for the signed-in user: the closing-card block from
* `/cards/status`, and the balance still on the closing card.
*
* The balance is the card's on-chain collateral summed over every token — the
* same read the withdraw screen uses, because that is what can actually be
* moved to the wallet. Read only for someone still holding the closing card,
* and on a slow cadence: this backs a banner, not a form.
* The balance is what is still the cardholder's own money: the card's on-chain
* collateral, capped at its spending power (`closingCardBalanceUsd`). The part
* of the collateral that pays for card payments already made is not theirs to
* withdraw, so it is never quoted as a balance. Read only for someone still
* holding the closing card, and on a slow cadence: this backs a banner, not a
* form.
*/
export function useRainSunset() {
const { data: cardStatus, isLoading: isStatusLoading } = useCardStatus();
Expand All @@ -33,8 +35,8 @@ export function useRainSunset() {
cardStatus,
sunset,
isLoading: isStatusLoading,
/** Total balance left on the closing card, in dollars; null until read. */
balanceUsd: sunset?.hasRainCard ? (balance.data?.totalCollateralUsd ?? null) : 0,
/** What the cardholder can still withdraw from the closing card, in dollars; null until read. */
balanceUsd: sunset?.hasRainCard ? closingCardBalanceUsd(balance.data) : 0,
collateral: balance.data ?? null,
isBalanceLoading: balance.isLoading,
refetchBalance: balance.refetch,
Expand Down
141 changes: 141 additions & 0 deletions lib/utils/__tests__/rainSunset.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ import {
blocksNewCard,
cardNoticeCopy,
closesPhrase,
closingCardBalanceUsd,
closingWithdrawalPlan,
floorCents,
formatClosingBalance,
formatClosingDate,
formatTokenUnits,
hasClosingBalance,
homeBannerCopy,
isClosingBalanceUnknown,
Expand Down Expand Up @@ -157,13 +160,151 @@ describe('rainSunset', () => {
expect(floorCents(undefined)).toBe(0n);
});

it('shows a token amount truncated to two decimals, never rounded up', () => {
// Beside a dollar figure that is rounded down: 3.239 USDT is $3.23, not "3.24 USDT".
expect(formatTokenUnits(3239000n, 6)).toBe('3.23');
expect(formatTokenUnits(1009000n, 6)).toBe('1.00');
expect(formatTokenUnits(240000n, 6)).toBe('0.24');
expect(formatTokenUnits(7910000n, 6)).toBe('7.91');
expect(formatTokenUnits(248500000n, 6)).toBe('248.50');
expect(formatTokenUnits(12349999999999999999n, 18)).toBe('12.34');
expect(formatTokenUnits(5n, 0)).toBe('5.00');
expect(formatTokenUnits(0n, 6)).toBe('0.00');
expect(formatTokenUnits(-1n, 6)).toBe('0.00');
});

it('rounds a token amount up for the cap it uses, down for what moved', () => {
expect(unitsToCents(5000n, 6, 'up')).toBe(1n);
expect(unitsToCents(5000n, 6, 'down')).toBe(0n);
expect(unitsToCents(248500000n, 6, 'up')).toBe(24850n);
});
});

describe('closingCardBalanceUsd', () => {
it('is the collateral capped at spending power: what is still the cardholder’s', () => {
expect(closingCardBalanceUsd({ totalCollateralUsd: 60, spendingPowerUsd: 42.5 })).toBe(42.5);
expect(closingCardBalanceUsd({ totalCollateralUsd: 30, spendingPowerUsd: 200 })).toBe(30);
});

it('does not count collateral that pays for card payments already made', () => {
// T-40, nbchacker29: $11.14 in the contract, $10.90 of it for three settled purchases.
const balance = closingCardBalanceUsd({ totalCollateralUsd: 11.14, spendingPowerUsd: 0.24 });
expect(balance).toBe(0.24);
expect(homeBannerCopy('closing-balance', sunset(), balance).message).toBe(
'Withdraw your $0.24 card balance before then.',
);

// T-40, redninjax39: the whole $288.69 was his own settled spend.
const spent = closingCardBalanceUsd({ totalCollateralUsd: 288.69, spendingPowerUsd: 0 });
expect(spent).toBe(0);
expect(hasClosingBalance(spent)).toBe(false);
expect(blocksNewCard(spent, sunset())).toBe(false);
expect(rainClosingBannerState(sunset(), spent)).toBe('closing-empty');
});

it('still blocks the new card on a real balance above the threshold', () => {
const balance = closingCardBalanceUsd({ totalCollateralUsd: 60, spendingPowerUsd: 42.5 });
expect(blocksNewCard(balance, sunset())).toBe(true);
});

it('keeps the whole collateral when spending power is unknown', () => {
expect(closingCardBalanceUsd({ totalCollateralUsd: 75 })).toBe(75);
expect(closingCardBalanceUsd({ totalCollateralUsd: 75, spendingPowerUsd: NaN })).toBe(75);
});

it('is unknown, never zero, until the balance has been read', () => {
expect(closingCardBalanceUsd(undefined)).toBeNull();
expect(closingCardBalanceUsd(null)).toBeNull();
expect(isClosingBalanceUnknown(closingCardBalanceUsd(undefined))).toBe(true);
});

it('never goes below zero', () => {
expect(closingCardBalanceUsd({ totalCollateralUsd: 10, spendingPowerUsd: -3 })).toBe(0);
});
});

describe('closingWithdrawalPlan', () => {
const usdc = { symbol: 'USDC', rawBalance: '7910000', decimals: 6 };
const usdt = { symbol: 'USDT', rawBalance: '3239000', decimals: 6 };

it('moves only what spending power allows and names the rest as held', () => {
// T-40, nbchacker29: the screen said "Withdraw $11.14"; $0.24 could move.
const plan = closingWithdrawalPlan([usdc, usdt], 0.24);
expect(plan.rows.map(row => [row.token.symbol, row.index, row.units, row.cents])).toEqual([
['USDC', 0, 240000n, 24n],
['USDT', 1, 0n, 0n],
]);
expect(plan.movableCents).toBe(24n);
expect(plan.heldCents).toBe(1090n);
});

it('moves everything when nothing caps it', () => {
for (const spendingPower of [undefined, 500]) {
const plan = closingWithdrawalPlan([usdc, usdt], spendingPower);
expect(plan.rows.map(row => row.units)).toEqual([7910000n, 3239000n]);
expect(plan.movableCents).toBe(1114n);
expect(plan.heldCents).toBe(0n);
}
});

it('leaves only sub-cent dust when the cap is the balance to the cent', () => {
const plan = closingWithdrawalPlan([usdc, usdt], 11.14);
expect(plan.rows.map(row => row.units)).toEqual([7910000n, 3230000n]);
expect(plan.movableCents).toBe(1114n);
// 0.009 USDT stays behind; it is not reported as a balance still on the card.
expect(plan.heldCents).toBe(0n);
});

it('moves nothing when the whole collateral is owed', () => {
const plan = closingWithdrawalPlan([usdc, usdt], 0);
expect(plan.rows.every(row => row.units === 0n)).toBe(true);
expect(plan.movableCents).toBe(0n);
expect(plan.heldCents).toBe(1114n);
});

it('carries the cap from one token into the next', () => {
const plan = closingWithdrawalPlan([usdc, usdt], 9);
expect(plan.rows.map(row => [row.units, row.cents])).toEqual([
[7910000n, 791n],
[1090000n, 109n],
]);
expect(plan.movableCents).toBe(900n);
expect(plan.heldCents).toBe(214n);
});

it('asks each token for exactly what the withdrawal itself would', () => {
const plan = closingWithdrawalPlan([usdc, usdt], 9);
expect(plan.rows[0].units).toBe(tokenWithdrawal(usdc, 900n).units);
expect(plan.rows[1].units).toBe(tokenWithdrawal(usdt, 109n).units);
expect(plan.heldCents).toBe(remainderCents(usdt, plan.rows[1].units));
});

it('never overstates the cap left after a sub-cent amount', () => {
const dust = { symbol: 'USDC', rawBalance: '5000', decimals: 6 };
const dollar = { symbol: 'USDT', rawBalance: '1000000', decimals: 6 };
const plan = closingWithdrawalPlan([dust, dollar], 0.1);
// The dust uses a whole cent of the cap and shows as nothing moved.
expect(plan.rows.map(row => [row.units, row.cents])).toEqual([
[5000n, 0n],
[90000n, 9n],
]);
expect(plan.movableCents).toBe(9n);
expect(plan.heldCents).toBe(91n);
});

it('works in a token’s own decimals', () => {
const dai = { symbol: 'DAI', rawBalance: '248500000000000000000', decimals: 18 };
const plan = closingWithdrawalPlan([dai], 12.34);
expect(plan.rows[0].units).toBe(12340000000000000000n);
expect(plan.movableCents).toBe(1234n);
expect(plan.heldCents).toBe(23616n);
});

it('is empty for an empty card', () => {
expect(closingWithdrawalPlan([], 5)).toEqual({ rows: [], movableCents: 0n, heldCents: 0n });
});
});

describe('tokenWithdrawal', () => {
const usdc = { rawBalance: '248500000', decimals: 6 };

Expand Down
Loading
Loading