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
87 changes: 87 additions & 0 deletions src/components/__tests__/SubscriptionAccessGate.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import SubscriptionAccessGate from '../common/SubscriptionAccessGate';
import { useWalletHoldings } from '@/hooks/useWallet';
import { useProfileStore } from '@/hooks/useProfileStore';

vi.mock('@/hooks/useWallet', () => ({
useWalletHoldings: vi.fn(),
}));

vi.mock('@/hooks/useProfileStore', () => ({
useProfileStore: vi.fn(),
}));

describe('SubscriptionAccessGate', () => {
const mockOnBuyClick = vi.fn();

beforeEach(() => {
vi.clearAllMocks();
});

it('shows non-connected state when no wallet is connected', () => {
(useProfileStore as unknown as ReturnType<typeof vi.fn>).mockImplementation((selector: unknown) => (selector as (state: unknown) => unknown)({ profile: null }));
(useWalletHoldings as unknown as ReturnType<typeof vi.fn>).mockReturnValue({ data: [], isLoading: false });

render(
<SubscriptionAccessGate creatorId="creator1" onBuyClick={mockOnBuyClick}>
<div>Exclusive Content</div>
</SubscriptionAccessGate>
);

expect(screen.getByTestId('subscription-gate-unconnected')).toBeInTheDocument();
expect(screen.getByText(/Wallet Not Connected/i)).toBeInTheDocument();
});

it('shows loading state while fetching holdings', () => {
(useProfileStore as unknown as ReturnType<typeof vi.fn>).mockImplementation((selector: unknown) => (selector as (state: unknown) => unknown)({ profile: { id: 'wallet1' } }));
(useWalletHoldings as unknown as ReturnType<typeof vi.fn>).mockReturnValue({ data: [], isLoading: true });

render(
<SubscriptionAccessGate creatorId="creator1" onBuyClick={mockOnBuyClick}>
<div>Exclusive Content</div>
</SubscriptionAccessGate>
);

expect(screen.getByTestId('subscription-gate-loading')).toBeInTheDocument();
});

it('shows locked state when holding is below minimum threshold', () => {
(useProfileStore as unknown as ReturnType<typeof vi.fn>).mockImplementation((selector: unknown) => (selector as (state: unknown) => unknown)({ profile: { id: 'wallet1' } }));
(useWalletHoldings as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
data: [{ creatorId: 'creator1', quantity: 0 }],
isLoading: false,
});

render(
<SubscriptionAccessGate creatorId="creator1" onBuyClick={mockOnBuyClick} minimumHolding={1}>
<div>Exclusive Content</div>
</SubscriptionAccessGate>
);

expect(screen.getByTestId('subscription-gate-locked')).toBeInTheDocument();
expect(screen.getByText(/Content Locked/i)).toBeInTheDocument();

const buyButton = screen.getByRole('button', { name: /Buy Keys to Unlock/i });
fireEvent.click(buyButton);
expect(mockOnBuyClick).toHaveBeenCalled();
});

it('shows unlocked state and content when holding meets minimum threshold', () => {
(useProfileStore as unknown as ReturnType<typeof vi.fn>).mockImplementation((selector: unknown) => (selector as (state: unknown) => unknown)({ profile: { id: 'wallet1' } }));
(useWalletHoldings as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
data: [{ creatorId: 'creator1', quantity: 1, last_buy_timestamp: Date.now() }],
isLoading: false,
});

render(
<SubscriptionAccessGate creatorId="creator1" onBuyClick={mockOnBuyClick} minimumHolding={1}>
<div>Exclusive Content</div>
</SubscriptionAccessGate>
);

expect(screen.getByTestId('subscription-gate-unlocked')).toBeInTheDocument();
expect(screen.getByText(/Active Subscription/i)).toBeInTheDocument();
expect(screen.getByText('Exclusive Content')).toBeInTheDocument();
});
});
16 changes: 8 additions & 8 deletions src/components/common/BatchTradePanel.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMemo, useState } from 'react';
import { useCallback, useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
Expand All @@ -21,21 +21,21 @@ export default function BatchTradePanel({ open, onOpenChange }: { open: boolean;
const [quantity, setQuantity] = useState(1);
const [slippageBps, setSlippageBps] = useState(500);
const [results, setResults] = useState<Awaited<ReturnType<typeof mutation.mutateAsync>>['results'] | null>(null);
const courses = coursesQuery.data ?? [];
const holdings = holdingsQuery.data ?? [];
const getCourse = (id: string) => courses.find(course => course.id === id);
const orderCost = (order: DraftOrder) => {
const courses = useMemo(() => coursesQuery.data ?? [], [coursesQuery.data]);
const holdings = useMemo(() => holdingsQuery.data ?? [], [holdingsQuery.data]);
const getCourse = useCallback((id: string) => courses.find(course => course.id === id), [courses]);
const orderCost = useCallback((order: DraftOrder) => {
const course = getCourse(order.creatorId);
const price = Number(order.side === 'buy' ? course?.priceStroops : course?.priceStroops) || 0;
return order.side === 'buy' ? calculateFeeBreakdown({ quantity: order.quantity, keyPriceStroops: price, currentSupply: course?.creatorShareSupply ?? 0, protocolFeeBps: course?.protocolFeeBps ?? 500, creatorFeeBps: course?.creatorFeeBps ?? 500 }).totalCostStroops : 0;
};
const totalCost = useMemo(() => orders.reduce((sum, order) => sum + orderCost(order), 0), [orders, courses]);
}, [getCourse]);
const totalCost = useMemo(() => orders.reduce((sum, order) => sum + orderCost(order), 0), [orders, orderCost]);
const totalFees = useMemo(() => orders.reduce((sum, order) => {
if (order.side !== 'buy') return sum;
const course = getCourse(order.creatorId);
const gross = (Number(course?.priceStroops) || 0) * order.quantity;
return sum + Math.round(gross * ((course?.protocolFeeBps ?? 500) + (course?.creatorFeeBps ?? 500)) / 10_000);
}, 0), [orders, courses]);
}, 0), [orders, getCourse]);
const sellExceeded = orders.some(order => order.side === 'sell' && (holdings.find(item => item.creatorId === order.creatorId)?.quantity ?? 0) < order.quantity);
const addOrder = () => {
if (!creatorId || quantity < 1 || !Number.isFinite(quantity)) return;
Expand Down
129 changes: 129 additions & 0 deletions src/components/common/SubscriptionAccessGate.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import type { ReactNode } from 'react';
import { useWalletHoldings } from '@/hooks/useWallet';
import { useProfileStore } from '@/hooks/useProfileStore';
import { Button } from '@/components/ui/button';
import { formatDistanceToNow } from 'date-fns';

interface SubscriptionAccessGateProps {
creatorId: string;
minimumHolding?: number;
children: ReactNode;
onBuyClick?: () => void;
}

export default function SubscriptionAccessGate({
creatorId,
minimumHolding = 1,
children,
onBuyClick,
}: SubscriptionAccessGateProps) {
const profile = useProfileStore(state => state.profile);
const userAddress = profile?.id;
const { data: holdings = [], isLoading } = useWalletHoldings(
userAddress ?? ''
);

const userPosition = holdings.find(h => h.creatorId === creatorId);
const quantity = userPosition?.quantity ?? 0;
const isUnlocked = quantity >= minimumHolding;

// Mock expiry countdown for now (e.g. 30 days from last buy, defaulting to 30 days from now if not present)
const expiryDate = userPosition?.last_buy_timestamp
? new Date(
new Date(userPosition.last_buy_timestamp).getTime() +
30 * 24 * 60 * 60 * 1000
)
: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);

if (!userAddress) {
return (
<div className="rounded-2xl border border-white/10 bg-[#06111f] p-8 text-center" data-testid="subscription-gate-unconnected">
<h3 className="mb-2 text-xl font-bold text-white">Wallet Not Connected</h3>
<p className="mb-4 text-white/70">
Connect your wallet to verify your key holdings and access this content.
</p>
</div>
);
}

if (isLoading) {
return (
<div className="rounded-2xl border border-white/10 bg-white/[0.02] p-8 text-center text-white/50 animate-pulse" data-testid="subscription-gate-loading">
Checking subscription status...
</div>
);
}

if (!isUnlocked) {
return (
<div className="rounded-2xl border border-rose-500/20 bg-rose-500/10 p-8 text-center" data-testid="subscription-gate-locked">
<div className="mb-4 text-rose-400">
<svg
className="mx-auto h-12 w-12"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
/>
</svg>
</div>
<h3 className="mb-2 text-xl font-bold text-white">Content Locked</h3>
<p className="mb-6 text-white/70">
You need at least {minimumHolding} key{minimumHolding === 1 ? '' : 's'}{' '}
to access this creator's gated content. You currently hold {quantity}.
</p>
{onBuyClick && (
<Button onClick={onBuyClick} variant="default" className="font-bold">
Buy Keys to Unlock
</Button>
)}
</div>
);
}

return (
<div className="space-y-6" data-testid="subscription-gate-unlocked">
<div className="flex items-center justify-between rounded-xl border border-emerald-500/20 bg-emerald-500/10 px-5 py-3">
<div className="flex items-center gap-3">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-emerald-500/20 text-emerald-400">
<svg
className="h-5 w-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
</div>
<div>
<h4 className="font-bold text-emerald-400">Active Subscription</h4>
<p className="text-xs text-emerald-400/80">
You hold {quantity} key{quantity === 1 ? '' : 's'}
</p>
</div>
</div>
{expiryDate && (
<div className="text-right">
<p className="text-xs uppercase tracking-wider text-emerald-400/70">
Expires
</p>
<p className="font-mono text-sm font-semibold text-emerald-400">
{formatDistanceToNow(expiryDate, { addSuffix: true })}
</p>
</div>
)}
</div>
{children}
</div>
);
}
Loading
Loading