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
154 changes: 154 additions & 0 deletions apps/web/__tests__/usePoolTicks.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { usePools } from '@/hooks/usePoolTicks';

const mockPools = [
{
id: 'pool-xlm-usdc-030',
token0: 'XLM',
token1: 'USDC',
token0Symbol: 'XLM',
token1Symbol: 'USDC',
feeTier: '0.30%',
currentPrice: 0.1085,
currentTick: -22000,
tvl: 4_200_000,
feeApr: 12.4,
volume24h: 340_000,
},
];

describe('usePools', () => {
beforeEach(() => {
vi.stubGlobal('fetch', vi.fn());
});

afterEach(() => {
vi.unstubAllGlobals();
});

it('shows initial loading state then returns pool data', async () => {
global.fetch = vi.fn().mockResolvedValueOnce({
ok: true,
json: async () => ({ items: mockPools }),
});

const { result } = renderHook(() => usePools());

expect(result.current.loading).toBe(true);
expect(result.current.pools).toHaveLength(0);
expect(result.current.isStale).toBe(true);

await waitFor(() => {
expect(result.current.loading).toBe(false);
});

expect(result.current.pools).toEqual(mockPools);
expect(result.current.error).toBeNull();
expect(result.current.isStale).toBe(false);
});

it('handles fetch failure gracefully with mock data and error', async () => {
global.fetch = vi.fn().mockRejectedValueOnce(new Error('Network error'));

const { result } = renderHook(() => usePools());

await waitFor(() => {
expect(result.current.loading).toBe(false);
});

expect(result.current.error).toBeInstanceOf(Error);
expect(result.current.pools).toHaveLength(3);
expect(result.current.isStale).toBe(true);
});

it('handles HTTP error gracefully with mock data and error', async () => {
global.fetch = vi.fn().mockResolvedValueOnce({
ok: false,
status: 500,
});

const { result } = renderHook(() => usePools());

await waitFor(() => {
expect(result.current.loading).toBe(false);
});

expect(result.current.error).toBeInstanceOf(Error);
expect(result.current.error?.message).toContain('500');
expect(result.current.pools).toHaveLength(3);
});

it('handles invalid JSON response gracefully', async () => {
global.fetch = vi.fn().mockResolvedValueOnce({
ok: true,
json: async () => { throw new Error('Invalid JSON'); },
});

const { result } = renderHook(() => usePools());

await waitFor(() => {
expect(result.current.loading).toBe(false);
});

expect(result.current.error).toBeInstanceOf(Error);
expect(result.current.pools).toHaveLength(3);
});

it('handles null response body gracefully', async () => {
global.fetch = vi.fn().mockResolvedValueOnce({
ok: true,
json: async () => null,
});

const { result } = renderHook(() => usePools());

await waitFor(() => {
expect(result.current.loading).toBe(false);
});

expect(result.current.error).toBeInstanceOf(Error);
expect(result.current.pools).toHaveLength(3);
expect(result.current.isStale).toBe(true);
});

it('handles empty items array response', async () => {
global.fetch = vi.fn().mockResolvedValueOnce({
ok: true,
json: async () => ({ items: [] }),
});

const { result } = renderHook(() => usePools());

await waitFor(() => {
expect(result.current.loading).toBe(false);
});

expect(result.current.pools).toHaveLength(0);
expect(result.current.error).toBeNull();
expect(result.current.isStale).toBe(false);
});

it('cancels state updates on unmount', async () => {
let resolveFetch: () => void;
global.fetch = vi.fn().mockImplementation(
() =>
new Promise((resolve) => {
resolveFetch = () =>
resolve({ ok: true, json: async () => ({ items: mockPools }) });
})
);

const { result, unmount } = renderHook(() => usePools());

expect(result.current.loading).toBe(true);

unmount();

resolveFetch!();

await waitFor(() => {
expect(result.current.pools).toHaveLength(0);
});
});
});
13 changes: 11 additions & 2 deletions apps/web/components/AddLiquidity/PoolSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,18 @@ export interface PoolSelectorProps {
}

export function PoolSelector({ selected, onSelect }: PoolSelectorProps) {
const { pools, loading } = usePools();
const { pools, loading, error, isStale } = usePools();

return (
<div className="flex flex-col gap-2">
<p className="text-xs font-medium text-zinc-500 dark:text-zinc-400">Select pool</p>
<div className="flex items-center gap-2">
<p className="text-xs font-medium text-zinc-500 dark:text-zinc-400">Select pool</p>
{isStale && !loading && (
<span className="text-xs text-amber-600 dark:text-amber-400" title="Showing cached/mock data">
(cached)
</span>
)}
</div>
{loading ? (
<div className="flex gap-2">
{[1, 2, 3].map((i) => (
Expand All @@ -24,6 +31,8 @@ export function PoolSelector({ selected, onSelect }: PoolSelectorProps) {
/>
))}
</div>
) : error ? (
<p className="text-sm text-red-500 dark:text-red-400">Failed to load pools. Showing cached data.</p>
) : (
<div className="flex flex-col gap-2">
{pools.map((pool) => {
Expand Down
34 changes: 26 additions & 8 deletions apps/web/hooks/usePoolTicks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,19 +67,35 @@ export function usePoolTicks(poolId: string | null) {

export function usePools() {
const [pools, setPools] = useState<PoolDetail[]>([]);
const [loading, setLoading] = useState(false);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const [lastUpdated, setLastUpdated] = useState<number | null>(null);

useEffect(() => {
let cancelled = false;
setLoading(true);
setError(null);

fetch(`${API_BASE}/pools?limit=50&orderBy=tvl`)
.then((r) => r.json())
.then((data: { items?: PoolDetail[] }) => {
if (!cancelled) setPools(data.items ?? []);
fetch(`${API_BASE}/pools?limit=50&orderBy=tvl`, { cache: 'no-store' })
.then((r) => {
if (!r.ok) throw new Error(`Failed to load pools: HTTP ${r.status}`);
return r.json();
})
.catch(() => {
if (!cancelled) setPools(MOCK_POOLS);
.then((data: unknown) => {
if (!cancelled) {
if (!data || typeof data !== 'object') {
throw new Error('Invalid response format');
}
setPools(((data as { items?: PoolDetail[] }).items ?? []));
setLastUpdated(Date.now());
}
})
.catch((err: unknown) => {
if (!cancelled) {
const error = err instanceof Error ? err : new Error('Failed to load pools');
setError(error);
setPools(MOCK_POOLS);
}
})
.finally(() => {
if (!cancelled) setLoading(false);
Expand All @@ -90,7 +106,9 @@ export function usePools() {
};
}, []);

return { pools, loading };
const isStale = lastUpdated === null;

return { pools, loading, error, isStale };
}

function generateSyntheticTicks(): TickData[] {
Expand Down
8 changes: 6 additions & 2 deletions apps/web/hooks/usePools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ interface UsePoolsParams {
}

export function usePools({ page, orderBy, search }: UsePoolsParams) {
return useQuery<PoolsResponse>({
const query = useQuery<PoolsResponse>({
queryKey: ['pools', page, orderBy, search],
queryFn: async () => {
const params = new URLSearchParams({
Expand All @@ -45,7 +45,11 @@ export function usePools({ page, orderBy, search }: UsePoolsParams) {
if (!res.ok) throw new Error('Failed to fetch pools');
return res.json();
},
refetchInterval: 30_000,
placeholderData: (prev) => prev,
refetchInterval: 30_000,
});

const isStale = query.data === undefined && !query.isLoading;

return { ...query, isStale };
}