Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions components/Invite/__tests__/inviteCopy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,51 @@ describe('inviteCopy', () => {
});
});

describe('inviteCopy with a KOL perk', () => {
const perk = {
tierDiscountPct: 50,
sepaFreeMonths: 1,
sepaFreeCapUsd: 10000,
endsAt: '2026-12-23T00:00:00.000Z',
};

it('leads with the discount, then the free SEPA and the card bonus', () => {
const copy = inviteCopy({ ...v4, code: 'ARTEM50', perk });

expect(copy.inviter).toBe('eli');
expect(headline(copy.title)).toBe('Get 50% off your first\nyear of Prime or Ultra');
expect(copy.title.filter(part => part.accent).map(part => part.text)).toEqual(['50% off']);
expect(copy.subtitle).toBe(
'Plus free SEPA deposits for your first month, up to $10,000. And spend $150 in your first 30 days for a $10 card bonus.',
);
expect(copy.steps).toEqual([
'Create your account',
'Deposit euros by SEPA with no fee',
'Upgrade to Prime or Ultra for 50% off',
]);
expect(copy.footnote).toBe('For new accounts created by 23 Dec.');
});

it('leads with free SEPA when there is no discount', () => {
const copy = inviteCopy({ ...v4, perk: { ...perk, tierDiscountPct: 0, sepaFreeMonths: 3 } });
expect(headline(copy.title)).toBe('Free SEPA deposits\nfor your first 3 months');
expect(
copy.subtitle.startsWith('Free SEPA deposits for your first 3 months, up to $10,000.'),
).toBe(true);
expect(copy.steps).toEqual([
'Create your account',
'Deposit euros by SEPA with no fee',
'Get your free card',
]);
});

it('falls back to the normal invite on a malformed perk', () => {
expect(headline(inviteCopy({ ...v4, perk: { tierDiscountPct: 'x' } }).title)).toBe(
'Get $10 to spend\nwith your card',
);
});
});

describe('inviterInitial', () => {
it('upper-cases the first character', () => {
expect(inviterInitial('eli')).toBe('E');
Expand Down
62 changes: 61 additions & 1 deletion components/Invite/inviteCopy.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
import {
perkDay,
readInvitePerk,
sepaPerkPhrase,
sepaPerkSentence,
} from '@/lib/referral/invitePerk';
import { formatUsdWhole } from '@/lib/referral/referralV4';

import type { ReferralInviteLookup } from '@/lib/types';
Expand All @@ -17,9 +23,63 @@ export interface InviteCopy {
footnote: string | null;
}

/** What the page says, from the lookup: v4's card bonus, the cashback offer, or a plain welcome. */
/**
* What the page says, from the lookup: a KOL's invite perk, v4's card bonus,
* the cashback offer, or a plain welcome.
*/
export const inviteCopy = (lookup: ReferralInviteLookup | undefined): InviteCopy => {
const inviter = lookup?.valid ? lookup.referrer.username : null;
const perk = lookup?.valid ? readInvitePerk(lookup.perk) : null;

// A KOL's perk code leads with the perk; the referral offer still applies
// and is mentioned after it.
if (lookup?.valid && perk) {
const title: InviteTitlePart[] =
perk.tierDiscountPct > 0
? [
{ text: 'Get ' },
{ text: `${perk.tierDiscountPct}% off`, accent: true },
{ text: ' your first\nyear of Prime or Ultra' },
]
: [
{ text: 'Free ' },
{ text: 'SEPA deposits', accent: true },
{
text: `\nfor your first ${perk.sepaFreeMonths === 1 ? 'month' : `${perk.sepaFreeMonths} months`}`,
},
];
const sentences: string[] = [];
if (perk.tierDiscountPct > 0 && perk.sepaFreeMonths > 0) {
sentences.push(`Plus ${sepaPerkPhrase(perk)}.`);
} else if (perk.tierDiscountPct > 0) {
sentences.push('The discount applies to your first year of membership.');
} else {
sentences.push(`${sepaPerkSentence(perk)}.`);
}
if (lookup.offer) {
sentences.push(
`And spend ${formatUsdWhole(lookup.offer.spendTargetUsd)} in your first ${lookup.offer.windowDays} days for a ${formatUsdWhole(lookup.offer.friendCreditUsd)} card bonus.`,
);
} else if (lookup.legacyOffer) {
sentences.push(
`And spend ${formatUsdWhole(lookup.legacyOffer.spendTargetUsd)} in your first ${lookup.legacyOffer.windowDays} days to get ${formatUsdWhole(lookup.legacyOffer.friendRewardUsd)} in ${lookup.legacyOffer.payoutToken}.`,
);
}
const steps = ['Create your account'];
if (perk.sepaFreeMonths > 0) steps.push('Deposit euros by SEPA with no fee');
if (perk.tierDiscountPct > 0) {
steps.push(`Upgrade to Prime or Ultra for ${perk.tierDiscountPct}% off`);
}
if (steps.length < 3) steps.push('Get your free card');
const lastDay = perkDay(perk.endsAt);
return {
inviter,
title,
subtitle: sentences.join(' '),
steps,
footnote: lastDay ? `For new accounts created by ${lastDay}.` : null,
};
}

if (lookup?.valid && lookup.offer) {
const { friendCreditUsd, spendTargetUsd, merchantTarget, windowDays } = lookup.offer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
canPayCashFor,
findOffer,
formatFuse,
formatInviteDiscount,
formatLockDuration,
formatRenewalTerms,
formatSaleEnds,
Expand Down Expand Up @@ -328,7 +329,7 @@ const UpgradeReviewContent = () => {
<TierPrice
priceUsd={firstYearFeeUsd}
listPriceUsd={offer.annualFeeUsd}
secondaryValue={formatSaleEnds(offer) || undefined}
secondaryValue={formatSaleEnds(offer) || formatInviteDiscount(offer) || undefined}
/>
</TierDetailRow>
{/* A bridged payment that landed short: what the bridge took comes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import {
membershipDateLabel,
nextPurchasableTier,
offerFirstYearFeeUsd,
offerInviteDiscount,
offerPaymentMode,
remainingFuseForTier,
} from '@/lib/tierUpgrade';
Expand Down Expand Up @@ -321,7 +322,9 @@ const UpgradeTierContent = ({ onRouteSelected, onTopUp }: UpgradeTierContentProp
listPriceUsd={offer.annualFeeUsd}
secondaryValue={
isOfferOnSale(offer) && offer.annualFeeUsd !== null
? `First year, then ${formatPriceUsd(offer.annualFeeUsd)}/year`
? offerInviteDiscount(offer)
? `First year with ${offerInviteDiscount(offer)?.pct}% invite discount, then ${formatPriceUsd(offer.annualFeeUsd)}/year`
: `First year, then ${formatPriceUsd(offer.annualFeeUsd)}/year`
: undefined
}
/>
Expand Down
5 changes: 4 additions & 1 deletion components/Signup/InviteCodeField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as Clipboard from 'expo-clipboard';
import Input from '@/components/ui/input';
import { Text } from '@/components/ui/text';
import { parseInviteCodeFromText } from '@/lib/referral/inviteCode';
import { invitePerkShort, readInvitePerk } from '@/lib/referral/invitePerk';
import { formatUsdWhole } from '@/lib/referral/referralV4';
import { cn } from '@/lib/utils';

Expand All @@ -17,9 +18,11 @@ export type InviteCodeStatus =
/** The lookup itself failed: say nothing, signup sends the code and the backend decides. */
| { kind: 'unverified' };

/** "Dana invited you · $10 card bonus". */
/** "Dana invited you · $10 card bonus", or "· 50% off Prime & Ultra + free SEPA" for a KOL's perk code. */
const validLine = (lookup: Extract<ReferralInviteLookup, { valid: true }>) => {
const who = `${lookup.referrer.username} invited you`;
const perk = readInvitePerk(lookup.perk);
if (perk) return `${who} · ${invitePerkShort(perk)}`;
if (lookup.offer) return `${who} · ${formatUsdWhole(lookup.offer.friendCreditUsd)} card bonus`;
if (lookup.legacyOffer) {
return `${who} · ${formatUsdWhole(lookup.legacyOffer.friendRewardUsd)} in ${lookup.legacyOffer.payoutToken}`;
Expand Down
19 changes: 19 additions & 0 deletions components/WirexBankAccount/KolPerkNotice.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { View } from 'react-native';

import { Text } from '@/components/ui/text';

/**
* "Your SEPA deposits are free until 23 Dec" on the euro account screen, while
* the user's KOL invite perk covers their deposits. Same look as the fee
* promotion notice, and shown in its place: the perk is the user's own and is
* used first.
*/
export const KolPerkNotice = ({ title, body }: { title: string; body: string }) => (
<View
accessibilityRole="summary"
className="mt-5 gap-1 rounded-twice border border-brand/30 bg-brand/10 px-5 py-4"
>
<Text className="text-[16px] font-semibold text-brand">{title}</Text>
<Text className="text-sm leading-5 text-white/70">{body}</Text>
</View>
);
10 changes: 8 additions & 2 deletions components/WirexBankAccount/WirexBankAccountDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,20 @@ import { DEPOSIT_MODAL } from '@/constants/modals';
import { path } from '@/constants/path';
import { TRACKING_EVENTS } from '@/constants/tracking-events';
import { useConfirmResidence } from '@/hooks/useConfirmResidence';
import { useEurDepositPromotion } from '@/hooks/useProductFees';
import { useEurDepositPromotion, useKolPerk } from '@/hooks/useProductFees';
import { useActivateWirexBankAccount, useWirexBankOverview } from '@/hooks/useWirexBankAccounts';
import { useWirexWalletLink } from '@/hooks/useWirexWalletLink';
import { track } from '@/lib/analytics';
import { getAsset } from '@/lib/assets';
import { kolSepaPerkCopy } from '@/lib/referral/invitePerk';
import { WirexBankAccountType, WirexBankRailStatusDto } from '@/lib/types/wirex-bank';
import { cn } from '@/lib/utils';
import { useCountryStore } from '@/store/useCountryStore';
import { useDepositStore } from '@/store/useDepositStore';
import { useKycStore } from '@/store/useKycStore';

import { FeePromotionNotice } from './FeePromotionNotice';
import { KolPerkNotice } from './KolPerkNotice';
import {
detailRows,
RAIL_PRESENTATION,
Expand Down Expand Up @@ -161,6 +163,8 @@ export const WirexBankAccountDetails = ({
const walletLink = useWirexWalletLink();
// Free SEPA deposits, while a promotion runs and the user has some left.
const eurPromotion = useEurDepositPromotion();
// Free SEPA from a KOL's invite perk, which is used before any promotion.
const kolSepaCopy = kolSepaPerkCopy(useKolPerk());
const router = useRouter();
const setModal = useDepositStore(state => state.setModal);
const countrySource = useCountryStore(state => state.countryInfo?.source);
Expand Down Expand Up @@ -422,7 +426,9 @@ export const WirexBankAccountDetails = ({
rows={detailRows(activeRail)}
header={switcher}
notice={
activeRail.accountType === WirexBankAccountType.SEPA && eurPromotion ? (
activeRail.accountType !== WirexBankAccountType.SEPA ? null : kolSepaCopy ? (
<KolPerkNotice title={kolSepaCopy.title} body={kolSepaCopy.body} />
) : eurPromotion ? (
<FeePromotionNotice promotion={eurPromotion} />
) : null
}
Expand Down
77 changes: 77 additions & 0 deletions hooks/__tests__/useKolPerk.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import React from 'react';

import { useKolPerk } from '@/hooks/useProductFees';

const { act, create } = jest.requireActual('react-test-renderer');
let mockQuery: { data: unknown; isError: boolean };
let perk: ReturnType<typeof useKolPerk>;
let root: any;
jest.mock('@tanstack/react-query', () => ({
useQuery: () => mockQuery,
useMutation: jest.fn(),
}));
jest.mock('@/store/useUserStore', () => ({
useUserStore: (selector: any) => selector({ users: [{ selected: true, userId: 'account-a' }] }),
}));
jest.mock('@/lib/api', () => ({
fetchFeePromotions: jest.fn(),
fetchKolPerk: jest.fn(),
fetchProductFeeRates: jest.fn(),
recordSwapFee: jest.fn(),
}));
jest.mock('@/lib/utils', () => ({ withRefreshToken: jest.fn() }));

const ACTIVE = {
kolUsername: 'artem.betev',
grantedAt: '2026-11-23T12:00:00.000Z',
tierDiscount: null,
sepa: {
freeUntil: '2026-12-23T12:00:00.000Z',
capUsd: 10000,
coveredUsd: 0,
remainingUsd: 10000,
waivedFeeUsd: 0,
active: true,
},
};

function Probe() {
const value = useKolPerk();
React.useEffect(() => {
perk = value;
}, [value]);
return null;
}
const render = () => act(() => root.update(<Probe />));

beforeEach(() => {
mockQuery = { data: ACTIVE, isError: false };
act(() => {
root = create(<Probe />);
});
});
afterEach(() => {
act(() => root.unmount());
});

it('shows the perk it read', () => {
expect(perk).toBe(ACTIVE);
});

it('hides the perk once a refresh fails, though the last read is still cached', () => {
// TanStack Query keeps `data` from the last success when a refetch fails.
mockQuery = { data: ACTIVE, isError: true };
render();
expect(perk).toBeNull();

// A later refresh that succeeds shows it again.
mockQuery = { data: ACTIVE, isError: false };
render();
expect(perk).toBe(ACTIVE);
});

it('shows nothing before the first read', () => {
mockQuery = { data: undefined, isError: false };
render();
expect(perk).toBeNull();
});
26 changes: 25 additions & 1 deletion hooks/useProductFees.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { useEffect, useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { minutesToMilliseconds, secondsToMilliseconds } from 'date-fns';

import { fetchFeePromotions, fetchProductFeeRates, recordSwapFee } from '@/lib/api';
import { fetchFeePromotions, fetchKolPerk, fetchProductFeeRates, recordSwapFee } from '@/lib/api';
import { readUserKolPerk } from '@/lib/referral/invitePerk';
import { FeeProduct, RecordSwapFeeParams } from '@/lib/types';
import { withRefreshToken } from '@/lib/utils';
import { eurDepositPromotion, nextEurPromotionChange } from '@/lib/utils/feePromotion';
Expand Down Expand Up @@ -88,6 +89,29 @@ export const useEurDepositPromotion = () => {
return eurDepositPromotion(data ?? null, now);
};

/**
* The user's KOL invite perk, or null — none, not loaded yet, or a failed
* load (the screen then simply doesn't advertise it). Polled like the fee
* promotions, so a deposit that uses up the cap reaches an open screen.
* A failed refresh hides it too: the perk it last read may since have run
* out, and a later refresh that succeeds shows it again.
*/
export const useKolPerk = () => {
const userId = useSelectedUserId();

const { data, isError } = useQuery({
queryKey: [PRODUCT_FEES, 'kolPerk', userId],
queryFn: async () => readUserKolPerk(await withRefreshToken(() => fetchKolPerk())),
staleTime: secondsToMilliseconds(60),
refetchInterval: secondsToMilliseconds(60),
refetchIntervalInBackground: false,
gcTime: minutesToMilliseconds(5),
enabled: Boolean(userId),
retry: false,
});
return isError ? null : (data ?? null);
};

/**
* The swap fee rate for this user, and where the fee must be sent.
*
Expand Down
Loading
Loading