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
93 changes: 59 additions & 34 deletions src/api/dapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> = {
testnet: 'https://trpc.digitalcash.dev',
Expand Down Expand Up @@ -80,29 +81,60 @@ export class DAPIClient {
onRetry?: (attempt: number, maxAttempts: number, error: unknown) => void,
signal?: AbortSignal
): Promise<Uint8Array> {
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<never>((_, 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<Uint8Array> => {
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`
);
}

/**
Expand All @@ -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;
}
Expand All @@ -141,14 +167,18 @@ export class DAPIClient {
/**
* Fetch islock from JSON-RPC API
*/
private async getIslock(txid: string, retryOptions?: RetryOptions): Promise<Uint8Array | null> {
private async getIslock(
txid: string,
retryOptions?: RetryOptions,
signal?: AbortSignal
): Promise<Uint8Array | null> {
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',
Expand All @@ -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);
Expand Down
83 changes: 47 additions & 36 deletions src/api/faucet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }): {
Expand All @@ -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<T>(
url: string,
options: RequestInit = {},
options: RequestInit,
read: (response: Response) => Promise<T>,
timeoutMs: number = REQUEST_TIMEOUT_MS
): Promise<Response> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);

): Promise<T> {
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);
}
}

Expand Down Expand Up @@ -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<FaucetStatus> {
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();
});
}

/**
Expand Down Expand Up @@ -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<string, unknown>;
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<string, unknown>;
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();
}
Loading
Loading