Skip to content

Commit 829c900

Browse files
authored
fix: show pending transactions confirming without a stale reload (#2867)
* fix: show pending transactions confirming without a stale reload * fix: scope tx cache by API and keep polling through transient failures
1 parent 2f0aaf5 commit 829c900

8 files changed

Lines changed: 344 additions & 19 deletions

File tree

‎src/api/__tests__/data-fetchers.test.ts‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,11 @@ test('holders and supply fetchers skip invalid asset identifiers', async () => {
4444
expect(fetchJsonMock).not.toHaveBeenCalled();
4545
});
4646

47+
const MINED_TX = { tx_id: '0x01', status: 'success', block: { height: 100 } };
48+
const PENDING_TX = { tx_id: '0x01', status: 'pending', receipt_time: 1700000000 };
49+
4750
test('fetchTx reads the v3 transaction, requesting the given heavy fields', async () => {
48-
const tx = { tx_id: '0x01' };
51+
const tx = MINED_TX;
4952
fetchMock.mockResolvedValue(new Response(JSON.stringify(tx)));
5053

5154
await expect(
@@ -62,7 +65,7 @@ test('fetchTx reads the v3 transaction, requesting the given heavy fields', asyn
6265
});
6366

6467
test('fetchTx omits the include parameter when no heavy fields are requested', async () => {
65-
fetchMock.mockResolvedValue(new Response('{}'));
68+
fetchMock.mockResolvedValue(new Response(JSON.stringify(MINED_TX)));
6669

6770
await fetchTx('https://api.hiro.so', '0x01');
6871
expect(fetchMock.mock.calls[0][0]).toBe('https://api.hiro.so/extended/v3/transactions/0x01');
@@ -85,3 +88,39 @@ test('fetchTxEvents reads the first page of v3 transaction events', async () =>
8588
'https://api.hiro.so/extended/v3/transactions/0x01/events?limit=100'
8689
);
8790
});
91+
92+
test('fetchTx serves a mined transaction from the data cache', async () => {
93+
fetchMock.mockResolvedValue(new Response(JSON.stringify(MINED_TX)));
94+
95+
await expect(fetchTx('https://api.hiro.so', '0x01')).resolves.toEqual(MINED_TX);
96+
expect(fetchMock).toHaveBeenCalledTimes(1);
97+
expect(fetchMock.mock.calls[0][1]).toMatchObject({
98+
cache: 'default',
99+
next: { revalidate: 3, tags: ['tx-id-0x01'] },
100+
});
101+
});
102+
103+
test('fetchTx re-reads a cached pending transaction without the cache', async () => {
104+
fetchMock
105+
.mockResolvedValueOnce(new Response(JSON.stringify(PENDING_TX)))
106+
.mockResolvedValueOnce(new Response(JSON.stringify(MINED_TX)));
107+
108+
await expect(
109+
fetchTx('https://api.hiro.so', '0x01', { include: ['result'], redirect: 'error' })
110+
).resolves.toEqual(MINED_TX);
111+
expect(fetchMock).toHaveBeenCalledTimes(2);
112+
expect(fetchMock.mock.calls[1][0]).toBe(
113+
'https://api.hiro.so/extended/v3/transactions/0x01?include=result'
114+
);
115+
expect(fetchMock.mock.calls[1][1]).toEqual({ redirect: 'error', cache: 'no-store' });
116+
});
117+
118+
test('fetchTx surfaces a failed uncached re-read as an ApiError', async () => {
119+
fetchMock
120+
.mockResolvedValueOnce(new Response(JSON.stringify(PENDING_TX)))
121+
.mockResolvedValueOnce(new Response('{}', { status: 404, statusText: 'Not Found' }));
122+
123+
const error = await fetchTx('https://api.hiro.so', '0x01').catch(e => e);
124+
expect(error).toBeInstanceOf(ApiError);
125+
expect(error).toMatchObject({ status: 404, endpoint: '/extended/v3/transactions/{tx_id}' });
126+
});

‎src/api/data-fetchers.ts‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -260,24 +260,32 @@ export async function fetchTx(
260260
): Promise<TxDetails> {
261261
const { include, ...requestOptions } = options;
262262
const query = include?.length ? `?include=${include.join(',')}` : '';
263-
const response = await stacksAPIFetch(`${apiUrl}/extended/v3/transactions/${txId}${query}`, {
264-
...requestOptions,
263+
const url = `${apiUrl}/extended/v3/transactions/${txId}${query}`;
264+
const readTx = async (init: RequestInit): Promise<TxDetails> => {
265+
const response = await stacksAPIFetch(url, { ...requestOptions, ...init });
266+
if (!response.ok) {
267+
throw new ApiError({
268+
message: `Failed to fetch transaction: ${response.status} ${response.statusText}`,
269+
status: response.status,
270+
endpoint: '/extended/v3/transactions/{tx_id}',
271+
method: 'GET',
272+
});
273+
}
274+
return response.json();
275+
};
276+
277+
const tx = await readTx({
265278
cache: 'default',
266279
next: {
267280
revalidate: CONFIRMED_TX_REVALIDATION_TIMEOUT_IN_SECONDS,
268281
tags: [getTxTag(txId)],
269282
},
270283
});
271-
if (!response.ok) {
272-
throw new ApiError({
273-
message: `Failed to fetch transaction: ${response.status} ${response.statusText}`,
274-
status: response.status,
275-
endpoint: '/extended/v3/transactions/{tx_id}',
276-
method: 'GET',
277-
});
278-
}
279-
const tx: TxDetails = await response.json();
280-
return tx;
284+
// Next serves a stale cache entry before revalidating it, so a cached copy can still be pending
285+
// after the transaction was mined. Mined transactions are final (barring reorgs) and safe to
286+
// serve from the cache; a pending one is re-read so the page doesn't lag behind the API.
287+
if ('block' in tx) return tx;
288+
return readTx({ cache: 'no-store' });
281289
}
282290

283291
export async function fetchTxEvents(

‎src/app/txid/[txId]/PageClient.tsx‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
'use client';
22

33
import { TxTableFiltersProvider } from '@/common/components/table/tx-table/useTxTableFilters';
4+
import { PENDING_TX_REFETCH_INTERVAL_MS } from '@/common/constants/env';
45
import { useTxById } from '@/common/queries/useTxById';
6+
import { TxDetails } from '@/common/types/tx-v3';
7+
import { getPendingTxRefetchInterval } from '@/common/utils/tx-details-utils';
58
import { Text } from '@/ui/Text';
69
import { Flex, Spinner } from '@chakra-ui/react';
10+
import { Query } from '@tanstack/react-query';
711

812
import { useTxIdPageData } from './TxIdPageContext';
913
import { CoinbasePage as CoinbasePageRedesign } from './redesign/CoinbasePage';
@@ -14,18 +18,33 @@ import { TokenTransferPage as TokenTransferPageRedesign } from './redesign/Token
1418

1519
function TransactionIdPage() {
1620
const { initialTxData, filters, txId } = useTxIdPageData();
17-
const { data: clientTxData, isLoading, error } = useTxById(txId, { enabled: !initialTxData });
18-
const tx = initialTxData || clientTxData;
21+
// Seeded with the server-rendered transaction and re-read while it's pending, so the page shows
22+
// the confirmation without a reload. On the contract-ID route, the transaction is the deploy.
23+
const {
24+
data: clientTxData,
25+
isLoading,
26+
error,
27+
} = useTxById(initialTxData?.tx_id ?? txId, {
28+
initialData: initialTxData,
29+
refetchInterval: (query: Query<TxDetails>) =>
30+
getPendingTxRefetchInterval(
31+
query.state.data,
32+
query.state.error,
33+
PENDING_TX_REFETCH_INTERVAL_MS
34+
),
35+
});
36+
const tx = clientTxData ?? initialTxData;
1937

20-
if (!initialTxData && isLoading) {
38+
if (!tx && isLoading) {
2139
return (
2240
<Flex align="center" justify="center" py={20}>
2341
<Spinner size="lg" />
2442
</Flex>
2543
);
2644
}
2745

28-
if (!initialTxData && error) {
46+
// A failed re-read keeps showing the last known transaction.
47+
if (!tx && error) {
2948
return (
3049
<Flex align="center" justify="center" py={20} direction="column" gap={4}>
3150
<Text color="error">Failed to load transaction</Text>
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
import { useApiClient } from '@/api/useApiClient';
2+
import { TxDetails } from '@/common/types/tx-v3';
3+
import { system } from '@/ui/theme/theme';
4+
import { ChakraProvider } from '@chakra-ui/react';
5+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
6+
import '@testing-library/jest-dom';
7+
import { act, render, screen } from '@testing-library/react';
8+
import { ReactNode } from 'react';
9+
10+
import TransactionIdPage from '../PageClient';
11+
import { TxIdPageDataProvider } from '../TxIdPageContext';
12+
13+
jest.mock('@/api/useApiClient');
14+
jest.mock('@/common/context/useGlobalContext', () => ({
15+
useGlobalContext: () => ({ activeNetwork: { url: mockActiveApiUrl } }),
16+
}));
17+
jest.mock('@/common/components/table/tx-table/useTxTableFilters', () => ({
18+
TxTableFiltersProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
19+
}));
20+
jest.mock('../redesign/TokenTransferPage', () => ({
21+
TokenTransferPage: ({ tx }: { tx: TxDetails }) => <div>status: {tx.status}</div>,
22+
}));
23+
24+
const TX_ID = '0x44c64a8975bdd4b2f6eef4b0d1ac1203ce6f67fe0e4490289495727de8f311f3';
25+
const transfer = {
26+
recipient: 'SP3FBR2AGK5H9QBDH3EEN6DF8EK8JY7RX8QJ5SVTE',
27+
amount: '1',
28+
memo: null,
29+
};
30+
const pendingTx = {
31+
tx_id: TX_ID,
32+
type: 'token_transfer',
33+
status: 'pending',
34+
receipt_time: 1700000000,
35+
token_transfer: transfer,
36+
} as unknown as TxDetails;
37+
const minedTx = {
38+
tx_id: TX_ID,
39+
type: 'token_transfer',
40+
status: 'success',
41+
block: { height: 100, hash: '0xblock', index_hash: '0xindex', time: 1700000100, tx_index: 0 },
42+
bitcoin_block: { height: 800, hash: '0xbtc', time: 1700000000 },
43+
token_transfer: transfer,
44+
} as unknown as TxDetails;
45+
46+
const mockClient = { GET: jest.fn() };
47+
let mockActiveApiUrl = 'https://api.hiro.so';
48+
49+
const ok = (data: TxDetails) => ({ data, error: undefined });
50+
const failure = (status: number) => ({
51+
data: undefined,
52+
error: { error: `HTTP ${status}` },
53+
response: { status },
54+
});
55+
56+
function newQueryClient() {
57+
return new QueryClient({ defaultOptions: { queries: { retry: false } } });
58+
}
59+
60+
function renderPage(initialTxData: TxDetails | undefined, queryClient = newQueryClient()) {
61+
return render(
62+
<ChakraProvider value={system}>
63+
<QueryClientProvider client={queryClient}>
64+
<TxIdPageDataProvider
65+
txId={TX_ID}
66+
initialTxData={initialTxData}
67+
filters={{
68+
fromAddress: '',
69+
toAddress: '',
70+
startTime: '',
71+
endTime: '',
72+
transactionType: [],
73+
}}
74+
>
75+
<TransactionIdPage />
76+
</TxIdPageDataProvider>
77+
</QueryClientProvider>
78+
</ChakraProvider>
79+
);
80+
}
81+
82+
async function advance(ms: number) {
83+
await act(async () => {
84+
await jest.advanceTimersByTimeAsync(ms);
85+
});
86+
}
87+
88+
beforeEach(() => {
89+
jest.useFakeTimers();
90+
mockActiveApiUrl = 'https://api.hiro.so';
91+
mockClient.GET.mockReset();
92+
jest.mocked(useApiClient).mockReturnValue(mockClient as never);
93+
});
94+
95+
afterEach(() => {
96+
jest.useRealTimers();
97+
});
98+
99+
test('re-reads a pending transaction until it is mined, without a reload', async () => {
100+
mockClient.GET.mockResolvedValueOnce({ data: pendingTx, error: undefined }).mockResolvedValue({
101+
data: minedTx,
102+
error: undefined,
103+
});
104+
renderPage(pendingTx);
105+
106+
expect(screen.getByText('status: pending')).toBeInTheDocument();
107+
// The server-rendered transaction is used as is; nothing is fetched on mount.
108+
expect(mockClient.GET).not.toHaveBeenCalled();
109+
110+
await advance(10_000);
111+
expect(screen.getByText('status: pending')).toBeInTheDocument();
112+
await advance(10_000);
113+
expect(await screen.findByText('status: success')).toBeInTheDocument();
114+
expect(mockClient.GET).toHaveBeenCalledTimes(2);
115+
expect(mockClient.GET).toHaveBeenLastCalledWith('/extended/v3/transactions/{tx_id}', {
116+
params: {
117+
path: { tx_id: TX_ID },
118+
query: { include: ['function_args', 'post_conditions', 'result'] },
119+
},
120+
});
121+
122+
// Mined transactions are final, so polling stops.
123+
await advance(60_000);
124+
expect(mockClient.GET).toHaveBeenCalledTimes(2);
125+
});
126+
127+
test('never re-reads a transaction that was already mined', async () => {
128+
renderPage(minedTx);
129+
130+
await advance(60_000);
131+
expect(screen.getByText('status: success')).toBeInTheDocument();
132+
expect(mockClient.GET).not.toHaveBeenCalled();
133+
});
134+
135+
test('keeps the last known transaction and stops polling once the transaction is gone', async () => {
136+
mockClient.GET.mockResolvedValue(failure(404));
137+
renderPage(pendingTx);
138+
139+
await advance(10_000);
140+
expect(screen.getByText('status: pending')).toBeInTheDocument();
141+
await advance(60_000);
142+
expect(mockClient.GET).toHaveBeenCalledTimes(1);
143+
});
144+
145+
test('keeps polling through transient failures until the transaction is mined', async () => {
146+
mockClient.GET.mockResolvedValueOnce(failure(503))
147+
.mockResolvedValueOnce(failure(429))
148+
.mockResolvedValue(ok(minedTx));
149+
renderPage(pendingTx);
150+
151+
await advance(10_000);
152+
await advance(10_000);
153+
expect(screen.getByText('status: pending')).toBeInTheDocument();
154+
await advance(10_000);
155+
expect(await screen.findByText('status: success')).toBeInTheDocument();
156+
expect(mockClient.GET).toHaveBeenCalledTimes(3);
157+
});
158+
159+
test('keeps a transaction loaded in the browser when a later re-read fails', async () => {
160+
// Server rendering disabled or failed: the page loads the transaction itself.
161+
mockClient.GET.mockResolvedValueOnce(ok(pendingTx)).mockResolvedValue(failure(404));
162+
renderPage(undefined);
163+
164+
expect(await screen.findByText('status: pending')).toBeInTheDocument();
165+
await advance(10_000);
166+
expect(mockClient.GET).toHaveBeenCalledTimes(2);
167+
expect(screen.getByText('status: pending')).toBeInTheDocument();
168+
expect(screen.queryByText('Failed to load transaction')).not.toBeInTheDocument();
169+
});
170+
171+
test('shows the server result for another API instead of the previous API cached copy', async () => {
172+
const queryClient = newQueryClient();
173+
const first = renderPage(minedTx, queryClient);
174+
expect(screen.getByText('status: success')).toBeInTheDocument();
175+
first.unmount();
176+
177+
// Same transaction ID through a different API (e.g. `?api=`), with the cache still populated.
178+
mockActiveApiUrl = 'https://api.example.test';
179+
renderPage(pendingTx, queryClient);
180+
181+
expect(screen.getByText('status: pending')).toBeInTheDocument();
182+
});

‎src/common/constants/env.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ export const TESTNET_BTC_ADDRESS_BASE_URL =
2323
process.env.NEXT_PUBLIC_TESTNET_BTC_ADDRESS_BASE_URL ||
2424
'https://mempool.bitcoin.regtest.hiro.so/address';
2525

26+
// How often an open transaction page re-reads a transaction that is still pending.
27+
export const PENDING_TX_REFETCH_INTERVAL_MS =
28+
Number(process.env.NEXT_PUBLIC_PENDING_TX_REFETCH_INTERVAL_MS) || 10_000;
29+
2630
export const DEVNET_PORT = process.env.NEXT_PUBLIC_EXPLORER_DEVNET_PORT || '8000';
2731
export const DEVNET_SERVER =
2832
process.env.NEXT_PUBLIC_EXPLORER_DEVNET_SERVER || 'http://localhost:3999';

‎src/common/queries/useTxById.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,15 @@ import { UseQueryResult, useQuery } from '@tanstack/react-query';
44

55
import { callApiWithErrorHandling } from '../../api/callApiWithErrorHandling';
66
import { useApiClient } from '../../api/useApiClient';
7+
import { useGlobalContext } from '../context/useGlobalContext';
78

89
export function useTxById(txId?: string, options: any = {}): UseQueryResult<TxDetails> {
910
const apiClient = useApiClient();
11+
const { activeNetwork } = useGlobalContext();
1012

1113
return useQuery({
12-
queryKey: ['txById', txId],
14+
// Keyed by API too: the same transaction can differ between APIs (e.g. `?api=` overrides).
15+
queryKey: ['txById', activeNetwork.url, txId],
1316
queryFn: async () => {
1417
if (!txId) return undefined;
1518

0 commit comments

Comments
 (0)