Skip to content
Open
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
74 changes: 74 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion src/components/NetworkBanner.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react

import type { NavSection } from "@/components/Sidebar";
import { useSorokit } from "@/context/useSorokit";
import { fetchWithRetry } from "@/lib/rpc";
import { cn } from "@/lib/utils";

export interface BannerConfig {
Expand Down Expand Up @@ -155,7 +156,7 @@ function useRpcLatency(
controller = new AbortController();
const started = performance.now();
try {
const res = await fetch(rpcUrl, {
const res = await fetchWithRetry(rpcUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "getHealth" }),
Expand Down
14 changes: 11 additions & 3 deletions src/components/NetworkSwitcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import React, { useCallback, useEffect, useRef, useState } from "react";
import { useSorokit } from "@/context/useSorokit";
import { useOutsideClick } from "@/hooks/useOutsideClick";
import type { NetworkInfo, NetworkName } from "@/lib/client";
import { fetchWithRetry, formatStellarError } from "@/lib/rpc";
import { cn } from "@/lib/utils";

export interface NetworkPreset {
Expand Down Expand Up @@ -129,22 +130,27 @@ export async function checkRpcHealth(
signal?.addEventListener("abort", onAbort, { once: true });

try {
const res = await fetch(rpcUrl.trim(), {
const res = await fetchWithRetry(rpcUrl.trim(), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "getHealth" }),
signal: controller.signal,
});
if (!res.ok) {
throw new Error(`RPC endpoint responded with HTTP ${res.status}.`);
const body: unknown = await res.json().catch(() => null);
const detail = formatStellarError(body);
throw new Error(
`RPC endpoint responded with HTTP ${res.status}${detail ? `: ${detail}` : ""}.`,
);
}
const body = (await res.json()) as {
result?: { status?: string };
error?: { message?: string };
};
if (body.error) {
const detail = formatStellarError(body);
throw new Error(
`RPC endpoint returned an error: ${body.error.message ?? "unknown error"}.`,
`RPC endpoint returned an error: ${detail ?? body.error.message ?? "unknown error"}.`,
);
}
if (body.result?.status && body.result.status !== "healthy") {
Expand All @@ -154,6 +160,7 @@ export async function checkRpcHealth(
if (timedOut) {
const error = new Error(
`RPC endpoint did not respond within ${Math.round(timeoutMs / 1000)}s.`,
{ cause: err },
);
(error as Error & { cause?: unknown }).cause = err;
throw error;
Expand All @@ -162,6 +169,7 @@ export async function checkRpcHealth(
if (err instanceof TypeError) {
const error = new Error(
"Could not reach the RPC endpoint. It may be offline or may not allow requests from this origin (CORS).",
{ cause: err },
);
(error as Error & { cause?: unknown }).cause = err;
throw error;
Expand Down
85 changes: 85 additions & 0 deletions src/lib/__tests__/adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ describe('ClientAdapter', () => {
adapter = createClientAdapter();
});

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

describe('Connection', () => {
it('should return error when no wallet is available', async () => {
const result = await adapter.connect();
Expand All @@ -21,6 +27,85 @@ describe('ClientAdapter', () => {
const result = await adapter.connect();
expect(result.data).not.toBe('GBAMQXTQ7IQKPZXJKZJQZJQ...');
});

it('times out an unresponsive hardware wallet after 15 seconds', async () => {
vi.useFakeTimers();
vi.stubGlobal('window', {
freighter: {
requestAccess: vi.fn(() => new Promise(() => {})),
getPublicKey: vi.fn(),
},
});

try {
const resultPromise = adapter.connect();
await vi.advanceTimersByTimeAsync(15_000);
const result = await resultPromise;

expect(result.status).toBe('error');
expect(result.error).toContain('timed out after 15 seconds');
expect(result.error).toContain('open the Stellar app');
} finally {
vi.useRealTimers();
vi.unstubAllGlobals();
}
});

it('backs off exponentially between failed extension connection attempts', async () => {
vi.useFakeTimers();
vi.spyOn(Math, 'random').mockReturnValue(0.5);
const requestAccess = vi.fn()
.mockRejectedValueOnce(new Error('Temporary wallet transport failure'))
.mockRejectedValueOnce(new Error('Temporary wallet transport failure'))
.mockResolvedValueOnce({});
vi.stubGlobal('window', {
freighter: {
requestAccess,
getPublicKey: vi.fn().mockResolvedValue('GTESTADDRESS'),
},
});

try {
const resultPromise = adapter.connect();
await vi.advanceTimersByTimeAsync(0);
expect(requestAccess).toHaveBeenCalledTimes(1);

await vi.advanceTimersByTimeAsync(249);
expect(requestAccess).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(1);
expect(requestAccess).toHaveBeenCalledTimes(2);

await vi.advanceTimersByTimeAsync(499);
expect(requestAccess).toHaveBeenCalledTimes(2);
await vi.advanceTimersByTimeAsync(1);

const result = await resultPromise;
expect(result.status).toBe('success');
expect(requestAccess).toHaveBeenCalledTimes(3);
} finally {
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
}
});

it('translates Ledger app-not-open error codes into actionable guidance', async () => {
const requestAccess = vi.fn().mockRejectedValue(new Error('Device returned 0x6804'));
vi.stubGlobal('window', {
freighter: {
requestAccess,
getPublicKey: vi.fn(),
},
});

const result = await adapter.connect();

expect(result.status).toBe('error');
expect(result.error).toContain('Open the Stellar app on your Ledger');
expect(result.error).toContain('unlock the device');
expect(requestAccess).toHaveBeenCalledTimes(1);
vi.unstubAllGlobals();
});
});

describe('Contract Invocation', () => {
Expand Down
Loading
Loading