diff --git a/src/api/dapi.ts b/src/api/dapi.ts index 0ec275e..3b72a7c 100644 --- a/src/api/dapi.ts +++ b/src/api/dapi.ts @@ -2,9 +2,10 @@ * Client for InstantSend lock retrieval via JSON-RPC API */ -import { withRetry, type RetryOptions } from '../utils/retry.js'; +import { withRetry, isRetryableError, type RetryOptions } from '../utils/retry.js'; import { describeIslock } from '../utils/islock-debug.js'; import { abortableSleep } from '../utils/sleep.js'; +import { fetchJson } from '../utils/fetch-json.js'; const API_URLS: Record = { testnet: 'https://trpc.digitalcash.dev', @@ -80,29 +81,60 @@ export class DAPIClient { onRetry?: (attempt: number, maxAttempts: number, error: unknown) => void, signal?: AbortSignal ): Promise { - const startTime = Date.now(); const pollInterval = 2000; // Poll every 2 seconds - while (Date.now() - startTime < timeoutMs) { - if (signal?.aborted) { - throw new Error(`InstantSend lock polling aborted for ${txid}`); - } - try { - const islock = await this.getIslock(txid, { onRetry }); - if (islock) { - return islock; + // `stop` fires on the overall deadline or a caller abort. It cancels the + // in-flight request and the poll sleep, and `stopped` settles the wait at + // that moment (even mid-backoff inside withRetry), so a stalled RPC server + // cannot hold the wait past `timeoutMs` and keep the chain-lock fallback + // unreachable. + const stop = new AbortController(); + const abort = () => stop.abort(); + if (signal?.aborted) abort(); + signal?.addEventListener('abort', abort, { once: true }); + const deadlineTimer = setTimeout(abort, timeoutMs); + const stopped = new Promise((_, reject) => { + const fail = () => + reject( + new Error( + signal?.aborted + ? `InstantSend lock polling aborted for ${txid}` + : `Timeout waiting for InstantSend lock for ${txid} after ${timeoutMs}ms` + ) + ); + if (stop.signal.aborted) fail(); + else stop.signal.addEventListener('abort', fail, { once: true }); + }); + const retryOptions: RetryOptions = { + onRetry, + shouldRetry: (error) => !stop.signal.aborted && isRetryableError(error), + }; + + const poll = async (): Promise => { + while (!stop.signal.aborted) { + try { + const islock = await this.getIslock(txid, retryOptions, stop.signal); + if (islock) { + return islock; + } + } catch (error) { + if (!stop.signal.aborted) { + console.warn('Error polling for islock:', error); + } } - } catch (error) { - console.warn('Error polling for islock:', error); - } - // Wait before next poll, but bail out immediately if aborted - await abortableSleep(pollInterval, signal); + // Wait before next poll, but bail out immediately on deadline/abort + await abortableSleep(pollInterval, stop.signal); + } + return stopped; + }; + + try { + return await Promise.race([poll(), stopped]); + } finally { + clearTimeout(deadlineTimer); + signal?.removeEventListener('abort', abort); } - - throw new Error( - `Timeout waiting for InstantSend lock for ${txid} after ${timeoutMs}ms` - ); } /** @@ -120,17 +152,11 @@ export class DAPIClient { return null; } - const response = await fetch(baseUrl, { + const data: BestChainLockResponse = await fetchJson(baseUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ method: 'getbestchainlock', params: [] }), }); - - if (!response.ok) { - throw new Error(`RPC API error: ${response.status} ${response.statusText}`); - } - - const data: BestChainLockResponse = await response.json(); if (!data.result || typeof data.result.height !== 'number') { return null; } @@ -141,14 +167,18 @@ export class DAPIClient { /** * Fetch islock from JSON-RPC API */ - private async getIslock(txid: string, retryOptions?: RetryOptions): Promise { + private async getIslock( + txid: string, + retryOptions?: RetryOptions, + signal?: AbortSignal + ): Promise { return withRetry(async () => { const baseUrl = this.rpcUrl ?? API_URLS[this.network]; if (!baseUrl) { throw new Error(`No RPC URL configured for network ${this.network}`); } - const response = await fetch(baseUrl, { + const data: IslockResponse = await fetchJson(baseUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -157,14 +187,9 @@ export class DAPIClient { method: 'getislocks', params: [[txid]], }), + signal, }); - if (!response.ok) { - throw new Error(`RPC API error: ${response.status} ${response.statusText}`); - } - - const data: IslockResponse = await response.json(); - // Check if we got a result if (data.result && data.result.length > 0) { const islockData = data.result.find((item) => item.txid === txid); diff --git a/src/api/faucet.ts b/src/api/faucet.ts index be9e3b9..7301e6f 100644 --- a/src/api/faucet.ts +++ b/src/api/faucet.ts @@ -2,6 +2,8 @@ * Faucet API client with CAP (proof-of-work) support */ +import { fetchWithDeadline, RequestTimeoutError } from '../utils/fetch-with-deadline.js'; + // Declare the global Cap class from @cap.js/widget declare const Cap: { new (options: { apiEndpoint: string }): { @@ -28,29 +30,23 @@ export interface FaucetResponse { } /** - * Create a fetch request with timeout support + * Fetch with one timeout covering both the response headers and the body + * read performed by `read`. Never retried automatically, so a timed-out + * faucet POST cannot be re-sent without the user asking again. */ -async function fetchWithTimeout( +async function fetchWithTimeout( url: string, - options: RequestInit = {}, + options: RequestInit, + read: (response: Response) => Promise, timeoutMs: number = REQUEST_TIMEOUT_MS -): Promise { - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), timeoutMs); - +): Promise { try { - const response = await fetch(url, { - ...options, - signal: controller.signal, - }); - return response; + return await fetchWithDeadline(url, options, timeoutMs, read); } catch (error) { - if (error instanceof Error && error.name === 'AbortError') { + if (error instanceof RequestTimeoutError) { throw new Error('Request timed out. Please try again.'); } throw error; - } finally { - clearTimeout(timeoutId); } } @@ -90,13 +86,13 @@ function extractErrorMessage(errorData: unknown, fallbackStatus: number): string * Fetch faucet status to check if CAP is required */ export async function getFaucetStatus(baseUrl: string): Promise { - const response = await fetchWithTimeout(`${baseUrl}/api/status`); - - if (!response.ok) { - throw new Error(`Failed to fetch faucet status: ${response.status}`); - } + return fetchWithTimeout(`${baseUrl}/api/status`, {}, async (response) => { + if (!response.ok) { + throw new Error(`Failed to fetch faucet status: ${response.status}`); + } - return response.json(); + return response.json(); + }); } /** @@ -205,29 +201,44 @@ export async function requestTestnetFunds( body.capToken = capToken; } - const response = await fetchWithTimeout(`${baseUrl}/api/core-faucet`, { + const init: RequestInit = { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(body), - }); + }; - if (!response.ok) { - const errorData = await response.json().catch(() => ({})); + // Once the faucet answers 2xx it has most likely sent funds, so a failed + // body read must not invite the user to request again. + let accepted = false; + try { + return await fetchWithTimeout(`${baseUrl}/api/core-faucet`, init, async (response) => { + if (!response.ok) { + const errorData = await response.json().catch(() => ({})); + + if (response.status === 429) { + const data = errorData as Record; + const retryAfter = typeof data.retryAfter === 'number' ? data.retryAfter : undefined; + if (retryAfter) { + const minutes = Math.ceil(retryAfter / 60); + throw new Error(`Rate limit exceeded. Try again in ${minutes} minute${minutes !== 1 ? 's' : ''}.`); + } + throw new Error('Rate limit exceeded. Please try again later.'); + } - if (response.status === 429) { - const data = errorData as Record; - const retryAfter = typeof data.retryAfter === 'number' ? data.retryAfter : undefined; - if (retryAfter) { - const minutes = Math.ceil(retryAfter / 60); - throw new Error(`Rate limit exceeded. Try again in ${minutes} minute${minutes !== 1 ? 's' : ''}.`); + throw new Error(extractErrorMessage(errorData, response.status)); } - throw new Error('Rate limit exceeded. Please try again later.'); - } - throw new Error(extractErrorMessage(errorData, response.status)); + accepted = true; + return response.json(); + }); + } catch (error) { + if (accepted) { + throw new Error( + 'The faucet accepted the request but its reply did not complete. Funds may already be on the way; wait for the deposit before requesting again.' + ); + } + throw error; } - - return response.json(); } diff --git a/src/api/insight.ts b/src/api/insight.ts index 33e75d2..4220baa 100644 --- a/src/api/insight.ts +++ b/src/api/insight.ts @@ -1,7 +1,27 @@ import type { UTXO, TxInfo } from '../types.js'; import type { NetworkConfig } from '../config.js'; -import { withRetry, type RetryOptions } from '../utils/retry.js'; +import { withRetry, isRetryableError, type RetryOptions } from '../utils/retry.js'; import { abortableSleep } from '../utils/sleep.js'; +import { fetchJson } from '../utils/fetch-json.js'; +import { fetchWithDeadline, RequestTimeoutError } from '../utils/fetch-with-deadline.js'; + +/** + * Broadcast POSTs get a longer deadline than reads. A timed-out broadcast may + * be retried by withRetry; re-sending the same signed tx is harmless while it + * is unconfirmed, but a retry after it was mined is rejected with + * "already in block chain" (see isAmbiguousBroadcastError). + */ +const BROADCAST_TIMEOUT_MS = 20000; + +/** + * Whether a broadcast error leaves the outcome unknown rather than failed: + * a timeout may have reached the node, and "already in block chain" means an + * earlier timed-out attempt of the same signed tx was mined. + */ +export function isAmbiguousBroadcastError(error: unknown): boolean { + if (error instanceof RequestTimeoutError) return true; + return error instanceof Error && error.message.includes('already in block chain'); +} export interface InsightApiResponse { success: boolean; @@ -24,13 +44,7 @@ export class InsightClient { */ async getUTXOs(address: string, retryOptions?: RetryOptions): Promise { return withRetry(async () => { - const response = await fetch(`${this.baseUrl}/addr/${address}/utxo`); - - if (!response.ok) { - throw new Error(`Insight API error: ${response.status} ${response.statusText}`); - } - - const data = await response.json(); + const data = await fetchJson(`${this.baseUrl}/addr/${address}/utxo`); // Map Insight API response to our UTXO type return data.map((utxo: Record) => ({ @@ -50,13 +64,7 @@ export class InsightClient { */ async getBlockHeight(retryOptions?: RetryOptions): Promise { return withRetry(async () => { - const response = await fetch(`${this.baseUrl}/status?q=getInfo`); - - if (!response.ok) { - throw new Error(`Insight API error: ${response.status} ${response.statusText}`); - } - - const data = await response.json(); + const data = await fetchJson(`${this.baseUrl}/status?q=getInfo`); const blocks = data?.info?.blocks; if (typeof blocks !== 'number') { throw new Error('Insight getInfo response missing info.blocks'); @@ -70,20 +78,24 @@ export class InsightClient { */ async broadcastTransaction(txHex: string, retryOptions?: RetryOptions): Promise { return withRetry(async () => { - const response = await fetch(`${this.baseUrl}/tx/send`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', + const result = await fetchWithDeadline( + `${this.baseUrl}/tx/send`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ rawtx: txHex }), }, - body: JSON.stringify({ rawtx: txHex }), - }); - - if (!response.ok) { - const errorText = await response.text(); - throw new Error(`Broadcast failed: ${response.status} - ${errorText}`); - } - - const result = await response.json(); + BROADCAST_TIMEOUT_MS, + async (response) => { + if (!response.ok) { + const errorText = await response.text(); + throw new Error(`Broadcast failed: ${response.status} - ${errorText}`); + } + return response.json(); + } + ); return result.txid; }, retryOptions); } @@ -91,15 +103,9 @@ export class InsightClient { /** * Get transaction details */ - async getTransaction(txid: string, retryOptions?: RetryOptions): Promise { + async getTransaction(txid: string, retryOptions?: RetryOptions, signal?: AbortSignal): Promise { return withRetry(async () => { - const response = await fetch(`${this.baseUrl}/tx/${txid}`); - - if (!response.ok) { - throw new Error(`Failed to get transaction: ${response.status}`); - } - - const data = await response.json(); + const data = await fetchJson(`${this.baseUrl}/tx/${txid}`, { signal }); // Insight returns blockheight: -1 while the tx is unconfirmed. const rawHeight = @@ -131,7 +137,12 @@ export class InsightClient { ): Promise { while (!signal?.aborted) { try { - const info = await this.getTransaction(txid); + // Don't burn backoff retries on a request the caller cancelled. + const info = await this.getTransaction( + txid, + { shouldRetry: (error) => !signal?.aborted && isRetryableError(error) }, + signal + ); onPoll?.(info); if (info.blockheight !== undefined) { return info.blockheight; diff --git a/src/api/request-deadlines.test.ts b/src/api/request-deadlines.test.ts new file mode 100644 index 0000000..31d3a38 --- /dev/null +++ b/src/api/request-deadlines.test.ts @@ -0,0 +1,206 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +// Keep the real JSON-RPC DAPIClient but avoid loading @dashevo/dapi-client. +vi.mock('./dapi-subscription.js', () => ({ + DAPISubscriptionClient: vi.fn().mockImplementation(() => ({})), +})); + +import { InsightClient, isAmbiguousBroadcastError } from './insight.js'; +import { RequestTimeoutError } from '../utils/fetch-with-deadline.js'; +import { DAPIClient } from './dapi.js'; +import { IslockService } from './islock.js'; +import { getFaucetStatus, requestTestnetFunds } from './faucet.js'; +import type { NetworkConfig } from '../config.js'; + +function onAbort(signal: AbortSignal | null | undefined, reject: (reason: unknown) => void): void { + if (!signal) return; + if (signal.aborted) reject(signal.reason); + signal.addEventListener('abort', () => reject(signal.reason), { once: true }); +} + +function stalledHeaders() { + return vi.fn((_url: string, init?: RequestInit) => new Promise((_, reject) => onAbort(init?.signal, reject))); +} + +function stalledBody(status = 200) { + return vi.fn(async (_url: string, init?: RequestInit) => { + const never = () => new Promise((_, reject) => onAbort(init?.signal, reject)); + return { ok: status < 400, status, statusText: 'X', json: never, text: never } as unknown as Response; + }); +} + +const insight = new InsightClient({ insightApiUrl: 'https://insight.test/api' } as NetworkConfig); + +/** Track settlement without tripping unhandled-rejection warnings. */ +function track(promise: Promise): { promise: Promise; settled: () => boolean } { + let settled = false; + promise.then( + () => (settled = true), + () => (settled = true) + ); + return { promise, settled: () => settled }; +} + +describe('per-request deadlines', () => { + beforeEach(() => { + vi.useFakeTimers(); + vi.spyOn(Math, 'random').mockReturnValue(0); // deterministic retry backoff + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); + + it('Insight UTXO lookup times out instead of hanging deposit detection', async () => { + vi.stubGlobal('fetch', stalledHeaders()); + const expectation = expect(insight.getUTXOs('yAddr', { maxAttempts: 1 })).rejects.toMatchObject({ + name: 'AbortError', + }); + await vi.advanceTimersByTimeAsync(8000); + await expectation; + }); + + it('Insight broadcast bounds the error-body text read', async () => { + vi.stubGlobal('fetch', stalledBody(400)); + const expectation = expect(insight.broadcastTransaction('00', { maxAttempts: 1 })).rejects.toThrow( + 'Request timeout after 20000ms' + ); + await vi.advanceTimersByTimeAsync(20_000); + await expectation; + }); + + it('Insight broadcast keeps the server error text', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('bad-txns-in-belowout', { status: 400 })) + ); + await expect(insight.broadcastTransaction('00', { maxAttempts: 1 })).rejects.toThrow( + 'Broadcast failed: 400 - bad-txns-in-belowout' + ); + }); + + it('block-height polling forwards its abort signal to the in-flight request', async () => { + const fetchMock = stalledHeaders(); + vi.stubGlobal('fetch', fetchMock); + const controller = new AbortController(); + const polling = track(insight.waitForBlockHeight('tx', 5000, controller.signal)); + await vi.advanceTimersByTimeAsync(10); + controller.abort(); + expect(fetchMock.mock.calls[0][1]?.signal?.aborted).toBe(true); + await vi.advanceTimersByTimeAsync(0); + // Settles right away: no backoff retries for a cancelled request. + await expect(polling.promise).rejects.toThrow('Block-height polling aborted'); + expect(fetchMock).toHaveBeenCalledOnce(); + }); + + it('JSON-RPC IS-lock wait rejects at its deadline when getislocks stalls', async () => { + const fetchMock = stalledHeaders(); + vi.stubGlobal('fetch', fetchMock); + const onRetry = vi.fn(); + const service = new IslockService({ network: 'mainnet' }); + const handle = await service.subscribeForInstantSendLock( + 'txid', + new Uint8Array([1]), + { txid: 'prev', vout: 0 }, + 60_000, + onRetry + ); + const wait = track(handle.wait()); + + await vi.advanceTimersByTimeAsync(59_999); + expect(wait.settled()).toBe(false); + // Stalled requests were cut off at 8s and retried, not left hanging. + expect(fetchMock.mock.calls.length).toBeGreaterThan(1); + expect(onRetry).toHaveBeenCalled(); + + await vi.advanceTimersByTimeAsync(1); + await expect(wait.promise).rejects.toThrow('Timeout waiting for InstantSend lock for txid after 60000ms'); + // The in-flight request was cancelled at the deadline. + expect(fetchMock.mock.lastCall?.[1]?.signal?.aborted).toBe(true); + }); + + it('JSON-RPC IS-lock wait rejects at its deadline when the response body stalls', async () => { + vi.stubGlobal('fetch', stalledBody()); + const client = new DAPIClient({ network: 'testnet' }); + const wait = track(client.waitForInstantSendLock('txid', 30_000)); + + await vi.advanceTimersByTimeAsync(29_999); + expect(wait.settled()).toBe(false); + await vi.advanceTimersByTimeAsync(1); + await expect(wait.promise).rejects.toThrow('Timeout waiting for InstantSend lock'); + }); + + it('JSON-RPC IS-lock wait rejects at its deadline even mid retry backoff', async () => { + vi.stubGlobal('fetch', stalledHeaders()); + const client = new DAPIClient({ network: 'testnet' }); + // First request times out at 8s, then withRetry backs off 1s: 8.5s lands in the backoff. + const wait = track(client.waitForInstantSendLock('txid', 8500)); + + await vi.advanceTimersByTimeAsync(8499); + expect(wait.settled()).toBe(false); + await vi.advanceTimersByTimeAsync(1); + await expect(wait.promise).rejects.toThrow('Timeout waiting for InstantSend lock for txid after 8500ms'); + }); + + it('JSON-RPC IS-lock wait forwards a caller abort to the in-flight request', async () => { + const fetchMock = stalledHeaders(); + vi.stubGlobal('fetch', fetchMock); + const controller = new AbortController(); + const client = new DAPIClient({ network: 'testnet' }); + const wait = track(client.waitForInstantSendLock('txid', 60_000, undefined, controller.signal)); + + await vi.advanceTimersByTimeAsync(10); + controller.abort(); + await vi.advanceTimersByTimeAsync(0); + expect(fetchMock.mock.calls[0][1]?.signal?.aborted).toBe(true); + await expect(wait.promise).rejects.toThrow('InstantSend lock polling aborted for txid'); + }); + + it('faucet status read times out with the existing user-facing message', async () => { + vi.stubGlobal('fetch', stalledBody()); + const expectation = expect(getFaucetStatus('https://faucet.test')).rejects.toThrow( + 'Request timed out. Please try again.' + ); + await vi.advanceTimersByTimeAsync(30_000); + await expectation; + }); + + it('faucet POST times out before headers with the existing message', async () => { + vi.stubGlobal('fetch', stalledHeaders()); + const expectation = expect(requestTestnetFunds('https://faucet.test', 'yAddr')).rejects.toThrow( + 'Request timed out. Please try again.' + ); + await vi.advanceTimersByTimeAsync(30_000); + await expectation; + }); + + it('faucet POST bounds the body read, warns funds may be sent, and is not retried', async () => { + const fetchMock = stalledBody(); + vi.stubGlobal('fetch', fetchMock); + const expectation = expect(requestTestnetFunds('https://faucet.test', 'yAddr')).rejects.toThrow( + 'wait for the deposit before requesting again' + ); + await vi.advanceTimersByTimeAsync(30_000); + await expectation; + await vi.runAllTimersAsync(); + expect(fetchMock).toHaveBeenCalledOnce(); + }); +}); + +describe('isAmbiguousBroadcastError', () => { + it('treats a timed-out or already-mined broadcast as unknown, not failed', () => { + expect(isAmbiguousBroadcastError(new RequestTimeoutError(20000))).toBe(true); + expect( + isAmbiguousBroadcastError(new Error('Broadcast failed: 400 - transaction already in block chain')) + ).toBe(true); + }); + + it('keeps definite rejections as failures', () => { + expect(isAmbiguousBroadcastError(new Error('Broadcast failed: 400 - 16: bad-txns-inputs-spent'))).toBe(false); + expect(isAmbiguousBroadcastError(new Error('API error: 500 Internal Server Error'))).toBe(false); + expect(isAmbiguousBroadcastError('nope')).toBe(false); + }); +}); diff --git a/src/main.ts b/src/main.ts index b90469e..a93f485 100644 --- a/src/main.ts +++ b/src/main.ts @@ -9,7 +9,7 @@ import { import { extractErrorMessage } from './utils/errors.js'; import { deriveAssetLockKeyPair } from './crypto/hd.js'; import { createAssetLockTransaction, serializeTransaction, calculateTxId } from './transaction/index.js'; -import { InsightClient } from './api/insight.js'; +import { InsightClient, isAmbiguousBroadcastError } from './api/insight.js'; import type { IslockService } from './api/islock.js'; import { fetchNetworkStatus } from './api/network-status.js'; import { DAPIClient } from './api/dapi.js'; @@ -2322,6 +2322,26 @@ function showValidationError(message: string): void { /** * Start the top-up process */ +/** + * Broadcast a signed asset lock transaction. + * + * A broadcast that timed out may still have reached the node, so it is not a + * failure: continue with the locally computed txid and let the IS lock wait + * (and its chain-lock fallback, which needs `state.txid`) settle the outcome. + * Definite rejections still throw. + */ +async function broadcastAssetLock(signedTxHex: string, txid: string): Promise { + try { + const broadcastedTxid = await insightClient.broadcastTransaction(signedTxHex); + if (broadcastedTxid !== txid) { + console.warn(`Broadcast txid ${broadcastedTxid} differs from local ${txid}`); + } + } catch (error) { + if (!isAmbiguousBroadcastError(error)) throw error; + console.warn(`Broadcast outcome unknown for ${txid}; waiting for its lock instead:`, error); + } +} + async function startTopUp() { try { if (isE2EMockMode()) { @@ -2428,10 +2448,7 @@ async function startTopUp() { ); // Step 6: Broadcast transaction - const broadcastedTxid = await insightClient.broadcastTransaction(signedTxHex); - if (broadcastedTxid !== txid) { - console.warn(`Broadcast txid ${broadcastedTxid} differs from local ${txid}`); - } + await broadcastAssetLock(signedTxHex, txid); updateState(setTransactionBroadcast(state, txid)); @@ -2548,10 +2565,7 @@ async function startSendToAddress() { ); // Step 6: Broadcast transaction - const broadcastedTxid = await insightClient.broadcastTransaction(signedTxHex); - if (broadcastedTxid !== txid) { - console.warn(`Broadcast txid ${broadcastedTxid} differs from local ${txid}`); - } + await broadcastAssetLock(signedTxHex, txid); updateState(setTransactionBroadcast(state, txid)); const islockBytes = await islockSub.wait(); @@ -2765,10 +2779,7 @@ async function startBridge() { ); // Step 6: Broadcast transaction - const broadcastedTxid = await insightClient.broadcastTransaction(signedTxHex); - if (broadcastedTxid !== txid) { - console.warn(`Broadcast txid ${broadcastedTxid} differs from local ${txid}`); - } + await broadcastAssetLock(signedTxHex, txid); updateState(setTransactionBroadcast(state, txid)); console.log('Waiting for InstantSend lock...'); @@ -2889,10 +2900,7 @@ async function recheckDeposit() { ); // Step 6: Broadcast transaction - const broadcastedTxid = await insightClient.broadcastTransaction(signedTxHex); - if (broadcastedTxid !== txid) { - console.warn(`Broadcast txid ${broadcastedTxid} differs from local ${txid}`); - } + await broadcastAssetLock(signedTxHex, txid); updateState(setTransactionBroadcast(state, txid)); console.log('Waiting for InstantSend lock...'); diff --git a/src/utils/fetch-json.ts b/src/utils/fetch-json.ts new file mode 100644 index 0000000..721d7c4 --- /dev/null +++ b/src/utils/fetch-json.ts @@ -0,0 +1,21 @@ +/** Bound both response headers and body; forward cancellation to fetch. */ +export async function fetchJson( + url: string, + init: RequestInit = {}, + timeoutMs = 8000 +): Promise { + const controller = new AbortController(); + const abort = () => controller.abort(); + const signal = init.signal; + if (signal?.aborted) abort(); + signal?.addEventListener('abort', abort, { once: true }); + const timer = setTimeout(abort, timeoutMs); + try { + const response = await fetch(url, { ...init, signal: controller.signal }); + if (!response.ok) throw new Error(`API error: ${response.status} ${response.statusText}`); + return await response.json(); + } finally { + clearTimeout(timer); + signal?.removeEventListener('abort', abort); + } +} diff --git a/src/utils/fetch-with-deadline.test.ts b/src/utils/fetch-with-deadline.test.ts new file mode 100644 index 0000000..c2f6f3b --- /dev/null +++ b/src/utils/fetch-with-deadline.test.ts @@ -0,0 +1,90 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { fetchJson } from './fetch-json.js'; +import { fetchWithDeadline, RequestTimeoutError } from './fetch-with-deadline.js'; + +/** Reject like real fetch does when the request signal aborts. */ +function onAbort(signal: AbortSignal | null | undefined, reject: (reason: unknown) => void): void { + if (!signal) return; + if (signal.aborted) reject(signal.reason); + signal.addEventListener('abort', () => reject(signal.reason), { once: true }); +} + +/** fetch that never sends response headers. */ +function stalledHeaders() { + return vi.fn((_url: string, init?: RequestInit) => new Promise((_, reject) => onAbort(init?.signal, reject))); +} + +/** fetch whose headers arrive but whose body never finishes. */ +function stalledBody() { + return vi.fn(async (_url: string, init?: RequestInit) => { + const never = () => new Promise((_, reject) => onAbort(init?.signal, reject)); + return { ok: true, status: 200, statusText: 'OK', json: never, text: never } as unknown as Response; + }); +} + +const readJson = async (response: Response) => response.json(); + +describe('request deadline helpers', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + it('fetchJson times out when fetch never resolves', async () => { + vi.stubGlobal('fetch', stalledHeaders()); + const expectation = expect(fetchJson('https://x/a', {}, 1000)).rejects.toMatchObject({ name: 'AbortError' }); + await vi.advanceTimersByTimeAsync(1000); + await expectation; + }); + + it('fetchJson times out when json() never resolves', async () => { + vi.stubGlobal('fetch', stalledBody()); + const expectation = expect(fetchJson('https://x/a', {}, 1000)).rejects.toMatchObject({ name: 'AbortError' }); + await vi.advanceTimersByTimeAsync(1000); + await expectation; + }); + + it('fetchJson forwards a caller abort to fetch', async () => { + const fetchMock = stalledHeaders(); + vi.stubGlobal('fetch', fetchMock); + const caller = new AbortController(); + const expectation = expect(fetchJson('https://x/a', { signal: caller.signal }, 60_000)).rejects.toMatchObject({ + name: 'AbortError', + }); + caller.abort(); + await expectation; + expect(fetchMock.mock.calls[0][1]?.signal?.aborted).toBe(true); + }); + + it('fetchWithDeadline reports its own timeout as RequestTimeoutError', async () => { + vi.stubGlobal('fetch', stalledHeaders()); + const expectation = expect(fetchWithDeadline('https://x/a', {}, 1000, readJson)).rejects.toBeInstanceOf( + RequestTimeoutError + ); + await vi.advanceTimersByTimeAsync(1000); + await expectation; + }); + + it('fetchWithDeadline bounds the body read', async () => { + vi.stubGlobal('fetch', stalledBody()); + const expectation = expect( + fetchWithDeadline('https://x/a', {}, 1000, async (response) => response.text()) + ).rejects.toThrow('Request timeout after 1000ms'); + await vi.advanceTimersByTimeAsync(1000); + await expectation; + }); + + it('fetchWithDeadline forwards a caller abort as AbortError, not a timeout', async () => { + vi.stubGlobal('fetch', stalledBody()); + const caller = new AbortController(); + const result = fetchWithDeadline('https://x/a', { signal: caller.signal }, 60_000, readJson); + const expectation = expect(result).rejects.toMatchObject({ name: 'AbortError' }); + await vi.advanceTimersByTimeAsync(10); + caller.abort(); + await expectation; + }); +}); diff --git a/src/utils/fetch-with-deadline.ts b/src/utils/fetch-with-deadline.ts new file mode 100644 index 0000000..775cc8a --- /dev/null +++ b/src/utils/fetch-with-deadline.ts @@ -0,0 +1,45 @@ +/** Thrown by fetchWithDeadline when its own timeout (not the caller) aborts the request. */ +export class RequestTimeoutError extends Error { + constructor(timeoutMs: number) { + // "timeout" keeps this retryable under isRetryableError(). + super(`Request timeout after ${timeoutMs}ms`); + this.name = 'RequestTimeoutError'; + } +} + +/** + * Sibling of fetchJson (./fetch-json.ts) for call sites that need the raw + * Response, e.g. to read a text error body or keep their own status handling + * and error messages. `timeoutMs` bounds the response headers and whatever + * body read `read` performs. A caller `init.signal` is forwarded; a caller + * abort rejects with fetch's AbortError, a timeout with RequestTimeoutError. + */ +export async function fetchWithDeadline( + url: string, + init: RequestInit, + timeoutMs: number, + read: (response: Response) => Promise +): Promise { + const controller = new AbortController(); + const abort = () => controller.abort(); + const signal = init.signal; + if (signal?.aborted) abort(); + signal?.addEventListener('abort', abort, { once: true }); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + abort(); + }, timeoutMs); + try { + const response = await fetch(url, { ...init, signal: controller.signal }); + return await read(response); + } catch (error) { + if (timedOut && !signal?.aborted && (error as { name?: string })?.name === 'AbortError') { + throw new RequestTimeoutError(timeoutMs); + } + throw error; + } finally { + clearTimeout(timer); + signal?.removeEventListener('abort', abort); + } +}