diff --git a/components/Card/CardDepositInternalForm.tsx b/components/Card/CardDepositInternalForm.tsx index 44a8a03a7..edde3c357 100644 --- a/components/Card/CardDepositInternalForm.tsx +++ b/components/Card/CardDepositInternalForm.tsx @@ -26,6 +26,7 @@ import { useShallow } from 'zustand/react/shallow'; import DepositPublicAddress from '@/components/DepositOption/DepositPublicAddress'; import Max from '@/components/Max'; +import TierBalanceOutflowNotice from '@/components/TierBalance/TierBalanceOutflowNotice'; import { Button } from '@/components/ui/button'; import { DropdownMenu, @@ -50,6 +51,7 @@ import { useCardProvider } from '@/hooks/useCardProvider'; import useDepositFromSolidUsdc from '@/hooks/useDepositFromSolidUsdc'; import { usePreviewDepositToCard } from '@/hooks/usePreviewDepositToCard'; import useSwapAndBridgeToCard from '@/hooks/useSwapAndBridgeToCard'; +import { useTierBalanceOutflowWarning } from '@/hooks/useTierBalance'; import useUser from '@/hooks/useUser'; import { track } from '@/lib/analytics'; import { getAsset } from '@/lib/assets'; @@ -616,6 +618,19 @@ export default function CardDepositInternalForm() { const { data: savingsMinimum } = useSponsoredMinimum(ADDRESSES.fuse.cardDepositManager); const isSavingsSource = watchedFrom === CardDepositSource.SAVINGS; + // Topping up from savings spends soUSD out of Earn, which can cost a tier held + // or being built on the "Hold in Earn" route. Priced at the soUSD rate read + // above, or the share's wallet quote until that lands. + const savingsOutflowUsd = useMemo(() => { + const amount = Number(watchedAmount || 0); + if (!isSavingsSource || !Number.isFinite(amount) || amount <= 0) return 0; + return amount * (exchangeRate > 0 ? exchangeRate : soUsdToken?.quoteRate || 0); + }, [isSavingsSource, watchedAmount, exchangeRate, soUsdToken?.quoteRate]); + const { warning: tierBalanceWarning, proceed: proceedPastWarning } = useTierBalanceOutflowWarning( + 'card_topup', + savingsOutflowUsd, + ); + const schema = useMemo(() => { return z.object({ amount: z @@ -738,6 +753,7 @@ export default function CardDepositInternalForm() { const onSubmit = useCallback( async (data: any) => { if (!user) return; + proceedPastWarning(); // Track submission const trackingParams: Record = { @@ -860,6 +876,7 @@ export default function CardDepositInternalForm() { setTransaction, swapAndBridge, updateActivity, + proceedPastWarning, ], ); @@ -1053,6 +1070,8 @@ export default function CardDepositInternalForm() { /> )} + {isSavingsSource && } + {/* {watchedFrom !== CardDepositSource.EXTERNAL && ( router.push(openYieldProduct(type) as Href)} - boost={} + boost={ + <> + {/* Draws nothing unless the "Hold in Earn" tier route is staged to this user. */} + + + + } /> ); diff --git a/components/Earn/EarnTierBalanceCard.tsx b/components/Earn/EarnTierBalanceCard.tsx new file mode 100644 index 000000000..9f7f30452 --- /dev/null +++ b/components/Earn/EarnTierBalanceCard.tsx @@ -0,0 +1,88 @@ +import { useEffect, useRef } from 'react'; +import { Pressable, View } from 'react-native'; + +import { PointsProgress } from '@/components/Rewards/NewRewards/TierUpgradeCard'; +import { Text } from '@/components/ui/text'; +import { TRACKING_EVENTS } from '@/constants/tracking-events'; +import { useAddToEarn, useTierBalance } from '@/hooks/useTierBalance'; +import { track } from '@/lib/analytics'; +import { trackNeedsTopUp, trackNudgeCopy, trackProgress } from '@/lib/tierBalance'; +import { cn } from '@/lib/utils'; + +interface EarnTierBalanceCardProps { + className?: string; +} + +/** + * The "Hold in Earn" route on the Earn page: how far the balance here is from + * unlocking (or keeping) a tier, laid out like the yield boost card beside it, + * with the points card's progress bar. + * + * Every figure is the backend's — the shortfall, the threshold, the days — and + * the card draws nothing for anyone the route is not staged to, or for an Ultra + * member by another route, who has nothing left to unlock. + */ +const EarnTierBalanceCard = ({ className }: EarnTierBalanceCardProps) => { + const { balance, relevant } = useTierBalance(); + const addToEarn = useAddToEarn('earn'); + + // Reported once per tier and state. + const viewed = useRef(null); + useEffect(() => { + if (!relevant) return; + const key = `${relevant.tier}:${relevant.status}`; + if (viewed.current === key) return; + viewed.current = key; + track(TRACKING_EVENTS.TIER_BALANCE_OPTION_VIEWED, { + route: 'balance', + tier: relevant.tier, + status: relevant.status, + surface: 'earn', + }); + }, [relevant]); + + if (!balance || !relevant) return null; + + const { title, body } = trackNudgeCopy(relevant, balance); + const progress = trackProgress(relevant, balance); + const canAdd = trackNeedsTopUp(relevant); + + return ( + + + + + {title} + {body} + + {canAdd ? ( + addToEarn(relevant)} + className="h-[37px] min-w-[80px] items-center justify-center rounded-full bg-[#94F27F] px-[21px] transition-all active:scale-95 active:opacity-80" + > + + Deposit + + + ) : null} + + + + + {progress.value ? ( + {progress.value} + ) : null} + {progress.target} + + + + + ); +}; + +export default EarnTierBalanceCard; diff --git a/components/Earn/EarnView.tsx b/components/Earn/EarnView.tsx index 89c4b03c3..8e744a693 100644 --- a/components/Earn/EarnView.tsx +++ b/components/Earn/EarnView.tsx @@ -142,7 +142,10 @@ export interface EarnViewProps { past30: number | undefined; products: EarnProduct[]; onOpenProduct: (type: VaultType) => void; - /** The yield boost card; it renders nothing for a user without one. */ + /** + * The yield boost card and the "Hold in Earn" tier nudge; each renders nothing + * for a user without one. + */ boost?: ReactNode; } diff --git a/components/Rewards/NewRewards/RewardsBenefitsScreenNew.tsx b/components/Rewards/NewRewards/RewardsBenefitsScreenNew.tsx index 37f6a4c37..bfc958d92 100644 --- a/components/Rewards/NewRewards/RewardsBenefitsScreenNew.tsx +++ b/components/Rewards/NewRewards/RewardsBenefitsScreenNew.tsx @@ -24,14 +24,18 @@ import PageLayout from '@/components/PageLayout'; import { BackButton } from '@/components/ui/back-button'; import { Text } from '@/components/ui/text'; import { path } from '@/constants/path'; +import { TRACKING_EVENTS } from '@/constants/tracking-events'; import { useCardProvider } from '@/hooks/useCardProvider'; import { useCardStatus } from '@/hooks/useCardStatus'; import { useRewardsUserData, useTierBenefits } from '@/hooks/useRewards'; import { useSavingsFundFlow } from '@/hooks/useSavingsFundFlow'; +import { useAddToEarn } from '@/hooks/useTierBalance'; import { useTierMembership } from '@/hooks/useTierMembership'; +import { track } from '@/lib/analytics'; import { isHigherTier } from '@/lib/rewardsUpgrade'; +import { activeTierBalance, tierBalanceTrack } from '@/lib/tierBalance'; import { availableRoutes, findOffer, offerFirstYearFeeUsd } from '@/lib/tierUpgrade'; -import { RewardsTier } from '@/lib/types'; +import { RewardsTier, type TierBalanceTrackDto } from '@/lib/types'; import { useSwapState } from '@/store/swapStore'; import { useDepositStore } from '@/store/useDepositStore'; import { useRewardsUpgradeStore } from '@/store/useRewardsUpgradeStore'; @@ -237,6 +241,9 @@ function RewardsBenefitsForAccount({ initialTier }: { initialTier: RewardsTier | : undefined; const { data: membership } = useTierMembership(); const openTierUpgrade = useTierUpgradeStore(state => state.open); + // The "Hold in Earn" route, for a user it is staged to; null for everyone else. + const balance = activeTierBalance(membership); + const addToEarn = useAddToEarn('tier_benefits'); const [selectedTierOverride, setSelectedTierOverride] = useState(initialTier); const [isUpgradeSheetOpen, setIsUpgradeSheetOpen] = useState(false); const [upgradeTier, setUpgradeTier] = useState( @@ -300,6 +307,34 @@ function RewardsBenefitsForAccount({ initialTier }: { initialTier: RewardsTier | return availableRoutes(offer, membership.contracts); }; + /** + * This tier's "Hold in Earn" track, when the page should offer it: Prime and + * Ultra, unless the user already holds the tier by another route and the + * track has nothing to report. + */ + const balanceTrackFor = (tier: RewardsTier): TierBalanceTrackDto | undefined => { + if (!balance || tier === RewardsTier.CORE) return undefined; + const balanceTrack = tierBalanceTrack(balance, tier); + const holdsTier = !isHigherTier(tier, membership?.currentTier ?? RewardsTier.CORE); + return holdsTier && balanceTrack.status === 'none' ? undefined : balanceTrack; + }; + + // Reported once per tier and state, when its page is the one on screen. + const selectedBalanceTrack = balanceTrackFor(selectedTier); + const viewedBalanceTracks = useRef(new Set()); + useEffect(() => { + if (!selectedBalanceTrack) return; + const key = `${selectedBalanceTrack.tier}:${selectedBalanceTrack.status}`; + if (viewedBalanceTracks.current.has(key)) return; + viewedBalanceTracks.current.add(key); + track(TRACKING_EVENTS.TIER_BALANCE_OPTION_VIEWED, { + route: 'balance', + tier: selectedBalanceTrack.tier, + status: selectedBalanceTrack.status, + surface: 'tier_benefits', + }); + }, [selectedBalanceTrack]); + const ctaFor = (tier: RewardsTier) => { const offer = findOffer(membership, tier); @@ -558,15 +593,20 @@ function RewardsBenefitsForAccount({ initialTier }: { initialTier: RewardsTier | showCardFx={showCardFx} offer={membership?.enabled ? findOffer(membership, tier) : undefined} contracts={membership?.contracts} + balance={balance} + balanceTrack={balanceTrackFor(tier)} + onAddToEarn={addToEarn} showUpgradeSpace={ !ctaFor(tier).held && (tier !== RewardsTier.CORE || (isError && !isRewardsFetching)) } subtitle={(() => { const pointsEnabled = membership?.pointsUnlockEnabled ?? true; - const offerCopy = membership?.enabled - ? tierOfferSubtitle(findOffer(membership, tier), membership.contracts) - : null; + const offerCopy = tierOfferSubtitle( + membership?.enabled ? findOffer(membership, tier) : undefined, + membership?.contracts, + balanceTrackFor(tier), + ); const copy = tier === RewardsTier.CORE ? 'Starting tier' @@ -584,6 +624,9 @@ function RewardsBenefitsForAccount({ initialTier }: { initialTier: RewardsTier | fontSize: 16 * Math.min(pageWidth / 420, 1), lineHeight: 20, color: 'rgba(255,255,255,0.7)', + // Three ways to a tier can run to a second line. + textAlign: 'center', + paddingHorizontal: 16, }} > {copy} diff --git a/components/Rewards/NewRewards/TierBenefitsPage.tsx b/components/Rewards/NewRewards/TierBenefitsPage.tsx index 9b861f63c..254b9d25f 100644 --- a/components/Rewards/NewRewards/TierBenefitsPage.tsx +++ b/components/Rewards/NewRewards/TierBenefitsPage.tsx @@ -1,5 +1,5 @@ import { type ReactNode, useEffect, useState } from 'react'; -import { Platform, StyleSheet, View } from 'react-native'; +import { Platform, Pressable, StyleSheet, View } from 'react-native'; import Animated, { cancelAnimation, Easing, @@ -20,9 +20,12 @@ import { } from '@/assets/images/rewards-tiers/core-tier-icons'; import { Text } from '@/components/ui/text'; import { type AssetPath, getAsset } from '@/lib/assets'; +import { trackNeedsTopUp, trackProgress, trackStatusLine } from '@/lib/tierBalance'; import { formatTierCashbackRate } from '@/lib/tierCashback'; import { RewardsTier, + type TierBalanceRouteDto, + type TierBalanceTrackDto, type TierBenefits, type TierCardFx, type TierFees, @@ -49,6 +52,7 @@ import { } from './tierBenefitsPresentation'; import { CARD_FX_FOOTNOTE, cardFxPerk, withCardFxRow } from './tierCardFx'; import TierStar from './TierHero/TierStar'; +import { PointsProgress } from './TierUpgradeCard'; const ART = { [RewardsTier.CORE]: { source: 'images/rewards-tiers/v4/card-core.png', width: 350, height: 254 }, @@ -856,6 +860,58 @@ function CashbackPanel({ ); } +/** + * Under the "Hold in Earn" row: how far the user is, where the track stands, and + * — when the next step is putting money in — the way to Earn's deposit. Every + * figure is the backend's; the progress bar is the one the points card uses. + */ +function BalanceRouteStatus({ + track, + balance, + s, + onAddToEarn, +}: { + track: TierBalanceTrackDto; + balance: TierBalanceRouteDto; + s: number; + onAddToEarn?: (track: TierBalanceTrackDto) => void; +}) { + const progress = trackProgress(track, balance); + const name = TIER_LABELS[track.tier]; + return ( + + + + + {progress.value ? ( + {progress.value} + ) : null} + + {progress.target} + + + + {trackStatusLine(track, balance)} + {`Every ${name} benefit, except Yield boost.`} + {onAddToEarn && trackNeedsTopUp(track) ? ( + onAddToEarn(track)} + className="mt-[9px] h-[35px] w-[129px] items-center justify-center self-start rounded-full bg-[#94F27F] transition-all active:scale-95 active:opacity-80" + > + + Add to Earn + + + ) : null} + + ); +} + export function TierBenefitsPage({ tier, active, @@ -872,6 +928,9 @@ export function TierBenefitsPage({ contracts, showUpgradeSpace, showCardFx, + balance, + balanceTrack, + onAddToEarn, }: { tier: RewardsTier; active: boolean; @@ -899,6 +958,13 @@ export function TierBenefitsPage({ * see `showsCardFxPricing`. */ showCardFx: boolean; + /** + * The "Hold in Earn" route and this tier's track on it, for a user the route + * is staged to. Absent, the page shows nothing of it. + */ + balance?: TierBalanceRouteDto | null; + balanceTrack?: TierBalanceTrackDto; + onAddToEarn?: (track: TierBalanceTrackDto) => void; }) { const s = scaleFor(width); const table = tierPresentationFees(tier, fees); @@ -909,7 +975,7 @@ export function TierBenefitsPage({ table.lines.filter(line => line.key !== 'fx'), cardFx, ); - const offers = tierOfferRows(offer, contracts); + const offers = tierOfferRows(offer, contracts, balance ? balanceTrack : undefined); const showsOffers = tier !== RewardsTier.CORE && offers.length > 0; const cardFxFootnote = cardFx ? ( {offers.map(row => ( - - - {row.label} - - + + + + {row.label} + + + + {row.balanceTrack && balance ? ( + + ) : null} ))} diff --git a/components/Rewards/NewRewards/TierMembershipSheetContent.tsx b/components/Rewards/NewRewards/TierMembershipSheetContent.tsx index 68a4a3fb6..40c0a4f96 100644 --- a/components/Rewards/NewRewards/TierMembershipSheetContent.tsx +++ b/components/Rewards/NewRewards/TierMembershipSheetContent.tsx @@ -8,6 +8,13 @@ import { Button } from '@/components/ui/button'; import { Text } from '@/components/ui/text'; import { useCancelTierSubscription, useTierMembership } from '@/hooks/useTierMembership'; import { getAsset } from '@/lib/assets'; +import { + activeTierBalance, + formatBalanceUsd, + formatThresholdUsd, + formatTierBalanceDate, + relevantTrack, +} from '@/lib/tierBalance'; import { getTierDisplayName } from '@/lib/tierNames'; import { availableRoutes, @@ -65,6 +72,11 @@ const TierMembershipSheetContent = ({ const subscriptionTierName = subscription ? getTierDisplayName(subscription.tier) : ''; const lock = membership?.lock; const dateLabel = membershipDateLabel(membership); + // The "Hold in Earn" route, when it is holding a tier for this user. + const balance = activeTierBalance(membership); + const balanceTrack = relevantTrack(balance, membership?.currentTier); + const heldByBalance = + balanceTrack?.status === 'active' || balanceTrack?.status === 'grace' ? balanceTrack : null; const subscriptionEnded = subscription?.status === TierSubscriptionStatus.EXPIRED || subscription?.status === TierSubscriptionStatus.REPLACED; @@ -152,6 +164,28 @@ const TierMembershipSheetContent = ({ ) : null} + {balance && heldByBalance ? ( + + + + {heldByBalance.status === 'grace' ? ( + + ) : null} + + ) : null} + {subscription ? ( { return Math.min(100, Math.max(0, (currentPoints / targetPoints) * 100)); }; -const PointsProgress = ({ percent }: { percent: number }) => { +/** The tier progress bar, shared with the "Hold in Earn" route's progress. */ +export const PointsProgress = ({ percent }: { percent: number }) => { const animatedProgress = useAnimatedStyle( () => ({ width: withTiming(`${percent}%`, { duration: 500 }) }), [percent], diff --git a/components/Rewards/NewRewards/__tests__/tierBenefitsPresentation.test.ts b/components/Rewards/NewRewards/__tests__/tierBenefitsPresentation.test.ts index 4fb0dce69..7cabaf2f1 100644 --- a/components/Rewards/NewRewards/__tests__/tierBenefitsPresentation.test.ts +++ b/components/Rewards/NewRewards/__tests__/tierBenefitsPresentation.test.ts @@ -5,7 +5,13 @@ import { tierPresentationContent, tierPresentationFees, } from '@/components/Rewards/NewRewards/tierBenefitsPresentation'; -import { RewardsTier, type TierBenefits, type TierFees, type TierOffer } from '@/lib/types'; +import { + RewardsTier, + type TierBalanceTrackDto, + type TierBenefits, + type TierFees, + type TierOffer, +} from '@/lib/types'; const { CORE, PRIME, ULTRA } = RewardsTier; const benefits = (tier: RewardsTier, overrides: Partial = {}) => @@ -286,4 +292,50 @@ describe('membership offer presentation', () => { expect(tierOfferSubtitle({ ...upgrade, lockAvailable: false }, noTreasury)).toBeNull(); }); }); + + describe('the Hold in Earn route', () => { + const track: TierBalanceTrackDto = { + tier: PRIME, + status: 'none', + thresholdUsd: 7_300, + shortfallUsd: 2_000, + progressPct: 70, + daysHeld: 0, + qualifiesOn: null, + unlockedAt: null, + graceEndsAt: null, + reentryAt: null, + }; + + it('is the last way to get the tier, at the threshold the backend sends', () => { + expect(tierOfferRows(offer(), undefined, track)).toEqual([ + { label: 'Annual membership', value: '$149.5/year' }, + { label: 'Or lock FUSE', value: '37.5K FUSE' }, + { label: 'Or hold in Earn', value: '$7.3K', balanceTrack: track }, + ]); + expect(tierOfferSubtitle(offer(), undefined, track)).toBe( + '$149.5/year, 37.5K FUSE locked or $7.3K in Earn', + ); + }); + + it('reads with one purchase route, or none', () => { + expect(tierOfferSubtitle(offer({ cashAvailable: false }), undefined, track)).toBe( + '37.5K FUSE locked or $7.3K in Earn', + ); + expect(tierOfferSubtitle(offer({ lockAvailable: false }), undefined, track)).toBe( + '$149.5/year or $7.3K in Earn', + ); + // Neither purchase route on, or no membership offer at all. + expect(tierOfferRows(undefined, undefined, track)).toEqual([ + { label: 'Hold in Earn', value: '$7.3K', balanceTrack: track }, + ]); + expect(tierOfferSubtitle(undefined, undefined, track)).toBe('Hold $7.3K in Earn'); + }); + + it('keeps the two-route copy when the route is not offered', () => { + expect(tierOfferSubtitle(offer(), undefined, undefined)).toBe( + '$149.5/year or 37.5K FUSE locked', + ); + }); + }); }); diff --git a/components/Rewards/NewRewards/__tests__/tierTrialCopy.test.ts b/components/Rewards/NewRewards/__tests__/tierTrialCopy.test.ts index 717af5296..11fb06221 100644 --- a/components/Rewards/NewRewards/__tests__/tierTrialCopy.test.ts +++ b/components/Rewards/NewRewards/__tests__/tierTrialCopy.test.ts @@ -8,7 +8,14 @@ import { trialRemainingLabel, upgradeCelebrationCopy, } from '@/components/Rewards/NewRewards/tierTrialCopy'; -import { RewardsTier, RewardsUserData, TierBenefits, TierTrial } from '@/lib/types'; +import { + RewardsTier, + RewardsUserData, + TierBalanceRouteDto, + TierBalanceTrackDto, + TierBenefits, + TierTrial, +} from '@/lib/types'; const trial = (overrides: Partial = {}): TierTrial => ({ id: 'trial-1', @@ -53,6 +60,13 @@ describe('tierPopupStats', () => { expect(tierPopupStats(undefined)).toEqual([]); }); + it('leaves the yield boost out for a tier held without it', () => { + expect(tierPopupStats(primeBenefits, { yieldBoost: false })).toEqual([ + { value: '4%', label: 'Cashback' }, + { value: '25%', label: 'Subscriptions' }, + ]); + }); + it('finds the tier being celebrated in the benefits list', () => { expect(benefitsForTier([primeBenefits], RewardsTier.PRIME)).toBe(primeBenefits); expect(benefitsForTier([primeBenefits], RewardsTier.ULTRA)).toBeUndefined(); @@ -137,6 +151,56 @@ describe('upgradeCelebrationCopy', () => { expect(copy.body).toBe('Your confirmed FUSE Savings balance has unlocked Prime.'); }); + describe('a tier unlocked by holding a balance in Earn', () => { + const track = (tier: RewardsTier.PRIME | RewardsTier.ULTRA): TierBalanceTrackDto => ({ + tier, + status: 'active', + thresholdUsd: tier === RewardsTier.PRIME ? 7_300 : 41_000, + shortfallUsd: 0, + progressPct: 100, + daysHeld: 21, + qualifiesOn: null, + unlockedAt: '2026-11-24T00:00:00Z', + graceEndsAt: null, + reentryAt: null, + }); + const balance = (overrides: Partial = {}): TierBalanceRouteDto => ({ + enabled: true, + grantsTier: RewardsTier.PRIME, + holdsCurrentTier: true, + currentUsd: 8_000, + measuredAt: null, + lowestUsd: 7_400, + lookbackDays: 21, + graceDays: 4, + reentryDays: 45, + breakdown: null, + rules: { countsCreditCollateral: true, subtractsCreditDebt: false, countsLockedFuse: true }, + prime: track(RewardsTier.PRIME), + ultra: { ...track(RewardsTier.ULTRA), status: 'none' }, + ...overrides, + }); + + it('names Earn, what keeps the tier, and that Yield boost is not part of it', () => { + const copy = upgradeCelebrationCopy(data(), balance()); + + expect(copy.title).toBe('Welcome to Prime'); + expect(copy.body).toBe( + 'Holding your balance in Earn has unlocked Prime. Every Prime benefit is yours, except Yield boost.', + ); + expect(copy.note).toBe('Keep $7.3K or more in Earn to hold this tier.'); + }); + + it('says nothing of Earn when another route holds the tier', () => { + expect(upgradeCelebrationCopy(data(), balance({ holdsCurrentTier: false })).body).toBe( + 'You reached the Prime points milestone. Your new benefits are now active.', + ); + expect(upgradeCelebrationCopy(data(), null).body).toBe( + 'You reached the Prime points milestone. Your new benefits are now active.', + ); + }); + }); + it('falls back to the points milestone', () => { expect(upgradeCelebrationCopy(data()).body).toBe( 'You reached the Prime points milestone. Your new benefits are now active.', diff --git a/components/Rewards/NewRewards/tierBenefitsPresentation.ts b/components/Rewards/NewRewards/tierBenefitsPresentation.ts index 4342477d4..8d470f4e1 100644 --- a/components/Rewards/NewRewards/tierBenefitsPresentation.ts +++ b/components/Rewards/NewRewards/tierBenefitsPresentation.ts @@ -1,3 +1,4 @@ +import { formatThresholdUsd } from '@/lib/tierBalance'; import { formatTierCashbackRate } from '@/lib/tierCashback'; import { canPayCashFor, @@ -8,6 +9,7 @@ import { import { TIER_YIELD_BOOST_RATES } from '@/lib/tierYieldBoost'; import { RewardsTier, + type TierBalanceTrackDto, type TierBenefits, type TierFees, type TierMembershipContracts, @@ -263,6 +265,11 @@ export interface TierOfferRow { * where a component can do that, and as "(was $999)" where only text can. */ listValue?: string; + /** + * Set on the "Hold in Earn" row only: the tier's track on that route, whose + * progress and status the panel draws under the row. + */ + balanceTrack?: TierBalanceTrackDto; } /** The addresses that decide whether the cash route can be built — see `canPayCashFor`. */ @@ -276,12 +283,29 @@ type OfferContracts = Pick< * only shown when the cash route can actually be taken — the same test * `availableRoutes` sells by — so an upgrade paid by transfer with no treasury * to pay is offered by its lock alone rather than at a price no button takes. + * + * `balanceTrack` adds the "Hold in Earn" route as the last way, for a user it is + * staged to: priced at the threshold the backend sends, and listed even when + * neither purchase route is on. */ export function tierOfferRows( offer: TierOffer | undefined, contracts?: OfferContracts, + balanceTrack?: TierBalanceTrackDto, ): TierOfferRow[] { - if (!offer) return []; + const rows: TierOfferRow[] = offer ? purchaseRows(offer, contracts) : []; + if (balanceTrack && balanceTrack.thresholdUsd > 0) { + rows.push({ + label: rows.length ? 'Or hold in Earn' : 'Hold in Earn', + value: formatThresholdUsd(balanceTrack.thresholdUsd), + balanceTrack, + }); + } + return rows; +} + +/** The two ways to buy a tier: an annual fee and a FUSE lock. */ +function purchaseRows(offer: TierOffer, contracts?: OfferContracts): TierOfferRow[] { const rows: TierOfferRow[] = []; // The first year's price is what is paid now — the sale price during a sale. const firstYear = offerFirstYearFeeUsd(offer); @@ -307,12 +331,34 @@ export function tierOfferRows( const offerRowText = (row: TierOfferRow) => row.listValue ? `${row.value} (was ${row.listValue})` : row.value; -export function tierOfferSubtitle(offer: TierOffer | undefined, contracts?: OfferContracts) { - const rows = tierOfferRows(offer, contracts); - if (rows.length === 2) return `${offerRowText(rows[0])} or ${rows[1].value} locked`; - if (rows.length === 1) - return rows[0].label === 'Lock FUSE' - ? `Requires ${rows[0].value} locked` - : offerRowText(rows[0]); - return null; +/** + * The ways to get a tier in one line, for the pager subtitle: "$999/year or + * 50K FUSE locked", and with the "Hold in Earn" route "$999/year, 50K FUSE + * locked or $7.5K in Earn". + * + * The upgrade button's own subtitle leaves `balanceTrack` out: that button sells + * the purchase routes only, and the balance route has its own action. + */ +export function tierOfferSubtitle( + offer: TierOffer | undefined, + contracts?: OfferContracts, + balanceTrack?: TierBalanceTrackDto, +) { + const rows = tierOfferRows(offer, contracts, balanceTrack); + const balance = rows.find(row => row.balanceTrack); + const purchase = rows.filter(row => !row.balanceTrack); + const purchaseText = + purchase.length === 2 + ? `${offerRowText(purchase[0])}${balance ? ',' : ' or'} ${purchase[1].value} locked` + : purchase.length === 1 + ? purchase[0].label === 'Lock FUSE' + ? balance + ? `${purchase[0].value} locked` + : `Requires ${purchase[0].value} locked` + : offerRowText(purchase[0]) + : null; + if (!balance) return purchaseText; + return purchaseText + ? `${purchaseText} or ${balance.value} in Earn` + : `Hold ${balance.value} in Earn`; } diff --git a/components/Rewards/NewRewards/tierTrialCopy.ts b/components/Rewards/NewRewards/tierTrialCopy.ts index bf0c43ef6..6d6383281 100644 --- a/components/Rewards/NewRewards/tierTrialCopy.ts +++ b/components/Rewards/NewRewards/tierTrialCopy.ts @@ -1,5 +1,12 @@ +import { formatThresholdUsd, tierBalanceTrack, unlockedByBalance } from '@/lib/tierBalance'; import { getTierDisplayName } from '@/lib/tierNames'; -import { RewardsTier, RewardsUserData, TierBenefits, TierTrial } from '@/lib/types'; +import { + RewardsTier, + RewardsUserData, + TierBalanceRouteDto, + TierBenefits, + TierTrial, +} from '@/lib/types'; import type { TierPopupStat } from './TierPopup'; @@ -11,8 +18,14 @@ import type { TierPopupStat } from './TierPopup'; * payload reports Core's zeroes, and quoting those under "Welcome to Prime" * would advertise nothing. A rate the backend has not sent drops its column * rather than rendering "undefined%". + * + * `yieldBoost: false` leaves the boost out, for a tier the user holds without + * it — the "Hold in Earn" route grants everything a tier gives but that. */ -export const tierPopupStats = (benefits?: TierBenefits): TierPopupStat[] => { +export const tierPopupStats = ( + benefits?: TierBenefits, + { yieldBoost = true }: { yieldBoost?: boolean } = {}, +): TierPopupStat[] => { if (!benefits) return []; const stats: TierPopupStat[] = []; @@ -28,7 +41,7 @@ export const tierPopupStats = (benefits?: TierBenefits): TierPopupStat[] => { }); } - if (benefits.yieldBoostPercentage) { + if (yieldBoost && benefits.yieldBoostPercentage) { stats.push({ value: `+${benefits.yieldBoostPercentage}%`, label: 'Yield boost', @@ -128,17 +141,36 @@ interface UpgradeCelebrationCopy { /** * The celebration's words for a tier the user now holds. * - * The body names how they got there, because the three routes are genuinely - * different news: a trial someone handed them, a points milestone they climbed - * to, and a FUSE balance that unlocked it outright (Figma 25480:2355). A trial - * also gets the line that says how long it runs — the one thing this upgrade - * has that the other two do not. + * The body names how they got there, because the routes are genuinely + * different news: a balance held in Earn, a trial someone handed them, a points + * milestone they climbed to, and a FUSE balance that unlocked it outright + * (Figma 25480:2355). A trial also gets the line that says how long it runs, + * and the Earn balance the line that says what keeps it. + * + * `balance` is the membership's "Hold in Earn" route; it only speaks when the + * route is what holds the tier just reached. */ -export const upgradeCelebrationCopy = (data: RewardsUserData): UpgradeCelebrationCopy => { +export const upgradeCelebrationCopy = ( + data: RewardsUserData, + balance?: TierBalanceRouteDto | null, +): UpgradeCelebrationCopy => { const tierName = getTierDisplayName(data.currentTier); const trial = data.activeTierTrial; const shared = { eyebrow: 'Tier upgraded', title: `Welcome to ${tierName}` }; + if ( + balance && + unlockedByBalance(balance, data.currentTier) && + data.currentTier !== RewardsTier.CORE + ) { + const track = tierBalanceTrack(balance, data.currentTier); + return { + ...shared, + body: `Holding your balance in Earn has unlocked ${tierName}. Every ${tierName} benefit is yours, except Yield boost.`, + note: `Keep ${formatThresholdUsd(track.thresholdUsd)} or more in Earn to hold this tier.`, + }; + } + if (trial && trial.tier === data.currentTier) { return { ...shared, diff --git a/components/Rewards/RewardsUpgradeFeedback.tsx b/components/Rewards/RewardsUpgradeFeedback.tsx index d5d38a76a..0ed5c0672 100644 --- a/components/Rewards/RewardsUpgradeFeedback.tsx +++ b/components/Rewards/RewardsUpgradeFeedback.tsx @@ -9,7 +9,9 @@ import { } from '@/components/Rewards/NewRewards/tierTrialCopy'; import { path } from '@/constants/path'; import { useRewardsUserData, useTierBenefits } from '@/hooks/useRewards'; +import { useTierMembership } from '@/hooks/useTierMembership'; import { REWARDS_RECONCILIATION_INTERVAL_MS } from '@/lib/rewardsUpgrade'; +import { activeTierBalance, unlockedByBalance } from '@/lib/tierBalance'; import { useRewardsUpgradeStore } from '@/store/useRewardsUpgradeStore'; import { isTierUpgradeOpen, useTierUpgradeStore } from '@/store/useTierUpgradeStore'; import { useUserStore } from '@/store/useUserStore'; @@ -51,6 +53,16 @@ export default function RewardsUpgradeFeedback() { const success = active ? state.success : undefined; + // Which route the tier came by decides the words, and the "Hold in Earn" one + // is told by the membership payload rather than the rewards one. The route + // unlocks on the backend's own schedule, so the copy on hand may predate it: + // read it again when a promotion lands. + const { data: membership, refetch: refetchMembership } = useTierMembership(); + const balance = activeTierBalance(membership); + useEffect(() => { + if (success) void refetchMembership(); + }, [success, refetchMembership]); + // Held after dismissal so the card can animate out: `dismiss` clears // `success`, and unmounting the popup on that would make it vanish rather // than fade. Only ever moves forward onto a real upgrade. @@ -63,7 +75,9 @@ export default function RewardsUpgradeFeedback() { // moment the flow closes — which a completed purchase does itself. if (!shown || upgradeFlowOpen) return null; - const copy = upgradeCelebrationCopy(shown); + const copy = upgradeCelebrationCopy(shown, balance); + // The route grants everything the tier gives but Yield boost. + const byBalance = unlockedByBalance(balance, shown.currentTier); return ( { diff --git a/components/Send/ContractAddressWarning.tsx b/components/Send/ContractAddressWarning.tsx index d0e456478..d9142c25f 100644 --- a/components/Send/ContractAddressWarning.tsx +++ b/components/Send/ContractAddressWarning.tsx @@ -1,39 +1,16 @@ -import { View } from 'react-native'; -import { Image } from 'expo-image'; -import { LinearGradient } from 'expo-linear-gradient'; - -import { Text } from '@/components/ui/text'; -import { getAsset } from '@/lib/assets'; +import WarningNotice from '@/components/WarningNotice'; interface ContractAddressWarningProps { chainName: string; } -const ContractAddressWarning = ({ chainName }: ContractAddressWarningProps) => { - return ( - - - - - - This appears to be a smart contract address - - - Please verify that the recipient address is able to receive assets on {chainName} - - - - - ); -}; +const ContractAddressWarning = ({ chainName }: ContractAddressWarningProps) => ( + +); export default ContractAddressWarning; diff --git a/components/Send/SendForm.tsx b/components/Send/SendForm.tsx index 87df25a23..f13ebb096 100644 --- a/components/Send/SendForm.tsx +++ b/components/Send/SendForm.tsx @@ -9,10 +9,12 @@ import { useShallow } from 'zustand/react/shallow'; import Max from '@/components/Max'; import RenderTokenIcon from '@/components/RenderTokenIcon'; +import TierBalanceOutflowNotice from '@/components/TierBalance/TierBalanceOutflowNotice'; import { Button } from '@/components/ui/button'; import { Text } from '@/components/ui/text'; import { SEND_MODAL } from '@/constants/modals'; import { TRACKING_EVENTS } from '@/constants/tracking-events'; +import { useEarnOutflowUsd, useTierBalanceOutflowWarning } from '@/hooks/useTierBalance'; import { useWalletTokens } from '@/hooks/useWalletTokens'; import { track } from '@/lib/analytics'; import getTokenIcon from '@/lib/getTokenIcon'; @@ -127,6 +129,19 @@ const SendForm: React.FC = ({ onNext }) => { return Number(amount) * (liveToken?.quoteRate || 0); }, [liveToken, amount]); + // Sending an Earn share (on any chain) takes it out of Earn, which can cost + // a tier held or being built on the "Hold in Earn" route. + const outflowUsd = useEarnOutflowUsd({ + address: liveToken?.contractAddress, + symbol: liveToken?.contractTickerSymbol, + amount: Number(amount), + priceUsd: liveToken?.quoteRate, + }); + const { warning: tierBalanceWarning, proceed: proceedPastWarning } = useTierBalanceOutflowWarning( + 'send', + outflowUsd, + ); + useEffect(() => { if (amount) setValue('amount', amount); }, [amount, setValue]); @@ -165,10 +180,11 @@ const SendForm: React.FC = ({ onNext }) => { const onSubmit = useCallback( (data: any) => { + proceedPastWarning(); setAmount(data.amount.toString()); onNext(); }, - [setAmount, onNext], + [setAmount, onNext, proceedPastWarning], ); return ( @@ -250,6 +266,7 @@ const SendForm: React.FC = ({ onNext }) => { {errors.amount && ( {errors.amount.message as string} )} + diff --git a/components/Swap/flow/SwapFormScreen.tsx b/components/Swap/flow/SwapFormScreen.tsx index 1542a4e4b..4ef8e246e 100644 --- a/components/Swap/flow/SwapFormScreen.tsx +++ b/components/Swap/flow/SwapFormScreen.tsx @@ -5,11 +5,13 @@ import { useShallow } from 'zustand/react/shallow'; import SwapAmountCard from '@/components/Swap/flow/SwapAmountCard'; import SwapDetailsCard from '@/components/Swap/flow/SwapDetailsCard'; +import TierBalanceOutflowNotice from '@/components/TierBalance/TierBalanceOutflowNotice'; import { Button } from '@/components/ui/button'; import { Text } from '@/components/ui/text'; import { SWAP_MODAL } from '@/constants/modals'; import { TRACKING_EVENTS } from '@/constants/tracking-events'; import { useSwapFlow } from '@/hooks/swap/useSwapFlow'; +import { useEarnOutflowUsd, useTierBalanceOutflowWarning } from '@/hooks/useTierBalance'; import { track } from '@/lib/analytics'; import { assetDisplayName } from '@/lib/swapAssets'; import { swapErrorButtonLabel } from '@/lib/swapErrors'; @@ -21,6 +23,7 @@ import { sanitizeAmountInput, ungroupAmountInput, } from '@/lib/utils/swap/format'; +import { isEarnShareToken } from '@/lib/vaults'; import { useSwapActionHandlers, useSwapState } from '@/store/swapStore'; /** Errors the button can fix by opening the "You get" picker. */ @@ -29,6 +32,9 @@ const PICK_ANOTHER = new Set(['NO_ROUTE', 'TOKEN_NOT_SWAPPABLE', 'SAME_TOKEN']); const balanceOf = (asset: SwapAsset | undefined): number | undefined => asset && 'balance' in asset ? (asset as SwapAssetWithBalance).balance : undefined; +const priceOf = (asset: SwapAsset | undefined): number | undefined => + asset && 'priceUsd' in asset ? (asset as SwapAssetWithBalance).priceUsd : undefined; + /** * Screen 1 of the swap: what you pay, what you get, and what it costs. One * form for every pair; Fuse pairs price on Algebra, the rest on LI.FI. @@ -103,6 +109,19 @@ const SwapFormScreen: React.FC = () => { }); }, [typedValue, fromAsset?.symbol]); + // Paying with an Earn share (on any chain) takes it out of Earn — unless what + // you get is an Earn share too, which keeps it there. + const paidOutOfEarn = useEarnOutflowUsd({ + address: fromAsset?.address, + symbol: fromAsset?.symbol, + amount: typedIntoGet ? 0 : Number(typedValue), + priceUsd: priceOf(fromAsset), + }); + const { warning: tierBalanceWarning, proceed: proceedPastWarning } = useTierBalanceOutflowWarning( + 'swap', + isEarnShareToken(toAsset?.address) ? 0 : paidOutOfEarn, + ); + const fromBalance = balanceOf(fromAsset); const toBalance = balanceOf(toAsset); const notEnough = error?.code === 'NOT_ENOUGH_BALANCE'; @@ -131,7 +150,10 @@ const SwapFormScreen: React.FC = () => { return { label: 'Review', disabled: !model.canReview, - onPress: () => setModal(SWAP_MODAL.OPEN_REVIEW), + onPress: () => { + proceedPastWarning(); + setModal(SWAP_MODAL.OPEN_REVIEW); + }, }; })(); @@ -182,6 +204,12 @@ const SwapFormScreen: React.FC = () => { onPickAsset={() => openPicker('get')} /> + {tierBalanceWarning ? ( + + + + ) : null} + {showBanner ? ( diff --git a/components/Swap/flow/__tests__/SwapFormScreen.test.tsx b/components/Swap/flow/__tests__/SwapFormScreen.test.tsx index f0453bac1..2d853a10f 100644 --- a/components/Swap/flow/__tests__/SwapFormScreen.test.tsx +++ b/components/Swap/flow/__tests__/SwapFormScreen.test.tsx @@ -28,6 +28,16 @@ jest.mock('@/lib/utils', () => ({ cn: (...classes: unknown[]) => classes.filter(Boolean).join(' '), })); jest.mock('@/hooks/swap/useSwapFlow', () => ({ useSwapFlow: () => mockModel })); +// The "Hold in Earn" warning reads the tier membership; this suite is about the form. +jest.mock('@/hooks/useTierBalance', () => ({ + useEarnOutflowUsd: () => 0, + useTierBalanceOutflowWarning: () => ({ warning: null, proceed: () => undefined }), +})); +jest.mock('@/lib/vaults', () => ({ isEarnShareToken: () => false })); +jest.mock('@/components/TierBalance/TierBalanceOutflowNotice', () => ({ + __esModule: true, + default: 'TierBalanceOutflowNotice', +})); jest.mock('@/store/swapStore', () => ({ useSwapActionHandlers: () => ({ onSwitchTokens: jest.fn(), onUserInput: mockUserInput }), useSwapState: (selector: any) => diff --git a/components/TierBalance/TierBalanceOutflowNotice.tsx b/components/TierBalance/TierBalanceOutflowNotice.tsx new file mode 100644 index 000000000..91d480d29 --- /dev/null +++ b/components/TierBalance/TierBalanceOutflowNotice.tsx @@ -0,0 +1,16 @@ +import WarningNotice from '@/components/WarningNotice'; +import { outflowWarningCopy, type TierBalanceOutflowWarning } from '@/lib/tierBalance'; + +/** + * What moving this money out of Earn does to a tier held, or being built, on + * the "Hold in Earn" route. Informational: the form's own button still goes + * ahead. Draws nothing without a warning, which is every user the route is not + * staged to. + */ +const TierBalanceOutflowNotice = ({ warning }: { warning: TierBalanceOutflowWarning | null }) => { + if (!warning) return null; + const { title, body } = outflowWarningCopy(warning); + return ; +}; + +export default TierBalanceOutflowNotice; diff --git a/components/Unstake/RegularWithdrawForm.tsx b/components/Unstake/RegularWithdrawForm.tsx index 8d34fb7fa..6f4101fa5 100644 --- a/components/Unstake/RegularWithdrawForm.tsx +++ b/components/Unstake/RegularWithdrawForm.tsx @@ -15,6 +15,7 @@ import { useShallow } from 'zustand/react/shallow'; import Max from '@/components/Max'; import NeedHelp from '@/components/NeedHelp'; import RenderTokenIcon from '@/components/RenderTokenIcon'; +import TierBalanceOutflowNotice from '@/components/TierBalance/TierBalanceOutflowNotice'; import TokenDetails from '@/components/TokenCard/TokenDetails'; import { Button } from '@/components/ui/button'; import { Text } from '@/components/ui/text'; @@ -24,6 +25,8 @@ import { getVaultKey, isSolidTokenSymbol } from '@/constants/withdraw'; import useBridgeForWithdraw from '@/hooks/useBridgeForWithdraw'; import useBridgeSoEthBaseToMainnet from '@/hooks/useBridgeSoEthBaseToMainnet'; import useBridgeToMainnetSoEth from '@/hooks/useBridgeToMainnetSoEth'; +import { useTierBalance, useTierBalanceOutflowWarning } from '@/hooks/useTierBalance'; +import { useTokenPriceUsd } from '@/hooks/useToken'; import useUser from '@/hooks/useUser'; import { useFuseVaultBalance, useSoEthVaultBalance, useSoFuseVaultBalance } from '@/hooks/useVault'; import { useVaultExchangeRate } from '@/hooks/useVaultExchangeRate'; @@ -375,6 +378,22 @@ const RegularWithdrawForm = () => { return `$${formatNumber(Number(watchedAmount || 0) * (selectedToken?.quoteRate || 0), 2)}`; }, [isSoEurc, exchangeRate, selectedToken, watchedAmount]); + // What this withdrawal takes out of Earn, in dollars, for the "Hold in Earn" + // warning: the share's USD quote, or for soEURC its euro value at the EURC + // price — fetched only for someone the route is staged to. + const { relevant: tierBalanceTrack } = useTierBalance(); + const { data: eurcPriceUsd } = useTokenPriceUsd(isSoEurc && tierBalanceTrack ? 'EURC' : ''); + const outflowUsd = useMemo(() => { + const amount = Number(watchedAmount || 0); + if (!Number.isFinite(amount) || amount <= 0) return 0; + if (isSoEurc) return amount * (exchangeRate ?? 1) * (Number(eurcPriceUsd) || 0); + return amount * (selectedToken?.quoteRate || 0); + }, [watchedAmount, isSoEurc, exchangeRate, eurcPriceUsd, selectedToken?.quoteRate]); + const { warning: tierBalanceWarning, proceed: proceedPastWarning } = useTierBalanceOutflowWarning( + 'withdraw', + outflowUsd, + ); + const handleTokenSelectorPress = () => { setModal(UNSTAKE_MODAL.OPEN_TOKEN_SELECTOR); }; @@ -388,6 +407,7 @@ const RegularWithdrawForm = () => { }; const onBridgeSubmit = async (data: WithdrawFormData) => { + proceedPastWarning(); if (bridgeMinimum !== undefined && parseUnits(String(data.amount), 6) < bridgeMinimum) { setError('amount', { message: sponsoredMinimumCopy('withdrawal', bridgeMinimum, 'soUSD'), @@ -411,6 +431,7 @@ const RegularWithdrawForm = () => { }; const onSwapSubmit = async (data: WithdrawFormData) => { + proceedPastWarning(); if (isSessionChainUnavailable) return; try { const transaction = await withdraw(data.amount.toString()); @@ -444,6 +465,7 @@ const RegularWithdrawForm = () => { }; const onSoFuseSubmit = async (data: WithdrawFormData) => { + proceedPastWarning(); try { const transaction = await withdrawSoFuse(data.amount.toString()); setTransaction({ @@ -473,6 +495,7 @@ const RegularWithdrawForm = () => { }; const onSoEurcSubmit = async (data: WithdrawFormData) => { + proceedPastWarning(); try { const transaction = await withdrawSoEurc(data.amount.toString()); setTransaction({ @@ -502,6 +525,7 @@ const RegularWithdrawForm = () => { }; const onBridgeSoEthSubmit = async (data: WithdrawFormData) => { + proceedPastWarning(); try { // Base shares pay their own LayerZero fee in Base ETH; Fuse shares go through the paymaster. await (isSoEthOnBase ? bridgeSoEthFromBase : bridgeSoEth)(data.amount.toString()); @@ -520,6 +544,7 @@ const RegularWithdrawForm = () => { }; const onWithdrawSoEthSubmit = async (data: WithdrawFormData) => { + proceedPastWarning(); try { const transaction = await withdrawSoEth(data.amount.toString()); setTransaction({ @@ -690,6 +715,7 @@ const RegularWithdrawForm = () => { + Actions {isSoFuse ? ( diff --git a/components/Unstake/SoBtcWithdrawForm.tsx b/components/Unstake/SoBtcWithdrawForm.tsx index 878fb91b4..5b3a3aa5c 100644 --- a/components/Unstake/SoBtcWithdrawForm.tsx +++ b/components/Unstake/SoBtcWithdrawForm.tsx @@ -10,6 +10,7 @@ import { useShallow } from 'zustand/react/shallow'; import Max from '@/components/Max'; import NeedHelp from '@/components/NeedHelp'; import RenderTokenIcon from '@/components/RenderTokenIcon'; +import TierBalanceOutflowNotice from '@/components/TierBalance/TierBalanceOutflowNotice'; import TokenDetails from '@/components/TokenCard/TokenDetails'; import { Button } from '@/components/ui/button'; import { Text } from '@/components/ui/text'; @@ -21,6 +22,7 @@ import { useSoBtcAvailability, useWithdrawSoBtc, } from '@/hooks/useSoBtcWithdraw'; +import { useTierBalanceOutflowWarning } from '@/hooks/useTierBalance'; import useUser from '@/hooks/useUser'; import { showFailureSheet } from '@/lib/errors'; import getTokenIcon from '@/lib/getTokenIcon'; @@ -131,6 +133,11 @@ const SoBtcWithdrawForm = () => { ? (soBtcSharesToAssets(amountShares, rate) * (10_000n - SOLVER_FEE_BPS)) / 10_000n : 0n; const amountBtc = amountShares && rate ? toBtc(soBtcSharesToAssets(amountShares, rate)) : 0; + // What leaves Earn, at the price the USD line under the amount already uses. + const { warning: tierBalanceWarning, proceed: proceedPastWarning } = useTierBalanceOutflowWarning( + 'withdraw', + btcPrice > 0 ? amountBtc * btcPrice : 0, + ); const validation: string | null = useMemo(() => { if (!amount) return null; @@ -167,6 +174,7 @@ const SoBtcWithdrawForm = () => { const onWithdraw = async () => { if (!amountShares) return; + proceedPastWarning(); try { const transaction = await withdrawSoBtc(amount.trim()); setTransaction({ amount: Number(amount), symbol: 'soBTC' }); @@ -194,6 +202,7 @@ const SoBtcWithdrawForm = () => { }; const onBridge = async () => { + proceedPastWarning(); try { await bridgeSoBtc(amount.trim()); setTransaction({ amount: Number(amount), symbol: 'soBTC' }); @@ -335,6 +344,8 @@ const SoBtcWithdrawForm = () => { + + Actions ( + + + + + {title} + + {body} + + + + +); + +export default WarningNotice; diff --git a/constants/tracking-events.ts b/constants/tracking-events.ts index e5791569e..cc669a042 100644 --- a/constants/tracking-events.ts +++ b/constants/tracking-events.ts @@ -646,6 +646,16 @@ export const TRACKING_EVENTS = { TIER_SUBSCRIPTION_CANCEL_COMPLETED: 'tier_subscription_cancel_completed', TIER_SUBSCRIPTION_RESUME_COMPLETED: 'tier_subscription_resume_completed', TIER_MEMBERSHIP_SHEET_OPENED: 'tier_membership_sheet_opened', + // The "Hold in Earn" route: a tier for keeping a balance in Earn, with no + // transaction of its own. Every event carries `route: 'balance'` and `tier`, + // like TIER_UPGRADE_ROUTE_SELECTED. `surface`/`source` say where it was seen + // (tier_benefits / earn); the outflow ones carry `flow` (withdraw / send / + // swap / card_topup) and `kind` (lose / grace / reset). + TIER_BALANCE_OPTION_VIEWED: 'tier_balance_option_viewed', + TIER_BALANCE_ADD_TO_EARN_PRESSED: 'tier_balance_add_to_earn_pressed', + TIER_BALANCE_OUTFLOW_WARNING_SHOWN: 'tier_balance_outflow_warning_shown', + TIER_BALANCE_OUTFLOW_WARNING_PROCEEDED: 'tier_balance_outflow_warning_proceeded', + TIER_BALANCE_OUTFLOW_WARNING_CANCELLED: 'tier_balance_outflow_warning_cancelled', // Cross-chain send ("Withdraw to another network"): USDC/USDT bridged from // Fuse to an exchange or the user's own wallet through the BridgePaymaster. diff --git a/hooks/__tests__/usePushNotifications.test.ts b/hooks/__tests__/usePushNotifications.test.ts index c2a17c1a6..30aa78c6c 100644 --- a/hooks/__tests__/usePushNotifications.test.ts +++ b/hooks/__tests__/usePushNotifications.test.ts @@ -310,10 +310,27 @@ describe('getNotificationRoute', () => { ['rewards-tier-reached', path.REWARDS], ['ai_api_limit_reached', path.AI_API], ['ai_api_paused', path.AI_API], + ['tier_balance_unlocked', path.REWARDS_BENEFITS], + ['tier_balance_grace_started', path.REWARDS_BENEFITS], + ['tier_balance_grace_cleared', path.REWARDS_BENEFITS], + ['tier_balance_ended', path.REWARDS_BENEFITS], ])('still routes %s on its type', (type, expected) => { expect(getNotificationRoute({ type })).toEqual(expected); }); + it('opens the tier benefits for a Hold in Earn push, whatever form its link takes', () => { + expect( + getNotificationRoute({ + type: 'tier_balance_grace_started', + link: link('/rewards/benefits'), + }), + ).toEqual(path.REWARDS_BENEFITS); + // The bare path the backend may send: unreadable as a URL, so the type decides. + expect( + getNotificationRoute({ type: 'tier_balance_grace_started', link: '/rewards/benefits' }), + ).toEqual(path.REWARDS_BENEFITS); + }); + it('opens the support chat for a support reply, whatever its link', () => { expect(getNotificationRoute({ type: 'support_message' })).toEqual(path.SUPPORT); expect(getNotificationRoute({ type: 'support_message', link: 'solid://support' })).toEqual( diff --git a/hooks/__tests__/useRewards.test.tsx b/hooks/__tests__/useRewards.test.tsx index 3c887233c..719dd36ba 100644 --- a/hooks/__tests__/useRewards.test.tsx +++ b/hooks/__tests__/useRewards.test.tsx @@ -29,6 +29,12 @@ jest.mock('@/lib/utils', () => ({ withRefreshToken: (fn: any) => fn() })); // what the popup draws. Stubbing the card keeps the animated tier star — and // through it expo-video and the asset registry — out of this environment. jest.mock('@/components/Rewards/NewRewards/TierPopup', () => 'TierPopup'); +// The celebration reads the membership only for the "Hold in Earn" route's words; +// the real hook would bring the wallet and session stack into this environment. +const mockRefetchMembership = jest.fn(); +jest.mock('@/hooks/useTierMembership', () => ({ + useTierMembership: () => ({ data: undefined, refetch: mockRefetchMembership }), +})); const data = (tier: RewardsTier) => ({ currentTier: tier, cashbackRate: 2, maxCashbackMonthly: 100 }) as RewardsUserData; diff --git a/hooks/usePushNotifications.ts b/hooks/usePushNotifications.ts index 9932285c9..8c0b9c6ab 100644 --- a/hooks/usePushNotifications.ts +++ b/hooks/usePushNotifications.ts @@ -248,6 +248,12 @@ function getNotificationRoute(data?: NotificationData): Href { // carry a link; this covers one whose link this build cannot read. if (type?.startsWith('ai_api_')) return path.AI_API; + // "Hold in Earn" tier pushes (tier_balance_unlocked, _grace_started, + // _grace_cleared, _ended) are all about where the tier stands, which the + // benefits screen shows. They link `/rewards/benefits`; this covers a link + // this build cannot read. + if (type?.startsWith('tier_balance_')) return path.REWARDS_BENEFITS; + // Legacy routing, for pushes that predate the deep link. Lifecycle types are // deliberately absent: they never had a branch here, so every one of them // fell to `default` and opened home — which is the gap the link fixes. diff --git a/hooks/useTierBalance.ts b/hooks/useTierBalance.ts new file mode 100644 index 000000000..bf8546041 --- /dev/null +++ b/hooks/useTierBalance.ts @@ -0,0 +1,174 @@ +import { useCallback, useEffect, useMemo, useRef } from 'react'; + +import { TRACKING_EVENTS } from '@/constants/tracking-events'; +import { getVaultKey } from '@/constants/withdraw'; +import { useOpenDepositFlow } from '@/hooks/useOpenDepositFlow'; +import { useTierMembership } from '@/hooks/useTierMembership'; +import { useTokenPriceUsd } from '@/hooks/useToken'; +import { useVaultDepositEntry } from '@/hooks/useVaultDepositEntry'; +import { useVaultExchangeRate } from '@/hooks/useVaultExchangeRate'; +import { track } from '@/lib/analytics'; +import { + activeTierBalance, + outflowWarning, + relevantTrack, + type TierBalanceOutflowFlow, + type TierBalanceOutflowWarning, +} from '@/lib/tierBalance'; +import { type TierBalanceTrackDto, VaultType } from '@/lib/types'; +import { isEarnShareToken } from '@/lib/vaults'; + +/** + * The "Hold in Earn" route for the selected account, read off the membership + * payload every tier screen already shares. + * + * `balance` is null for anyone the backend has not given the route to, and for + * an older backend that does not send it: every caller renders nothing new then. + */ +export const useTierBalance = () => { + const { data: membership } = useTierMembership(); + const balance = activeTierBalance(membership); + const currentTier = membership?.currentTier; + const relevant = useMemo(() => relevantTrack(balance, currentTier), [balance, currentTier]); + return { balance, currentTier, relevant }; +}; + +/** Where an "Add to Earn" press came from, for analytics. */ +export type TierBalanceSource = 'tier_benefits' | 'earn'; + +/** + * Opens the existing Earn deposit flow for the balance route's "Add to Earn". + * + * The route has nothing to sign, so this is the whole of its action: the same + * deposit entry Earn's own Deposit button uses, on USD Yield. + */ +export const useAddToEarn = (source: TierBalanceSource) => { + const { modal, onBeforeOpen } = useVaultDepositEntry(VaultType.USDC); + const openDepositFlow = useOpenDepositFlow(); + + return useCallback( + (balanceTrack: TierBalanceTrackDto) => { + track(TRACKING_EVENTS.TIER_BALANCE_ADD_TO_EARN_PRESSED, { + route: 'balance', + tier: balanceTrack.tier, + status: balanceTrack.status, + source, + }); + onBeforeOpen(); + openDepositFlow({ + modal, + source: `tier_balance_${source}`, + buttonText: 'Add to Earn', + preserveSelectedVault: true, + }); + }, + [modal, onBeforeOpen, openDepositFlow, source], + ); +}; + +/** + * What sending or swapping `amount` of a token takes out of Earn, in USD — 0 + * for a token that is not an Earn share (on any chain), or one the form has no + * price for yet. + * + * Priced at the USD quote the form already shows. soEURC has none — it is held + * in euros — so it is valued at its euro rate and the EURC price, both read only + * for someone the route is staged to. + */ +export const useEarnOutflowUsd = ({ + address, + symbol, + amount, + priceUsd, +}: { + address: string | undefined; + symbol: string | undefined; + amount: number; + priceUsd: number | undefined; +}): number => { + const { relevant } = useTierBalance(); + const isShare = isEarnShareToken(address); + const isEuro = isShare && getVaultKey(symbol) === 'EUR'; + const hasQuote = (priceUsd ?? 0) > 0; + const needsEuroPrice = !!relevant && isEuro && !hasQuote; + const { data: eurRate } = useVaultExchangeRate('EUR', needsEuroPrice); + const { data: eurcPriceUsd } = useTokenPriceUsd(needsEuroPrice ? 'EURC' : ''); + + if (!isShare || !Number.isFinite(amount) || amount <= 0) return 0; + if (hasQuote) return amount * (priceUsd ?? 0); + if (isEuro) return amount * (eurRate ?? 0) * (Number(eurcPriceUsd) || 0); + return 0; +}; + +/** + * The outflow warning for a form moving money out of Earn, and its analytics. + * + * `outflowUsd` is what leaves Earn, priced by the form; 0 (or undefined while it + * cannot price it) shows nothing. The warning is reported once each time a new + * one appears; `proceed` is called from the form's own action, and a form closed + * after showing a warning without proceeding reports that it was cancelled. + */ +export const useTierBalanceOutflowWarning = ( + flow: TierBalanceOutflowFlow, + outflowUsd: number | undefined, +) => { + const { balance, currentTier } = useTierBalance(); + const warning = useMemo( + () => outflowWarning(balance, currentTier, outflowUsd ?? 0), + [balance, currentTier, outflowUsd], + ); + + // What the handlers and the unmount read: the warning on screen right now, + // the last one reported, and whether the user went ahead. + const latest = useRef<{ + warning: TierBalanceOutflowWarning | null; + flow: TierBalanceOutflowFlow; + }>({ warning: null, flow }); + const shown = useRef(null); + const proceeded = useRef(false); + + useEffect(() => { + latest.current = { warning, flow }; + if (!warning) return; + // Once per warning, not once per keystroke that keeps it up. + const last = shown.current; + if (last && last.kind === warning.kind && last.tier === warning.tier) return; + shown.current = warning; + track(TRACKING_EVENTS.TIER_BALANCE_OUTFLOW_WARNING_SHOWN, { + route: 'balance', + flow, + kind: warning.kind, + tier: warning.tier, + }); + }, [warning, flow]); + + const proceed = useCallback(() => { + proceeded.current = true; + const { warning: active, flow: activeFlow } = latest.current; + if (!active) return; + track(TRACKING_EVENTS.TIER_BALANCE_OUTFLOW_WARNING_PROCEEDED, { + route: 'balance', + flow: activeFlow, + kind: active.kind, + tier: active.tier, + }); + }, []); + + useEffect( + () => () => { + // Read at unmount on purpose: the last warning shown, and whether the + // user went ahead after it. + const last = shown.current; + if (!last || proceeded.current) return; + track(TRACKING_EVENTS.TIER_BALANCE_OUTFLOW_WARNING_CANCELLED, { + route: 'balance', + flow: latest.current.flow, + kind: last.kind, + tier: last.tier, + }); + }, + [], + ); + + return { warning, proceed }; +}; diff --git a/lib/__tests__/earnShareToken.test.ts b/lib/__tests__/earnShareToken.test.ts new file mode 100644 index 000000000..f761cc02b --- /dev/null +++ b/lib/__tests__/earnShareToken.test.ts @@ -0,0 +1,46 @@ +import { fuse } from 'viem/chains'; + +import { ADDRESSES, PRODUCTION_VAULT_ADDRESSES } from '@/lib/config'; +import { SOBTC_ADDRESSES } from '@/lib/soBtc'; +import { isEarnShareToken } from '@/lib/vaults'; + +// `constants/vaults` reaches `lib/wagmi` through `lib/soBtc`, and wagmi ships ESM +// only. Nothing here reads a chain. +jest.mock('@/lib/wagmi', () => ({})); + +/** + * Moving any of these takes money out of Earn, so the send and swap forms warn + * about a tier held on the "Hold in Earn" route — on every chain the shares sit + * on, not just Fuse. + */ +describe('isEarnShareToken', () => { + it.each([ + ['soUSD on Fuse', PRODUCTION_VAULT_ADDRESSES.fuse.vault], + ['soUSD on Ethereum', PRODUCTION_VAULT_ADDRESSES.ethereum.vault], + ['soUSD on Base', PRODUCTION_VAULT_ADDRESSES.base.vault], + ['soFUSE', PRODUCTION_VAULT_ADDRESSES.fuse.fuseVault], + ['soETH on Fuse', PRODUCTION_VAULT_ADDRESSES.fuse.soEthVault], + ['soETH on Ethereum', PRODUCTION_VAULT_ADDRESSES.ethereum.soEthVault], + ['soETH on Base', PRODUCTION_VAULT_ADDRESSES.base.soEthVault], + ['soEURC on Base', PRODUCTION_VAULT_ADDRESSES.base.soEurcVault], + ['soBTC on Base', SOBTC_ADDRESSES.base.vault], + ['soBTC on Ethereum', SOBTC_ADDRESSES.ethereum.vault], + ["this build's soUSD on Fuse", ADDRESSES.fuse.vault], + ["this build's soFUSE", ADDRESSES.fuse.fuseVault], + ["this build's soEURC on Base", ADDRESSES.base.soEurcVault], + ])('recognizes %s, in any letter case', (_name, address) => { + expect(isEarnShareToken(address)).toBe(true); + expect(isEarnShareToken(address.toLowerCase())).toBe(true); + expect(isEarnShareToken(`0x${address.slice(2).toUpperCase()}`)).toBe(true); + }); + + it('does not take a coin, a copied ticker or nothing for a share', () => { + expect(isEarnShareToken(ADDRESSES.ethereum.usdc)).toBe(false); + expect(isEarnShareToken(ADDRESSES.base.usdc)).toBe(false); + // A token that only calls itself soUSD. + expect(isEarnShareToken(`0xsoUSD${fuse.id}`)).toBe(false); + expect(isEarnShareToken('0x0000000000000000000000000000000000000000')).toBe(false); + expect(isEarnShareToken(undefined)).toBe(false); + expect(isEarnShareToken('')).toBe(false); + }); +}); diff --git a/lib/__tests__/queryPersistence.test.ts b/lib/__tests__/queryPersistence.test.ts index 34f76d005..0e5a1360c 100644 --- a/lib/__tests__/queryPersistence.test.ts +++ b/lib/__tests__/queryPersistence.test.ts @@ -211,11 +211,28 @@ describe('persist then restore', () => { const { families: _families, ...legacy } = JSON.parse(mockDisk.get(DISK_KEY)!); mockDisk.set(DISK_KEY, JSON.stringify(legacy)); - expect(QUERY_FAMILY_VERSIONS.tierMembership).toBe(2); expect(restoreQueryCache(newClient())).toBe(4); expect(getQueryCacheRestoreInfo().droppedFamilies).toEqual([]); }); + it('drops a tier membership written before it carried the balance route', () => { + signIn('u1'); + const client = newClient(); + persist(client); + client.setQueryData(['tierMembership', 'u1', 'transfer'], { enabled: true, offers: [] }); + client.setQueryData(['vault', 'balance', SAFE, 'USDC'], 100); + jest.advanceTimersByTime(2_000); + // Written before family versions existed, so read as tierMembership 2. + const { families: _families, ...legacy } = JSON.parse(mockDisk.get(DISK_KEY)!); + mockDisk.set(DISK_KEY, JSON.stringify(legacy)); + + expect(QUERY_FAMILY_VERSIONS.tierMembership).toBe(3); + const restored = newClient(); + expect(restoreQueryCache(restored)).toBe(1); + expect(restored.getQueryData(['tierMembership', 'u1', 'transfer'])).toBeUndefined(); + expect(getQueryCacheRestoreInfo().droppedFamilies).toEqual(['tierMembership']); + }); + it('reports why nothing was restored', () => { signIn('u1'); expect(restoreQueryCache(newClient())).toBe(0); diff --git a/lib/__tests__/refreshRewardsAfterSavings.test.ts b/lib/__tests__/refreshRewardsAfterSavings.test.ts index 487c45dcd..04661cc4c 100644 --- a/lib/__tests__/refreshRewardsAfterSavings.test.ts +++ b/lib/__tests__/refreshRewardsAfterSavings.test.ts @@ -32,6 +32,15 @@ it('refetches the rewards payload without waiting for a promotion', () => { expect(useRewardsUpgradeStore.getState().pendingUntil).toBeUndefined(); }); +it('refetches the tier membership, whose Hold in Earn route reads the Earn balance', () => { + const queryClient = new QueryClient(); + const invalidate = jest.spyOn(queryClient, 'invalidateQueries').mockResolvedValue(); + + refreshRewardsAfterSavings(queryClient, 'a'); + + expect(invalidate).toHaveBeenCalledWith({ queryKey: ['tierMembership', 'a'] }); +}); + it('ignores an account that is no longer selected', () => { const queryClient = new QueryClient(); const invalidate = jest.spyOn(queryClient, 'invalidateQueries').mockResolvedValue(); diff --git a/lib/__tests__/tierBalance.test.ts b/lib/__tests__/tierBalance.test.ts new file mode 100644 index 000000000..01f41fe03 --- /dev/null +++ b/lib/__tests__/tierBalance.test.ts @@ -0,0 +1,355 @@ +import { + activeTierBalance, + formatShortfallUsd, + formatThresholdUsd, + formatTierBalanceDate, + outflowWarning, + outflowWarningCopy, + relevantTrack, + trackNeedsTopUp, + trackNudgeCopy, + trackProgress, + trackStatusLine, + unlockedByBalance, +} from '@/lib/tierBalance'; +import { + RewardsTier, + type TierBalanceRouteDto, + type TierBalanceTrackDto, + type TierMembershipState, +} from '@/lib/types'; + +const { CORE, PRIME, ULTRA } = RewardsTier; +const NOW = new Date('2026-11-24T12:00:00Z'); + +// Deliberately not the launch config: every figure in the copy has to come from here. +const PRIME_USD = 7_300; +const ULTRA_USD = 41_000; + +const trackFor = ( + tier: RewardsTier.PRIME | RewardsTier.ULTRA, + overrides: Partial = {}, +): TierBalanceTrackDto => ({ + tier, + status: 'none', + thresholdUsd: tier === PRIME ? PRIME_USD : ULTRA_USD, + shortfallUsd: 0, + progressPct: 0, + daysHeld: 0, + qualifiesOn: null, + unlockedAt: null, + graceEndsAt: null, + reentryAt: null, + ...overrides, +}); + +const route = ( + overrides: Partial = {}, + prime: Partial = {}, + ultra: Partial = {}, +): TierBalanceRouteDto => ({ + enabled: true, + grantsTier: CORE, + holdsCurrentTier: false, + currentUsd: 5_000, + measuredAt: '2026-11-24T10:00:00Z', + lowestUsd: 4_800, + lookbackDays: 21, + graceDays: 4, + reentryDays: 45, + breakdown: null, + rules: { countsCreditCollateral: true, subtractsCreditDebt: false, countsLockedFuse: true }, + prime: trackFor(PRIME, prime), + ultra: trackFor(ULTRA, ultra), + ...overrides, +}); + +describe('activeTierBalance', () => { + it('shows nothing for a payload without the route, a null one, or one not enabled', () => { + expect(activeTierBalance(undefined)).toBeNull(); + expect(activeTierBalance(null)).toBeNull(); + // An older backend sends no field at all. + expect(activeTierBalance({} as Pick)).toBeNull(); + expect(activeTierBalance({ balance: null })).toBeNull(); + expect(activeTierBalance({ balance: route({ enabled: false }) })).toBeNull(); + }); + + it('hands back the route for a user it is staged to', () => { + const balance = route(); + expect(activeTierBalance({ balance })).toBe(balance); + }); +}); + +describe('relevantTrack', () => { + it('talks about a tier the route holds first, Ultra before Prime', () => { + const balance = route({}, { status: 'active' }, { status: 'grace' }); + expect(relevantTrack(balance, ULTRA)?.tier).toBe(ULTRA); + expect(relevantTrack(route({}, { status: 'grace' }), PRIME)?.tier).toBe(PRIME); + }); + + it('otherwise takes the lowest tier above the current one that is building', () => { + expect(relevantTrack(route({}, { status: 'building' }), CORE)?.tier).toBe(PRIME); + expect(relevantTrack(route({}, { status: 'none' }, { status: 'building' }), CORE)?.tier).toBe( + ULTRA, + ); + // A Prime member by subscription: only Ultra is above them. + expect( + relevantTrack(route({}, { status: 'building' }, { status: 'building' }), PRIME)?.tier, + ).toBe(ULTRA); + }); + + it('falls back to the next tier up when nothing is building', () => { + expect(relevantTrack(route(), CORE)?.tier).toBe(PRIME); + expect(relevantTrack(route(), undefined)?.tier).toBe(PRIME); + expect(relevantTrack(route({}, {}, { status: 'cooldown' }), PRIME)?.tier).toBe(ULTRA); + }); + + it('has nothing to say to an Ultra member by another route, or without the route', () => { + expect(relevantTrack(route({}, { status: 'building' }), ULTRA)).toBeNull(); + expect(relevantTrack(null, CORE)).toBeNull(); + expect(relevantTrack(route({ enabled: false }), CORE)).toBeNull(); + }); +}); + +describe('outflowWarning', () => { + it('warns that building progress restarts when the balance would drop under the threshold', () => { + const balance = route( + { currentUsd: 8_000 }, + { status: 'building', daysHeld: 9, qualifiesOn: '2026-12-06' }, + ); + expect(outflowWarning(balance, CORE, 701)).toEqual({ + kind: 'reset', + tier: PRIME, + thresholdUsd: PRIME_USD, + graceDays: 4, + graceEndsAt: null, + lookbackDays: 21, + daysHeld: 9, + reentryDays: 45, + }); + // Still at the threshold afterwards: nothing to say. + expect(outflowWarning(balance, CORE, 700)).toBeNull(); + }); + + it('warns of the grace period when the route holds the tier and the drop starts it', () => { + const balance = route( + { currentUsd: 8_000, holdsCurrentTier: true, grantsTier: PRIME }, + { status: 'active', unlockedAt: '2026-10-01T00:00:00Z' }, + ); + expect(outflowWarning(balance, PRIME, 1_000)).toMatchObject({ kind: 'grace', graceDays: 4 }); + // No grace configured: the drop ends the tier. + expect(outflowWarning({ ...balance, graceDays: 0 }, PRIME, 1_000)?.kind).toBe('lose'); + }); + + it('warns of losing the tier when its grace is already running', () => { + const balance = route( + { currentUsd: 7_000, holdsCurrentTier: true, grantsTier: PRIME }, + { status: 'grace', graceEndsAt: '2026-11-28T00:00:00Z' }, + ); + expect(outflowWarning(balance, PRIME, 50)).toMatchObject({ + kind: 'lose', + tier: PRIME, + graceEndsAt: '2026-11-28T00:00:00Z', + }); + }); + + it('says nothing when another route holds the tier anyway', () => { + const balance = route( + { currentUsd: 8_000, holdsCurrentTier: false, grantsTier: PRIME }, + { status: 'active' }, + ); + expect(outflowWarning(balance, PRIME, 5_000)).toBeNull(); + }); + + it('follows the Ultra track for an Ultra member the route holds', () => { + const balance = route( + { currentUsd: 42_000, holdsCurrentTier: true, grantsTier: ULTRA }, + { status: 'active' }, + { status: 'active' }, + ); + expect(outflowWarning(balance, ULTRA, 2_000)).toMatchObject({ + kind: 'grace', + tier: ULTRA, + thresholdUsd: ULTRA_USD, + }); + expect(outflowWarning(balance, ULTRA, 1_000)).toBeNull(); + }); + + it('says nothing for a track with nothing to lose', () => { + expect(outflowWarning(route({ currentUsd: 100 }), CORE, 50)).toBeNull(); + expect(outflowWarning(route({ currentUsd: 100 }, { status: 'cooldown' }), CORE, 50)).toBeNull(); + }); + + it('says nothing for an outflow it cannot price, or before a balance is measured', () => { + const balance = route({ currentUsd: 8_000 }, { status: 'building' }); + expect(outflowWarning(balance, CORE, 0)).toBeNull(); + expect(outflowWarning(balance, CORE, -5)).toBeNull(); + expect(outflowWarning(balance, CORE, Number.NaN)).toBeNull(); + expect(outflowWarning({ ...balance, currentUsd: null }, CORE, 8_000)).toBeNull(); + }); + + it('says nothing without the route', () => { + expect(outflowWarning(null, CORE, 1_000_000)).toBeNull(); + expect(outflowWarning(route({ enabled: false }, { status: 'building' }), CORE, 9e9)).toBeNull(); + }); +}); + +describe('formatting', () => { + it('writes thresholds compactly and shortfalls rounded up', () => { + expect(formatThresholdUsd(7_500)).toBe('$7.5K'); + expect(formatThresholdUsd(35_000)).toBe('$35K'); + expect(formatThresholdUsd(250)).toBe('$250'); + expect(formatShortfallUsd(1_234.01)).toBe('$1,235'); + expect(formatShortfallUsd(-3)).toBe('$0'); + }); + + it('writes the qualifying day as that UTC day, wherever the reader is', () => { + expect(formatTierBalanceDate('2026-12-24', NOW)).toBe('Dec 24'); + expect(formatTierBalanceDate('2027-01-02', NOW)).toBe('Jan 2, 2027'); + }); + + it('writes instants in the reader’s day, and nothing for a missing date', () => { + expect(formatTierBalanceDate('2026-12-03T12:00:00Z', NOW)).toBe('Dec 3'); + expect(formatTierBalanceDate(null, NOW)).toBe(''); + expect(formatTierBalanceDate('not a date', NOW)).toBe(''); + }); +}); + +describe('trackStatusLine', () => { + it('says what is missing for a track with nothing yet', () => { + const balance = route({ currentUsd: 5_000 }, { shortfallUsd: 2_300.4 }); + expect(trackStatusLine(balance.prime, balance, NOW)).toBe( + 'Add $2,301 to Earn and keep it there 21 days to unlock Prime', + ); + // Before the first measurement there is no shortfall to quote. + const unmeasured = route({ currentUsd: null }, { shortfallUsd: 7_300 }); + expect(trackStatusLine(unmeasured.prime, unmeasured, NOW)).toBe( + 'Hold $7.3K in Earn for 21 days to unlock Prime', + ); + }); + + it('says until when a building track has to hold', () => { + const balance = route({}, { status: 'building', qualifiesOn: '2026-12-06', daysHeld: 9 }); + expect(trackStatusLine(balance.prime, balance, NOW)).toBe( + 'Keep it there until Dec 6 to unlock Prime', + ); + const undated = route({}, { status: 'building', daysHeld: 9 }); + expect(trackStatusLine(undated.prime, undated, NOW)).toBe( + 'Keep it there 12 days more to unlock Prime', + ); + }); + + it('says how an active, grace or cooldown track stands', () => { + const active = route({}, {}, { status: 'active' }); + expect(trackStatusLine(active.ultra, active, NOW)).toBe('Unlocked by holding $41K in Earn'); + + const grace = route({}, { status: 'grace', graceEndsAt: '2026-11-28T12:00:00Z' }); + expect(trackStatusLine(grace.prime, grace, NOW)).toBe( + 'Top up to $7.3K by Nov 28 to keep Prime', + ); + + const cooldown = route({}, { status: 'cooldown', reentryAt: '2027-01-08T12:00:00Z' }); + expect(trackStatusLine(cooldown.prime, cooldown, NOW)).toBe('Available again on Jan 8, 2027'); + }); +}); + +describe('trackNudgeCopy', () => { + it('leads with what more unlocks the tier', () => { + const balance = route({ currentUsd: 5_000 }, { shortfallUsd: 2_300 }); + expect(trackNudgeCopy(balance.prime, balance, NOW)).toEqual({ + title: '$2,300 more unlocks Prime', + body: 'Hold $7.3K in Earn for 21 days to unlock Prime', + }); + }); + + it('asks for a top-up by the end of the grace period', () => { + const balance = route({}, { status: 'grace', graceEndsAt: '2026-11-28T12:00:00Z' }); + expect(trackNudgeCopy(balance.prime, balance, NOW)).toEqual({ + title: 'Top up to keep Prime', + body: 'Your Earn balance is under $7.3K. Top it up by Nov 28.', + }); + }); +}); + +describe('trackProgress', () => { + it('counts days for a building track and dollars otherwise', () => { + const building = route({}, { status: 'building', daysHeld: 7 }); + expect(trackProgress(building.prime, building)).toEqual({ + percent: (7 / 21) * 100, + value: '7', + target: '/21 days', + }); + + const none = route({ currentUsd: 3_650.9 }, { progressPct: 50 }); + expect(trackProgress(none.prime, none)).toEqual({ + percent: 50, + value: '$3.65K', + target: '/$7.3K', + }); + + const unmeasured = route({ currentUsd: null }, { progressPct: 140 }); + expect(trackProgress(unmeasured.prime, unmeasured)).toEqual({ + percent: 100, + value: null, + target: '/$7.3K', + }); + }); +}); + +describe('trackNeedsTopUp', () => { + it('asks for money only when that is the next step', () => { + expect(trackNeedsTopUp(trackFor(PRIME, { status: 'none' }))).toBe(true); + expect(trackNeedsTopUp(trackFor(PRIME, { status: 'grace' }))).toBe(true); + expect(trackNeedsTopUp(trackFor(PRIME, { status: 'building' }))).toBe(false); + expect(trackNeedsTopUp(trackFor(PRIME, { status: 'active' }))).toBe(false); + expect(trackNeedsTopUp(trackFor(PRIME, { status: 'cooldown' }))).toBe(false); + }); +}); + +describe('outflowWarningCopy', () => { + const base = { + tier: PRIME, + thresholdUsd: PRIME_USD, + graceDays: 4, + graceEndsAt: null, + lookbackDays: 21, + daysHeld: 9, + reentryDays: 45, + } as const; + + it('quotes the progress that would restart', () => { + expect(outflowWarningCopy({ ...base, kind: 'reset' }, NOW)).toEqual({ + title: 'This restarts your progress to Prime', + body: 'Your Earn balance would drop below $7.3K, and your 9 days toward Prime would start over. It takes 21 days at $7.3K or more to unlock it.', + }); + }); + + it('quotes the grace period and the re-entry wait from the payload', () => { + expect(outflowWarningCopy({ ...base, kind: 'grace' }, NOW).body).toBe( + "Your Earn balance would drop below $7.3K. You'd have up to 4 days to bring it back up before Prime ends. Holding can't unlock it again for 45 days after that.", + ); + }); + + it('dates the end of a running grace period', () => { + expect( + outflowWarningCopy({ ...base, kind: 'lose', graceEndsAt: '2026-11-28T12:00:00Z' }, NOW), + ).toEqual({ + title: 'You could lose Prime', + body: "Your Earn balance would stay below $7.3K. Prime ends on Nov 28 unless it's back above $7.3K by then. Holding can't unlock it again for 45 days after that.", + }); + expect(outflowWarningCopy({ ...base, kind: 'lose', reentryDays: 0 }, NOW).body).toBe( + 'Your Earn balance would drop below $7.3K, which ends Prime.', + ); + }); +}); + +describe('unlockedByBalance', () => { + it('credits the route only with a tier it alone holds', () => { + const held = route({ holdsCurrentTier: true, grantsTier: PRIME }, { status: 'active' }); + expect(unlockedByBalance(held, PRIME)).toBe(true); + expect(unlockedByBalance(held, ULTRA)).toBe(false); + expect(unlockedByBalance({ ...held, holdsCurrentTier: false }, PRIME)).toBe(false); + expect(unlockedByBalance({ ...held, enabled: false }, PRIME)).toBe(false); + expect(unlockedByBalance(null, PRIME)).toBe(false); + }); +}); diff --git a/lib/queryPersistence.ts b/lib/queryPersistence.ts index 9d08a5352..fd2daa2e3 100644 --- a/lib/queryPersistence.ts +++ b/lib/queryPersistence.ts @@ -48,9 +48,10 @@ export const QUERY_CACHE_VERSION = 2; * * tierMembership 2: fetched with `?paymentModes=transfer`; its offers carry the * first-year price and payment mode. + * tierMembership 3: carries `balance`, the "Hold in Earn" route. */ export const QUERY_FAMILY_VERSIONS: Readonly> = { - tierMembership: 2, + tierMembership: 3, }; /** diff --git a/lib/refreshRewardsAfterSavings.ts b/lib/refreshRewardsAfterSavings.ts index fcf4aec79..a71229e76 100644 --- a/lib/refreshRewardsAfterSavings.ts +++ b/lib/refreshRewardsAfterSavings.ts @@ -3,12 +3,21 @@ import { QueryClient } from '@tanstack/react-query'; import { selectedRewardsUserId } from '@/store/useRewardsUpgradeStore'; /** - * Refetch what a savings balance change makes stale: the rewards payload and - * the account's balances. + * The tier membership's query family — `TIER_MEMBERSHIP_QUERY_KEY` in + * `hooks/useTierMembership`, repeated here so this module stays free of that + * hook's wallet and transaction imports. + */ +const TIER_MEMBERSHIP_QUERY_FAMILY = 'tierMembership'; + +/** + * Refetch what a savings balance change makes stale: the rewards payload, the + * tier membership (its "Hold in Earn" route is measured off the Earn balance) + * and the account's balances. * * It does not wait for a promotion. Only a lock or an annual fee raises a tier - * now — see `tierPurchased` — so polling after a deposit or a claim only ever - * ran out, and told the user no higher tier had been confirmed. + * on the spot — see `tierPurchased`; the Earn balance unlocks one only at the + * backend's evaluation, days later — so polling after a deposit or a claim only + * ever ran out, and told the user no higher tier had been confirmed. */ export const refreshRewardsAfterSavings = ( queryClient: QueryClient, @@ -17,6 +26,7 @@ export const refreshRewardsAfterSavings = ( ) => { if (selectedRewardsUserId() !== userId) return; void queryClient.invalidateQueries({ queryKey: ['rewards', 'userData', userId] }); + void queryClient.invalidateQueries({ queryKey: [TIER_MEMBERSHIP_QUERY_FAMILY, userId] }); if (safeAddress) { const address = safeAddress.toLowerCase(); void queryClient.invalidateQueries({ diff --git a/lib/tierBalance.ts b/lib/tierBalance.ts new file mode 100644 index 000000000..ed7e09612 --- /dev/null +++ b/lib/tierBalance.ts @@ -0,0 +1,390 @@ +import { isHigherTier } from '@/lib/rewardsUpgrade'; +import { getTierDisplayName } from '@/lib/tierNames'; +import { + RewardsTier, + type TierBalanceRouteDto, + type TierBalanceTier, + type TierBalanceTrackDto, + type TierMembershipState, +} from '@/lib/types'; + +/** + * The "Hold in Earn" tier route: Prime or Ultra for keeping a USD balance in + * Earn for a lookback period, next to the paid membership and the FUSE lock. + * + * Every rule and number here is the backend's. The thresholds, the lookback, + * grace and re-entry periods and the shortfall all come in the payload, so an + * admin changing one reaches every screen without a release — nothing in this + * file, or in any copy built from it, may name an amount or a day count of its + * own. + * + * The route involves no transaction, so it is not a `TierUpgradeRoute` and never + * goes through the upgrade modal: its only action is adding money to Earn. + */ + +/** The tiers the route can grant, lowest first. */ +export const TIER_BALANCE_TIERS: readonly TierBalanceTier[] = [ + RewardsTier.PRIME, + RewardsTier.ULTRA, +]; + +/** + * The route's payload, when the app may show anything about it. + * + * Staged to the internal team: everyone else gets `balance: null`, and a backend + * from before the route sends no field at all. Both, and a payload that is + * present but not enabled, are the same answer — nothing new on any screen. + */ +export const activeTierBalance = ( + membership: Pick | null | undefined, +): TierBalanceRouteDto | null => + membership?.balance?.enabled === true ? membership.balance : null; + +/** One tier's track. */ +export const tierBalanceTrack = ( + balance: TierBalanceRouteDto, + tier: TierBalanceTier, +): TierBalanceTrackDto => (tier === RewardsTier.ULTRA ? balance.ultra : balance.prime); + +const isHeld = (track: TierBalanceTrackDto) => + track.status === 'active' || track.status === 'grace'; + +/** + * The track the app talks about, or null when there is nothing to say. + * + * A tier the route already holds comes first, Ultra over Prime. Otherwise the + * lowest tier above the current one that is building, else simply the lowest + * tier above the current one: Prime for a Core user, Ultra for a Prime user. + * An Ultra member by another route has nothing above them to be nudged toward. + */ +export const relevantTrack = ( + balance: TierBalanceRouteDto | null | undefined, + currentTier: RewardsTier | undefined, +): TierBalanceTrackDto | null => { + if (!balance?.enabled) return null; + if (isHeld(balance.ultra)) return balance.ultra; + if (isHeld(balance.prime)) return balance.prime; + + const above = TIER_BALANCE_TIERS.filter(tier => + isHigherTier(tier, currentTier ?? RewardsTier.CORE), + ).map(tier => tierBalanceTrack(balance, tier)); + return above.find(track => track.status === 'building') ?? above[0] ?? null; +}; + +/** + * What moving money out of Earn would do to the relevant track. + * + * - `reset`: the tier is building, and the days held so far would start over. + * - `grace`: the route holds the user's tier, and the drop would start its grace + * period — the tier ends unless the balance is back up before it runs out. + * - `lose`: the route holds the user's tier and the drop ends it, either because + * the grace period is already running or because there is none. + */ +export type TierBalanceOutflowKind = 'lose' | 'grace' | 'reset'; + +export interface TierBalanceOutflowWarning { + kind: TierBalanceOutflowKind; + tier: TierBalanceTier; + thresholdUsd: number; + graceDays: number; + /** When a running grace period ends, for `lose` in grace. */ + graceEndsAt: string | null; + lookbackDays: number; + /** Days already held toward the tier, for `reset`. */ + daysHeld: number; + /** How long the route stays shut once a tier it held has ended, for `lose`. */ + reentryDays: number; +} + +/** + * The warning to show before `outflowUsd` leaves Earn, or null for none. + * + * Informational only — every flow lets the user carry on. Shown when, for the + * relevant track: + * - it is active or in grace, the route is what holds the user's current tier, + * and the balance after the outflow would be under the threshold; or + * - it is building and the balance after the outflow would be under the + * threshold, which resets the progress. + * + * Nothing for an outflow of nothing (or one the form cannot price yet), and + * nothing before the backend has measured a balance to subtract it from. + */ +export const outflowWarning = ( + balance: TierBalanceRouteDto | null | undefined, + currentTier: RewardsTier | undefined, + outflowUsd: number, +): TierBalanceOutflowWarning | null => { + if (!Number.isFinite(outflowUsd) || outflowUsd <= 0) return null; + const track = relevantTrack(balance, currentTier); + if (!balance || !track || balance.currentUsd === null) return null; + if (balance.currentUsd - outflowUsd >= track.thresholdUsd) return null; + + const warning = (kind: TierBalanceOutflowKind): TierBalanceOutflowWarning => ({ + kind, + tier: track.tier, + thresholdUsd: track.thresholdUsd, + graceDays: balance.graceDays, + graceEndsAt: track.graceEndsAt, + lookbackDays: balance.lookbackDays, + daysHeld: track.daysHeld, + reentryDays: balance.reentryDays, + }); + + if (track.status === 'building') return warning('reset'); + if (!isHeld(track) || !balance.holdsCurrentTier) return null; + if (track.status === 'active' && balance.graceDays > 0) return warning('grace'); + return warning('lose'); +}; + +// --------------------------------------------------------------------------- +// Copy. Every figure in it comes from the payload. +// --------------------------------------------------------------------------- + +const tierName = (tier: TierBalanceTier) => getTierDisplayName(tier); + +/** "30 days" / "1 day". */ +export const daysLabel = (days: number): string => `${days} ${days === 1 ? 'day' : 'days'}`; + +const COMPACT_USD = new Intl.NumberFormat('en-US', { + notation: 'compact', + maximumFractionDigits: 2, +}); + +/** A threshold as running copy writes it: "$7.5K", "$35K", "$250". */ +export const formatThresholdUsd = (amount: number): string => `$${COMPACT_USD.format(amount)}`; + +/** + * An amount still to add, rounded UP to the dollar so adding it always clears + * the threshold: "$1,235". + */ +export const formatShortfallUsd = (amount: number): string => + `$${Math.ceil(Math.max(0, amount)).toLocaleString('en-US')}`; + +/** A measured balance, rounded DOWN so it never reads as enough when it is not. */ +export const formatBalanceUsd = (amount: number): string => + `$${COMPACT_USD.format(Math.floor(Math.max(0, amount)))}`; + +const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; +const DAY_KEY = /^(\d{4})-(\d{2})-(\d{2})$/; + +/** + * A route date as copy writes it: "Dec 24", with the year when it is not this + * one. Empty for a missing or unreadable date. + * + * `qualifiesOn` is a UTC day ("2026-12-24"), not an instant: it is written as + * that day wherever the reader is, where `new Date("2026-12-24")` would show + * Dec 23 to anyone west of Greenwich. The other dates are instants, written in + * the reader's own day. + */ +export const formatTierBalanceDate = ( + value: string | null | undefined, + now: Date = new Date(), +): string => { + if (!value) return ''; + const day = DAY_KEY.exec(value); + let year: number; + let month: number; + let date: number; + if (day) { + year = Number(day[1]); + month = Number(day[2]) - 1; + date = Number(day[3]); + } else { + const parsed = new Date(value); + if (Number.isNaN(parsed.getTime())) return ''; + year = parsed.getFullYear(); + month = parsed.getMonth(); + date = parsed.getDate(); + } + if (!MONTHS[month]) return ''; + return year === now.getFullYear() + ? `${MONTHS[month]} ${date}` + : `${MONTHS[month]} ${date}, ${year}`; +}; + +/** "Hold $7.5K in Earn for 30 days". */ +export const holdRequirementCopy = ( + track: TierBalanceTrackDto, + balance: Pick, +): string => + `Hold ${formatThresholdUsd(track.thresholdUsd)} in Earn for ${daysLabel(balance.lookbackDays)}`; + +/** Days still to hold before a building track unlocks. */ +const daysLeft = (track: TierBalanceTrackDto, lookbackDays: number) => + Math.max(0, lookbackDays - track.daysHeld); + +/** + * The one line that says where a track stands, by status: + * - none: what is still missing, or what it takes when nothing is; + * - building: how long the balance has to stay; + * - active: that holding unlocked it; + * - grace: by when to top up to keep it; + * - cooldown: when the route opens again. + */ +export const trackStatusLine = ( + track: TierBalanceTrackDto, + balance: Pick, + now: Date = new Date(), +): string => { + const name = tierName(track.tier); + const threshold = formatThresholdUsd(track.thresholdUsd); + const lookback = daysLabel(balance.lookbackDays); + + switch (track.status) { + case 'building': { + const date = formatTierBalanceDate(track.qualifiesOn, now); + if (date) return `Keep it there until ${date} to unlock ${name}`; + const left = daysLeft(track, balance.lookbackDays); + return left > 0 + ? `Keep it there ${daysLabel(left)} more to unlock ${name}` + : `Keep it there to unlock ${name}`; + } + case 'active': + return `Unlocked by holding ${threshold} in Earn`; + case 'grace': { + const date = formatTierBalanceDate(track.graceEndsAt, now); + return date + ? `Top up to ${threshold} by ${date} to keep ${name}` + : `Top up to ${threshold} to keep ${name}`; + } + case 'cooldown': { + const date = formatTierBalanceDate(track.reentryAt, now); + return date ? `Available again on ${date}` : 'Available again soon'; + } + case 'none': + default: + if (balance.currentUsd !== null && track.shortfallUsd > 0) { + return `Add ${formatShortfallUsd(track.shortfallUsd)} to Earn and keep it there ${lookback} to unlock ${name}`; + } + return `${holdRequirementCopy(track, balance)} to unlock ${name}`; + } +}; + +/** + * The Earn page's nudge: a headline ("$1,235 more unlocks Prime", "Top up to + * keep Prime") and the line under it, which never repeats the headline. + */ +export const trackNudgeCopy = ( + track: TierBalanceTrackDto, + balance: Pick, + now: Date = new Date(), +): { title: string; body: string } => { + const name = tierName(track.tier); + const threshold = formatThresholdUsd(track.thresholdUsd); + switch (track.status) { + case 'building': + return { title: `Unlocking ${name}`, body: trackStatusLine(track, balance, now) }; + case 'active': + return { + title: `${name} unlocked by holding`, + body: `Keep ${threshold} or more in Earn to keep ${name}`, + }; + case 'grace': { + const date = formatTierBalanceDate(track.graceEndsAt, now); + return { + title: `Top up to keep ${name}`, + body: date + ? `Your Earn balance is under ${threshold}. Top it up by ${date}.` + : `Your Earn balance is under ${threshold}.`, + }; + } + case 'cooldown': + return { title: `${name} by holding`, body: trackStatusLine(track, balance, now) }; + case 'none': + default: + return { + title: + balance.currentUsd !== null && track.shortfallUsd > 0 + ? `${formatShortfallUsd(track.shortfallUsd)} more unlocks ${name}` + : `Unlock ${name} by holding`, + body: `${holdRequirementCopy(track, balance)} to unlock ${name}`, + }; + } +}; + +/** Whether a track's next step is adding money to Earn. */ +export const trackNeedsTopUp = (track: TierBalanceTrackDto): boolean => + track.status === 'none' || track.status === 'grace'; + +/** The progress bar beside a track: days for a building track, dollars otherwise. */ +export interface TierBalanceProgress { + /** 0..100. */ + percent: number; + /** The figure reached, or null when there is none to show yet. */ + value: string | null; + /** The figure aimed at, written to follow `value`: "/$7.5K", "/30 days". */ + target: string; +} + +const clampPercent = (value: number) => + Number.isFinite(value) ? Math.min(100, Math.max(0, value)) : 0; + +export const trackProgress = ( + track: TierBalanceTrackDto, + balance: Pick, +): TierBalanceProgress => { + if (track.status === 'building' && balance.lookbackDays > 0) { + return { + percent: clampPercent((track.daysHeld / balance.lookbackDays) * 100), + value: String(track.daysHeld), + target: `/${daysLabel(balance.lookbackDays)}`, + }; + } + return { + percent: track.status === 'active' ? 100 : clampPercent(track.progressPct), + value: balance.currentUsd === null ? null : formatBalanceUsd(balance.currentUsd), + target: `/${formatThresholdUsd(track.thresholdUsd)}`, + }; +}; + +/** The words of an outflow warning. */ +export const outflowWarningCopy = ( + warning: TierBalanceOutflowWarning, + now: Date = new Date(), +): { title: string; body: string } => { + const name = tierName(warning.tier); + const threshold = formatThresholdUsd(warning.thresholdUsd); + const reentry = + warning.reentryDays > 0 + ? ` Holding can't unlock it again for ${daysLabel(warning.reentryDays)} after that.` + : ''; + + switch (warning.kind) { + case 'reset': + return { + title: `This restarts your progress to ${name}`, + body: + warning.daysHeld > 0 + ? `Your Earn balance would drop below ${threshold}, and your ${daysLabel(warning.daysHeld)} toward ${name} would start over. It takes ${daysLabel(warning.lookbackDays)} at ${threshold} or more to unlock it.` + : `Your Earn balance would drop below ${threshold}. It takes ${daysLabel(warning.lookbackDays)} at ${threshold} or more to unlock ${name}.`, + }; + case 'grace': + return { + title: `This puts your ${name} tier at risk`, + body: `Your Earn balance would drop below ${threshold}. You'd have up to ${daysLabel(warning.graceDays)} to bring it back up before ${name} ends.${reentry}`, + }; + case 'lose': + default: { + const date = formatTierBalanceDate(warning.graceEndsAt, now); + return { + title: `You could lose ${name}`, + body: date + ? `Your Earn balance would stay below ${threshold}. ${name} ends on ${date} unless it's back above ${threshold} by then.${reentry}` + : `Your Earn balance would drop below ${threshold}, which ends ${name}.${reentry}`, + }; + } + } +}; + +/** The balance celebration: true when the route is what just gave the user `tier`. */ +export const unlockedByBalance = ( + balance: TierBalanceRouteDto | null | undefined, + tier: RewardsTier, +): boolean => + !!balance?.enabled && + balance.holdsCurrentTier && + balance.grantsTier === tier && + tier !== RewardsTier.CORE; + +/** Where an outflow warning was shown, for analytics. */ +export type TierBalanceOutflowFlow = 'withdraw' | 'send' | 'swap' | 'card_topup'; diff --git a/lib/types.ts b/lib/types.ts index 0d6338bb4..93e3ada2c 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -4917,4 +4917,83 @@ export interface TierMembershipState { */ bridgeFeeCoverPct?: number; contracts: TierMembershipContracts; + /** + * The "Hold in Earn" route: a tier unlocked by keeping a USD balance in Earn + * for a lookback period. Null for anyone without access (it is staged to the + * internal team) or while the route is off, and absent on older backends — + * both mean the app shows nothing about it. Read it through `lib/tierBalance`. + */ + balance?: TierBalanceRouteDto | null; +} + +/** Where one tier stands on the balance route. */ +export type TierBalanceTrackStatus = 'none' | 'building' | 'active' | 'grace' | 'cooldown'; + +/** The tiers the balance route can grant. */ +export type TierBalanceTier = RewardsTier.PRIME | RewardsTier.ULTRA; + +/** + * One tier's progress on the balance route. Prime and Ultra are tracked apart: + * an Ultra member who drops under Ultra's threshold but stays above Prime's + * goes through Ultra's grace and lands on Prime. + */ +export interface TierBalanceTrackDto { + tier: TierBalanceTier; + status: TierBalanceTrackStatus; + /** Pinned threshold while active/grace; today's threshold otherwise. USD. */ + thresholdUsd: number; + /** How much more is needed now (0 when currentUsd >= thresholdUsd). USD. */ + shortfallUsd: number; + /** 0..100, currentUsd / thresholdUsd. */ + progressPct: number; + /** Consecutive measured days at or above the threshold, up to lookbackDays. */ + daysHeld: number; + /** building: the UTC day (YYYY-MM-DD) the tier unlocks if the balance stays. */ + qualifiesOn: string | null; + /** active/grace: when the route granted it (ISO). */ + unlockedAt: string | null; + /** grace: the instant the tier ends unless the balance is back above (ISO). */ + graceEndsAt: string | null; + /** cooldown: when the route can unlock this tier again (ISO). */ + reentryAt: string | null; +} + +/** What the qualifying Earn balance is made of, in USD. */ +export interface TierBalanceBreakdownDto { + /** Vault shares sitting in the Safe, all chains. */ + walletUsd: number; + /** Vault shares escrowed as Credit collateral (Fuse + Base Cash module v2). */ + creditCollateralUsd: number; + /** soFUSE locked in the tier lock. */ + lockedFuseUsd: number; + /** Credit debt (subtracted when the config says so). */ + creditDebtUsd: number; + /** Per asset, wallet + collateral + locked. */ + byVault: { usd: number; eur: number; eth: number; btc: number; fuse: number }; +} + +/** The user's position on the balance route, as `GET /accounts/v1/tier-membership` reports it. */ +export interface TierBalanceRouteDto { + /** The user may use the route (feature on and access granted). Always true in the app payload. */ + enabled: boolean; + /** Tier this route grants right now. */ + grantsTier: RewardsTier; + /** True when the user's current tier would be lower without this route. */ + holdsCurrentTier: boolean; + /** Latest measured qualifying Earn balance, USD. Null before the first measurement. */ + currentUsd: number | null; + measuredAt: string | null; + /** Lowest daily balance over the lookback window (measured days only). */ + lowestUsd: number | null; + lookbackDays: number; + graceDays: number; + reentryDays: number; + breakdown: TierBalanceBreakdownDto | null; + rules: { + countsCreditCollateral: boolean; + subtractsCreditDebt: boolean; + countsLockedFuse: boolean; + }; + prime: TierBalanceTrackDto; + ultra: TierBalanceTrackDto; } diff --git a/lib/vaults.ts b/lib/vaults.ts index a548d3a6b..24d209d68 100644 --- a/lib/vaults.ts +++ b/lib/vaults.ts @@ -1,4 +1,4 @@ -import { formatUnits } from 'viem'; +import { formatUnits, zeroAddress } from 'viem'; import { arbitrum, base, fuse, mainnet } from 'viem/chains'; import { @@ -10,6 +10,7 @@ import { } from '@/constants/bridge'; import { VAULTS } from '@/constants/vaults'; import { PRODUCTION_VAULT_ADDRESSES } from '@/lib/config'; +import { SOBTC_ADDRESSES } from '@/lib/soBtc'; import { isSoEthBaseConfigured } from '@/lib/soEthWithdraw'; import { DepositMethod, TokenBalance, Vault, VaultDepositConfig, VaultType } from '@/lib/types'; @@ -85,6 +86,33 @@ export const isVaultShareToken = (contractAddress?: string): boolean => { return LIVE_VAULTS.some(vault => vault.vaults.some(v => v.address.toLowerCase() === address)); }; +/** + * Every Earn share token the app knows, lowercased: each vault's shares on + * Fuse, Base and Ethereum, the production shares a development wallet may hold, + * and soBTC on both its chains even in a build that does not list the vault. + */ +const EARN_SHARE_ADDRESSES: ReadonlySet = new Set( + [ + ...VAULTS.flatMap(vault => vault.vaults.map(entry => entry.address)), + ...Object.values(PRODUCTION_VAULT_ADDRESSES).flatMap(chain => Object.values(chain)), + SOBTC_ADDRESSES.base.vault, + SOBTC_ADDRESSES.ethereum.vault, + ] + .map(address => address.toLowerCase()) + .filter(address => address !== zeroAddress), +); + +/** + * Whether a token is an Earn share (soUSD, soEURC, soETH, soBTC, soFUSE) on any + * chain — the test for "moving this takes money out of Earn". + * + * Matched by address against every chain at once, not against the token's own + * chain or Fuse alone: shares bridge between Fuse, Base and Ethereum and keep + * counting toward Earn wherever they sit. + */ +export const isEarnShareToken = (address?: string): boolean => + !!address && EARN_SHARE_ADDRESSES.has(address.toLowerCase()); + /** * The vault a wallet token belongs to — matched either as the vault share token * (by address) or as the vault's underlying asset (by symbol). Tokens without a