Skip to content
Open
  •  
  •  
  •  
2 changes: 1 addition & 1 deletion .storybook/__fixtures__/account-history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function mockConfirmedSignatureInfo(overrides: SignatureOverrides = {}):
confirmationStatus: 'finalized',
err: null,
memo: null,
signature: gen.signature(),
signature: gen.signature(overrides.slot ?? 0),
slot: 312_456_789,
...overrides,
};
Expand Down
3 changes: 1 addition & 2 deletions .storybook/__fixtures__/messages.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { DEFAULT_BLOCKHASH } from '@__fixtures__/gen';
import { PublicKey, VersionedMessage } from '@solana/web3.js';

const DEFAULT_BLOCKHASH = '4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZAMdL4VZHirm';

export function mockVersionedMessage(overrides: Record<string, unknown> = {}): VersionedMessage {
return {
addressTableLookups: [],
Expand Down
7 changes: 4 additions & 3 deletions .storybook/__mocks__/MockAccountsProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ type MockAccountsProviderProps = {
* an account by address without touching this shared fixture - see `withMockTransactions`.
*/
accounts?: State['entries'];
state?: State;
};

/**
Expand Down Expand Up @@ -79,10 +80,10 @@ type MockAccountsProviderProps = {
*
* To add more mock accounts, add entries to the `mockState.entries` object.
*/
export function MockAccountsProvider({ accounts, children }: MockAccountsProviderProps) {
export function MockAccountsProvider({ accounts, children, state: base = mockState }: MockAccountsProviderProps) {
const state: State = React.useMemo(
() => (accounts ? { ...mockState, entries: { ...mockState.entries, ...accounts } } : mockState),
[accounts],
() => (accounts ? { ...base, entries: { ...base.entries, ...accounts } } : base),
[accounts, base],
);

return (
Expand Down
20 changes: 20 additions & 0 deletions .storybook/create-preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { INITIAL_VIEWPORTS } from 'storybook/viewport';
import { rubikFont } from '@/app/styles';

import { BREAKPOINT_VIEWPORTS } from './breakpoints';
import { createNextjsParameters } from './decorators';
import type { Preview } from './types';

// Storybook serialises story args with JSON.stringify (for the controls panel and inter-frame
Expand Down Expand Up @@ -39,6 +40,7 @@ export function createPreview({ mswEnabled }: { mswEnabled: boolean }): Preview

return {
parameters: {
...createNextjsParameters(),
a11y: {
// Document-scoped rules that can never pass for a component rendered in isolation (no <main>/<h1>/landmark).
config: {
Expand Down Expand Up @@ -116,6 +118,10 @@ export function createPreview({ mswEnabled }: { mswEnabled: boolean }): Preview
},
],

// The check parses the DOM again instead of reading React's nesting warning, because React logs
// each warning once per page.
afterEach: assertValidMarkup,

initialGlobals: {
backgrounds: {
value: 'dark',
Expand All @@ -125,3 +131,17 @@ export function createPreview({ mswEnabled }: { mswEnabled: boolean }): Preview
loaders: mswEnabled ? [mswLoader] : [],
};
}

function assertValidMarkup() {
const rendered = document.body.innerHTML;
const reparsed = document.createElement('body');
reparsed.innerHTML = rendered;
if (reparsed.innerHTML === rendered) return;

let at = 0;
while (rendered[at] === reparsed.innerHTML[at]) at++;
Comment on lines +139 to +142

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Markup errors become slow

On a markup mismatch, the loop reads reparsed.innerHTML once for every matching character. Each read serializes the whole body again. An invalid element near the end of a large story can therefore make the check disproportionately slow. Save reparsed.innerHTML once and reuse that string for the comparison, loop, and error message.

const around = (html: string) => html.slice(Math.max(0, at - 80), at + 80);
throw new Error(
`The HTML parser builds a different DOM from the story markup.\nRendered: ${around(rendered)}\nReparsed: ${around(reparsed.innerHTML)}`,
);
}
92 changes: 20 additions & 72 deletions .storybook/decorators.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { DEFAULT_SIGNATURE } from '@__fixtures__/gen';
import { InstructionNodeCard } from '@components/instruction/InstructionNodeCard';
import { toConnectableUrl } from '@entities/cluster';
import { TxInstructionSurface } from '@entities/instruction-card';
import { DispatchContext, FetchersContext, type State, StateContext } from '@providers/accounts';
import type { State } from '@providers/accounts';
import type { ClusterState } from '@providers/cluster';
import { ScrollAnchorProvider } from '@providers/scroll-anchor';
import { TransactionsProvider } from '@providers/transactions';
import { IMAGE_SIZE } from '@shared/lib/og/image-size';
import { type Cluster, clusterSelection, clusterUrl } from '@utils/cluster';
import React, { useLayoutEffect, useRef } from 'react';
import { fn } from 'storybook/test';
Expand All @@ -21,15 +21,6 @@ import { MockTokenInfoBatchProvider } from './__mocks__/MockTokenInfoBatchProvid
import { MockTransactionsProvider } from './__mocks__/MockTransactionsProvider';
import type { Decorator, Parameters } from './types';

const noopFetcher = async () => undefined;
// MultipleAccountFetcher has private constructor params (nominal-typed) — no structural object matches.
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- decorator-only stub
const noopAccountsFetchers = {
parsed: { fetch: noopFetcher },
raw: { fetch: noopFetcher },
skip: { fetch: noopFetcher },
} as unknown as React.ContextType<typeof FetchersContext>;

/** Wraps stories with ClusterProvider. Usage: `decorators: [withCluster]` */
export const withCluster: Decorator = Story => (
<ClusterProvider>
Expand Down Expand Up @@ -119,13 +110,9 @@ export function withAccountsState(state: State): Decorator {
return function WithAccountsState(Story) {
return (
<ClusterProvider>
<StateContext.Provider value={state}>
<DispatchContext.Provider value={() => undefined}>
<FetchersContext.Provider value={noopAccountsFetchers}>
<Story />
</FetchersContext.Provider>
</DispatchContext.Provider>
</StateContext.Provider>
<MockAccountsProvider state={state}>
<Story />
</MockAccountsProvider>
</ClusterProvider>
);
};
Expand All @@ -146,35 +133,13 @@ export const withCardTableField: Decorator = Story => (
</ClusterProvider>
);

/** Wraps stories with ClusterProvider, TransactionsProvider, and MockAccountsProvider. Usage: `decorators: [withTransactions]` */
export const withTransactions: Decorator = Story => (
<ClusterProvider>
<TransactionsProvider>
<MockAccountsProvider>
<Story />
</MockAccountsProvider>
</TransactionsProvider>
</ClusterProvider>
);

/** Wraps stories with MockTokenInfoBatchProvider. Usage: `decorators: [withTokenInfoBatch]` */
export const withTokenInfoBatch: Decorator = Story => (
<MockTokenInfoBatchProvider>
<Story />
</MockTokenInfoBatchProvider>
);

/** Wraps stories with ClusterProvider, MockTokenInfoBatchProvider, and MockAccountsProvider. Usage: `decorators: [withClusterAccountsAndTokenInfo]` */
export const withClusterAccountsAndTokenInfo: Decorator = Story => (
<ClusterProvider>
<MockTokenInfoBatchProvider>
<MockAccountsProvider>
<Story />
</MockAccountsProvider>
</MockTokenInfoBatchProvider>
</ClusterProvider>
);

/** Wraps stories with ClusterProvider and MockStatsProvider. Usage: `decorators: [withStats]` */
export const withStats: Decorator = Story => (
<ClusterProvider>
Expand All @@ -200,6 +165,14 @@ export const withMockTransactions: Decorator = (Story, context) => (
</ClusterProvider>
);

/** Wraps stories with the providers an instruction card reads on the tx page. Usage: `decorators: instructionCardDecorators` */
export const instructionCardDecorators: Decorator[] = [
withScrollAnchor,
withTokenInfoBatch,
withTxInstructionSurface,
withMockTransactions,
];

/**
* Wraps stories with ClusterProvider, MockAccountsProvider, and MockHistoryProvider.
* Seeds the history cache from `parameters.history` (empty cache when omitted).
Expand All @@ -215,6 +188,13 @@ export const withHistory: Decorator = (Story, context) => (
</ClusterProvider>
);

/** Sizes stories to an Open Graph image. Usage: `decorators: [withOgImageFrame]` */
export const withOgImageFrame: Decorator = Story => (
<div style={{ height: IMAGE_SIZE.height, width: IMAGE_SIZE.width }}>
<Story />
</div>
);

type NextjsNavigationOptions = {
pathname?: string;
query?: Record<string, string>;
Expand All @@ -231,8 +211,6 @@ export const createNextjsParameters = (options?: NextjsNavigationOptions): Param
},
});

export const nextjsParameters: Parameters = createNextjsParameters();

/** Mocks navigator.clipboard.writeText for stories that copy text. Usage: `decorators: [withClipboardMock]` */
export const withClipboardMock: Decorator = Story => {
Object.defineProperty(navigator, 'clipboard', {
Expand All @@ -243,36 +221,6 @@ export const withClipboardMock: Decorator = Story => {
return <Story />;
};

const MCP_PONG = { id: 1, jsonrpc: '2.0', result: { content: [{ text: 'pong', type: 'text' }] } };

// Patched during render so the swap lands before any child effect fires, and restored on unmount so the
// stub cannot leak into another story sharing this browser context.
function McpHealthyBoundary({ children }: { children: React.ReactNode }) {
const original = useRef(globalThis.fetch);

if (globalThis.fetch === original.current) {
globalThis.fetch = fn(() => Promise.resolve(Response.json(MCP_PONG)));
}
useLayoutEffect(() => {
const restore = original.current;
return () => {
globalThis.fetch = restore;
};
}, []);

return <>{children}</>;
}

/**
* Answers the /mcp health probe with a pong so the status badge settles on "Ready".
* Without it the badge races from "Checking" to "Unreachable" mid-screenshot.
*/
export const withMcpHealthy: Decorator = Story => (
<McpHealthyBoundary>
<Story />
</McpHealthyBoundary>
);

/** Errored variant — writeText rejects so consumers flip to 'errored' state. */
export const withClipboardMockErrored: Decorator = Story => {
Object.defineProperty(navigator, 'clipboard', {
Expand Down
19 changes: 19 additions & 0 deletions app/__fixtures__/instruction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { PublicKey, TransactionInstruction } from '@solana/web3.js';

export function makeInstruction({
data = [],
keys = [],
programId,
writable = false,
}: {
data?: Uint8Array | number[];
keys?: PublicKey[];
programId: PublicKey | string;
writable?: boolean;
}): TransactionInstruction {
return new TransactionInstruction({
data: Buffer.from(data),
keys: keys.map(pubkey => ({ isSigner: false, isWritable: writable, pubkey })),
programId: new PublicKey(programId),
});
}
5 changes: 5 additions & 0 deletions app/__tests__/address-stub.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { PublicKey } from '@solana/web3.js';

export function Address({ pubkey, fallbackText }: { pubkey: PublicKey; fallbackText?: string }) {
return <span data-testid="address">{fallbackText ?? pubkey.toBase58()}</span>;
}
7 changes: 7 additions & 0 deletions app/__tests__/mock-parsed-extensions-stubs.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { PublicKey } from '@solana/web3.js';
import { populatePartialParsedTokenExtension } from '@utils/token-extension';

import { TokenExtension } from '../validators/accounts/token-extension';

Expand All @@ -20,3 +21,9 @@ export const transferFeeConfig0 = {
withheldAmount: 500000,
},
} as TokenExtension;

export const parsedTransferFeeConfig0 = {
extension: transferFeeConfig0.extension,
parsed: transferFeeConfig0,
...populatePartialParsedTokenExtension(transferFeeConfig0.extension),
};
10 changes: 10 additions & 0 deletions app/__tests__/mock-rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,16 @@ export function rpcStub(methods: Record<string, Mock>) {
);
}

/** Like `rpcStub`, but each `send()` resolves to `{ value }`, the envelope of kit's account reads. */
export function rpcValueStub(methods: Record<string, Mock>) {
return Object.fromEntries(
Object.entries(methods).map(([name, method]) => [
name,
(...args: unknown[]) => ({ send: async () => ({ value: await method(...args) }) }),
]),
);
}

/** Returns the update a mocked cache dispatch received last. */
export function lastDispatch<T>(dispatch: Mock<Dispatch<T>>): Update<T> {
const action = dispatch.mock.lastCall?.[0];
Expand Down
19 changes: 19 additions & 0 deletions app/__tests__/rpc-errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, SolanaError } from '@solana/kit';
import { expect } from 'vitest';

export function httpError(statusCode: number) {
return new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, {
headers: new Headers(),
message: `HTTP ${statusCode}`,
statusCode,
});
}

export function connectionFailure(code: string) {
const cause = Object.assign(new Error(`${code} on connect`), { code });
return Object.assign(new TypeError('fetch failed'), { cause });
}

export function reported(extras: Record<string, unknown>) {
return expect.objectContaining({ sentry: true, sentryExtras: expect.objectContaining(extras) });
}
29 changes: 19 additions & 10 deletions app/__tests__/rpc-fetch.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import { afterEach, beforeEach, vi } from 'vitest';

/**
* Serves JSON-RPC responses to the real kit client through a stubbed global `fetch`.
* The calling spec must also undo the global `@solana/kit` mock, or kit never reaches `fetch`.
*/
export function stubRpcFetch() {
export function stubFetch() {
const fetchMock = vi.fn();

beforeEach(() => {
Expand All @@ -16,15 +12,28 @@ export function stubRpcFetch() {
fetchMock.mockReset();
});

function respondWith(result: unknown) {
const body = JSON.stringify({ id: 1, jsonrpc: '2.0', result });
// kit reads the body as text so it can upcast integers to bigints as it parses.
fetchMock.mockResolvedValueOnce({ ok: true, status: 200, text: async () => body });
function respondWith(status: number, body: unknown) {
fetchMock.mockResolvedValueOnce(Response.json(body, { status }));
}

return { fetchMock, respondWith };
}

/**
* Serves JSON-RPC responses to the real kit client through a stubbed global `fetch`.
* The calling spec must also undo the global `@solana/kit` mock, or kit never reaches `fetch`.
*/
export function stubRpcFetch() {
const { fetchMock, respondWith } = stubFetch();

function requestBody() {
return JSON.parse(fetchMock.mock.calls[0][1].body);
}

return { fetchMock, requestBody, respondWith };
return {
fetchMock,
requestBody,
respondWith: (result: unknown, status = 200) => respondWith(status, { id: 1, jsonrpc: '2.0', result }),
respondWithError: (error: unknown, status = 200) => respondWith(status, { error, id: 1, jsonrpc: '2.0' }),
};
}
4 changes: 4 additions & 0 deletions app/__tests__/swr-hook.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,7 @@ export function clusterContext({
url,
};
}

export function connectedTo(cluster: Cluster, url: string): ClusterContext {
return clusterContext({ cluster, connectableUrl: url, status: ClusterStatus.Connected, url });
}
11 changes: 11 additions & 0 deletions app/__tests__/swr-idle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { vi } from 'vitest';

export const idleSwrModule = {
default: vi.fn(() => ({
data: undefined,
error: undefined,
isLoading: false,
isValidating: false,
mutate: vi.fn(),
})),
};
Loading