diff --git a/.storybook/__fixtures__/account-history.ts b/.storybook/__fixtures__/account-history.ts index 7812179e8b..9c903b31a9 100644 --- a/.storybook/__fixtures__/account-history.ts +++ b/.storybook/__fixtures__/account-history.ts @@ -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, }; diff --git a/.storybook/__fixtures__/messages.ts b/.storybook/__fixtures__/messages.ts index de70c88d00..4d488588b6 100644 --- a/.storybook/__fixtures__/messages.ts +++ b/.storybook/__fixtures__/messages.ts @@ -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 = {}): VersionedMessage { return { addressTableLookups: [], diff --git a/.storybook/__mocks__/MockAccountsProvider.tsx b/.storybook/__mocks__/MockAccountsProvider.tsx index d118a55722..923bcf4613 100644 --- a/.storybook/__mocks__/MockAccountsProvider.tsx +++ b/.storybook/__mocks__/MockAccountsProvider.tsx @@ -52,6 +52,7 @@ type MockAccountsProviderProps = { * an account by address without touching this shared fixture - see `withMockTransactions`. */ accounts?: State['entries']; + state?: State; }; /** @@ -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 ( diff --git a/.storybook/create-preview.tsx b/.storybook/create-preview.tsx index a4334d135d..6c8451310e 100644 --- a/.storybook/create-preview.tsx +++ b/.storybook/create-preview.tsx @@ -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 @@ -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
/

/landmark). config: { @@ -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', @@ -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++; + 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)}`, + ); +} diff --git a/.storybook/decorators.tsx b/.storybook/decorators.tsx index fba60d9a7f..7477e50ba4 100644 --- a/.storybook/decorators.tsx +++ b/.storybook/decorators.tsx @@ -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'; @@ -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; - /** Wraps stories with ClusterProvider. Usage: `decorators: [withCluster]` */ export const withCluster: Decorator = Story => ( @@ -119,13 +110,9 @@ export function withAccountsState(state: State): Decorator { return function WithAccountsState(Story) { return ( - - undefined}> - - - - - + + + ); }; @@ -146,17 +133,6 @@ export const withCardTableField: Decorator = Story => ( ); -/** Wraps stories with ClusterProvider, TransactionsProvider, and MockAccountsProvider. Usage: `decorators: [withTransactions]` */ -export const withTransactions: Decorator = Story => ( - - - - - - - -); - /** Wraps stories with MockTokenInfoBatchProvider. Usage: `decorators: [withTokenInfoBatch]` */ export const withTokenInfoBatch: Decorator = Story => ( @@ -164,17 +140,6 @@ export const withTokenInfoBatch: Decorator = Story => ( ); -/** Wraps stories with ClusterProvider, MockTokenInfoBatchProvider, and MockAccountsProvider. Usage: `decorators: [withClusterAccountsAndTokenInfo]` */ -export const withClusterAccountsAndTokenInfo: Decorator = Story => ( - - - - - - - -); - /** Wraps stories with ClusterProvider and MockStatsProvider. Usage: `decorators: [withStats]` */ export const withStats: Decorator = Story => ( @@ -200,6 +165,14 @@ export const withMockTransactions: Decorator = (Story, context) => ( ); +/** 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). @@ -215,6 +188,13 @@ export const withHistory: Decorator = (Story, context) => ( ); +/** Sizes stories to an Open Graph image. Usage: `decorators: [withOgImageFrame]` */ +export const withOgImageFrame: Decorator = Story => ( +
+ +
+); + type NextjsNavigationOptions = { pathname?: string; query?: Record; @@ -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', { @@ -243,36 +221,6 @@ export const withClipboardMock: Decorator = Story => { return ; }; -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 => ( - - - -); - /** Errored variant — writeText rejects so consumers flip to 'errored' state. */ export const withClipboardMockErrored: Decorator = Story => { Object.defineProperty(navigator, 'clipboard', { diff --git a/app/__fixtures__/instruction.ts b/app/__fixtures__/instruction.ts new file mode 100644 index 0000000000..9357ffba57 --- /dev/null +++ b/app/__fixtures__/instruction.ts @@ -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), + }); +} diff --git a/app/__tests__/address-stub.tsx b/app/__tests__/address-stub.tsx new file mode 100644 index 0000000000..593ed62b56 --- /dev/null +++ b/app/__tests__/address-stub.tsx @@ -0,0 +1,5 @@ +import type { PublicKey } from '@solana/web3.js'; + +export function Address({ pubkey, fallbackText }: { pubkey: PublicKey; fallbackText?: string }) { + return {fallbackText ?? pubkey.toBase58()}; +} diff --git a/app/__tests__/mock-parsed-extensions-stubs.ts b/app/__tests__/mock-parsed-extensions-stubs.ts index a4716d958c..d30f1c6ede 100644 --- a/app/__tests__/mock-parsed-extensions-stubs.ts +++ b/app/__tests__/mock-parsed-extensions-stubs.ts @@ -1,4 +1,5 @@ import { PublicKey } from '@solana/web3.js'; +import { populatePartialParsedTokenExtension } from '@utils/token-extension'; import { TokenExtension } from '../validators/accounts/token-extension'; @@ -20,3 +21,9 @@ export const transferFeeConfig0 = { withheldAmount: 500000, }, } as TokenExtension; + +export const parsedTransferFeeConfig0 = { + extension: transferFeeConfig0.extension, + parsed: transferFeeConfig0, + ...populatePartialParsedTokenExtension(transferFeeConfig0.extension), +}; diff --git a/app/__tests__/mock-rpc.ts b/app/__tests__/mock-rpc.ts index 1150505990..7122c2d2d9 100644 --- a/app/__tests__/mock-rpc.ts +++ b/app/__tests__/mock-rpc.ts @@ -72,6 +72,16 @@ export function rpcStub(methods: Record) { ); } +/** Like `rpcStub`, but each `send()` resolves to `{ value }`, the envelope of kit's account reads. */ +export function rpcValueStub(methods: Record) { + 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(dispatch: Mock>): Update { const action = dispatch.mock.lastCall?.[0]; diff --git a/app/__tests__/rpc-errors.ts b/app/__tests__/rpc-errors.ts new file mode 100644 index 0000000000..388faa7d78 --- /dev/null +++ b/app/__tests__/rpc-errors.ts @@ -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) { + return expect.objectContaining({ sentry: true, sentryExtras: expect.objectContaining(extras) }); +} diff --git a/app/__tests__/rpc-fetch.ts b/app/__tests__/rpc-fetch.ts index 85b5fa8661..88fb259c3b 100644 --- a/app/__tests__/rpc-fetch.ts +++ b/app/__tests__/rpc-fetch.ts @@ -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(() => { @@ -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' }), + }; } diff --git a/app/__tests__/swr-hook.tsx b/app/__tests__/swr-hook.tsx index 46b278d652..0616c8560a 100644 --- a/app/__tests__/swr-hook.tsx +++ b/app/__tests__/swr-hook.tsx @@ -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 }); +} diff --git a/app/__tests__/swr-idle.ts b/app/__tests__/swr-idle.ts new file mode 100644 index 0000000000..8c4620817f --- /dev/null +++ b/app/__tests__/swr-idle.ts @@ -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(), + })), +}; diff --git a/app/api/search/__tests__/route.test.ts b/app/api/search/__tests__/route.test.ts index 071168762e..692d5d04c2 100644 --- a/app/api/search/__tests__/route.test.ts +++ b/app/api/search/__tests__/route.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { gen } from '@/app/__fixtures__/gen'; +import { stubFetch } from '@/app/__tests__/rpc-fetch'; import { GENESIS_HASHES } from '@/app/entities/chain-id/lib/const'; import { getAssetBatch } from '@/app/entities/digital-asset/api'; @@ -12,19 +13,9 @@ vi.mock('@/app/entities/digital-asset/api', () => ({ getAssetBatch: vi.fn(), })); -const fetchMock = vi.fn(); -vi.stubGlobal('fetch', fetchMock); +const { fetchMock, respondWith } = stubFetch(); const getAssetBatchMock = vi.mocked(getAssetBatch); -function mockFetch(status: number, body: unknown) { - const ok = status >= 200 && status < 300; - fetchMock.mockResolvedValueOnce({ - json: async () => body, - ok, - status, - } as Response); -} - let testSeq = 0; function makeRequest(q: string, cluster = 'mainnet-beta') { return new Request(`http://localhost/api/search?q=${encodeURIComponent(q)}-${++testSeq}&cluster=${cluster}`); @@ -33,13 +24,11 @@ function makeRequest(q: string, cluster = 'mainnet-beta') { const originalEnv = { ...process.env }; beforeEach(() => { - vi.stubGlobal('fetch', fetchMock); process.env = { ...originalEnv, JUPITER_API_KEY: 'test-key' }; getAssetBatchMock.mockResolvedValue(undefined); }); afterEach(() => { - vi.unstubAllGlobals(); process.env = originalEnv; vi.resetAllMocks(); }); @@ -55,7 +44,7 @@ describe('GET /api/search', () => { }); it('should return results with cache headers for non-mainnet cluster', async () => { - mockFetch(200, []); + respondWith(200, []); const res = await GET(new Request(`http://localhost/api/search?q=sol-${++testSeq}&cluster=devnet`)); expect(res.status).toBe(200); const data = await res.json(); @@ -74,7 +63,7 @@ describe('GET /api/search', () => { }); it('should return empty with cache headers when Jupiter returns empty array', async () => { - mockFetch(200, []); + respondWith(200, []); const res = await GET(makeRequest('sol')); const data = await res.json(); expect(data).toMatchObject({ results: { tokens: [] }, success: true }); @@ -84,7 +73,7 @@ describe('GET /api/search', () => { describe('Jupiter discovery', () => { it('should normalize tokens on success', async () => { - mockFetch(200, [makeJupiterToken()]); + respondWith(200, [makeJupiterToken()]); const res = await GET(makeRequest('sol')); const data = await res.json(); @@ -100,13 +89,13 @@ describe('GET /api/search', () => { }); it('should return cache headers on success', async () => { - mockFetch(200, [makeJupiterToken()]); + respondWith(200, [makeJupiterToken()]); const res = await GET(makeRequest('sol')); expect(res.headers.get('Cache-Control')).toContain('s-maxage=30'); }); it('should detect address query type', async () => { - mockFetch(200, [makeJupiterToken()]); + respondWith(200, [makeJupiterToken()]); const res = await GET( new Request(`http://localhost/api/search?q=${encodeURIComponent(VALID_ADDRESS)}-${++testSeq}`), ); @@ -118,10 +107,10 @@ describe('GET /api/search', () => { describe('Jupiter failure', () => { it.each([ - ['returns 401', () => mockFetch(401, {})], - ['returns 429', () => mockFetch(429, {})], - ['returns 500', () => mockFetch(500, {})], - ['returns an object instead of an array', () => mockFetch(200, { unexpected: 'shape' })], + ['returns 401', () => respondWith(401, {})], + ['returns 429', () => respondWith(429, {})], + ['returns 500', () => respondWith(500, {})], + ['returns an object instead of an array', () => respondWith(200, { unexpected: 'shape' })], ['rejects with a network error', () => fetchMock.mockRejectedValueOnce(new TypeError('fetch failed'))], [ 'is aborted', @@ -152,7 +141,7 @@ describe('GET /api/search', () => { describe('DAS icon enrichment', () => { it('should enrich icon from DAS when logoUri is null', async () => { - mockFetch(200, [makeJupiterToken({ logoURI: null })]); + respondWith(200, [makeJupiterToken({ logoURI: null })]); getAssetBatchMock.mockResolvedValueOnce([makeDasAsset(VALID_ADDRESS, 'https://das.example.com/sol.png')]); const res = await GET(makeRequest('sol')); @@ -161,7 +150,7 @@ describe('GET /api/search', () => { }); it('should prefer logoUri over DAS image when both present', async () => { - mockFetch(200, [makeJupiterToken({ logoURI: 'https://original.com/sol.png' })]); + respondWith(200, [makeJupiterToken({ logoURI: 'https://original.com/sol.png' })]); getAssetBatchMock.mockResolvedValueOnce([makeDasAsset(VALID_ADDRESS, 'https://das.example.com/sol.png')]); const res = await GET(makeRequest('sol')); @@ -170,7 +159,7 @@ describe('GET /api/search', () => { }); it('should use undefined icon when DAS returns no asset and logoUri is absent', async () => { - mockFetch(200, [makeJupiterToken({ logoURI: null })]); + respondWith(200, [makeJupiterToken({ logoURI: null })]); getAssetBatchMock.mockResolvedValueOnce(undefined); const res = await GET(makeRequest('sol')); @@ -188,7 +177,7 @@ describe('GET /api/search', () => { }); it('should filter out unverified Jupiter tokens when flag is set', async () => { - mockFetch(200, [ + respondWith(200, [ makeJupiterToken({ isVerified: true }), makeJupiterToken({ id: OTHER_ADDRESS, isVerified: false, name: 'Other', symbol: 'OTH' }), ]); @@ -202,7 +191,7 @@ describe('GET /api/search', () => { }); it('should keep verified Jupiter tokens when flag is set', async () => { - mockFetch(200, [makeJupiterToken({ isVerified: true })]); + respondWith(200, [makeJupiterToken({ isVerified: true })]); const res = await GET(makeRequest('sol')); const data = await res.json(); @@ -212,7 +201,7 @@ describe('GET /api/search', () => { }); it('should return empty when all Jupiter results are unverified', async () => { - mockFetch(200, [ + respondWith(200, [ makeJupiterToken({ isVerified: false }), makeJupiterToken({ id: OTHER_ADDRESS, isVerified: false, name: 'Other', symbol: 'OTH' }), ]); @@ -224,7 +213,7 @@ describe('GET /api/search', () => { }); it('should exclude a Jupiter token that omits isVerified when flag is set', async () => { - mockFetch(200, [{ decimals: 9, id: VALID_ADDRESS, name: 'Wrapped SOL', symbol: 'SOL' }]); + respondWith(200, [{ decimals: 9, id: VALID_ADDRESS, name: 'Wrapped SOL', symbol: 'SOL' }]); const res = await GET(makeRequest('sol')); const data = await res.json(); @@ -262,7 +251,7 @@ describe('GET /api/search', () => { }); it('should resolve Custom + mainnet genesisHash and run search', async () => { - mockFetch(200, [makeJupiterToken()]); + respondWith(200, [makeJupiterToken()]); const res = await GET( new Request( `http://localhost/api/search?q=sol-${++testSeq}&cluster=custom&genesisHash=${GENESIS_HASHES.MAINNET}`, diff --git a/app/api/slot-time/__tests__/route.spec.ts b/app/api/slot-time/__tests__/route.spec.ts index 816b35ecf7..23f0498f9d 100644 --- a/app/api/slot-time/__tests__/route.spec.ts +++ b/app/api/slot-time/__tests__/route.spec.ts @@ -3,26 +3,22 @@ import { createSolanaRpc, SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR, SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND, - SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, SolanaError, } from '@solana/kit'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { connectionFailure, httpError, reported } from '@/app/__tests__/rpc-errors'; import { Logger } from '@/app/shared/lib/logger'; import { ROUTE_TIMEOUT_MS, UPSTREAM_TIMEOUT_MS } from '@/app/shared/lib/timeouts'; import { Cluster } from '@/app/utils/cluster'; import { GET, maxDuration } from '../route'; -const mocks = vi.hoisted(() => ({ getRecentPerformanceSamples: vi.fn(), send: vi.fn() })); +const mocks = { getRecentPerformanceSamples: vi.fn(), send: vi.fn() }; -vi.mock('@solana/kit', async () => { - const actual = await vi.importActual('@solana/kit'); - return { - ...actual, - createSolanaRpc: vi.fn(() => ({ getRecentPerformanceSamples: mocks.getRecentPerformanceSamples })), - }; -}); +vi.mocked(createSolanaRpc).mockImplementation( + () => ({ getRecentPerformanceSamples: mocks.getRecentPerformanceSamples }) as never, +); // Stubbed, so a local `.env` cannot decide what the route resolves to — an empty one would fail these // tests for a reason that has nothing to do with the route. @@ -257,27 +253,3 @@ describe('GET /api/slot-time', () => { function createRequest(cluster: Cluster) { return new Request(`http://localhost:3000/api/slot-time?cluster=${cluster}`); } - -/** A node answering over HTTP rather than in JSON-RPC: a gateway, a key check, a wrong path. */ -function httpError(statusCode: number) { - return new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, { - headers: new Headers(), - message: `HTTP ${statusCode}`, - statusCode, - }); -} - -/** Shaped the way undici reports one: the code sits on an `Error` nested as `cause`. */ -function connectionFailure(code: string) { - const cause = Object.assign(new Error(`${code} on connect`), { code }); - return Object.assign(new TypeError('fetch failed'), { cause }); -} - -/** - * What has to be on a log call for the failure to reach Sentry at all: the flag, and the reason under - * `sentryExtras`, which is the only part of a context Sentry receives. A bare `toHaveBeenCalled` passes - * with both dropped, and the tier then fails silently for everyone. - */ -function reported(extras: Record) { - return expect.objectContaining({ sentry: true, sentryExtras: expect.objectContaining(extras) }); -} diff --git a/app/api/supply/__tests__/route.spec.ts b/app/api/supply/__tests__/route.spec.ts index 40065f976b..0745d8e5b5 100644 --- a/app/api/supply/__tests__/route.spec.ts +++ b/app/api/supply/__tests__/route.spec.ts @@ -3,23 +3,20 @@ import { SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR, SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND, SOLANA_ERROR__JSON_RPC__PARSE_ERROR, - SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, SolanaError, } from '@solana/kit'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { connectionFailure, httpError, reported } from '@/app/__tests__/rpc-errors'; import { Logger } from '@/app/shared/lib/logger'; import { ROUTE_TIMEOUT_MS, UPSTREAM_TIMEOUT_MS } from '@/app/shared/lib/timeouts'; import { Cluster } from '@/app/utils/cluster'; import { GET, maxDuration } from '../route'; -const mocks = vi.hoisted(() => ({ getSupply: vi.fn(), send: vi.fn() })); +const mocks = { getSupply: vi.fn(), send: vi.fn() }; -vi.mock('@solana/kit', async () => { - const actual = await vi.importActual('@solana/kit'); - return { ...actual, createSolanaRpc: vi.fn(() => ({ getSupply: mocks.getSupply })) }; -}); +vi.mocked(createSolanaRpc).mockImplementation(() => ({ getSupply: mocks.getSupply }) as never); // Stubbed, so a local `.env` cannot decide what the route resolves to — an empty one would fail these // tests for a reason that has nothing to do with the route. @@ -180,13 +177,7 @@ describe('GET /api/supply', () => { expect(response.headers.get('Cache-Control')).toBe(ERROR_CACHE); // Under `sentryExtras`, because that is the only part of the context Sentry receives — a plain // field would report which cluster is dead to the console alone. - expect(Logger.error).toHaveBeenCalledWith( - expect.any(Error), - expect.objectContaining({ - sentry: true, - sentryExtras: expect.objectContaining({ cluster: Cluster.Testnet.toString() }), - }), - ); + expect(Logger.error).toHaveBeenCalledWith(expect.any(Error), reported({ cluster: Cluster.Testnet.toString() })); expect(mocks.getSupply).not.toHaveBeenCalled(); }); @@ -257,13 +248,7 @@ describe('GET /api/supply', () => { expect(response.headers.get('Cache-Control')).toBe(ERROR_CACHE); expect(Logger.error).toHaveBeenCalledWith( expect.anything(), - expect.objectContaining({ - sentry: true, - sentryExtras: expect.objectContaining({ - cluster: Cluster.Mainnet.toString(), - reason: 'rpc-refused', - }), - }), + reported({ cluster: Cluster.Mainnet.toString(), reason: 'rpc-refused' }), ); expect(Logger.panic).not.toHaveBeenCalled(); }); @@ -309,13 +294,7 @@ describe('GET /api/supply', () => { const response = await GET(createRequest(Cluster.Mainnet)); expect(await response.json()).toEqual({ error: 'Failed to fetch supply' }); - expect(Logger.error).toHaveBeenCalledWith( - expect.any(Error), - expect.objectContaining({ - sentry: true, - sentryExtras: expect.objectContaining({ reason: 'unclassified' }), - }), - ); + expect(Logger.error).toHaveBeenCalledWith(expect.any(Error), reported({ reason: 'unclassified' })); }); // A name that stops resolving and a TLS handshake nothing completes are upstream, not a caller's @@ -358,27 +337,3 @@ describe('GET /api/supply', () => { function createRequest(cluster: Cluster) { return new Request(`http://localhost:3000/api/supply?cluster=${cluster}`); } - -/** A node answering over HTTP rather than in JSON-RPC: a gateway, a key check, a wrong path. */ -function httpError(statusCode: number) { - return new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, { - headers: new Headers(), - message: `HTTP ${statusCode}`, - statusCode, - }); -} - -/** Shaped the way undici reports one: the code sits on an `Error` nested as `cause`. */ -function connectionFailure(code: string) { - const cause = Object.assign(new Error(`${code} on connect`), { code }); - return Object.assign(new TypeError('fetch failed'), { cause }); -} - -/** - * What has to be on a log call for the failure to reach Sentry at all: the flag, and the reason under - * `sentryExtras`, which is the only part of a context Sentry receives. A bare `toHaveBeenCalled` passes - * with both dropped, and the tier then fails silently for everyone. - */ -function reported(extras: Record) { - return expect.objectContaining({ sentry: true, sentryExtras: expect.objectContaining(extras) }); -} diff --git a/app/api/token-info/__tests__/route.spec.ts b/app/api/token-info/__tests__/route.spec.ts index 397738553b..917b991a75 100644 --- a/app/api/token-info/__tests__/route.spec.ts +++ b/app/api/token-info/__tests__/route.spec.ts @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { gen } from '@/app/__fixtures__/gen'; import { TokenInfoHttpError, TokenInfoInvalidResponseError } from '@/app/entities/token-info'; +import { tokenInfo } from '@/app/entities/token-info/__fixtures__/token-info'; import type { TokenInfo } from '@/app/entities/token-info/server'; import { Logger } from '@/app/shared/lib/logger'; import { Cluster } from '@/app/utils/cluster'; @@ -31,18 +32,6 @@ vi.mock('@entities/token-info/server', async () => { }; }); -function token(address: string, overrides: Partial = {}): TokenInfo { - return { - address, - decimals: 6, - logoURI: null, - name: `Token ${address.slice(0, 4)}`, - symbol: 'TKN', - verified: true, - ...overrides, - }; -} - describe('POST /api/token-info', () => { beforeEach(() => { vi.clearAllMocks(); @@ -129,23 +118,23 @@ describe('POST /api/token-info', () => { }); it('should accept a single address and still answer with an array', async () => { - mocks.getTokenInfos.mockResolvedValueOnce([token(MINT_A)]); + mocks.getTokenInfos.mockResolvedValueOnce([tokenInfo(MINT_A, true)]); const { POST } = await importRoute(); const res = await POST(createRequest({ address: MINT_A, cluster: Cluster.Mainnet })); expect(res.status).toBe(200); - expect(await res.json()).toEqual({ content: [token(MINT_A)] }); + expect(await res.json()).toEqual({ content: [tokenInfo(MINT_A, true)] }); expect(mocks.getTokenInfos).toHaveBeenCalledWith([MINT_A], Cluster.Mainnet, undefined, expect.anything()); }); it('should resolve several addresses in one request', async () => { - mocks.getTokenInfos.mockResolvedValueOnce([token(MINT_A), token(MINT_B)]); + mocks.getTokenInfos.mockResolvedValueOnce([tokenInfo(MINT_A, true), tokenInfo(MINT_B, true)]); const { POST } = await importRoute(); const res = await POST(createRequest({ addresses: [MINT_A, MINT_B], cluster: Cluster.Mainnet })); - expect(await res.json()).toEqual({ content: [token(MINT_A), token(MINT_B)] }); + expect(await res.json()).toEqual({ content: [tokenInfo(MINT_A, true), tokenInfo(MINT_B, true)] }); expect(mocks.getTokenInfos).toHaveBeenCalledWith( [MINT_A, MINT_B], Cluster.Mainnet, @@ -187,8 +176,8 @@ describe('POST /api/token-info', () => { }); it('should read on-chain metadata only for mints the list is missing', async () => { - mocks.getTokenInfos.mockResolvedValueOnce([token(MINT_A)]); - mocks.getTokenInfosFromMetaplex.mockResolvedValueOnce([token(MINT_C, { verified: false })]); + mocks.getTokenInfos.mockResolvedValueOnce([tokenInfo(MINT_A, true)]); + mocks.getTokenInfosFromMetaplex.mockResolvedValueOnce([tokenInfo(MINT_C, false)]); const { POST } = await importRoute(); const res = await POST( @@ -206,11 +195,11 @@ describe('POST /api/token-info', () => { expect.any(String), expect.not.objectContaining({ baseUrl: expect.anything() }), ); - expect(await res.json()).toEqual({ content: [token(MINT_A), token(MINT_C, { verified: false })] }); + expect(await res.json()).toEqual({ content: [tokenInfo(MINT_A, true), tokenInfo(MINT_C, false)] }); }); it('should skip the on-chain lookup when the list already covers every mint', async () => { - mocks.getTokenInfos.mockResolvedValueOnce([token(MINT_A), token(MINT_B)]); + mocks.getTokenInfos.mockResolvedValueOnce([tokenInfo(MINT_A, true), tokenInfo(MINT_B, true)]); const { POST } = await importRoute(); await POST( @@ -225,7 +214,7 @@ describe('POST /api/token-info', () => { }); it('should still return the listed tokens when the on-chain lookup throws', async () => { - mocks.getTokenInfos.mockResolvedValueOnce([token(MINT_A)]); + mocks.getTokenInfos.mockResolvedValueOnce([tokenInfo(MINT_A, true)]); mocks.getTokenInfosFromMetaplex.mockRejectedValueOnce(new Error('rpc exploded')); const { POST } = await importRoute(); @@ -238,7 +227,7 @@ describe('POST /api/token-info', () => { ); expect(res.status).toBe(200); - expect(await res.json()).toEqual({ content: [token(MINT_A)] }); + expect(await res.json()).toEqual({ content: [tokenInfo(MINT_A, true)] }); expect(Logger.warn).toHaveBeenCalled(); }); @@ -322,13 +311,13 @@ describe('POST /api/token-info', () => { }); it('should still answer the tokens it did resolve when only some were dropped', async () => { - failUpstream([token(MINT_A)]); + failUpstream([tokenInfo(MINT_A, true)]); const { POST } = await importRoute(); const res = await POST(createRequest({ addresses: [MINT_A, MINT_B], cluster: Cluster.Mainnet })); expect(res.status).toBe(200); - expect(await res.json()).toEqual({ content: [token(MINT_A)] }); + expect(await res.json()).toEqual({ content: [tokenInfo(MINT_A, true)] }); }); it('should keep answering 200 for a genuine all-not-found, which reports no error', async () => { diff --git a/app/api/token-market-data/[address]/__tests__/route.test.ts b/app/api/token-market-data/[address]/__tests__/route.test.ts index 5401ef1821..51831a24ef 100644 --- a/app/api/token-market-data/[address]/__tests__/route.test.ts +++ b/app/api/token-market-data/[address]/__tests__/route.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; +import { stubFetch } from '@/app/__tests__/rpc-fetch'; import { createCoinGeckoMarketData, createTokenMarketData, @@ -9,12 +10,8 @@ import { Logger } from '@/app/shared/lib/logger'; import { GET } from '../route'; const VALID_ADDRESS = 'B61SyRxF2b8JwSLZHgEUF6rtn6NUikkrK1EMEgP6nhXW'; -const fetchMock = vi.fn(); -vi.stubGlobal('fetch', fetchMock); +const { fetchMock, respondWith } = stubFetch(); -function mockFetchResponse(status: number, body: Record = {}) { - fetchMock.mockResolvedValueOnce({ json: async () => body, ok: status >= 200 && status < 300, status } as Response); -} function callRoute(address: string) { return GET(new Request(`http://localhost/api/token-market-data/${address}`), { params: Promise.resolve({ address }), @@ -32,14 +29,14 @@ describe('Token Market Data API Route', () => { }); it('should return the normalized shape', async () => { - mockFetchResponse(200, createCoinGeckoMarketData()); + respondWith(200, createCoinGeckoMarketData()); const r = await callRoute(VALID_ADDRESS); expect(r.status).toBe(200); expect(await r.json()).toEqual(createTokenMarketData()); }); it('should emit null marketCapRank for unranked tokens', async () => { - mockFetchResponse( + respondWith( 200, createCoinGeckoMarketData({ market_cap_rank: null, @@ -50,7 +47,7 @@ describe('Token Market Data API Route', () => { }); it('should omit priceChange24h when upstream lacks it', async () => { - mockFetchResponse( + respondWith( 200, createCoinGeckoMarketData({ market_cap_rank: null, @@ -61,7 +58,7 @@ describe('Token Market Data API Route', () => { }); it('should render price-only when market cap and volume are missing', async () => { - mockFetchResponse( + respondWith( 200, createCoinGeckoMarketData({ market_cap_rank: null, market_data: { current_price: { usd: 1.23 } } }), ); @@ -74,7 +71,7 @@ describe('Token Market Data API Route', () => { }); it('should return 404 with "No market data" when there is no USD price', async () => { - mockFetchResponse( + respondWith( 200, createCoinGeckoMarketData({ last_updated: null, @@ -89,12 +86,12 @@ describe('Token Market Data API Route', () => { }); it('should return 404 when upstream 404s', async () => { - mockFetchResponse(404); + respondWith(404, {}); expect((await callRoute(VALID_ADDRESS)).status).toBe(404); }); it('should return 429 and log to sentry when rate limited', async () => { - mockFetchResponse(429); + respondWith(429, {}); const r = await callRoute(VALID_ADDRESS); expect(r.status).toBe(429); expect(Logger.warn).toHaveBeenCalledWith('[api:token-market-data] Rate limit exceeded', { sentry: true }); @@ -102,7 +99,7 @@ describe('Token Market Data API Route', () => { it('should return 502 and log to sentry on a malformed schema', async () => { // Has a USD price (passes the pre-check) but last_updated is the wrong type. - mockFetchResponse( + respondWith( 200, createCoinGeckoMarketData({ last_updated: 12345, @@ -114,13 +111,7 @@ describe('Token Market Data API Route', () => { }); it('should return 502 and log when the upstream body is not valid JSON', async () => { - fetchMock.mockResolvedValueOnce({ - json: async () => { - throw new SyntaxError('Unexpected token < in JSON'); - }, - ok: true, - status: 200, - } as unknown as Response); + fetchMock.mockResolvedValueOnce(new Response('')); const r = await callRoute(VALID_ADDRESS); expect(r.status).toBe(502); expect(Logger.warn).toHaveBeenCalledWith('[api:token-market-data] Failed to parse upstream JSON', { @@ -143,7 +134,7 @@ describe('Token Market Data API Route', () => { it('should use the public API when COINGECKO_API_KEY is unset', async () => { vi.stubEnv('COINGECKO_API_KEY', ''); - mockFetchResponse(200, createCoinGeckoMarketData({ market_data: {} })); + respondWith(200, createCoinGeckoMarketData({ market_data: {} })); await callRoute(VALID_ADDRESS); const [url, options] = fetchMock.mock.calls[0]; expect(url).toContain('https://api.coingecko.com/api/v3/coins/solana/contract/'); @@ -152,7 +143,7 @@ describe('Token Market Data API Route', () => { it('should use the pro API with the key when COINGECKO_API_KEY is set', async () => { vi.stubEnv('COINGECKO_API_KEY', 'test-key'); - mockFetchResponse(200, createCoinGeckoMarketData({ market_data: {} })); + respondWith(200, createCoinGeckoMarketData({ market_data: {} })); await callRoute(VALID_ADDRESS); const [url, options] = fetchMock.mock.calls[0]; expect(url).toContain('https://pro-api.coingecko.com/api/v3/coins/solana/contract/'); diff --git a/app/api/verification/coingecko/__tests__/route.test.ts b/app/api/verification/coingecko/__tests__/route.test.ts index 674af05254..a0a3a4dc24 100644 --- a/app/api/verification/coingecko/__tests__/route.test.ts +++ b/app/api/verification/coingecko/__tests__/route.test.ts @@ -1,17 +1,14 @@ import { gen } from '@__fixtures__/gen'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { stubFetch } from '@/app/__tests__/rpc-fetch'; import { Logger } from '@/app/shared/lib/logger'; import { GET } from '../[address]/route'; const VALID_ADDRESS = gen.address(1); -const fetchMock = vi.fn(); -vi.stubGlobal('fetch', fetchMock); +const { fetchMock, respondWith } = stubFetch(); -function mockFetch(status: number, body: Record = {}) { - fetchMock.mockResolvedValueOnce({ json: async () => body, ok: status >= 200 && status < 300, status } as Response); -} function callRoute(address: string) { return GET(new Request(`http://localhost/api/verification/coingecko/${address}`), { params: Promise.resolve({ address }), @@ -31,7 +28,7 @@ describe('CoinGecko verification route (gt_verified)', () => { it('should call the keyless GeckoTerminal endpoint when COINGECKO_API_KEY is unset', async () => { vi.stubEnv('COINGECKO_API_KEY', ''); - mockFetch(200, { data: { attributes: { gt_verified: true } } }); + respondWith(200, { data: { attributes: { gt_verified: true } } }); const r = await callRoute(VALID_ADDRESS); expect(r.status).toBe(200); const [url, options] = fetchMock.mock.calls[0]; @@ -41,7 +38,7 @@ describe('CoinGecko verification route (gt_verified)', () => { }); it('should call the pro onchain /info endpoint with x-cg-pro-api-key', async () => { - mockFetch(200, { data: { attributes: { gt_verified: true } } }); + respondWith(200, { data: { attributes: { gt_verified: true } } }); await callRoute(VALID_ADDRESS); const [url, options] = fetchMock.mock.calls[0]; expect(url).toBe(`https://pro-api.coingecko.com/api/v3/onchain/networks/solana/tokens/${VALID_ADDRESS}/info`); @@ -49,55 +46,55 @@ describe('CoinGecko verification route (gt_verified)', () => { }); it('should return verified:true when gt_verified is true', async () => { - mockFetch(200, { data: { attributes: { gt_verified: true } } }); + respondWith(200, { data: { attributes: { gt_verified: true } } }); const r = await callRoute(VALID_ADDRESS); expect(r.status).toBe(200); expect(await r.json()).toEqual({ verified: true }); }); it('should return verified:false when gt_verified is false', async () => { - mockFetch(200, { data: { attributes: { gt_verified: false } } }); + respondWith(200, { data: { attributes: { gt_verified: false } } }); expect(await (await callRoute(VALID_ADDRESS)).json()).toEqual({ verified: false }); }); it('should return verified:false when gt_verified is absent', async () => { - mockFetch(200, { data: { attributes: {} } }); + respondWith(200, { data: { attributes: {} } }); const r = await callRoute(VALID_ADDRESS); expect(r.status).toBe(200); expect(await r.json()).toEqual({ verified: false }); }); it('should return verified:false when gt_verified is null without a 502', async () => { - mockFetch(200, { data: { attributes: { gt_verified: null } } }); + respondWith(200, { data: { attributes: { gt_verified: null } } }); const r = await callRoute(VALID_ADDRESS); expect(r.status).toBe(200); expect(await r.json()).toEqual({ verified: false }); }); it('should pass through coingecko_coin_id as coinGeckoId', async () => { - mockFetch(200, { data: { attributes: { coingecko_coin_id: 'usd-coin', gt_verified: true } } }); + respondWith(200, { data: { attributes: { coingecko_coin_id: 'usd-coin', gt_verified: true } } }); expect(await (await callRoute(VALID_ADDRESS)).json()).toEqual({ coinGeckoId: 'usd-coin', verified: true }); }); it('should omit coinGeckoId when coingecko_coin_id is null', async () => { - mockFetch(200, { data: { attributes: { coingecko_coin_id: null, gt_verified: true } } }); + respondWith(200, { data: { attributes: { coingecko_coin_id: null, gt_verified: true } } }); expect(await (await callRoute(VALID_ADDRESS)).json()).toEqual({ verified: true }); }); it('should pass through a 404', async () => { - mockFetch(404); + respondWith(404, {}); expect((await callRoute(VALID_ADDRESS)).status).toBe(404); }); it('should return 429 and log to sentry when rate limited', async () => { - mockFetch(429); + respondWith(429, {}); const r = await callRoute(VALID_ADDRESS); expect(r.status).toBe(429); expect(Logger.warn).toHaveBeenCalledWith('[api:coingecko] Rate limit exceeded', { sentry: true }); }); it.each([408, 500, 502, 503])('should pass through %i and report it to sentry as a warning', async status => { - mockFetch(status); + respondWith(status, {}); const r = await callRoute(VALID_ADDRESS); expect(r.status).toBe(status); expect(Logger.warn).toHaveBeenCalledWith(`[api:coingecko] Upstream returned ${status}`, { @@ -108,25 +105,19 @@ describe('CoinGecko verification route (gt_verified)', () => { }); it('should pass through a 403 and log panic', async () => { - mockFetch(403); + respondWith(403, {}); const r = await callRoute(VALID_ADDRESS); expect(r.status).toBe(403); expect(Logger.panic).toHaveBeenCalledWith(new Error('CoinGecko onchain info API error: 403')); }); it('should return 502 on a schema mismatch', async () => { - mockFetch(200, { unexpected: 'shape' }); + respondWith(200, { unexpected: 'shape' }); expect((await callRoute(VALID_ADDRESS)).status).toBe(502); }); it('should return 502 and log when the upstream body is not valid JSON', async () => { - fetchMock.mockResolvedValueOnce({ - json: async () => { - throw new SyntaxError('Unexpected token < in JSON'); - }, - ok: true, - status: 200, - } as unknown as Response); + fetchMock.mockResolvedValueOnce(new Response('')); const r = await callRoute(VALID_ADDRESS); expect(r.status).toBe(502); expect(Logger.warn).toHaveBeenCalledWith('[api:coingecko] Failed to parse upstream JSON', { diff --git a/app/api/verification/jupiter/__tests__/route.test.ts b/app/api/verification/jupiter/__tests__/route.test.ts index 613bd434cf..f5fecf4896 100644 --- a/app/api/verification/jupiter/__tests__/route.test.ts +++ b/app/api/verification/jupiter/__tests__/route.test.ts @@ -1,6 +1,7 @@ import { gen } from '@__fixtures__/gen'; import { vi } from 'vitest'; +import { stubFetch } from '@/app/__tests__/rpc-fetch'; import { Logger } from '@/app/shared/lib/logger'; // The route reads JUPITER_API_KEY into a module-level const, so the env must @@ -14,8 +15,7 @@ import { GET } from '../[mintAddress]/route'; const VALID_MINT = gen.address(1); -const fetchMock = vi.fn(); -vi.stubGlobal('fetch', fetchMock); +const { fetchMock, respondWith } = stubFetch(); describe('Jupiter API Route', () => { afterEach(() => { @@ -29,7 +29,7 @@ describe('Jupiter API Route', () => { }); it('should call the Jupiter search endpoint with the API key header and return verified: true', async () => { - mockFetchResponse(200, [{ id: VALID_MINT, isVerified: true }]); + respondWith(200, [{ id: VALID_MINT, isVerified: true }]); const response = await callRoute(VALID_MINT); const [url, options] = fetchMock.mock.calls[0]; @@ -47,14 +47,14 @@ describe('Jupiter API Route', () => { [{ id: 'OtherMint11111111111111111111111111111111111', isVerified: true }], ], ])('should return verified: false when %s', async (_reason, body) => { - mockFetchResponse(200, body); + respondWith(200, body); const response = await callRoute(VALID_MINT); expect(response.status).toBe(200); expect(await response.json()).toEqual({ verified: false }); }); it('should return 502 with short cache when the response shape is unexpected', async () => { - mockFetchResponse(200, { unexpected: 'shape' }); + respondWith(200, { unexpected: 'shape' }); const response = await callRoute(VALID_MINT); expect(response.status).toBe(502); expect(await response.json()).toEqual({ error: 'Upstream schema mismatch' }); @@ -65,7 +65,7 @@ describe('Jupiter API Route', () => { }); it('should return 404 silently when Jupiter responds with 404', async () => { - mockFetchResponse(404); + respondWith(404, []); const response = await callRoute(VALID_MINT); expect(response.status).toBe(404); expect(await response.json()).toEqual({ error: 'Failed to fetch jupiter data' }); @@ -74,7 +74,7 @@ describe('Jupiter API Route', () => { }); it('should return 429 and log to sentry when rate limited', async () => { - mockFetchResponse(429); + respondWith(429, []); const response = await callRoute(VALID_MINT); expect(response.status).toBe(429); expect(await response.json()).toEqual({ error: 'Failed to fetch jupiter data' }); @@ -82,7 +82,7 @@ describe('Jupiter API Route', () => { }); it.each([408, 500, 502, 503])('should pass through %i and report it to sentry as a warning', async status => { - mockFetchResponse(status); + respondWith(status, []); const response = await callRoute(VALID_MINT); expect(response.status).toBe(status); expect(await response.json()).toEqual({ error: 'Failed to fetch jupiter data' }); @@ -94,7 +94,7 @@ describe('Jupiter API Route', () => { }); it('should return upstream status and log panic for other error codes', async () => { - mockFetchResponse(403); + respondWith(403, []); const response = await callRoute(VALID_MINT); expect(response.status).toBe(403); expect(await response.json()).toEqual({ error: 'Failed to fetch jupiter data' }); @@ -124,16 +124,6 @@ describe('Jupiter API Route', () => { }); }); -function mockFetchResponse(status: number, body: unknown = []) { - const ok = status >= 200 && status < 300; - // Cast: tests only stub the surface of Response that the route touches. - fetchMock.mockResolvedValueOnce({ - json: async () => body, - ok, - status, - } as Response); -} - function callRoute(mintAddress: string) { const request = new Request(`http://localhost:3000/api/verification/jupiter/${mintAddress}`); return GET(request, { params: Promise.resolve({ mintAddress }) }); diff --git a/app/api/verification/rugcheck/__tests__/route.test.ts b/app/api/verification/rugcheck/__tests__/route.test.ts index 9d128b595d..899b2658fd 100644 --- a/app/api/verification/rugcheck/__tests__/route.test.ts +++ b/app/api/verification/rugcheck/__tests__/route.test.ts @@ -1,14 +1,14 @@ import { gen } from '@__fixtures__/gen'; import { vi } from 'vitest'; +import { stubFetch } from '@/app/__tests__/rpc-fetch'; import { Logger } from '@/app/shared/lib/logger'; import { GET } from '../[mintAddress]/route'; const VALID_MINT = gen.address(1); -const fetchMock = vi.fn(); -vi.stubGlobal('fetch', fetchMock); +const { fetchMock, respondWith } = stubFetch(); describe('Rugcheck API Route', () => { const originalEnv = process.env; @@ -40,7 +40,7 @@ describe('Rugcheck API Route', () => { [422, 'unable to generate report'], [404, 'invalid token mint'], ])('should return %i when rugcheck responds with 400 (%s)', async (expectedStatus, error) => { - mockFetchResponse(400, { error }); + respondWith(400, { error }); const response = await callRoute(VALID_MINT); expect(response.status).toBe(expectedStatus); expect(await response.json()).toEqual({ error: 'No rugcheck data available' }); @@ -48,28 +48,28 @@ describe('Rugcheck API Route', () => { }); it('should return 400 and report to sentry when rugcheck responds with 400 and unexpected body', async () => { - mockFetchResponse(400, { error: 'bad request' }); + respondWith(400, { error: 'bad request' }); const response = await callRoute(VALID_MINT); expect(response.status).toBe(400); expect(Logger.panic).toHaveBeenCalled(); }); it('should return 404 when rugcheck responds with 404', async () => { - mockFetchResponse(404); + respondWith(404, {}); const response = await callRoute(VALID_MINT); expect(response.status).toBe(404); expect(await response.json()).toEqual({ error: 'No rugcheck data available' }); }); it('should return 429 and log to sentry when rate limited', async () => { - mockFetchResponse(429); + respondWith(429, {}); const response = await callRoute(VALID_MINT); expect(response.status).toBe(429); expect(Logger.warn).toHaveBeenCalledWith('[api:rugcheck] Rate limit exceeded', { sentry: true }); }); it.each([408, 500, 502, 503])('should pass through %i and report it to sentry as a warning', async status => { - mockFetchResponse(status); + respondWith(status, {}); const response = await callRoute(VALID_MINT); expect(response.status).toBe(status); expect(Logger.warn).toHaveBeenCalledWith(`[api:rugcheck] Upstream returned ${status}`, { @@ -80,14 +80,14 @@ describe('Rugcheck API Route', () => { }); it('should return 502 when response schema is invalid', async () => { - mockFetchResponse(200, { unexpected: 'shape' }); + respondWith(200, { unexpected: 'shape' }); const response = await callRoute(VALID_MINT); expect(response.status).toBe(502); expect(await response.json()).toEqual({ error: 'Invalid response from rugcheck API' }); }); it('should return score on success', async () => { - mockFetchResponse(200, { score_normalised: 85 }); + respondWith(200, { score_normalised: 85 }); const response = await callRoute(VALID_MINT); expect(response.status).toBe(200); expect(await response.json()).toEqual({ score: 85 }); @@ -129,16 +129,6 @@ describe('Rugcheck API Route', () => { }); }); -function mockFetchResponse(status: number, body: Record = {}) { - const ok = status >= 200 && status < 300; - // Cast: tests only stub the surface of Response that the route touches. - fetchMock.mockResolvedValueOnce({ - json: async () => body, - ok, - status, - } as Response); -} - function callRoute(mintAddress: string) { const request = new Request(`http://localhost:3000/api/verification/rugcheck/${mintAddress}`); return GET(request, { params: Promise.resolve({ mintAddress }) }); diff --git a/app/components/__stories__/DeveloperResources.responsive.stories.tsx b/app/components/__stories__/DeveloperResources.responsive.stories.tsx index d583d72c15..3bdd2e0b5a 100644 --- a/app/components/__stories__/DeveloperResources.responsive.stories.tsx +++ b/app/components/__stories__/DeveloperResources.responsive.stories.tsx @@ -1,4 +1,4 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { DeveloperResources } from '../DeveloperResources'; @@ -7,7 +7,6 @@ import { DeveloperResources } from '../DeveloperResources'; const meta = { component: DeveloperResources, decorators: [withViewportFromGlobal], - parameters: { viewport: { options: INITIAL_VIEWPORTS } }, tags: ['autodocs', 'test'], title: 'Components/DeveloperResources@Media', } satisfies Meta; diff --git a/app/components/__stories__/Footer.responsive.stories.tsx b/app/components/__stories__/Footer.responsive.stories.tsx index 265be28f9a..4a446c686d 100644 --- a/app/components/__stories__/Footer.responsive.stories.tsx +++ b/app/components/__stories__/Footer.responsive.stories.tsx @@ -1,16 +1,12 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import { nextjsParameters, withCluster } from '../../../.storybook/decorators'; +import { withCluster } from '../../../.storybook/decorators'; import { Footer } from '../Footer'; const meta: Meta = { component: Footer, decorators: [withCluster, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Layout/Footer@Media', }; diff --git a/app/components/__stories__/Footer.stories.tsx b/app/components/__stories__/Footer.stories.tsx index dc387285b8..0e4af339d5 100644 --- a/app/components/__stories__/Footer.stories.tsx +++ b/app/components/__stories__/Footer.stories.tsx @@ -1,13 +1,12 @@ import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; -import { nextjsParameters, withCluster } from '../../../.storybook/decorators'; +import { withCluster } from '../../../.storybook/decorators'; import { Footer } from '../Footer'; const meta = { component: Footer, decorators: [withCluster], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Layout/Footer', } satisfies Meta; diff --git a/app/components/__stories__/LiveTransactionStatsCard.responsive.stories.tsx b/app/components/__stories__/LiveTransactionStatsCard.responsive.stories.tsx index 2c434b4671..12ebf8f25d 100644 --- a/app/components/__stories__/LiveTransactionStatsCard.responsive.stories.tsx +++ b/app/components/__stories__/LiveTransactionStatsCard.responsive.stories.tsx @@ -1,5 +1,5 @@ -import { nextjsParameters, withStats } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withMockRpc, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withStats } from '@storybook-config/decorators'; +import { withMockRpc, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { LiveTransactionStatsCard } from '../LiveTransactionStatsCard'; @@ -8,10 +8,6 @@ import { LiveTransactionStatsCard } from '../LiveTransactionStatsCard'; const meta: Meta = { component: LiveTransactionStatsCard, decorators: [withMockRpc, withViewportFromGlobal, withStats], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/LiveTransactionStatsCard@Media', }; diff --git a/app/components/__stories__/LiveTransactionStatsCard.stories.tsx b/app/components/__stories__/LiveTransactionStatsCard.stories.tsx index 25546b95c3..40da820f6e 100644 --- a/app/components/__stories__/LiveTransactionStatsCard.stories.tsx +++ b/app/components/__stories__/LiveTransactionStatsCard.stories.tsx @@ -1,4 +1,4 @@ -import { nextjsParameters, withStats } from '@storybook-config/decorators'; +import { withStats } from '@storybook-config/decorators'; import { withMockRpc } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; @@ -7,7 +7,6 @@ import { LiveTransactionStatsCard } from '../LiveTransactionStatsCard'; const meta: Meta = { component: LiveTransactionStatsCard, decorators: [withMockRpc, withStats], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/LiveTransactionStatsCard', }; diff --git a/app/components/__stories__/Navbar.responsive.stories.tsx b/app/components/__stories__/Navbar.responsive.stories.tsx index f9f644a8ef..c07d17e1d3 100644 --- a/app/components/__stories__/Navbar.responsive.stories.tsx +++ b/app/components/__stories__/Navbar.responsive.stories.tsx @@ -1,5 +1,5 @@ -import { nextjsParameters, withCluster } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withCluster } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { Navbar } from '../Navbar'; @@ -9,9 +9,7 @@ const meta = { component: Navbar, decorators: [withCluster, withViewportFromGlobal], parameters: { - ...nextjsParameters, docs: { story: { height: '120px' } }, - viewport: { options: INITIAL_VIEWPORTS }, }, tags: ['autodocs', 'test'], title: 'Components/Navbar@Media', diff --git a/app/components/__stories__/Navbar.stories.tsx b/app/components/__stories__/Navbar.stories.tsx index 0fac641ad2..1245a5f218 100644 --- a/app/components/__stories__/Navbar.stories.tsx +++ b/app/components/__stories__/Navbar.stories.tsx @@ -1,4 +1,4 @@ -import { nextjsParameters, withCluster, withClusterState } from '@storybook-config/decorators'; +import { withCluster, withClusterState } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { Cluster, ClusterStatus } from '@utils/cluster'; @@ -8,7 +8,6 @@ const meta = { component: Navbar, decorators: [withCluster], parameters: { - ...nextjsParameters, // Logo + navbar drawer need vertical room; pin the docs canvas so the full row is visible. docs: { story: { height: '80px' } }, }, diff --git a/app/components/__stories__/StatsNotReady.stories.tsx b/app/components/__stories__/StatsNotReady.stories.tsx index c4b88d5fc7..e419256aad 100644 --- a/app/components/__stories__/StatsNotReady.stories.tsx +++ b/app/components/__stories__/StatsNotReady.stories.tsx @@ -1,4 +1,4 @@ -import { nextjsParameters, withStats } from '@storybook-config/decorators'; +import { withStats } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { StatsNotReady } from '../StatsNotReady'; @@ -6,7 +6,6 @@ import { StatsNotReady } from '../StatsNotReady'; const meta: Meta = { component: StatsNotReady, decorators: [withStats], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/StatsNotReady', }; diff --git a/app/components/__tests__/ProgramLogsCardBody.spec.tsx b/app/components/__tests__/ProgramLogsCardBody.spec.tsx index 3ffa7f4003..02cc1c7f10 100644 --- a/app/components/__tests__/ProgramLogsCardBody.spec.tsx +++ b/app/components/__tests__/ProgramLogsCardBody.spec.tsx @@ -3,14 +3,9 @@ import { type AnchorIdl, type CodamaIdl, IdlVariant, type ProgramIdls } from '@e import anchorModernIdl from '@entities/idl/mocks/anchor/anchor-0.30.1-devi51mZmdwUJGU9hjN27vEz64Gps7uUefqxg27EAtH.json'; import referenceIdl from '@entities/idl/mocks/anchor/reference-0.29.json'; import codamaIdl from '@entities/idl/mocks/codama/codama-1.0.0-ProgM6JCCvbYkfKqJYHePx4xxSUSqJp7rh8Lyv7nk7S.json'; +import { compileV0Message } from '@entities/transaction-data/__fixtures__/wire-transactions'; import { getBase58Decoder } from '@solana/kit'; -import { - type ParsedMessage, - PublicKey, - TransactionInstruction, - TransactionMessage, - type VersionedMessage, -} from '@solana/web3.js'; +import { type ParsedMessage, PublicKey, TransactionInstruction, type VersionedMessage } from '@solana/web3.js'; import { render, screen } from '@testing-library/react'; import { beforeEach, describe, expect, it, vi } from 'vitest'; @@ -138,21 +133,15 @@ function renamedIdl(name: string): AnchorIdl { return { ...anchorModernIdl, instructions: [{ ...first, name }, ...rest] } as unknown as AnchorIdl; } -function renderLogs(message: VersionedMessage | ParsedMessage = v0Message()) { +function renderLogs( + message: VersionedMessage | ParsedMessage = compileV0Message(gen.publicKey(0), CREATE_AMM_CONFIG_IX), +) { const logs = [{ computeUnits: 0, failed: false, invokedProgram: DEVI.toBase58(), logs: [], truncated: false }]; return render( , ); } -function v0Message(): VersionedMessage { - return new TransactionMessage({ - instructions: [CREATE_AMM_CONFIG_IX], - payerKey: gen.publicKey(0), - recentBlockhash: PublicKey.default.toBase58(), - }).compileToV0Message(); -} - function parsedMessage(): ParsedMessage { const { data, keys } = CREATE_AMM_CONFIG_IX; return { diff --git a/app/components/account/__fixtures__/compressed-nft.ts b/app/components/account/__fixtures__/compressed-nft.ts new file mode 100644 index 0000000000..a65ded10e0 --- /dev/null +++ b/app/components/account/__fixtures__/compressed-nft.ts @@ -0,0 +1,65 @@ +import type { CompressedNft } from '@providers/compressed-nft'; + +export function compressedNft({ + assetInterface = 'V1_NFT', + collection = null, + compressed = true, + mutable = true, + name = 'Compressed Ape #42', + owner = '', + symbol = 'cAPE', +}: Partial<{ + assetInterface: string; + collection: string | null; + compressed: boolean; + mutable: boolean; + name: string; + owner: string; + symbol: string; +}> = {}): CompressedNft { + return { + authorities: [], + burnt: false, + compression: { + asset_hash: '', + compressed, + creator_hash: '', + data_hash: '', + eligible: compressed, + leaf_id: 0, + seq: 0, + tree: '', + }, + content: { + $schema: '', + files: [], + // Empty json_uri → useMetadataJsonLink short-circuits to null; ArtContent renders the placeholder. + json_uri: '', + links: { external_url: '', image: '' }, + metadata: { attributes: [], description: '', name, symbol, token_standard: '' }, + }, + creators: [], + grouping: collection ? [{ group_key: 'collection', group_value: collection }] : [], + id: 'CompressedNftaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + interface: assetInterface, + mutable, + ownership: { delegate: null, delegated: false, frozen: false, owner, ownership_model: 'single' }, + royalty: { + basis_points: 0, + locked: false, + percent: 0, + primary_sale_happened: false, + royalty_model: '', + target: null, + }, + supply: { edition_nonce: null, print_current_supply: 0, print_max_supply: 0 }, + }; +} + +export const FUNGIBLE_TOKEN = { + assetInterface: 'FungibleToken', + compressed: false, + mutable: false, + name: 'dogwifhat', + symbol: '$WIF', +}; diff --git a/app/components/account/__fixtures__/owned-tokens.ts b/app/components/account/__fixtures__/owned-tokens.ts new file mode 100644 index 0000000000..44a89520d7 --- /dev/null +++ b/app/components/account/__fixtures__/owned-tokens.ts @@ -0,0 +1,38 @@ +import { tokenInfo } from '@entities/token-info/__fixtures__/token-info'; +import type { TokenInfoWithPubkey } from '@providers/accounts/tokens'; +import { FetchStatus } from '@providers/cache'; +import { PublicKey } from '@solana/web3.js'; + +export const OWNER = '11111111111111111111111111111111'; +export const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; +export const TOKEN_ACCOUNT = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'; + +export function ownedTokensEntry(tokens: TokenInfoWithPubkey[]) { + return { data: { tokens }, status: FetchStatus.Fetched }; +} + +export function ownedToken( + tokenAmount: TokenInfoWithPubkey['info']['tokenAmount'], + pubkey = TOKEN_ACCOUNT, + mint = USDC_MINT, +): TokenInfoWithPubkey { + return { + info: { + isNative: false, + mint: new PublicKey(mint), + owner: new PublicKey(OWNER), + state: 'initialized', + tokenAmount, + }, + pubkey: new PublicKey(pubkey), + }; +} + +export const USDC_HOLDING = ownedToken({ amount: '1234560000', decimals: 6, uiAmountString: '1234.56' }); + +export const USDC_TOKEN_INFO = tokenInfo(USDC_MINT, true, { + logoURI: + 'https://raw.githubusercontent.com/solana-labs/token-list/main/assets/mainnet/EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v/logo.png', + name: 'USD Coin', + symbol: 'USDC', +}); diff --git a/app/components/account/__stories__/AccountHeader.responsive.stories.tsx b/app/components/account/__stories__/AccountHeader.responsive.stories.tsx index 6d5b53e72a..3a8b9aef18 100644 --- a/app/components/account/__stories__/AccountHeader.responsive.stories.tsx +++ b/app/components/account/__stories__/AccountHeader.responsive.stories.tsx @@ -1,14 +1,12 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { TokenMintHeaderCard } from '../AccountHeader'; +import * as Base from './AccountHeader.stories'; const meta: Meta = { component: TokenMintHeaderCard, decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Account/AccountHeader/TokenMintHeaderCard@Media', }; @@ -16,9 +14,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - token: { logoURI: undefined, name: 'USD Coin', symbol: 'USDC' }, -}; +const args = Base.WithLogo.args; export const Mobile: Story = { args, diff --git a/app/components/account/__stories__/AnchorAccountCard.responsive.stories.tsx b/app/components/account/__stories__/AnchorAccountCard.responsive.stories.tsx index f41f28dc7e..7e399aed59 100644 --- a/app/components/account/__stories__/AnchorAccountCard.responsive.stories.tsx +++ b/app/components/account/__stories__/AnchorAccountCard.responsive.stories.tsx @@ -1,27 +1,13 @@ -import { Account } from '@providers/accounts'; -import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withCluster } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withCluster } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { AnchorAccountCard } from '../AnchorAccountCard'; - -const sampleAccount: Account = { - data: { raw: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]) }, - executable: false, - lamports: 1_000_000_000, - owner: new PublicKey('11111111111111111111111111111111'), - pubkey: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), - space: 9, -}; +import * as Base from './AnchorAccountCard.stories'; const meta: Meta = { component: AnchorAccountCard, decorators: [withCluster, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Account/AnchorAccountCard@Media', }; @@ -29,7 +15,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { account: sampleAccount }; +const args = Base.NoIdl.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/components/account/__stories__/AnchorAccountCard.stories.tsx b/app/components/account/__stories__/AnchorAccountCard.stories.tsx index e63eb331cd..0bb8bbcac8 100644 --- a/app/components/account/__stories__/AnchorAccountCard.stories.tsx +++ b/app/components/account/__stories__/AnchorAccountCard.stories.tsx @@ -1,25 +1,16 @@ -import { Account } from '@providers/accounts'; -import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withCluster } from '@storybook-config/decorators'; +import { makeAccount } from '@entities/account/__fixtures__/account'; +import { withCluster } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { AnchorAccountCard } from '../AnchorAccountCard'; -const sampleAccount: Account = { - data: { raw: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]) }, - executable: false, - lamports: 1_000_000_000, - owner: new PublicKey('11111111111111111111111111111111'), - pubkey: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), - space: 9, -}; +const sampleAccount = makeAccount({ data: { raw: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]) }, space: 9 }); // Without an Anchor IDL the card renders the ErrorCard fallback. Rendering with a real // decoded account requires a working Anchor IDL fetch, which isn't available in Storybook. const meta = { component: AnchorAccountCard, decorators: [withCluster], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Account/AnchorAccountCard', } satisfies Meta; diff --git a/app/components/account/__stories__/AttestationDataCard.responsive.stories.tsx b/app/components/account/__stories__/AttestationDataCard.responsive.stories.tsx index 29dd4a54e8..bbe0134116 100644 --- a/app/components/account/__stories__/AttestationDataCard.responsive.stories.tsx +++ b/app/components/account/__stories__/AttestationDataCard.responsive.stories.tsx @@ -1,55 +1,13 @@ -import { Account, type State } from '@providers/accounts'; -import { FetchStatus } from '@providers/cache'; -import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withAccountsState } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import { fromBase64 } from '@/app/shared/lib/bytes'; -import { MAINNET_BETA_URL } from '@/app/utils/cluster'; - import { AttestationDataCard } from '../sas/AttestationDataCard'; -import attestationFixture from './mocks/bluprynt-attestation.json'; -import schemaFixture from './mocks/bluprynt-schema.json'; +import * as Base from './AttestationDataCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. -type FixtureAccount = { - address: string; - info: { data: [string, 'base64']; executable: boolean; lamports: number; owner: string; space: number }; -}; - -function buildAccount(fixture: FixtureAccount): Account { - return { - data: { raw: fromBase64(fixture.info.data[0]) }, - executable: fixture.info.executable, - lamports: fixture.info.lamports, - owner: new PublicKey(fixture.info.owner), - pubkey: new PublicKey(fixture.address), - space: fixture.info.space, - }; -} - -const schemaAccount = buildAccount(schemaFixture as unknown as FixtureAccount); -const attestationAccount = buildAccount(attestationFixture as unknown as FixtureAccount); - -const stateWithSchema: State = { - entries: { - [schemaAccount.pubkey.toBase58()]: { data: schemaAccount, status: FetchStatus.Fetched }, - }, - url: MAINNET_BETA_URL, -}; - -function onNotFound(): never { - throw new Error('Fixture failed to decode — check the captured account bytes.'); -} - const meta = { component: AttestationDataCard, - decorators: [withViewportFromGlobal, withAccountsState(stateWithSchema)], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withViewportFromGlobal], tags: ['autodocs', 'test'], title: 'Components/Account/AttestationDataCard@Media', } satisfies Meta; @@ -57,19 +15,22 @@ const meta = { export default meta; type Story = StoryObj; -const args = { account: attestationAccount, onNotFound }; +const { args, decorators } = Base.AttestationWithSchema; export const Mobile: Story = { args, + decorators, globals: { viewport: { value: 'iphonex' } }, }; export const TabletPortrait: Story = { args, + decorators, globals: { viewport: { value: 'ipad' } }, }; export const TabletLandscape: Story = { args, + decorators, globals: { viewport: { isRotated: true, value: 'ipad' } }, }; diff --git a/app/components/account/__stories__/AttestationDataCard.stories.tsx b/app/components/account/__stories__/AttestationDataCard.stories.tsx index 34dbaff877..f5bf2d3b50 100644 --- a/app/components/account/__stories__/AttestationDataCard.stories.tsx +++ b/app/components/account/__stories__/AttestationDataCard.stories.tsx @@ -1,10 +1,8 @@ -import { Account, DispatchContext, FetchersContext, type State, StateContext } from '@providers/accounts'; +import { Account, type State } from '@providers/accounts'; import { FetchStatus } from '@providers/cache'; import { PublicKey } from '@solana/web3.js'; -import { MockClusterProvider as ClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; -import { nextjsParameters } from '@storybook-config/decorators'; -import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; -import React from 'react'; +import { withAccountsState } from '@storybook-config/decorators'; +import type { Meta, StoryObj } from '@storybook-config/types'; import { fromBase64 } from '@/app/shared/lib/bytes'; import { MAINNET_BETA_URL } from '@/app/utils/cluster'; @@ -32,8 +30,6 @@ function buildAccount(fixture: FixtureAccount): Account { const schemaAccount = buildAccount(schemaFixture as unknown as FixtureAccount); const attestationAccount = buildAccount(attestationFixture as unknown as FixtureAccount); -const noop = () => undefined; - // AttestationCard reads the schema from useAccountInfo to deserialize attestation `data`. const stateWithSchema: State = { entries: { @@ -42,29 +38,12 @@ const stateWithSchema: State = { url: MAINNET_BETA_URL, }; -function MockAccountsState({ children, state }: { children: React.ReactNode; state: State }) { - return ( - - - - - {children} - - - - - ); -} - function onNotFound(): never { throw new Error('Fixture failed to decode — check the captured account bytes.'); } const meta = { component: AttestationDataCard, - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Account/AttestationDataCard', } satisfies Meta; @@ -72,17 +51,9 @@ const meta = { export default meta; type Story = StoryObj; -const withEmptyAccounts: Decorator = Story => ( - - - -); +const withEmptyAccounts = withAccountsState({ entries: {}, url: MAINNET_BETA_URL }); -const withSchemaInCache: Decorator = Story => ( - - - -); +const withSchemaInCache = withAccountsState(stateWithSchema); // Schema account (decodes as SAS Schema → renders SchemaCard with the Borsh layout). export const Schema: Story = { diff --git a/app/components/account/__stories__/BlockhashesCard.responsive.stories.tsx b/app/components/account/__stories__/BlockhashesCard.responsive.stories.tsx index c71b53d2a4..33bedb2c8f 100644 --- a/app/components/account/__stories__/BlockhashesCard.responsive.stories.tsx +++ b/app/components/account/__stories__/BlockhashesCard.responsive.stories.tsx @@ -1,16 +1,13 @@ -import { gen } from '@__fixtures__/gen'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BlockhashesCard } from '../BlockhashesCard'; +import * as Base from './BlockhashesCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta: Meta = { component: BlockhashesCard, decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Account/BlockhashesCard@Media', }; @@ -18,12 +15,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - blockhashes: Array.from({ length: 4 }, (_, i) => ({ - blockhash: gen.blockhash(i), - feeCalculator: { lamportsPerSignature: '5000' }, - })), -}; +const args = Base.WithEntries.args; export const Mobile: Story = { args, diff --git a/app/components/account/__stories__/BufferBuildCard.stories.tsx b/app/components/account/__stories__/BufferBuildCard.stories.tsx index 3af4b42369..a3ae81ab5c 100644 --- a/app/components/account/__stories__/BufferBuildCard.stories.tsx +++ b/app/components/account/__stories__/BufferBuildCard.stories.tsx @@ -1,4 +1,4 @@ -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import type { OsecBuild } from '@/app/utils/verified-builds'; @@ -42,7 +42,6 @@ const UNTRUSTED_BUILD: OsecBuild = { const meta = { component: BaseBufferBuildCard, decorators: [withClusterAndAccounts, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Account/BufferBuildCard', } satisfies Meta; diff --git a/app/components/account/__stories__/CompressedNFTInfoCard.responsive.stories.tsx b/app/components/account/__stories__/CompressedNFTInfoCard.responsive.stories.tsx index 3b7e2d6049..9d2dc431ed 100644 --- a/app/components/account/__stories__/CompressedNFTInfoCard.responsive.stories.tsx +++ b/app/components/account/__stories__/CompressedNFTInfoCard.responsive.stories.tsx @@ -1,44 +1,14 @@ -import { DEFAULT_BLOCKHASH, gen } from '@__fixtures__/gen'; -import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import type { CompressedNft, CompressedNftProof } from '@/app/providers/compressed-nft'; - import { DasCompressionInfoCard } from '../CompressedNFTInfoCard'; +import * as Base from './CompressedNFTInfoCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. -const TREE_KEY = TOKEN_PROGRAM_ADDRESS; - -const sampleProof: CompressedNftProof = { - leaf: DEFAULT_BLOCKHASH, - node_index: 0, - proof: [gen.blockhash(1), gen.blockhash(2), gen.blockhash(3), gen.blockhash(4)], - root: gen.blockhash(5), - tree_id: TREE_KEY, -}; - -const sampleCompressedNft = { - compression: { - asset_hash: gen.blockhash(10), - compressed: true, - creator_hash: gen.blockhash(11), - data_hash: gen.blockhash(12), - eligible: true, - leaf_id: 42, - seq: 17, - tree: TREE_KEY, - }, -} as unknown as CompressedNft; - const meta = { component: DasCompressionInfoCard, decorators: [withViewportFromGlobal, withClusterAndAccounts, withTokenInfoBatch], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Account/CompressedNFTInfoCard@Media', } satisfies Meta; @@ -46,10 +16,7 @@ const meta = { export default meta; type Story = StoryObj; -const args = { - compressedNft: sampleCompressedNft, - proof: sampleProof, -}; +const args = Base.Default.args; export const Mobile: Story = { args, diff --git a/app/components/account/__stories__/CompressedNFTInfoCard.stories.tsx b/app/components/account/__stories__/CompressedNFTInfoCard.stories.tsx index f594ce51ab..99dafc1967 100644 --- a/app/components/account/__stories__/CompressedNFTInfoCard.stories.tsx +++ b/app/components/account/__stories__/CompressedNFTInfoCard.stories.tsx @@ -1,5 +1,5 @@ import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import type { CompressedNft, CompressedNftProof } from '@/app/providers/compressed-nft'; @@ -43,7 +43,6 @@ const meta = { component: DasCompressionInfoCard, decorators: [withClusterAndAccounts, withTokenInfoBatch], parameters: { - ...nextjsParameters, docs: { description: { component: [ diff --git a/app/components/account/__stories__/CompressedNftCard.responsive.stories.tsx b/app/components/account/__stories__/CompressedNftCard.responsive.stories.tsx index 3f34b16508..5ec10a0e00 100644 --- a/app/components/account/__stories__/CompressedNftCard.responsive.stories.tsx +++ b/app/components/account/__stories__/CompressedNftCard.responsive.stories.tsx @@ -1,60 +1,13 @@ import { withClusterAndAccounts } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import type { CompressedNft } from '@/app/providers/compressed-nft'; - import { CompressedNFTHeader } from '../CompressedNftCard'; - -const compressedNft = { - authorities: [], - burnt: false, - compression: { - asset_hash: '', - compressed: true, - creator_hash: '', - data_hash: '', - eligible: true, - leaf_id: 0, - seq: 0, - tree: '', - }, - content: { - $schema: '', - files: [], - json_uri: '', - links: { external_url: '', image: '' }, - metadata: { - attributes: [], - description: '', - name: 'Compressed Ape #42', - symbol: 'cAPE', - token_standard: '', - }, - }, - creators: [], - grouping: [], - id: 'CompressedNftaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', - interface: '', - mutable: true, - ownership: { delegate: null, delegated: false, frozen: false, owner: '', ownership_model: 'single' }, - royalty: { - basis_points: 0, - locked: false, - percent: 0, - primary_sale_happened: false, - royalty_model: '', - target: null, - }, - supply: { edition_nonce: null, print_current_supply: 0, print_max_supply: 0 }, -} satisfies CompressedNft; +import * as Base from './CompressedNftCard.stories'; const meta: Meta = { component: CompressedNFTHeader, decorators: [withClusterAndAccounts, withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Account/CompressedNFTHeader@Media', }; @@ -62,7 +15,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { compressedNft }; +const args = Base.Default.args; export const Mobile: Story = { args, diff --git a/app/components/account/__stories__/CompressedNftCard.stories.tsx b/app/components/account/__stories__/CompressedNftCard.stories.tsx index a12eeb1dae..5ca5bbba6b 100644 --- a/app/components/account/__stories__/CompressedNftCard.stories.tsx +++ b/app/components/account/__stories__/CompressedNftCard.stories.tsx @@ -1,67 +1,9 @@ +import { compressedNft, FUNGIBLE_TOKEN } from '@components/account/__fixtures__/compressed-nft'; import { withClusterAndAccounts } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import type { CompressedNft } from '@/app/providers/compressed-nft'; - import { CompressedNFTHeader } from '../CompressedNftCard'; -function buildCompressedNft( - overrides: Partial<{ - name: string; - symbol: string; - mutable: boolean; - compressed: boolean; - assetInterface: string; - collection: string | null; - }> = {}, -): CompressedNft { - const { - name = 'Compressed Ape #42', - symbol = 'cAPE', - mutable = true, - compressed = true, - assetInterface = 'V1_NFT', - collection = null, - } = overrides; - return { - authorities: [], - burnt: false, - compression: { - asset_hash: '', - compressed, - creator_hash: '', - data_hash: '', - eligible: compressed, - leaf_id: 0, - seq: 0, - tree: '', - }, - content: { - $schema: '', - files: [], - // Empty json_uri → useMetadataJsonLink short-circuits to null; ArtContent renders the placeholder. - json_uri: '', - links: { external_url: '', image: '' }, - metadata: { attributes: [], description: '', name, symbol, token_standard: '' }, - }, - creators: [], - grouping: collection ? [{ group_key: 'collection', group_value: collection }] : [], - id: 'CompressedNftaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', - interface: assetInterface, - mutable, - ownership: { delegate: null, delegated: false, frozen: false, owner: '', ownership_model: 'single' }, - royalty: { - basis_points: 0, - locked: false, - percent: 0, - primary_sale_happened: false, - royalty_model: '', - target: null, - }, - supply: { edition_nonce: null, print_current_supply: 0, print_max_supply: 0 }, - }; -} - const meta: Meta = { component: CompressedNFTHeader, decorators: [withClusterAndAccounts], @@ -73,33 +15,25 @@ export default meta; type Story = StoryObj; export const Default: Story = { - args: { compressedNft: buildCompressedNft() }, + args: { compressedNft: compressedNft() }, }; export const Immutable: Story = { - args: { compressedNft: buildCompressedNft({ mutable: false }) }, + args: { compressedNft: compressedNft({ mutable: false }) }, }; export const NoName: Story = { - args: { compressedNft: buildCompressedNft({ name: '' }) }, + args: { compressedNft: compressedNft({ name: '' }) }, }; export const NoSymbol: Story = { - args: { compressedNft: buildCompressedNft({ symbol: '' }) }, + args: { compressedNft: compressedNft({ symbol: '' }) }, }; export const VerifiedCollection: Story = { - args: { compressedNft: buildCompressedNft({ collection: 'CoLLeCtionaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }) }, + args: { compressedNft: compressedNft({ collection: 'CoLLeCtionaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }) }, }; export const UncompressedToken: Story = { - args: { - compressedNft: buildCompressedNft({ - assetInterface: 'FungibleToken', - compressed: false, - mutable: false, - name: 'dogwifhat', - symbol: '$WIF', - }), - }, + args: { compressedNft: compressedNft(FUNGIBLE_TOKEN) }, }; diff --git a/app/components/account/__stories__/ConcurrentMerkleTreeCard.responsive.stories.tsx b/app/components/account/__stories__/ConcurrentMerkleTreeCard.responsive.stories.tsx index fa74387ae9..62c2904414 100644 --- a/app/components/account/__stories__/ConcurrentMerkleTreeCard.responsive.stories.tsx +++ b/app/components/account/__stories__/ConcurrentMerkleTreeCard.responsive.stories.tsx @@ -1,5 +1,5 @@ -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { ConcurrentMerkleTreeCard } from '../ConcurrentMerkleTreeCard'; @@ -8,10 +8,6 @@ import { buildConcurrentMerkleTreeData } from './mocks/concurrent-merkle-tree'; const meta: Meta = { component: ConcurrentMerkleTreeCard, decorators: [withCluster, withTokenInfoBatch, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Account/ConcurrentMerkleTreeCard@Media', }; diff --git a/app/components/account/__stories__/ConcurrentMerkleTreeCard.stories.tsx b/app/components/account/__stories__/ConcurrentMerkleTreeCard.stories.tsx index 90bd31d0e1..2c15d87ca0 100644 --- a/app/components/account/__stories__/ConcurrentMerkleTreeCard.stories.tsx +++ b/app/components/account/__stories__/ConcurrentMerkleTreeCard.stories.tsx @@ -1,4 +1,4 @@ -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { ConcurrentMerkleTreeCard } from '../ConcurrentMerkleTreeCard'; @@ -7,7 +7,6 @@ import { buildConcurrentMerkleTreeData } from './mocks/concurrent-merkle-tree'; const meta = { component: ConcurrentMerkleTreeCard, decorators: [withCluster, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Account/ConcurrentMerkleTreeCard', } satisfies Meta; diff --git a/app/components/account/__stories__/FeatureAccountSection.responsive.stories.tsx b/app/components/account/__stories__/FeatureAccountSection.responsive.stories.tsx index e397b0d846..624bee6fb4 100644 --- a/app/components/account/__stories__/FeatureAccountSection.responsive.stories.tsx +++ b/app/components/account/__stories__/FeatureAccountSection.responsive.stories.tsx @@ -1,19 +1,14 @@ -import { gen } from '@__fixtures__/gen'; -import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { FeatureAccountSection } from '../FeatureAccountSection'; +import * as Base from './FeatureAccountSection.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta = { component: FeatureAccountSection, decorators: [withClusterAndAccounts, withTokenInfoBatch, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Account/FeatureAccountSection@Media', } satisfies Meta; @@ -21,16 +16,7 @@ const meta = { export default meta; type Story = StoryObj; -const args = { - account: { - data: {}, - executable: false, - lamports: 1_000_000_000, - owner: PublicKey.default, - pubkey: gen.publicKey(1), - space: 9, - }, -}; +const args = Base.UnknownFeatureAccount.args; export const Mobile: Story = { args, diff --git a/app/components/account/__stories__/FeatureAccountSection.stories.tsx b/app/components/account/__stories__/FeatureAccountSection.stories.tsx index 51b2f5a550..9a652a5c9d 100644 --- a/app/components/account/__stories__/FeatureAccountSection.stories.tsx +++ b/app/components/account/__stories__/FeatureAccountSection.stories.tsx @@ -1,6 +1,6 @@ import { gen } from '@__fixtures__/gen'; -import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { makeAccount } from '@entities/account/__fixtures__/account'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { FeatureAccountSection } from '../FeatureAccountSection'; @@ -8,7 +8,6 @@ import { FeatureAccountSection } from '../FeatureAccountSection'; const meta = { component: FeatureAccountSection, decorators: [withClusterAndAccounts, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Account/FeatureAccountSection', } satisfies Meta; @@ -18,14 +17,7 @@ type Story = StoryObj; // Random pubkey that won't match any known feature gate; ErrorBoundary falls back to UnknownAccountCard // when isFeature parsing fails on the empty account body. -const unknownAccount = { - data: {}, - executable: false, - lamports: 1_000_000_000, - owner: PublicKey.default, - pubkey: gen.publicKey(1), - space: 9, -}; +const unknownAccount = makeAccount({ pubkey: gen.publicKey(1), space: 9 }); export const UnknownFeatureAccount: Story = { args: { diff --git a/app/components/account/__stories__/FeatureGateCard.responsive.stories.tsx b/app/components/account/__stories__/FeatureGateCard.responsive.stories.tsx index 0c67b65ea0..89bae6a584 100644 --- a/app/components/account/__stories__/FeatureGateCard.responsive.stories.tsx +++ b/app/components/account/__stories__/FeatureGateCard.responsive.stories.tsx @@ -1,20 +1,14 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { FeatureGateCard } from '../FeatureGateCard'; -import { FeatureGateMarkdown } from '../FeatureGateMarkdown'; -import { SIMD_0266_MARKDOWN, SIMD_0266_URL } from './feature-gate-fixtures'; +import * as Base from './FeatureGateCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta: Meta = { - args: { - children: {SIMD_0266_MARKDOWN}, - }, + args: Base.Default.args, component: FeatureGateCard, decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Account/FeatureGateCard@Media', }; diff --git a/app/components/account/__stories__/MetaplexNFTAttributesCard.responsive.stories.tsx b/app/components/account/__stories__/MetaplexNFTAttributesCard.responsive.stories.tsx index 90d8d695a5..721cbeea19 100644 --- a/app/components/account/__stories__/MetaplexNFTAttributesCard.responsive.stories.tsx +++ b/app/components/account/__stories__/MetaplexNFTAttributesCard.responsive.stories.tsx @@ -1,32 +1,12 @@ -import { nextjsParameters } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; -import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import type { Meta, StoryObj } from '@storybook-config/types'; import { NormalMetaplexNFTAttributesCard } from '../MetaplexNFTAttributesCard'; - -const METADATA_URI = 'https://example.test/nft-metadata.json'; - -const sampleAttributesJson = { - attributes: [ - { trait_type: 'Background', value: 'Cosmic Purple' }, - { trait_type: 'Eyes', value: 'Laser' }, - { trait_type: 'Mouth', value: 'Smile' }, - { trait_type: 'Rarity Rank', value: 42 }, - ], -}; - -const withFetchOverride: Decorator = Story => { - global.fetch = (async () => ({ json: async () => sampleAttributesJson, ok: true }) as Response) as typeof fetch; - return ; -}; +import * as Base from './MetaplexNFTAttributesCard.stories'; const meta: Meta = { component: NormalMetaplexNFTAttributesCard, - decorators: [withFetchOverride, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withViewportFromGlobal], tags: ['autodocs', 'test'], title: 'Components/Account/MetaplexNFTAttributesCard@Media', }; @@ -34,8 +14,8 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { metadataUri: METADATA_URI }; +const { args, decorators } = Base.WithAttributes; -export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; -export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; -export const TabletLandscape: Story = { args, globals: { viewport: { isRotated: true, value: 'ipad' } } }; +export const Mobile: Story = { args, decorators, globals: { viewport: { value: 'iphonex' } } }; +export const TabletPortrait: Story = { args, decorators, globals: { viewport: { value: 'ipad' } } }; +export const TabletLandscape: Story = { args, decorators, globals: { viewport: { isRotated: true, value: 'ipad' } } }; diff --git a/app/components/account/__stories__/MetaplexNFTAttributesCard.stories.tsx b/app/components/account/__stories__/MetaplexNFTAttributesCard.stories.tsx index 3a94954d98..3fc26dd4f4 100644 --- a/app/components/account/__stories__/MetaplexNFTAttributesCard.stories.tsx +++ b/app/components/account/__stories__/MetaplexNFTAttributesCard.stories.tsx @@ -1,4 +1,3 @@ -import { nextjsParameters } from '@storybook-config/decorators'; import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; import { NormalMetaplexNFTAttributesCard } from '../MetaplexNFTAttributesCard'; @@ -31,7 +30,6 @@ function makeFetchOverride(body: unknown, ok = true): Decorator { const meta = { component: NormalMetaplexNFTAttributesCard, - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Account/MetaplexNFTAttributesCard', } satisfies Meta; diff --git a/app/components/account/__stories__/MetaplexNFTHeader.responsive.stories.tsx b/app/components/account/__stories__/MetaplexNFTHeader.responsive.stories.tsx index 2be12ddd75..0dbf0bf20f 100644 --- a/app/components/account/__stories__/MetaplexNFTHeader.responsive.stories.tsx +++ b/app/components/account/__stories__/MetaplexNFTHeader.responsive.stories.tsx @@ -1,32 +1,13 @@ import { withClusterAndAccounts } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import type { NFTData } from '@/app/providers/accounts'; - import { MetaplexNFTHeader } from '../MetaplexNFTHeader'; - -const ADDRESS = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; - -const nftData = { - editionInfo: { masterEdition: { supply: 1000n } as never }, - json: undefined, - metadata: { - collection: { __option: 'None' }, - creators: { __option: 'None' }, - isMutable: true, - name: 'Bored Ape #1234', - primarySaleHappened: false, - symbol: 'BAYC', - }, -} as unknown as NFTData; +import * as Base from './MetaplexNFTHeader.stories'; const meta: Meta = { component: MetaplexNFTHeader, decorators: [withClusterAndAccounts, withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Account/MetaplexNFTHeader@Media', }; @@ -34,7 +15,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { address: ADDRESS, nftData }; +const args = Base.MasterEdition.args; export const Mobile: Story = { args, diff --git a/app/components/account/__stories__/MetaplexNFTHeader.stories.tsx b/app/components/account/__stories__/MetaplexNFTHeader.stories.tsx index 2c94fa814c..d37483ea1b 100644 --- a/app/components/account/__stories__/MetaplexNFTHeader.stories.tsx +++ b/app/components/account/__stories__/MetaplexNFTHeader.stories.tsx @@ -1,46 +1,10 @@ +import { makeNftData } from '@entities/nft/__fixtures__/make-nft-data'; import { withClusterAndAccounts } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import type { NFTData } from '@/app/providers/accounts'; - import { MetaplexNFTHeader } from '../MetaplexNFTHeader'; -// MetaplexNFTHeader reads flat fields on `metadata`; the local `NFTData` type is acknowledged -// as incomplete (see app/features/metadata/mocks.ts), so each fixture casts via `as unknown as NFTData`. -function buildNftData( - overrides: Partial<{ - name: string; - symbol: string; - isMutable: boolean; - primarySaleHappened: boolean; - collection: { key: string; verified: boolean } | null; - edition: { masterEdition?: { supply: bigint }; edition?: { edition: bigint } }; - image: string; - }> = {}, -): NFTData { - const { - name = 'Bored Ape #1234', - symbol = 'BAYC', - isMutable = true, - primarySaleHappened = false, - collection = null, - edition = {}, - image = '', - } = overrides; - - return { - editionInfo: edition, - json: image ? { image } : undefined, - metadata: { - collection: collection ? { __option: 'Some', value: collection } : { __option: 'None' }, - creators: { __option: 'None' }, - isMutable, - name, - primarySaleHappened, - symbol, - }, - } as unknown as NFTData; -} +const BORED_APE = { json: undefined, name: 'Bored Ape #1234', symbol: 'BAYC' }; const meta: Meta = { component: MetaplexNFTHeader, @@ -54,22 +18,21 @@ type Story = StoryObj; export const Default: Story = { args: { - nftData: buildNftData(), + nftData: makeNftData(BORED_APE), }, }; export const MasterEdition: Story = { args: { - nftData: buildNftData({ - edition: { masterEdition: { supply: 1000n } as never }, - }), + nftData: makeNftData({ ...BORED_APE, editionInfo: { masterEdition: { supply: 1000n } as never } }), }, }; export const NumberedEdition: Story = { args: { - nftData: buildNftData({ - edition: { + nftData: makeNftData({ + ...BORED_APE, + editionInfo: { edition: { edition: 42n } as never, masterEdition: { supply: 1000n } as never, }, @@ -79,18 +42,18 @@ export const NumberedEdition: Story = { export const NoName: Story = { args: { - nftData: buildNftData({ name: '' }), + nftData: makeNftData({ ...BORED_APE, name: '' }), }, }; export const NoSymbol: Story = { args: { - nftData: buildNftData({ symbol: '' }), + nftData: makeNftData({ ...BORED_APE, symbol: '' }), }, }; export const Immutable: Story = { args: { - nftData: buildNftData({ isMutable: false }), + nftData: makeNftData({ ...BORED_APE, isMutable: false }), }, }; diff --git a/app/components/account/__stories__/OwnedTokensCard.responsive.stories.tsx b/app/components/account/__stories__/OwnedTokensCard.responsive.stories.tsx index 748649ce9b..bf12e4fa1c 100644 --- a/app/components/account/__stories__/OwnedTokensCard.responsive.stories.tsx +++ b/app/components/account/__stories__/OwnedTokensCard.responsive.stories.tsx @@ -1,68 +1,13 @@ -import { - DispatchContext as TokensDispatch, - type State as TokensState, - StateContext as TokensStateCtx, -} from '@providers/accounts/tokens'; -import { FetchStatus } from '@providers/cache'; -import { PublicKey } from '@solana/web3.js'; -import { MockAccountsProvider } from '@storybook-config/__mocks__/MockAccountsProvider'; -import { MockClusterProvider as ClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; -import { nextjsParameters, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; -import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; -import React from 'react'; +import { withTokenInfoBatch } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import type { Meta, StoryObj } from '@storybook-config/types'; import { OwnedTokensCard } from '../OwnedTokensCard'; - -const ADDRESS = '11111111111111111111111111111111'; -const noop = () => undefined; - -const tokensState = (entries: TokensState['entries']): TokensState => ({ - entries, - url: 'https://api.mainnet-beta.solana.com', -}); - -const sampleEntry = { - data: { - tokens: [ - { - info: { - isNative: false, - mint: new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), - owner: new PublicKey(ADDRESS), - state: 'initialized' as const, - tokenAmount: { amount: '1234560000', decimals: 6, uiAmount: 1234.56, uiAmountString: '1234.56' }, - }, - logoURI: - 'https://raw.githubusercontent.com/solana-labs/token-list/main/assets/mainnet/EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v/logo.png', - name: 'USD Coin', - pubkey: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), - symbol: 'USDC', - }, - ], - }, - status: FetchStatus.Fetched, -}; - -const withTokens: Decorator = Story => ( - - - - - - - - - -); +import * as Base from './OwnedTokensCard.stories'; const meta: Meta = { component: OwnedTokensCard, - decorators: [withTokenInfoBatch, withTokens, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withTokenInfoBatch, withViewportFromGlobal], tags: ['autodocs', 'test'], title: 'Components/Account/OwnedTokensCard@Media', }; @@ -70,19 +15,22 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { address: ADDRESS }; +const { args, decorators } = Base.WithHoldings; export const Mobile: Story = { args, + decorators, globals: { viewport: { value: 'iphonex' } }, }; export const TabletPortrait: Story = { args, + decorators, globals: { viewport: { value: 'ipad' } }, }; export const TabletLandscape: Story = { args, + decorators, globals: { viewport: { isRotated: true, value: 'ipad' } }, }; diff --git a/app/components/account/__stories__/OwnedTokensCard.stories.tsx b/app/components/account/__stories__/OwnedTokensCard.stories.tsx index 1f6f664967..bfdb8dfde5 100644 --- a/app/components/account/__stories__/OwnedTokensCard.stories.tsx +++ b/app/components/account/__stories__/OwnedTokensCard.stories.tsx @@ -1,17 +1,22 @@ import { gen } from '@__fixtures__/gen'; +import { + ownedToken, + ownedTokensEntry, + OWNER, + USDC_HOLDING, + USDC_MINT, + USDC_TOKEN_INFO, +} from '@components/account/__fixtures__/owned-tokens'; import { ChainId } from '@entities/chain-id'; -import { type TokenInfo } from '@entities/token-info'; import { getTokenInfosSwrKey } from '@entities/token-info/client'; import { DispatchContext as TokensDispatch, type State as TokensState, StateContext as TokensStateCtx, } from '@providers/accounts/tokens'; -import { FetchStatus } from '@providers/cache'; -import { PublicKey } from '@solana/web3.js'; import { MockAccountsProvider } from '@storybook-config/__mocks__/MockAccountsProvider'; import { MockClusterProvider as ClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; -import { nextjsParameters, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withTokenInfoBatch } from '@storybook-config/decorators'; import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; import React from 'react'; import { expect, within } from 'storybook/test'; @@ -19,28 +24,16 @@ import { SWRConfig, unstable_serialize } from 'swr'; import { OwnedTokensCard } from '../OwnedTokensCard'; -const ADDRESS = '11111111111111111111111111111111'; const noop = () => undefined; -const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; const WSOL_MINT = 'So11111111111111111111111111111111111111112'; -const usdcTokenInfo: TokenInfo = { - address: USDC_MINT, - decimals: 6, - logoURI: - 'https://raw.githubusercontent.com/solana-labs/token-list/main/assets/mainnet/EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v/logo.png', - name: 'USD Coin', - symbol: 'USDC', - verified: true, -}; - // The card resolves every held mint in one lookup, so seed that lookup's cache entry rather than the // per-mint batch provider. No entry for WSOL: an unresolved mint draws the fallback logo and, having // no verified flag, sorts below the seeded row. const seededTokenInfos = { [unstable_serialize(getTokenInfosSwrKey([USDC_MINT, WSOL_MINT], ChainId.MAINNET))]: new Map([ - [USDC_MINT, usdcTokenInfo], + [USDC_MINT, USDC_TOKEN_INFO], ]), }; @@ -49,52 +42,13 @@ const tokensState = (entries: TokensState['entries']): TokensState => ({ url: 'https://api.mainnet-beta.solana.com', }); -const sampleTokensEntry = { - data: { - tokens: [ - { - info: { - isNative: false, - mint: new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), - owner: new PublicKey(ADDRESS), - state: 'initialized' as const, - tokenAmount: { amount: '1234560000', decimals: 6, uiAmount: 1234.56, uiAmountString: '1234.56' }, - }, - pubkey: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), - }, - ], - }, - status: FetchStatus.Fetched, -}; +const sampleTokensEntry = ownedTokensEntry([USDC_HOLDING]); -const sampleTokensWithLogosEntry = { - data: { - tokens: [ - { - info: { - isNative: false, - mint: new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), - owner: new PublicKey(ADDRESS), - state: 'initialized' as const, - tokenAmount: { amount: '1234560000', decimals: 6, uiAmount: 1234.56, uiAmountString: '1234.56' }, - }, - pubkey: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), - }, - { - info: { - isNative: false, - mint: new PublicKey(WSOL_MINT), - owner: new PublicKey(ADDRESS), - state: 'initialized' as const, - tokenAmount: { amount: '5000000000', decimals: 9, uiAmount: 5, uiAmountString: '5' }, - }, - // No seeded logo for this mint exercises the fallback-logo branch alongside the seeded USDC row. - pubkey: gen.publicKey(2), - }, - ], - }, - status: FetchStatus.Fetched, -}; +const sampleTokensWithLogosEntry = ownedTokensEntry([ + USDC_HOLDING, + // No seeded logo for this mint exercises the fallback-logo branch alongside the seeded USDC row. + ownedToken({ amount: '5000000000', decimals: 9, uiAmountString: '5' }, gen.address(2), WSOL_MINT), +]); function MockTokensState({ children, value }: { children: React.ReactNode; value: TokensState }) { return ( @@ -109,23 +63,19 @@ function MockTokensState({ children, value }: { children: React.ReactNode; value } const withTokens: Decorator = Story => ( - + ); const withTokensAndLogos: Decorator = Story => ( - + ); const withNoTokens: Decorator = Story => ( - + ); @@ -133,7 +83,6 @@ const withNoTokens: Decorator = Story => ( const meta = { component: OwnedTokensCard, decorators: [withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Account/OwnedTokensCard', } satisfies Meta; @@ -142,12 +91,12 @@ export default meta; type Story = StoryObj; export const WithHoldings: Story = { - args: { address: ADDRESS }, + args: { address: OWNER }, decorators: [withTokens], }; export const WithLogos: Story = { - args: { address: ADDRESS }, + args: { address: OWNER }, decorators: [ // Its own cache, and no revalidation: a fallback is only read when nothing is cached, and it // does not stop SWR refetching. There is no route to answer that fetch here, so without both @@ -165,11 +114,11 @@ export const WithLogos: Story = { // GridTable mobile="stack" renders the balance in both the desktop and mobile layouts. const balances = await within(canvasElement).findAllByText('1234.56 USDC'); expect(balances.length).toBeGreaterThan(0); - await expect(canvasElement.querySelector('img')).toHaveAttribute('src', usdcTokenInfo.logoURI); + await expect(canvasElement.querySelector('img')).toHaveAttribute('src', USDC_TOKEN_INFO.logoURI); }, }; export const Empty: Story = { - args: { address: ADDRESS }, + args: { address: OWNER }, decorators: [withNoTokens], }; diff --git a/app/components/account/__stories__/ProgramMultisigCard.responsive.stories.tsx b/app/components/account/__stories__/ProgramMultisigCard.responsive.stories.tsx index 2f4c65dd87..7573824c50 100644 --- a/app/components/account/__stories__/ProgramMultisigCard.responsive.stories.tsx +++ b/app/components/account/__stories__/ProgramMultisigCard.responsive.stories.tsx @@ -1,22 +1,14 @@ -import { DEFAULT_SLOT } from '@__fixtures__/gen'; -import { PublicKey } from '@solana/web3.js'; -import { createNextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import type { UpgradeableLoaderAccountData } from '@/app/providers/accounts'; - import { ProgramMultisigCard } from '../ProgramMultisigCard'; +import * as Base from './ProgramMultisigCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. -// Devnet short-circuits useSquadsMultisigLookup so Suspense resolves without RPC calls. const meta = { component: ProgramMultisigCard, - decorators: [withViewportFromGlobal, withClusterAndAccounts, withTokenInfoBatch], - parameters: { - ...createNextjsParameters({ query: { cluster: 'devnet' } }), - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withViewportFromGlobal, ...Base.default.decorators], + parameters: Base.default.parameters, tags: ['autodocs', 'test'], title: 'Components/Account/ProgramMultisigCard@Media', } satisfies Meta; @@ -24,20 +16,7 @@ const meta = { export default meta; type Story = StoryObj; -const args = { - data: { - parsed: { - info: { programData: PublicKey.default }, - type: 'program', - }, - program: 'bpf-upgradeable-loader', - programData: { - authority: PublicKey.default, - data: ['', 'base64'], - slot: DEFAULT_SLOT, - }, - } satisfies UpgradeableLoaderAccountData, -}; +const args = Base.Default.args; export const Mobile: Story = { args, diff --git a/app/components/account/__stories__/ProgramMultisigCard.stories.tsx b/app/components/account/__stories__/ProgramMultisigCard.stories.tsx index 06f2d4436a..44ebbfb889 100644 --- a/app/components/account/__stories__/ProgramMultisigCard.stories.tsx +++ b/app/components/account/__stories__/ProgramMultisigCard.stories.tsx @@ -1,9 +1,9 @@ +import { makeProgramAccountData, makeProgramDataInfo } from '@entities/account/__fixtures__/account'; import { PublicKey } from '@solana/web3.js'; import { createNextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; import { SWRConfig, unstable_serialize } from 'swr'; -import type { UpgradeableLoaderAccountData } from '@/app/providers/accounts'; import { Cluster } from '@/app/utils/cluster'; import { ProgramMultisigCard } from '../ProgramMultisigCard'; @@ -37,17 +37,6 @@ type Story = StoryObj; export const Default: Story = { args: { - data: { - parsed: { - info: { programData: PublicKey.default }, - type: 'program', - }, - program: 'bpf-upgradeable-loader', - programData: { - authority: PublicKey.default, - data: ['', 'base64'], - slot: 312_000_000, - }, - } satisfies UpgradeableLoaderAccountData, + data: makeProgramAccountData(makeProgramDataInfo()), }, }; diff --git a/app/components/account/__stories__/RewardsCard.responsive.stories.tsx b/app/components/account/__stories__/RewardsCard.responsive.stories.tsx index 367a78d6d3..c8b425a5ea 100644 --- a/app/components/account/__stories__/RewardsCard.responsive.stories.tsx +++ b/app/components/account/__stories__/RewardsCard.responsive.stories.tsx @@ -1,68 +1,14 @@ -import { DEFAULT_SLOT, gen } from '@__fixtures__/gen'; -import { DispatchContext as RewardsDispatch, StateContext as RewardsStateCtx } from '@providers/accounts/rewards'; -import { FetchStatus } from '@providers/cache'; -import { PublicKey } from '@solana/web3.js'; -import { MockClusterProvider as ClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; -import { nextjsParameters, withClusterAndAccounts } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; -import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; -import React from 'react'; +import { withClusterAndAccounts } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import type { Meta, StoryObj } from '@storybook-config/types'; import { RewardsCard } from '../RewardsCard'; +import * as Base from './RewardsCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. -const ADDRESS = PublicKey.default.toBase58(); -const noop = () => undefined; - -const rewardsState = { - entries: { - [ADDRESS]: { - data: { - foundOldest: true, - highestFetchedEpoch: 502, - lowestFetchedEpoch: 500, - rewards: [ - { - amount: 12_500_000, - commission: null, - effectiveSlot: DEFAULT_SLOT, - epoch: 502, - postBalance: 5_012_500_000, - rewardType: 'staking', - }, - { - amount: 11_800_000, - commission: null, - effectiveSlot: Number(gen.slot(1)), - epoch: 501, - postBalance: 5_000_000_000, - rewardType: 'staking', - }, - ], - }, - status: FetchStatus.Fetched, - }, - }, - url: 'https://api.mainnet-beta.solana.com', -}; - -const withRewards: Decorator = Story => ( - - - - - - - -); - const meta = { component: RewardsCard, - decorators: [withViewportFromGlobal, withClusterAndAccounts, withRewards], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withViewportFromGlobal, withClusterAndAccounts], tags: ['autodocs', 'test'], title: 'Components/Account/RewardsCard@Media', } satisfies Meta; @@ -70,19 +16,22 @@ const meta = { export default meta; type Story = StoryObj; -const args = { address: ADDRESS }; +const { args, decorators } = Base.WithRewardsList; export const Mobile: Story = { args, + decorators, globals: { viewport: { value: 'iphonex' } }, }; export const TabletPortrait: Story = { args, + decorators, globals: { viewport: { value: 'ipad' } }, }; export const TabletLandscape: Story = { args, + decorators, globals: { viewport: { isRotated: true, value: 'ipad' } }, }; diff --git a/app/components/account/__stories__/RewardsCard.stories.tsx b/app/components/account/__stories__/RewardsCard.stories.tsx index c03ea414df..e84a36c4eb 100644 --- a/app/components/account/__stories__/RewardsCard.stories.tsx +++ b/app/components/account/__stories__/RewardsCard.stories.tsx @@ -1,7 +1,7 @@ import { DispatchContext as RewardsDispatch, StateContext as RewardsStateCtx } from '@providers/accounts/rewards'; import { FetchStatus } from '@providers/cache'; import { MockClusterProvider as ClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; -import { nextjsParameters, withClusterAndAccounts } from '@storybook-config/decorators'; +import { withClusterAndAccounts } from '@storybook-config/decorators'; import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; import React from 'react'; @@ -55,7 +55,6 @@ const withRewards: Decorator = Story => ( const meta = { component: RewardsCard, decorators: [withClusterAndAccounts], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Account/RewardsCard', } satisfies Meta; diff --git a/app/components/account/__stories__/SlotHashesCard.responsive.stories.tsx b/app/components/account/__stories__/SlotHashesCard.responsive.stories.tsx index ca5e4ea64b..1231b6e445 100644 --- a/app/components/account/__stories__/SlotHashesCard.responsive.stories.tsx +++ b/app/components/account/__stories__/SlotHashesCard.responsive.stories.tsx @@ -1,20 +1,14 @@ -import { gen } from '@__fixtures__/gen'; -import { nextjsParameters, withCluster } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withCluster } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import type { SysvarSlotHashesAccount } from '@/app/validators/accounts/sysvar'; - import { SlotHashesCard } from '../SlotHashesCard'; +import * as Base from './SlotHashesCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta: Meta = { component: SlotHashesCard, decorators: [withViewportFromGlobal, withCluster], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Account/SlotHashesCard@Media', }; @@ -22,16 +16,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const baseSlot = gen.slot(0); -const args = { - sysvarAccount: { - info: Array.from({ length: 4 }, (_, i) => ({ - hash: gen.blockhash(i), - slot: Number(baseSlot) - i, - })), - type: 'slotHashes', - } satisfies SysvarSlotHashesAccount, -}; +const args = Base.WithEntries.args; export const Mobile: Story = { args, diff --git a/app/components/account/__stories__/SlotHashesCard.stories.tsx b/app/components/account/__stories__/SlotHashesCard.stories.tsx index 51d4185cdb..a4d4c35dd4 100644 --- a/app/components/account/__stories__/SlotHashesCard.stories.tsx +++ b/app/components/account/__stories__/SlotHashesCard.stories.tsx @@ -1,4 +1,4 @@ -import { nextjsParameters, withCluster } from '@storybook-config/decorators'; +import { withCluster } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import type { SysvarSlotHashesAccount } from '@/app/validators/accounts/sysvar'; @@ -9,7 +9,6 @@ const meta: Meta = { component: SlotHashesCard, decorators: [withCluster], parameters: { - ...nextjsParameters, docs: { description: { component: [ diff --git a/app/components/account/__stories__/TokenExtensionsCard.stories.tsx b/app/components/account/__stories__/TokenExtensionsCard.stories.tsx index 65522f8a4a..81af58d9ab 100644 --- a/app/components/account/__stories__/TokenExtensionsCard.stories.tsx +++ b/app/components/account/__stories__/TokenExtensionsCard.stories.tsx @@ -1,4 +1,4 @@ -import { nextjsParameters, withClusterAndAccounts } from '@storybook-config/decorators'; +import { withClusterAndAccounts } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { TokenExtensionsCard } from '../TokenExtensionsCard'; @@ -8,7 +8,6 @@ import { TokenExtensionsCard } from '../TokenExtensionsCard'; const meta = { component: TokenExtensionsCard, decorators: [withClusterAndAccounts], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Account/TokenExtensionsCard', } satisfies Meta; diff --git a/app/components/account/__stories__/TokenExtensionsSection.stories.tsx b/app/components/account/__stories__/TokenExtensionsSection.stories.tsx index f4de2f5148..68936a2b5c 100644 --- a/app/components/account/__stories__/TokenExtensionsSection.stories.tsx +++ b/app/components/account/__stories__/TokenExtensionsSection.stories.tsx @@ -1,4 +1,4 @@ -import { nextjsParameters, withClusterAndAccounts } from '@storybook-config/decorators'; +import { withClusterAndAccounts } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import type { TokenExtension } from '@/app/validators/accounts/token-extension'; @@ -44,7 +44,6 @@ const sampleExtensions: TokenExtension[] = [ const meta = { component: TokenExtensionsSection, decorators: [withClusterAndAccounts], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Account/TokenExtensionsSection', } satisfies Meta; diff --git a/app/components/account/__stories__/TokenHistoryCard.responsive.stories.tsx b/app/components/account/__stories__/TokenHistoryCard.responsive.stories.tsx index 08e82d6e9b..40f9e65f7a 100644 --- a/app/components/account/__stories__/TokenHistoryCard.responsive.stories.tsx +++ b/app/components/account/__stories__/TokenHistoryCard.responsive.stories.tsx @@ -1,80 +1,12 @@ -import { - DispatchContext as TokensDispatch, - type State as TokensState, - StateContext as TokensStateCtx, -} from '@providers/accounts/tokens'; -import { FetchStatus } from '@providers/cache'; -import { - DispatchContext as ParsedDetailsDispatch, - StateContext as ParsedDetailsStateCtx, -} from '@providers/transactions/parsed'; -import { PublicKey } from '@solana/web3.js'; -import { MockAccountsProvider } from '@storybook-config/__mocks__/MockAccountsProvider'; -import { MockClusterProvider as ClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; -import { MockHistoryProvider } from '@storybook-config/__mocks__/MockHistoryProvider'; -import { nextjsParameters, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; -import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; -import React from 'react'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import type { Meta, StoryObj } from '@storybook-config/types'; import { TokenHistoryCard } from '../TokenHistoryCard'; - -const ADDRESS = PublicKey.default.toBase58(); -const MAINNET_RPC_URL = 'https://api.mainnet-beta.solana.com'; -const noop = () => undefined; - -type ParsedDetailsState = React.ContextType; - -const tokensStateValue: TokensState = { - entries: { - [ADDRESS]: { - data: { - tokens: [ - { - info: { - isNative: false, - mint: new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), - owner: PublicKey.default, - state: 'initialized', - tokenAmount: { amount: '0', decimals: 6, uiAmountString: '0' }, - }, - pubkey: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), - }, - ], - }, - status: FetchStatus.Fetched, - }, - }, - url: MAINNET_RPC_URL, -}; - -const emptyParsedDetailsState: ParsedDetailsState = { entries: {}, url: MAINNET_RPC_URL }; - -const withToken: Decorator = Story => ( - - - - - - - - - - - - - - - -); +import * as Base from './TokenHistoryCard.stories'; const meta: Meta = { component: TokenHistoryCard, - decorators: [withTokenInfoBatch, withToken, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [...Base.default.decorators, withViewportFromGlobal], tags: ['autodocs', 'test'], title: 'Components/Account/TokenHistoryCard@Media', }; @@ -82,7 +14,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { address: ADDRESS }; +const args = Base.InitialLoadPrompt.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/components/account/__stories__/TokenHistoryCard.stories.tsx b/app/components/account/__stories__/TokenHistoryCard.stories.tsx index a0eaac93cd..626d5192d0 100644 --- a/app/components/account/__stories__/TokenHistoryCard.stories.tsx +++ b/app/components/account/__stories__/TokenHistoryCard.stories.tsx @@ -14,7 +14,7 @@ import { ConfirmedSignatureInfo, PublicKey } from '@solana/web3.js'; import { MockAccountsProvider } from '@storybook-config/__mocks__/MockAccountsProvider'; import { MockClusterProvider as ClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; import { MockHistoryProvider } from '@storybook-config/__mocks__/MockHistoryProvider'; -import { createNextjsParameters, nextjsParameters, withTokenInfoBatch } from '@storybook-config/decorators'; +import { createNextjsParameters, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; import React from 'react'; import { expect, userEvent, within } from 'storybook/test'; @@ -117,7 +117,6 @@ async function loadHistory(canvasElement: HTMLElement) { const meta = { component: TokenHistoryCard, decorators: [withCard, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Account/TokenHistoryCard', } satisfies Meta; diff --git a/app/components/account/__stories__/UnknownAccountCard.responsive.stories.tsx b/app/components/account/__stories__/UnknownAccountCard.responsive.stories.tsx index 199cac18a0..c4e0787909 100644 --- a/app/components/account/__stories__/UnknownAccountCard.responsive.stories.tsx +++ b/app/components/account/__stories__/UnknownAccountCard.responsive.stories.tsx @@ -1,19 +1,14 @@ -import { gen } from '@__fixtures__/gen'; -import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { UnknownAccountCard } from '../UnknownAccountCard'; +import * as Base from './UnknownAccountCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta = { component: UnknownAccountCard, decorators: [withClusterAndAccounts, withTokenInfoBatch, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Account/UnknownAccountCard@Media', } satisfies Meta; @@ -21,16 +16,7 @@ const meta = { export default meta; type Story = StoryObj; -const args = { - account: { - data: {}, - executable: false, - lamports: 1_000_000_000, - owner: PublicKey.default, - pubkey: gen.publicKey(1), - space: 165, - }, -}; +const args = Base.WithBalance.args; export const Mobile: Story = { args, diff --git a/app/components/account/__stories__/UnknownAccountCard.stories.tsx b/app/components/account/__stories__/UnknownAccountCard.stories.tsx index b3b934325d..92cafe0b98 100644 --- a/app/components/account/__stories__/UnknownAccountCard.stories.tsx +++ b/app/components/account/__stories__/UnknownAccountCard.stories.tsx @@ -1,6 +1,6 @@ import { gen } from '@__fixtures__/gen'; -import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { makeAccount } from '@entities/account/__fixtures__/account'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { UnknownAccountCard } from '../UnknownAccountCard'; @@ -8,7 +8,6 @@ import { UnknownAccountCard } from '../UnknownAccountCard'; const meta = { component: UnknownAccountCard, decorators: [withClusterAndAccounts, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Account/UnknownAccountCard', } satisfies Meta; @@ -16,14 +15,7 @@ const meta = { export default meta; type Story = StoryObj; -const baseAccount = { - data: {}, - executable: false, - lamports: 1_000_000_000, - owner: PublicKey.default, - pubkey: gen.publicKey(1), - space: 165, -}; +const baseAccount = makeAccount({ pubkey: gen.publicKey(1), space: 165 }); export const WithBalance: Story = { args: { diff --git a/app/components/account/__stories__/VerifiedBuildCard.responsive.stories.tsx b/app/components/account/__stories__/VerifiedBuildCard.responsive.stories.tsx index a1da6050f3..df6fae6f3d 100644 --- a/app/components/account/__stories__/VerifiedBuildCard.responsive.stories.tsx +++ b/app/components/account/__stories__/VerifiedBuildCard.responsive.stories.tsx @@ -1,42 +1,14 @@ -import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import type { OsecRegistryInfo } from '@/app/utils/verified-builds'; -import { VerificationStatus } from '@/app/utils/verified-builds'; - import { BaseVerifiedBuildCard } from '../VerifiedBuildCard'; +import * as Base from './VerifiedBuildCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. -const PROGRAM_DATA = { - programData: { - authority: '5vJwnLeyjV8uNJSp1zn7VLW8GwiQbcsQbGaVSwRmkE4r', - data: ['', 'base64'], - slot: 0, - }, -} as any; - -const VERIFIED_FIXTURE: OsecRegistryInfo = { - executable_hash: '0000000000000000000000000000000000000000000000000000000000000000', - is_verified: true, - last_verified_at: '2026-01-01T00:00:00.000Z', - message: 'Verification information provided by a trusted signer.', - on_chain_hash: '0000000000000000000000000000000000000000000000000000000000000000', - onchain_repo_url: 'https://github.com/example/verified-program', - repo_url: 'https://github.com/example/verified-program', - signer: '5vJwnLeyjV8uNJSp1zn7VLW8GwiQbcsQbGaVSwRmkE4r', - verification_status: VerificationStatus.Verified, - verify_command: `solana-verify verify-from-repo -um --program-id ${TOKEN_PROGRAM_ADDRESS} https://github.com/example/verified-program --commit-hash abc1234`, -}; - const meta = { component: BaseVerifiedBuildCard, decorators: [withViewportFromGlobal, withClusterAndAccounts, withTokenInfoBatch], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Account/VerifiedBuildCard@Media', } satisfies Meta; @@ -44,11 +16,7 @@ const meta = { export default meta; type Story = StoryObj; -const args = { - data: PROGRAM_DATA, - isLoading: false, - registryInfo: VERIFIED_FIXTURE, -}; +const args = Base.Verified.args; export const Mobile: Story = { args, diff --git a/app/components/account/__stories__/VerifiedBuildCard.stories.tsx b/app/components/account/__stories__/VerifiedBuildCard.stories.tsx index ef79c630ed..9ba480e3da 100644 --- a/app/components/account/__stories__/VerifiedBuildCard.stories.tsx +++ b/app/components/account/__stories__/VerifiedBuildCard.stories.tsx @@ -1,4 +1,5 @@ -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { makeProgramAccountData, makeProgramDataInfo } from '@entities/account/__fixtures__/account'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import type { OsecRegistryInfo } from '@/app/utils/verified-builds'; @@ -10,13 +11,7 @@ import { BaseVerifiedBuildCard } from '../VerifiedBuildCard'; // calls useVerifiedProgram (verify.osec.io + RPC PDA fetch); Base takes the resolved data as // props so stories can drive every variant without mocking the network or the SWR cache. -const PROGRAM_DATA = { - programData: { - authority: '5vJwnLeyjV8uNJSp1zn7VLW8GwiQbcsQbGaVSwRmkE4r', - data: ['', 'base64'], - slot: 0, - }, -} as any; +const PROGRAM_DATA = makeProgramAccountData(makeProgramDataInfo()); const VERIFIED_FIXTURE: OsecRegistryInfo = { executable_hash: '0000000000000000000000000000000000000000000000000000000000000000', @@ -57,7 +52,6 @@ const PDA_UPLOADED_FIXTURE: OsecRegistryInfo = { const meta = { component: BaseVerifiedBuildCard, decorators: [withClusterAndAccounts, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Account/VerifiedBuildCard', } satisfies Meta; diff --git a/app/components/account/__tests__/AccountHeader.spec.tsx b/app/components/account/__tests__/AccountHeader.spec.tsx index d7ce771a1b..58b5eaa819 100644 --- a/app/components/account/__tests__/AccountHeader.spec.tsx +++ b/app/components/account/__tests__/AccountHeader.spec.tsx @@ -1,3 +1,4 @@ +import { makeAccount, makeProgramAccountData } from '@entities/account/__fixtures__/account'; import { PublicKey } from '@solana/web3.js'; import { render, screen } from '@testing-library/react'; import React from 'react'; @@ -7,7 +8,7 @@ import { AccountHeader } from '@/app/components/account/AccountHeader'; import { accountBytes, MAINNET_NFTS, nftokenAccount } from '@/app/features/nftoken/__tests__/fixtures'; import { useSecurityTxt } from '@/app/features/security-txt'; import { createNeodymeSecurityTxt, createPmpSecurityTxt } from '@/app/features/security-txt/ui/__tests__/helpers'; -import type { Account, UpgradeableLoaderAccountData } from '@/app/providers/accounts'; +import type { Account, AccountData } from '@/app/providers/accounts'; import { Cluster } from '@/app/utils/cluster'; import { PROGRAM_INFO_BY_ID } from '@/app/utils/programs'; @@ -131,14 +132,11 @@ describe('AccountHeader', () => { it('should render the "Stake Account" title instead of the generic "Account" fallback', () => { const stakeAddress = '5ASxtmcPKDeD8NoE5QpskizPokqDdX1qHFiqZb1spLdo'; - const account = { - data: { parsed: { parsed: { type: 'delegated' }, program: 'stake' } }, - executable: false, - lamports: 100, - owner: PublicKey.default, + const account = makeAccount({ + data: { parsed: { parsed: { type: 'delegated' }, program: 'stake' } } as unknown as AccountData, pubkey: new PublicKey(stakeAddress), space: 200, - } as unknown as Account; + }); render(); @@ -181,24 +179,10 @@ function renderHeader(address: string) { } function programAccount(address: string): Account { - const parsedData: UpgradeableLoaderAccountData = { - parsed: { - info: { - programData: PublicKey.default, - }, - type: 'program', - }, - program: 'bpf-upgradeable-loader', - }; - - return { - data: { - parsed: parsedData, - }, + return makeAccount({ + data: { parsed: makeProgramAccountData() }, executable: true, - lamports: 0, - owner: PublicKey.default, pubkey: new PublicKey(address), space: 0, - }; + }); } diff --git a/app/components/account/__tests__/AnchorAccountCard.spec.tsx b/app/components/account/__tests__/AnchorAccountCard.spec.tsx index 8fd2492ff6..d1e8ed92e8 100644 --- a/app/components/account/__tests__/AnchorAccountCard.spec.tsx +++ b/app/components/account/__tests__/AnchorAccountCard.spec.tsx @@ -1,3 +1,4 @@ +import { makeAccount } from '@entities/account/__fixtures__/account'; import { type AnchorIdl, type CodamaIdl, IdlVariant, type ProgramIdls } from '@entities/idl'; import anchorModernIdl from '@entities/idl/mocks/anchor/anchor-0.30.1-devi51mZmdwUJGU9hjN27vEz64Gps7uUefqxg27EAtH.json'; import referenceIdl from '@entities/idl/mocks/anchor/reference-0.29.json'; @@ -6,8 +7,6 @@ import { PublicKey } from '@solana/web3.js'; import { render, screen } from '@testing-library/react'; import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { type Account } from '@/app/providers/accounts'; - import { AnchorAccountCard } from '../AnchorAccountCard'; const idlState: ProgramIdls = { idls: [] }; @@ -30,13 +29,11 @@ const ANCHOR_ACCOUNT_IDL = { const CODAMA_IDL = codamaIdl as unknown as CodamaIdl; const UNBUILDABLE_IDL = referenceIdl as unknown as AnchorIdl; -const ACCOUNT: Account = { +const ACCOUNT = makeAccount({ data: { raw: Uint8Array.from([...AMM_CONFIG_DISCRIMINATOR, ...new Array(200).fill(0)]) }, - executable: false, lamports: 1, owner: new PublicKey(anchorModernIdl.address), - pubkey: PublicKey.default, -}; +}); describe('AnchorAccountCard', () => { beforeEach(() => useProgramIdls.mockClear()); diff --git a/app/components/account/__tests__/CompressedNftCard.spec.tsx b/app/components/account/__tests__/CompressedNftCard.spec.tsx index c08efa9e1f..5bf0de83ca 100644 --- a/app/components/account/__tests__/CompressedNftCard.spec.tsx +++ b/app/components/account/__tests__/CompressedNftCard.spec.tsx @@ -1,10 +1,11 @@ +import { compressedNft, FUNGIBLE_TOKEN } from '@components/account/__fixtures__/compressed-nft'; +import { makeAccount } from '@entities/account/__fixtures__/account'; import { TOKEN_PROGRAM_ID } from '@providers/accounts/tokens'; import { PublicKey } from '@solana/web3.js'; import { render, screen } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; import { CompressedNftCard, CompressedNFTHeader, getAssetTypeLabel } from '@/app/components/account/CompressedNftCard'; -import type { Account } from '@/app/providers/accounts'; import type { CompressedNft } from '@/app/providers/compressed-nft'; const useCompressedNft = vi.hoisted(() => vi.fn<() => CompressedNft | null>(() => null)); @@ -27,93 +28,25 @@ vi.mock('../UnknownAccountCard', () => ({ UnknownAccountCard: () =>
, })); -function makeAccount(): Account { - return { - data: { raw: Buffer.alloc(82) }, - executable: false, - lamports: 1_000_000, - owner: TOKEN_PROGRAM_ID, - pubkey: PublicKey.default, - space: 82, - }; -} +const MINT_ACCOUNT = makeAccount({ data: { raw: Buffer.alloc(82) }, owner: TOKEN_PROGRAM_ID, space: 82 }); + +const KEY = PublicKey.default.toBase58(); // getAsset resolves fungible mints too, and returns an empty owner for them. -function makeFungibleAsset(overrides: Partial = {}): CompressedNft { - return { - authorities: [{ address: PublicKey.default.toBase58(), scopes: ['full'] }], - burnt: false, - compression: { - asset_hash: '', - compressed: false, - creator_hash: '', - data_hash: '', - eligible: false, - leaf_id: 0, - seq: 0, - tree: '', - }, - content: { - $schema: '', - files: [], - json_uri: '', - links: { external_url: '', image: '' }, - metadata: { - attributes: [], - description: '', - name: 'dogwifhat', - symbol: '$WIF', - token_standard: 'Fungible', - }, - }, - creators: [], - grouping: [], - id: PublicKey.default.toBase58(), - interface: 'FungibleToken', - mutable: false, - ownership: { delegate: null, delegated: false, frozen: false, owner: '', ownership_model: 'token' }, - royalty: { - basis_points: 0, - locked: false, - percent: 0, - primary_sale_happened: false, - royalty_model: 'creators', - target: null, - }, - supply: { edition_nonce: null, print_current_supply: 0, print_max_supply: 0 }, - ...overrides, - }; +function makeFungibleAsset(assetInterface = FUNGIBLE_TOKEN.assetInterface) { + return compressedNft({ ...FUNGIBLE_TOKEN, assetInterface }); } // A non-compressed asset that does have an owner, so the card can still describe it. -function makeCoreAsset(overrides: Partial = {}): CompressedNft { - const base = makeFungibleAsset(); - return { - ...base, - grouping: [{ group_key: 'collection', group_value: PublicKey.default.toBase58() }], - interface: 'MplCoreAsset', - ownership: { ...base.ownership, owner: PublicKey.default.toBase58(), ownership_model: 'single' }, - ...overrides, - }; -} - -function makeCompressedNft(overrides: Partial = {}): CompressedNft { - const base = makeFungibleAsset(); - return { - ...base, - compression: { ...base.compression, compressed: true, eligible: true }, - grouping: [{ group_key: 'collection', group_value: PublicKey.default.toBase58() }], - interface: 'V1_NFT', - ownership: { ...base.ownership, owner: PublicKey.default.toBase58(), ownership_model: 'single' }, - ...overrides, - }; +function makeCoreAsset() { + return compressedNft({ assetInterface: 'MplCoreAsset', collection: KEY, compressed: false, owner: KEY }); } describe('CompressedNftCard', () => { it('should fall back to the unknown-account card for an asset with no owner', () => { useCompressedNft.mockReturnValue(makeFungibleAsset()); - render(); + render(); expect(screen.getByTestId('unknown-account-card')).toBeDefined(); }); @@ -121,7 +54,7 @@ describe('CompressedNftCard', () => { it('should still describe a non-compressed asset that has an owner', () => { useCompressedNft.mockReturnValue(makeCoreAsset()); - render(); + render(); expect(screen.queryByTestId('unknown-account-card')).toBeNull(); expect(screen.getByText('Owner')).toBeDefined(); @@ -131,17 +64,17 @@ describe('CompressedNftCard', () => { describe('getAssetTypeLabel', () => { it('should label a compressed asset as a compressed NFT', () => { - expect(getAssetTypeLabel(makeCompressedNft())).toBe('Metaplex Compressed NFT'); + expect(getAssetTypeLabel(compressedNft({ collection: KEY }))).toBe('Metaplex Compressed NFT'); }); it('should label an uncompressed asset from its interface', () => { expect(getAssetTypeLabel(makeFungibleAsset())).toBe('Token'); - expect(getAssetTypeLabel(makeFungibleAsset({ interface: 'V1_NFT' }))).toBe('Metaplex NFT'); - expect(getAssetTypeLabel(makeFungibleAsset({ interface: 'MplCoreAsset' }))).toBe('Metaplex Core Asset'); + expect(getAssetTypeLabel(makeFungibleAsset('V1_NFT'))).toBe('Metaplex NFT'); + expect(getAssetTypeLabel(makeFungibleAsset('MplCoreAsset'))).toBe('Metaplex Core Asset'); }); it('should fall back to a generic label for an unknown interface', () => { - expect(getAssetTypeLabel(makeFungibleAsset({ interface: 'SomethingNew' }))).toBe('Asset'); + expect(getAssetTypeLabel(makeFungibleAsset('SomethingNew'))).toBe('Asset'); }); }); @@ -157,7 +90,7 @@ describe('CompressedNFTHeader', () => { }); it('should keep compressed labels for a real compressed NFT', () => { - render(); + render(); expect(screen.getByText('Metaplex Compressed NFT')).toBeDefined(); expect(screen.getByText('Compressed')).toBeDefined(); diff --git a/app/components/account/__tests__/FeatureAccountSection.spec.tsx b/app/components/account/__tests__/FeatureAccountSection.spec.tsx index 55bd1c3da7..2cb4d1f476 100644 --- a/app/components/account/__tests__/FeatureAccountSection.spec.tsx +++ b/app/components/account/__tests__/FeatureAccountSection.spec.tsx @@ -14,9 +14,7 @@ import { FEATURE_PROGRAM_ID } from '@/app/utils/parseFeatureAccount'; const { refreshAccount } = vi.hoisted(() => ({ refreshAccount: vi.fn() })); -vi.mock('next/navigation', () => ({ - useSearchParams: vi.fn(), -})); +vi.mock('next/navigation', () => import('@/app/__tests__/next-navigation')); vi.mock('@/app/providers/cluster', () => ({ EPOCH_INFO_REFRESH_MS: 30_000, diff --git a/app/components/account/__tests__/MetaplexNFTAttributesCard.spec.tsx b/app/components/account/__tests__/MetaplexNFTAttributesCard.spec.tsx index 14729108f7..049fe64887 100644 --- a/app/components/account/__tests__/MetaplexNFTAttributesCard.spec.tsx +++ b/app/components/account/__tests__/MetaplexNFTAttributesCard.spec.tsx @@ -6,7 +6,7 @@ import React from 'react'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { MetaplexNFTAttributesCard } from '@/app/components/account/MetaplexNFTAttributesCard'; -import { makeMetadata } from '@/app/entities/nft/lib/__tests__/make-nft-data'; +import { makeMetadata } from '@/app/entities/nft/__fixtures__/make-nft-data'; import type { Account, TokenProgramData } from '@/app/providers/accounts'; vi.mock('@/app/providers/cluster', () => ({ diff --git a/app/components/account/__tests__/MetaplexNFTHeader.spec.tsx b/app/components/account/__tests__/MetaplexNFTHeader.spec.tsx index 8d0b58408c..4931a63d5a 100644 --- a/app/components/account/__tests__/MetaplexNFTHeader.spec.tsx +++ b/app/components/account/__tests__/MetaplexNFTHeader.spec.tsx @@ -9,7 +9,7 @@ import { getIsMutablePill, MetaplexNFTHeader, } from '@/app/components/account/MetaplexNFTHeader'; -import { makeNftData } from '@/app/entities/nft/lib/__tests__/make-nft-data'; +import { makeNftData } from '@/app/entities/nft/__fixtures__/make-nft-data'; vi.mock('@providers/cluster', () => ({ useCluster: vi.fn(() => ({ cluster: 'mainnet-beta', url: 'https://api.mainnet-beta.solana.com' })), diff --git a/app/components/account/__tests__/OwnedTokensCard.spec.tsx b/app/components/account/__tests__/OwnedTokensCard.spec.tsx index 30fd3738df..084fbab4d7 100644 --- a/app/components/account/__tests__/OwnedTokensCard.spec.tsx +++ b/app/components/account/__tests__/OwnedTokensCard.spec.tsx @@ -1,6 +1,14 @@ import { gen } from '@__fixtures__/gen'; -import { FetchStatus } from '@providers/cache'; -import { PublicKey } from '@solana/web3.js'; +import { + ownedToken, + ownedTokensEntry, + OWNER, + TOKEN_ACCOUNT, + USDC_HOLDING, + USDC_MINT, + USDC_TOKEN_INFO, +} from '@components/account/__fixtures__/owned-tokens'; +import { tokenInfo } from '@entities/token-info/__fixtures__/token-info'; import { render, screen, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { Cluster } from '@utils/cluster'; @@ -71,46 +79,25 @@ vi.mock('@components/account/token-extensions/ScaledUiAmountMultiplierTooltip', import { OwnedTokensCard } from '../OwnedTokensCard'; -const OWNER = '11111111111111111111111111111111'; -const MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; const LOGO = 'https://example.test/usdc.png'; -const TOKEN_ACCOUNT_A = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'; const TOKEN_ACCOUNT_B = 'SysvarC1ock11111111111111111111111111111111'; // Distinct mints for the ordering specs, named for the tier each is set up to land in. -const VERIFIED_MINT = MINT; +const VERIFIED_MINT = USDC_MINT; const LISTED_MINT = 'So11111111111111111111111111111111111111112'; const UNKNOWN_MINT = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'; -type TokenAmount = { amount: string; decimals: number; uiAmountString: string }; - /** One base unit at zero decimals, for specs that assert on order rather than on balances. */ -const UNIT_AMOUNT: TokenAmount = { amount: '1', decimals: 0, uiAmountString: '1' }; - -function makeTokenAccount(tokenAmount: TokenAmount, pubkey: string = TOKEN_ACCOUNT_A, mint: string = MINT) { - return { info: { mint: new PublicKey(mint), tokenAmount }, pubkey: new PublicKey(pubkey) }; -} +const UNIT_AMOUNT = { amount: '1', decimals: 0, uiAmountString: '1' }; // One mint held in two accounts, each scaled by 2: the row totals 8, so the tooltip must show 4 pre-scaling. function twoAccountsOfOneMint() { - return makeEntryWith([ - makeTokenAccount({ amount: '1000000', decimals: 6, uiAmountString: '2' }, TOKEN_ACCOUNT_A), - makeTokenAccount({ amount: '3000000', decimals: 6, uiAmountString: '6' }, TOKEN_ACCOUNT_B), + return ownedTokensEntry([ + ownedToken({ amount: '1000000', decimals: 6, uiAmountString: '2' }, TOKEN_ACCOUNT), + ownedToken({ amount: '3000000', decimals: 6, uiAmountString: '6' }, TOKEN_ACCOUNT_B), ]); } -function makeEntryWith(tokens: ReturnType[]) { - return { data: { tokens }, status: FetchStatus.Fetched }; -} - -function makeEntry() { - return makeEntryWith([makeTokenAccount({ amount: '1234560000', decimals: 6, uiAmountString: '1234.56' })]); -} - -function tokenInfo(address: string, verified: boolean) { - return { address, decimals: 6, logoURI: null, name: `Token ${address.slice(0, 4)}`, symbol: 'TKN', verified }; -} - /** The resolved lookup, settled. Pass the entries the UTL list is meant to know about. */ function resolved(entries: ReturnType[] = []) { return { isLoading: false, tokenInfos: new Map(entries.map(entry => [entry.address, entry])) }; @@ -141,7 +128,7 @@ function loadMoreButton() { describe('should render OwnedTokensCard from a single bulk lookup', () => { beforeEach(() => { useClusterMock.mockReturnValue({ cluster: Cluster.Mainnet, genesisHash: 'genesis', url: 'http://rpc' }); - useAccountOwnedTokensMock.mockReturnValue(makeEntry()); + useAccountOwnedTokensMock.mockReturnValue(ownedTokensEntry([USDC_HOLDING])); useSearchParamsMock.mockReturnValue(searchParams(null)); useTokenInfosMock.mockReturnValue(resolved()); }); @@ -151,12 +138,7 @@ describe('should render OwnedTokensCard from a single bulk lookup', () => { }); it('should render the symbol and logo from the bulk lookup and label the mint Address without a second fetch', () => { - useTokenInfosMock.mockReturnValue({ - isLoading: false, - tokenInfos: new Map([ - [MINT, { address: MINT, decimals: 6, logoURI: LOGO, name: 'USD Coin', symbol: 'USDC', verified: true }], - ]), - }); + useTokenInfosMock.mockReturnValue(resolved([{ ...USDC_TOKEN_INFO, logoURI: LOGO }])); render(); @@ -164,7 +146,7 @@ describe('should render OwnedTokensCard from a single bulk lookup', () => { const logo = grid().getByTestId('token-logo'); expect(logo.getAttribute('data-uri')).toBe(LOGO); // The card resolves every held mint in one call, so rows fetch nothing themselves. - expect(useTokenInfosMock).toHaveBeenCalledWith([MINT], Cluster.Mainnet, 'genesis'); + expect(useTokenInfosMock).toHaveBeenCalledWith([USDC_MINT], Cluster.Mainnet, 'genesis'); // Symbol comes from the lookup, rendered next to the amount in the balance cell. expect(grid().getByText('USDC', { exact: false })).toBeInTheDocument(); // Mint Address is labeled from the already-resolved info (tokenLabelInfo), so it fetches nothing. @@ -195,8 +177,8 @@ describe('should render OwnedTokensCard from a single bulk lookup', () => { it('should render the pre-scaling raw amount without u64 precision loss', () => { // 2^53 + 1 base units: Number() rounds this to ...992, dropping the trailing 3 from the displayed amount. useAccountOwnedTokensMock.mockReturnValue( - makeEntryWith([ - makeTokenAccount({ amount: '9007199254740993', decimals: 6, uiAmountString: '18014398509.481986' }), + ownedTokensEntry([ + ownedToken({ amount: '9007199254740993', decimals: 6, uiAmountString: '18014398509.481986' }), ]), ); @@ -233,10 +215,10 @@ describe('should render OwnedTokensCard from a single bulk lookup', () => { describe('should order holdings by verification tier', () => { function heldInWorstOrder() { - return makeEntryWith([ - makeTokenAccount(UNIT_AMOUNT, TOKEN_ACCOUNT_A, UNKNOWN_MINT), - makeTokenAccount(UNIT_AMOUNT, TOKEN_ACCOUNT_A, LISTED_MINT), - makeTokenAccount(UNIT_AMOUNT, TOKEN_ACCOUNT_A, VERIFIED_MINT), + return ownedTokensEntry([ + ownedToken(UNIT_AMOUNT, TOKEN_ACCOUNT, UNKNOWN_MINT), + ownedToken(UNIT_AMOUNT, TOKEN_ACCOUNT, LISTED_MINT), + ownedToken(UNIT_AMOUNT, TOKEN_ACCOUNT, VERIFIED_MINT), ]); } @@ -271,9 +253,7 @@ describe('should order holdings by verification tier', () => { it('should keep RPC order within a tier', () => { const [first, second, third, fourth] = [gen.address(1), gen.address(2), gen.address(3), gen.address(4)]; useAccountOwnedTokensMock.mockReturnValue( - makeEntryWith( - [first, second, third, fourth].map(mint => makeTokenAccount(UNIT_AMOUNT, TOKEN_ACCOUNT_A, mint)), - ), + ownedTokensEntry([first, second, third, fourth].map(mint => ownedToken(UNIT_AMOUNT, TOKEN_ACCOUNT, mint))), ); useTokenInfosMock.mockReturnValue(resolved([tokenInfo(first, true), tokenInfo(third, true)])); @@ -293,7 +273,7 @@ describe('should page the ordered holdings', () => { useClusterMock.mockReturnValue({ cluster: Cluster.Mainnet, genesisHash: 'genesis', url: 'http://rpc' }); useSearchParamsMock.mockReturnValue(searchParams(null)); useAccountOwnedTokensMock.mockReturnValue( - makeEntryWith(allMints.map(mint => makeTokenAccount(UNIT_AMOUNT, TOKEN_ACCOUNT_A, mint))), + ownedTokensEntry(allMints.map(mint => ownedToken(UNIT_AMOUNT, TOKEN_ACCOUNT, mint))), ); useTokenInfosMock.mockReturnValue(resolved(verifiedMints.map(mint => tokenInfo(mint, true)))); }); @@ -333,7 +313,7 @@ describe('should render the account address column only in detail display', () = beforeEach(() => { useClusterMock.mockReturnValue({ cluster: Cluster.Mainnet, genesisHash: 'genesis', url: 'http://rpc' }); useTokenInfosMock.mockReturnValue(resolved()); - useAccountOwnedTokensMock.mockReturnValue(makeEntry()); + useAccountOwnedTokensMock.mockReturnValue(ownedTokensEntry([USDC_HOLDING])); }); afterEach(() => { @@ -350,7 +330,7 @@ describe('should render the account address column only in detail display', () = grid() .getAllByTestId('address') .map(node => node.textContent), - ).toEqual([TOKEN_ACCOUNT_A, MINT]); + ).toEqual([TOKEN_ACCOUNT, USDC_MINT]); }); it('should omit the account address in summary display', () => { @@ -359,7 +339,7 @@ describe('should render the account address column only in detail display', () = render(); expect(screen.queryByText('Account Address')).not.toBeInTheDocument(); - expect(visibleMints()).toEqual([MINT]); + expect(visibleMints()).toEqual([USDC_MINT]); }); // One row per mint, so a mint held twice shows a summed balance against a single account. @@ -373,7 +353,7 @@ describe('should render the account address column only in detail display', () = grid() .getAllByTestId('address') .map(node => node.textContent), - ).toEqual([TOKEN_ACCOUNT_B, MINT]); + ).toEqual([TOKEN_ACCOUNT_B, USDC_MINT]); }); }); @@ -381,11 +361,21 @@ describe('should project holdings into the mobile stack', () => { beforeEach(() => { useClusterMock.mockReturnValue({ cluster: Cluster.Mainnet, genesisHash: 'genesis', url: 'http://rpc' }); useSearchParamsMock.mockReturnValue(searchParams(null)); - useAccountOwnedTokensMock.mockReturnValue(makeEntry()); + useAccountOwnedTokensMock.mockReturnValue(ownedTokensEntry([USDC_HOLDING])); useTokenInfosMock.mockReturnValue({ isLoading: false, tokenInfos: new Map([ - [MINT, { address: MINT, decimals: 6, logoURI: LOGO, name: 'USD Coin', symbol: 'USDC', verified: true }], + [ + USDC_MINT, + { + address: USDC_MINT, + decimals: 6, + logoURI: LOGO, + name: 'USD Coin', + symbol: 'USDC', + verified: true, + }, + ], ]), }); }); diff --git a/app/components/account/__tests__/ParsedAccountRenderer.spec.tsx b/app/components/account/__tests__/ParsedAccountRenderer.spec.tsx index 0ae1f625f1..5756d6ef8a 100644 --- a/app/components/account/__tests__/ParsedAccountRenderer.spec.tsx +++ b/app/components/account/__tests__/ParsedAccountRenderer.spec.tsx @@ -1,3 +1,4 @@ +import { makeAccount } from '@entities/account/__fixtures__/account'; import type { Account } from '@providers/accounts'; import { type CacheEntry, FetchStatus } from '@providers/cache'; import { PublicKey } from '@solana/web3.js'; @@ -60,14 +61,7 @@ describe('ParsedAccountRenderer', () => { const ADDRESS = PublicKey.default.toBase58(); -const ACCOUNT: Account = { - data: {}, - executable: false, - lamports: 1, - owner: PublicKey.default, - pubkey: PublicKey.default, - space: 0, -}; +const ACCOUNT = makeAccount({ space: 0 }); function ClickCounter() { const [clicks, setClicks] = useState(0); diff --git a/app/components/account/__tests__/ProgramMultisigCard.spec.tsx b/app/components/account/__tests__/ProgramMultisigCard.spec.tsx index bb34d9efbd..105db340a0 100644 --- a/app/components/account/__tests__/ProgramMultisigCard.spec.tsx +++ b/app/components/account/__tests__/ProgramMultisigCard.spec.tsx @@ -1,12 +1,11 @@ import { gen } from '@__fixtures__/gen'; +import { makeProgramAccountData } from '@entities/account/__fixtures__/account'; import { type AnchorIdl, IdlVariant, type ProgramIdls } from '@entities/idl'; import anchorModernIdl from '@entities/idl/mocks/anchor/anchor-0.30.1-devi51mZmdwUJGU9hjN27vEz64Gps7uUefqxg27EAtH.json'; -import { PublicKey } from '@solana/web3.js'; import { render, screen } from '@testing-library/react'; import { Cluster } from '@utils/cluster'; import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { type UpgradeableLoaderAccountData } from '@/app/providers/accounts'; import { useSquadsMultisig, useSquadsMultisigLookup } from '@/app/providers/squadsMultisig'; import { ProgramMultisigCard } from '../ProgramMultisigCard'; @@ -24,10 +23,7 @@ vi.mock('@/app/providers/squadsMultisig', async importOriginal => ({ useSquadsMultisigLookup: vi.fn(), })); -const PROGRAM_DATA: UpgradeableLoaderAccountData = { - parsed: { info: { programData: PublicKey.default }, type: 'program' }, - program: 'bpf-upgradeable-loader', -}; +const PROGRAM_DATA = makeProgramAccountData(); describe('ProgramMultisigCard', () => { beforeEach(() => { diff --git a/app/components/account/__tests__/TokenExtensionsCard.spec.tsx b/app/components/account/__tests__/TokenExtensionsCard.spec.tsx index 3832944699..ddd848b702 100644 --- a/app/components/account/__tests__/TokenExtensionsCard.spec.tsx +++ b/app/components/account/__tests__/TokenExtensionsCard.spec.tsx @@ -1,4 +1,5 @@ import { gen } from '@__fixtures__/gen'; +import { makeAccount } from '@entities/account/__fixtures__/account'; import type { Account } from '@providers/accounts'; import { type CacheEntry, FetchStatus } from '@providers/cache'; import { PublicKey } from '@solana/web3.js'; @@ -49,14 +50,7 @@ describe('TokenExtensionsCard', () => { const MINT = gen.address(0); -const ACCOUNT: Account = { - data: {}, - executable: false, - lamports: 1, - owner: PublicKey.default, - pubkey: new PublicKey(MINT), - space: 0, -}; +const ACCOUNT = makeAccount({ pubkey: new PublicKey(MINT), space: 0 }); function renderCard() { render(); diff --git a/app/components/account/__tests__/TokenHistoryCard.FilterDropdown.spec.tsx b/app/components/account/__tests__/TokenHistoryCard.FilterDropdown.spec.tsx index c0249751fe..e45f334c24 100644 --- a/app/components/account/__tests__/TokenHistoryCard.FilterDropdown.spec.tsx +++ b/app/components/account/__tests__/TokenHistoryCard.FilterDropdown.spec.tsx @@ -6,15 +6,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; const FILTER_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; -vi.mock('next/navigation', () => ({ - usePathname: vi.fn(() => '/address/x/tokens'), - // Selected filter = FILTER_MINT so the toggle button renders that mint's label (the exact regression surface). - useSearchParams: vi.fn(() => ({ - get: vi.fn((k: string) => (k === 'filter' ? FILTER_MINT : null)), - has: vi.fn(), - toString: () => `filter=${FILTER_MINT}`, - })), -})); +vi.mock('next/navigation', () => import('@/app/__tests__/next-navigation')); const { useClusterMock } = vi.hoisted(() => ({ useClusterMock: vi.fn() })); vi.mock('@providers/cluster', async importOriginal => { diff --git a/app/components/account/address-lookup-table/__stories__/LookupTableEntriesCard.responsive.stories.tsx b/app/components/account/address-lookup-table/__stories__/LookupTableEntriesCard.responsive.stories.tsx index 62cfa8f847..b69e2c505a 100644 --- a/app/components/account/address-lookup-table/__stories__/LookupTableEntriesCard.responsive.stories.tsx +++ b/app/components/account/address-lookup-table/__stories__/LookupTableEntriesCard.responsive.stories.tsx @@ -1,12 +1,10 @@ -import { DEFAULT_SLOT } from '@__fixtures__/gen'; -import { PublicKey, SYSVAR_CLOCK_PUBKEY, SYSVAR_RENT_PUBKEY } from '@solana/web3.js'; -import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import type { AddressLookupTableAccountInfo } from '@validators/accounts/address-lookup-table'; import { LookupTableEntriesCard } from '../LookupTableEntriesCard'; +import * as Base from './LookupTableEntriesCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. type ParsedArgs = { parsedLookupTable: AddressLookupTableAccountInfo }; @@ -14,10 +12,6 @@ type ParsedArgs = { parsedLookupTable: AddressLookupTableAccountInfo }; const meta = { component: LookupTableEntriesCard, decorators: [withViewportFromGlobal, withCluster, withTokenInfoBatch], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Account/AddressLookupTable/LookupTableEntriesCard@Media', } satisfies Meta; @@ -25,21 +19,7 @@ const meta = { export default meta; type Story = StoryObj; -const samplePubkeys = [ - new PublicKey(TOKEN_PROGRAM_ADDRESS), - PublicKey.default, - SYSVAR_RENT_PUBKEY, - SYSVAR_CLOCK_PUBKEY, -]; - -const args = { - parsedLookupTable: { - addresses: samplePubkeys, - deactivationSlot: BigInt('18446744073709551615'), - lastExtendedSlot: DEFAULT_SLOT, - lastExtendedSlotStartIndex: 0, - } satisfies AddressLookupTableAccountInfo, -}; +const args = Base.WithEntries.args; export const Mobile: Story = { args, diff --git a/app/components/account/address-lookup-table/__stories__/LookupTableEntriesCard.stories.tsx b/app/components/account/address-lookup-table/__stories__/LookupTableEntriesCard.stories.tsx index f8a82791e5..2c3e97104f 100644 --- a/app/components/account/address-lookup-table/__stories__/LookupTableEntriesCard.stories.tsx +++ b/app/components/account/address-lookup-table/__stories__/LookupTableEntriesCard.stories.tsx @@ -1,5 +1,5 @@ import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import type { AddressLookupTableAccountInfo } from '@validators/accounts/address-lookup-table'; @@ -11,7 +11,6 @@ type ParsedArgs = { parsedLookupTable: AddressLookupTableAccountInfo }; const meta = { component: LookupTableEntriesCard, decorators: [withCluster, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Account/AddressLookupTable/LookupTableEntriesCard', } satisfies Meta; diff --git a/app/components/account/history/__stories__/TokenTransfersCard.responsive.stories.tsx b/app/components/account/history/__stories__/TokenTransfersCard.responsive.stories.tsx index 1481ccc469..78191b5707 100644 --- a/app/components/account/history/__stories__/TokenTransfersCard.responsive.stories.tsx +++ b/app/components/account/history/__stories__/TokenTransfersCard.responsive.stories.tsx @@ -1,25 +1,13 @@ -import { mockAccountHistory, mockConfirmedSignatureInfo } from '@storybook-config/__fixtures__/account-history'; -import { nextjsParameters, withHistory } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withHistory } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { TokenTransfersCard } from '../TokenTransfersCard'; - -const ADDRESS = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'; +import * as Base from './TokenTransfersCard.stories'; const meta: Meta = { component: TokenTransfersCard, decorators: [withHistory, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - history: { - [ADDRESS]: mockAccountHistory({ - fetched: [mockConfirmedSignatureInfo({ blockTime: null, slot: 312_456_789 })], - foundOldest: true, - }), - }, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Account/History/TokenTransfersCard@Media', }; @@ -27,8 +15,8 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { address: ADDRESS }; +const { args, parameters } = Base.WithSignatures; -export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; -export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; -export const TabletLandscape: Story = { args, globals: { viewport: { isRotated: true, value: 'ipad' } } }; +export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } }, parameters }; +export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } }, parameters }; +export const TabletLandscape: Story = { args, globals: { viewport: { isRotated: true, value: 'ipad' } }, parameters }; diff --git a/app/components/account/history/__stories__/TokenTransfersCard.stories.tsx b/app/components/account/history/__stories__/TokenTransfersCard.stories.tsx index 3161bfc8c7..ff66d4c368 100644 --- a/app/components/account/history/__stories__/TokenTransfersCard.stories.tsx +++ b/app/components/account/history/__stories__/TokenTransfersCard.stories.tsx @@ -1,8 +1,5 @@ import { mockAccountHistory, mockConfirmedSignatureInfo } from '@storybook-config/__fixtures__/account-history'; -import { MockAccountsProvider } from '@storybook-config/__mocks__/MockAccountsProvider'; -import { MockClusterProvider as ClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; -import { MockHistoryProvider } from '@storybook-config/__mocks__/MockHistoryProvider'; -import { nextjsParameters } from '@storybook-config/decorators'; +import { withHistory } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { TokenTransfersCard } from '../TokenTransfersCard'; @@ -11,7 +8,7 @@ const ADDRESS = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'; const meta: Meta = { component: TokenTransfersCard, - parameters: nextjsParameters, + decorators: [withHistory], tags: ['autodocs', 'test'], title: 'Components/Account/History/TokenTransfersCard', }; @@ -21,42 +18,22 @@ type Story = StoryObj; export const EmptyHistory: Story = { args: { address: ADDRESS }, - decorators: [ - Story => ( - - - - - - - - ), - ], + parameters: { + history: { [ADDRESS]: mockAccountHistory({ fetched: [], foundOldest: true }) }, + }, }; export const WithSignatures: Story = { args: { address: ADDRESS }, - decorators: [ - Story => ( - - - - - - - - ), - ], + parameters: { + history: { + [ADDRESS]: mockAccountHistory({ + fetched: [ + mockConfirmedSignatureInfo({ blockTime: null, slot: 312_456_789 }), + mockConfirmedSignatureInfo({ blockTime: null, slot: 312_456_790 }), + ], + foundOldest: false, + }), + }, + }, }; diff --git a/app/components/account/token-extensions/__stories__/TokenExtensionBadge.stories.tsx b/app/components/account/token-extensions/__stories__/TokenExtensionBadge.stories.tsx index 54076fb12a..186749a7d7 100644 --- a/app/components/account/token-extensions/__stories__/TokenExtensionBadge.stories.tsx +++ b/app/components/account/token-extensions/__stories__/TokenExtensionBadge.stories.tsx @@ -2,8 +2,7 @@ import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, fn, within } from 'storybook/test'; -import * as mockExtensions from '@/app/__tests__/mock-parsed-extensions-stubs'; -import { populatePartialParsedTokenExtension } from '@/app/utils/token-extension'; +import { parsedTransferFeeConfig0 } from '@/app/__tests__/mock-parsed-extensions-stubs'; import { TokenExtensionBadge } from '../TokenExtensionBadge'; @@ -20,16 +19,10 @@ const meta = { export default meta; type Story = StoryObj; -const extension = { - extension: mockExtensions.transferFeeConfig0.extension, - parsed: mockExtensions.transferFeeConfig0, - ...populatePartialParsedTokenExtension(mockExtensions.transferFeeConfig0.extension), -}; - // More on writing stories with args: https://storybook.js.org/docs/writing-stories/args export const Primary: Story = { args: { - extension, + extension: parsedTransferFeeConfig0, }, async play({ canvasElement }) { const canvas = within(canvasElement); diff --git a/app/components/account/token-extensions/__stories__/TokenExtensionBadges.stories.tsx b/app/components/account/token-extensions/__stories__/TokenExtensionBadges.stories.tsx index 6d9e3f0219..231644f161 100644 --- a/app/components/account/token-extensions/__stories__/TokenExtensionBadges.stories.tsx +++ b/app/components/account/token-extensions/__stories__/TokenExtensionBadges.stories.tsx @@ -1,8 +1,7 @@ import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; -import * as mockExtensions from '@/app/__tests__/mock-parsed-extensions-stubs'; -import { populatePartialParsedTokenExtension } from '@/app/utils/token-extension'; +import { parsedTransferFeeConfig0 } from '@/app/__tests__/mock-parsed-extensions-stubs'; import { TokenExtensionBadges } from '../TokenExtensionBadges'; @@ -15,16 +14,10 @@ const meta = { export default meta; type Story = StoryObj; -const extension = { - extension: mockExtensions.transferFeeConfig0.extension, - parsed: mockExtensions.transferFeeConfig0, - ...populatePartialParsedTokenExtension(mockExtensions.transferFeeConfig0.extension), -}; - // More on writing stories with args: https://storybook.js.org/docs/writing-stories/args export const Primary: Story = { args: { - extensions: new Array(5).fill(null).map(() => extension), + extensions: new Array(5).fill(null).map(() => parsedTransferFeeConfig0), }, async play({ canvasElement }) { const canvas = within(canvasElement); diff --git a/app/components/account/token-extensions/__stories__/TokenExtensionsStatusRow.stories.tsx b/app/components/account/token-extensions/__stories__/TokenExtensionsStatusRow.stories.tsx index fd31047ab0..c9d5b8fd29 100644 --- a/app/components/account/token-extensions/__stories__/TokenExtensionsStatusRow.stories.tsx +++ b/app/components/account/token-extensions/__stories__/TokenExtensionsStatusRow.stories.tsx @@ -2,9 +2,8 @@ import { gen } from '@__fixtures__/gen'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; -import * as mockExtensions from '@/app/__tests__/mock-parsed-extensions-stubs'; +import { parsedTransferFeeConfig0 } from '@/app/__tests__/mock-parsed-extensions-stubs'; import { OverviewCard } from '@/app/shared/ui/OverviewCard'; -import { populatePartialParsedTokenExtension } from '@/app/utils/token-extension'; import { TokenExtensionsStatusRow } from '../TokenExtensionsStatusRow'; @@ -18,11 +17,6 @@ const meta = { ), ], - parameters: { - nextjs: { - appDirectory: true, - }, - }, tags: ['autodocs', 'test'], title: 'Components/Account/token-extensions/TokenExtensionsStatusRow', } satisfies Meta; @@ -30,17 +24,11 @@ const meta = { export default meta; type Story = StoryObj; -const extension = { - extension: mockExtensions.transferFeeConfig0.extension, - parsed: mockExtensions.transferFeeConfig0, - ...populatePartialParsedTokenExtension(mockExtensions.transferFeeConfig0.extension), -}; - // More on writing stories with args: https://storybook.js.org/docs/writing-stories/args export const Primary: Story = { args: { address: gen.address(1), - extensions: new Array(5).fill(null).map(() => extension), + extensions: new Array(5).fill(null).map(() => parsedTransferFeeConfig0), }, async play({ canvasElement }) { const canvas = within(canvasElement); diff --git a/app/components/block/__stories__/BlockAccountsCard.responsive.stories.tsx b/app/components/block/__stories__/BlockAccountsCard.responsive.stories.tsx index 07f56c351a..1bd2d3a2b1 100644 --- a/app/components/block/__stories__/BlockAccountsCard.responsive.stories.tsx +++ b/app/components/block/__stories__/BlockAccountsCard.responsive.stories.tsx @@ -1,7 +1,6 @@ -import type { BlockData } from '@entities/block-data'; -import { blockhash } from '@solana/kit'; -import { nextjsParameters, withCluster } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { makeBlock } from '@entities/block-data/__fixtures__/block-builders'; +import { withCluster } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BlockAccountsCard } from '../BlockAccountsCard'; @@ -9,10 +8,6 @@ import { BlockAccountsCard } from '../BlockAccountsCard'; const meta: Meta = { component: BlockAccountsCard, decorators: [withCluster, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Block/BlockAccountsCard@Media', }; @@ -20,15 +15,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const block: BlockData = { - blockTime: null, - blockhash: blockhash('11111111111111111111111111111111'), - parentSlot: 0n, - previousBlockhash: blockhash('11111111111111111111111111111111'), - rewards: [], - transactions: [], -}; -const args = { block, blockSlot: 312_456_789 }; +const args = { block: makeBlock([]), blockSlot: 312_456_789 }; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/components/block/__stories__/BlockAccountsCard.stories.tsx b/app/components/block/__stories__/BlockAccountsCard.stories.tsx index 3b2f7c0352..cd643ebea3 100644 --- a/app/components/block/__stories__/BlockAccountsCard.stories.tsx +++ b/app/components/block/__stories__/BlockAccountsCard.stories.tsx @@ -1,14 +1,14 @@ -import type { BlockData, BlockTransaction } from '@entities/block-data'; -import { address, blockhash, lamports } from '@solana/kit'; -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { makeBlock, makeBlockTransaction } from '@entities/block-data/__fixtures__/block-builders'; +import { address, lamports } from '@solana/kit'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BlockAccountsCard } from '../BlockAccountsCard'; +import { ACCOUNT_IDS } from './fixtures'; const meta: Meta = { component: BlockAccountsCard, decorators: [withCluster, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Block/BlockAccountsCard', }; @@ -16,65 +16,31 @@ const meta: Meta = { export default meta; type Story = StoryObj; -// Account addresses used by the synthetic block below (valid base58 — no 0, O, I, l). 13 entries so -// the list exceeds the initial 10 rows and the "Load More" control shows. -const ACCOUNT_IDS = [ - '11111111111111111111111111111111', - 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb', - 'So11111111111111111111111111111111111111112', - 'SysvarRent111111111111111111111111111111111', - 'SysvarC1ock11111111111111111111111111111111', - 'Stake11111111111111111111111111111111111111', - 'Vote111111111111111111111111111111111111111', - 'BPFLoaderUpgradeab1e11111111111111111111111', - 'ComputeBudget111111111111111111111111111111', - 'AddressLookupTab1e1111111111111111111111111', - 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL', - 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s', -]; - // Build the Kit-native block shape consumed by BlockAccountsCard. Account j // is referenced in every (j+1)-th transaction (descending usage); every 3rd account is writable, so // the read-write / read-only split varies across rows. -function makeBlock(txCount: number): BlockData { +function blockWithTransactions(txCount: number) { const keys = ACCOUNT_IDS.map(address); - const transactions: BlockTransaction[] = Array.from({ length: txCount }, (_, k) => { - const accountKeyIndexes = ACCOUNT_IDS.map((_, j) => j).filter(j => k % (j + 1) === 0); - return { - index: k, - message: { - header: { - numReadonlyNonSignerAccounts: 8, - numReadonlySignerAccounts: 0, - numSignerAccounts: 0, + return makeBlock( + Array.from({ length: txCount }, (_, k) => { + const accountKeyIndexes = ACCOUNT_IDS.map((_, j) => j).filter(j => k % (j + 1) === 0); + return makeBlockTransaction({ + index: k, + message: { + header: { numReadonlyNonSignerAccounts: 8, numReadonlySignerAccounts: 0, numSignerAccounts: 0 }, + instructions: [{ accountIndices: accountKeyIndexes, programAddressIndex: 0 }], + staticAccounts: keys, + version: 'legacy', }, - instructions: [{ accountIndices: accountKeyIndexes, programAddressIndex: 0 }], - lifetimeToken: blockhash('11111111111111111111111111111111'), - staticAccounts: keys, - version: 'legacy', - }, - meta: { - err: null, - fee: lamports(5_000n), - logMessages: [], - }, - signatures: [], - }; - }); - return { - blockTime: null, - blockhash: blockhash('11111111111111111111111111111111'), - parentSlot: 0n, - previousBlockhash: blockhash('11111111111111111111111111111111'), - rewards: [], - transactions, - }; + meta: { fee: lamports(5_000n) }, + }); + }), + ); } export const WithData: Story = { args: { - block: makeBlock(20), + block: blockWithTransactions(20), blockSlot: 312_456_789, }, }; @@ -82,7 +48,7 @@ export const WithData: Story = { // Empty block — wrapper-only story for visual-regression coverage of the outer card. export const EmptyBlock: Story = { args: { - block: makeBlock(0), + block: blockWithTransactions(0), blockSlot: 312_456_789, }, }; diff --git a/app/components/block/__stories__/BlockHistoryCard.responsive.stories.tsx b/app/components/block/__stories__/BlockHistoryCard.responsive.stories.tsx index 932a7f8661..7e5a9f2f30 100644 --- a/app/components/block/__stories__/BlockHistoryCard.responsive.stories.tsx +++ b/app/components/block/__stories__/BlockHistoryCard.responsive.stories.tsx @@ -1,27 +1,13 @@ -import type { BlockData } from '@entities/block-data'; -import { blockhash } from '@solana/kit'; -import { nextjsParameters, withCluster } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { makeBlock } from '@entities/block-data/__fixtures__/block-builders'; +import { withCluster } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BlockHistoryCard } from '../BlockHistoryCard'; -const emptyBlock: BlockData = { - blockTime: null, - blockhash: blockhash('11111111111111111111111111111111'), - parentSlot: 0n, - previousBlockhash: blockhash('11111111111111111111111111111111'), - rewards: [], - transactions: [], -}; - const meta: Meta = { component: BlockHistoryCard, decorators: [withCluster, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Block/BlockHistoryCard@Media', }; @@ -29,7 +15,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { block: emptyBlock, epoch: 500n }; +const args = { block: makeBlock([]), epoch: 500n }; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/components/block/__stories__/BlockHistoryCard.stories.tsx b/app/components/block/__stories__/BlockHistoryCard.stories.tsx index 8c226c4c07..97ce92ec1a 100644 --- a/app/components/block/__stories__/BlockHistoryCard.stories.tsx +++ b/app/components/block/__stories__/BlockHistoryCard.stories.tsx @@ -1,19 +1,11 @@ -import type { BlockData, BlockTransaction } from '@entities/block-data'; -import { address, blockhash, getBase58Decoder, lamports, signature } from '@solana/kit'; -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { gen } from '@__fixtures__/gen'; +import { makeBlock, makeBlockTransaction } from '@entities/block-data/__fixtures__/block-builders'; +import { address, lamports, signature } from '@solana/kit'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BlockHistoryCard } from '../BlockHistoryCard'; -const emptyBlock: BlockData = { - blockTime: null, - blockhash: blockhash('11111111111111111111111111111111'), - parentSlot: 0n, - previousBlockhash: blockhash('11111111111111111111111111111111'), - rewards: [], - transactions: [], -}; - // Programs the synthetic transactions invoke. Deliberately excludes the Compute Budget program so // `estimateRequestedComputeUnits` never tries to parse the (empty) instruction data — it just adds the // per-program reserved units, which is enough to populate the "Reserved CUs" column. Vote is last so it @@ -27,14 +19,6 @@ const PROGRAM_IDS = [ ]; const VOTE_INDEX = 3; -// Distinct placeholder signature per row — the Signature cell only truncates for display, it doesn't -// base58-decode, so these render as `Sig0…0000` style links. -const signatureFor = (i: number) => { - const bytes = new Uint8Array(64); - bytes[63] = i + 1; - return signature(getBase58Decoder().decode(bytes)); -}; - // Standard-shaped program logs so `parseProgramLogs` can extract compute units. Each invocation emits the // runtime's invoke / consumed / success triplet; the consumed amount varies per program and position so // per-row Compute totals differ. A failed tx ends its last instruction with an error line instead of @@ -52,45 +36,43 @@ function logsForTx(programIdxs: number[], failed: boolean): string[] { return logs; } -function makeBlock(txCount: number): BlockData { +function blockWithTransactions(txCount: number) { const keys = PROGRAM_IDS.map(address); - const transactions: BlockTransaction[] = Array.from({ length: txCount }, (_, k) => { - const failed = k % 4 === 0; - // Primary rotates over the non-vote programs and is invoked a varying number of times (1..12) so - // the "N ×" counter exercises single- and double-digit widths; every other tx also invokes Vote - // once as a secondary. - const primary = k % VOTE_INDEX; - const primaryCount = 1 + (k % 12); - const programIdxs = [ - ...Array.from({ length: primaryCount }, () => primary), - ...(k % 2 === 0 ? [VOTE_INDEX] : []), - ]; - return { - index: k, - message: { - header: { numReadonlyNonSignerAccounts: 0, numReadonlySignerAccounts: 0, numSignerAccounts: 0 }, - instructions: programIdxs.map(idx => ({ data: new Uint8Array(), programAddressIndex: idx })), - lifetimeToken: blockhash('11111111111111111111111111111111'), - staticAccounts: keys, - version: 'legacy', - }, - meta: { - costUnits: BigInt(1_000 + (k % 7) * 350), - err: failed ? { InstructionError: [0, { Custom: 1 }] } : null, - fee: lamports(5_000n), - innerInstructions: [], - logMessages: logsForTx(programIdxs, failed), - }, - signatures: [signatureFor(k)], - }; - }); - return { ...emptyBlock, transactions }; + return makeBlock( + Array.from({ length: txCount }, (_, k) => { + const failed = k % 4 === 0; + // Primary rotates over the non-vote programs and is invoked a varying number of times (1..12) so + // the "N ×" counter exercises single- and double-digit widths; every other tx also invokes Vote + // once as a secondary. + const primary = k % VOTE_INDEX; + const primaryCount = 1 + (k % 12); + const programIdxs = [ + ...Array.from({ length: primaryCount }, () => primary), + ...(k % 2 === 0 ? [VOTE_INDEX] : []), + ]; + return makeBlockTransaction({ + index: k, + message: { + instructions: programIdxs.map(idx => ({ data: new Uint8Array(), programAddressIndex: idx })), + staticAccounts: keys, + version: 'legacy', + }, + meta: { + costUnits: BigInt(1_000 + (k % 7) * 350), + err: failed ? { InstructionError: [0, { Custom: 1 }] } : null, + fee: lamports(5_000n), + innerInstructions: [], + logMessages: logsForTx(programIdxs, failed), + }, + signatures: [signature(gen.signature(k))], + }); + }), + ); } const meta = { component: BlockHistoryCard, decorators: [withCluster, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Block/BlockHistoryCard', } satisfies Meta; @@ -100,15 +82,15 @@ type Story = StoryObj; // A handful of transactions — a mix of Success / Failed rows and invoked programs. export const WithTransactions: Story = { - args: { block: makeBlock(8), epoch: 500n }, + args: { block: blockWithTransactions(8), epoch: 500n }, }; // More than one page (PAGE_SIZE = 25) so the "Load More" footer shows. export const ManyTransactions: Story = { - args: { block: makeBlock(30), epoch: 500n }, + args: { block: blockWithTransactions(30), epoch: 500n }, }; // No transactions → the "This block has no transactions" ErrorCard fallback. export const EmptyBlock: Story = { - args: { block: emptyBlock, epoch: 500n }, + args: { block: makeBlock([]), epoch: 500n }, }; diff --git a/app/components/block/__stories__/BlockOverviewCard.stories.tsx b/app/components/block/__stories__/BlockOverviewCard.stories.tsx index 2cb74a4fed..10c3146e41 100644 --- a/app/components/block/__stories__/BlockOverviewCard.stories.tsx +++ b/app/components/block/__stories__/BlockOverviewCard.stories.tsx @@ -1,6 +1,6 @@ import type { BlockData } from '@entities/block-data'; import { address, blockhash, unixTimestamp } from '@solana/kit'; -import { nextjsParameters, withClusterAccountsAndTokenInfo } from '@storybook-config/decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BlockOverviewCard } from '../BlockOverviewCard'; @@ -20,8 +20,7 @@ const CHILD_LEADER = address('Stake11111111111111111111111111111111111111'); const meta = { component: BlockOverviewCard, - decorators: [withClusterAccountsAndTokenInfo], - parameters: nextjsParameters, + decorators: [withClusterAndAccounts, withTokenInfoBatch], tags: ['autodocs', 'test'], title: 'Components/Block/BlockOverviewCard', } satisfies Meta; diff --git a/app/components/block/__stories__/BlockProgramsCard.responsive.stories.tsx b/app/components/block/__stories__/BlockProgramsCard.responsive.stories.tsx index e366502612..b7064ae5dd 100644 --- a/app/components/block/__stories__/BlockProgramsCard.responsive.stories.tsx +++ b/app/components/block/__stories__/BlockProgramsCard.responsive.stories.tsx @@ -1,7 +1,6 @@ -import type { BlockData } from '@entities/block-data'; -import { blockhash } from '@solana/kit'; -import { nextjsParameters, withCluster } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { makeBlock } from '@entities/block-data/__fixtures__/block-builders'; +import { withCluster } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BlockProgramsCard } from '../BlockProgramsCard'; @@ -9,10 +8,6 @@ import { BlockProgramsCard } from '../BlockProgramsCard'; const meta: Meta = { component: BlockProgramsCard, decorators: [withCluster, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Block/BlockProgramsCard@Media', }; @@ -20,15 +15,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const block: BlockData = { - blockTime: null, - blockhash: blockhash('11111111111111111111111111111111'), - parentSlot: 0n, - previousBlockhash: blockhash('11111111111111111111111111111111'), - rewards: [], - transactions: [], -}; -const args = { block }; +const args = { block: makeBlock([]) }; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/components/block/__stories__/BlockProgramsCard.stories.tsx b/app/components/block/__stories__/BlockProgramsCard.stories.tsx index 725674a0de..3a9e6abcd3 100644 --- a/app/components/block/__stories__/BlockProgramsCard.stories.tsx +++ b/app/components/block/__stories__/BlockProgramsCard.stories.tsx @@ -1,6 +1,6 @@ -import type { BlockData, BlockTransaction } from '@entities/block-data'; -import { address, blockhash, lamports } from '@solana/kit'; -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { makeBlock, makeBlockTransaction } from '@entities/block-data/__fixtures__/block-builders'; +import { address, lamports } from '@solana/kit'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BlockProgramsCard } from '../BlockProgramsCard'; @@ -8,7 +8,6 @@ import { BlockProgramsCard } from '../BlockProgramsCard'; const meta: Meta = { component: BlockProgramsCard, decorators: [withCluster, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Block/BlockProgramsCard', }; @@ -29,52 +28,43 @@ const PROGRAM_IDS = [ // appears in every (j+1)-th transaction, giving a descending usage distribution; every 5th tx is // marked failed (`err`) so Success Rate lands below 100%. All txs carry `meta`, so the Success Rate // column shows. -function makeBlock(txCount: number): BlockData { +function blockWithTransactions(txCount: number) { const keys = PROGRAM_IDS.map(address); - const transactions: BlockTransaction[] = Array.from({ length: txCount }, (_, k) => { - const instructions = PROGRAM_IDS.map((_, j) => j) - .filter(j => k % (j + 1) === 0) - .map(j => ({ programAddressIndex: j })); - return { - index: k, - message: { - header: { - numReadonlyNonSignerAccounts: keys.length, - numReadonlySignerAccounts: 0, - numSignerAccounts: 0, + return makeBlock( + Array.from({ length: txCount }, (_, k) => { + const instructions = PROGRAM_IDS.map((_, j) => j) + .filter(j => k % (j + 1) === 0) + .map(j => ({ programAddressIndex: j })); + return makeBlockTransaction({ + index: k, + message: { + header: { + numReadonlyNonSignerAccounts: keys.length, + numReadonlySignerAccounts: 0, + numSignerAccounts: 0, + }, + instructions, + staticAccounts: keys, + version: 'legacy', }, - instructions, - lifetimeToken: blockhash('11111111111111111111111111111111'), - staticAccounts: keys, - version: 'legacy', - }, - meta: { - err: k % 5 === 0 ? { InstructionError: [0, { Custom: 1 }] } : null, - fee: lamports(5_000n), - innerInstructions: [], - logMessages: [], - }, - signatures: [], - }; - }); - return { - blockTime: null, - blockhash: blockhash('11111111111111111111111111111111'), - parentSlot: 0n, - previousBlockhash: blockhash('11111111111111111111111111111111'), - rewards: [], - transactions, - }; + meta: { + err: k % 5 === 0 ? { InstructionError: [0, { Custom: 1 }] } : null, + fee: lamports(5_000n), + innerInstructions: [], + }, + }); + }), + ); } export const WithData: Story = { args: { - block: makeBlock(12), + block: blockWithTransactions(12), }, }; export const EmptyBlock: Story = { args: { - block: makeBlock(0), + block: blockWithTransactions(0), }, }; diff --git a/app/components/block/__stories__/BlockRewardsCard.responsive.stories.tsx b/app/components/block/__stories__/BlockRewardsCard.responsive.stories.tsx index 51809b7919..a4f722d4a9 100644 --- a/app/components/block/__stories__/BlockRewardsCard.responsive.stories.tsx +++ b/app/components/block/__stories__/BlockRewardsCard.responsive.stories.tsx @@ -1,33 +1,13 @@ -import type { BlockData } from '@entities/block-data'; -import { address, blockhash, lamports, type Reward } from '@solana/kit'; -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BlockRewardsCard } from '../BlockRewardsCard'; - -const PUBKEYS = [ - '11111111111111111111111111111111', - 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - 'So11111111111111111111111111111111111111112', - 'SysvarRent111111111111111111111111111111111', -]; - -const sampleReward = (i: number): Reward => ({ - commission: 5, - lamports: BigInt(1_500_000 + i * 1_000), - postBalance: lamports(BigInt(12_345_678_900 + i * 1_000_000)), - pubkey: address(PUBKEYS[i % PUBKEYS.length]), - rewardType: i % 2 === 0 ? 'Staking' : 'Voting', -}); +import * as Base from './BlockRewardsCard.stories'; const meta: Meta = { component: BlockRewardsCard, decorators: [withCluster, withTokenInfoBatch, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Block/BlockRewardsCard@Media', }; @@ -35,15 +15,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const block: BlockData = { - blockTime: null, - blockhash: blockhash('11111111111111111111111111111111'), - parentSlot: 0n, - previousBlockhash: blockhash('11111111111111111111111111111111'), - rewards: Array.from({ length: 4 }, (_, index) => sampleReward(index)), - transactions: [], -}; -const args = { block }; +const args = Base.WithRewards.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/components/block/__stories__/BlockRewardsCard.stories.tsx b/app/components/block/__stories__/BlockRewardsCard.stories.tsx index f554765246..1a004914c4 100644 --- a/app/components/block/__stories__/BlockRewardsCard.stories.tsx +++ b/app/components/block/__stories__/BlockRewardsCard.stories.tsx @@ -1,14 +1,14 @@ -import type { BlockData } from '@entities/block-data'; -import { address, blockhash, lamports, type Reward } from '@solana/kit'; -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { makeBlock } from '@entities/block-data/__fixtures__/block-builders'; +import { address, lamports, type Reward } from '@solana/kit'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BlockRewardsCard } from '../BlockRewardsCard'; +import { ACCOUNT_IDS } from './fixtures'; const meta: Meta = { component: BlockRewardsCard, decorators: [withCluster, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Block/BlockRewardsCard', }; @@ -16,39 +16,18 @@ const meta: Meta = { export default meta; type Story = StoryObj; -// Each base58 pubkey must use the valid alphabet (no 0, O, I, l). We rotate through a fixed -// set of known-good pubkeys to give every reward row a distinct, parseable address. -const PUBKEYS = [ - '11111111111111111111111111111111', - 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb', - 'So11111111111111111111111111111111111111112', - 'SysvarRent111111111111111111111111111111111', - 'SysvarC1ock11111111111111111111111111111111', - 'Stake11111111111111111111111111111111111111', - 'Vote111111111111111111111111111111111111111', - 'BPFLoaderUpgradeab1e11111111111111111111111', - 'ComputeBudget111111111111111111111111111111', - 'AddressLookupTab1e1111111111111111111111111', - 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL', - 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s', -]; - +// We rotate through a fixed set of known-good pubkeys to give every reward row a distinct, parseable address. const sampleReward = (i: number): Reward => ({ commission: 5, lamports: BigInt(1_500_000 + i * 1_000), postBalance: lamports(BigInt(12_345_678_900 + i * 1_000_000)), - pubkey: address(PUBKEYS[i % PUBKEYS.length]), + pubkey: address(ACCOUNT_IDS[i % ACCOUNT_IDS.length]), rewardType: i % 2 === 0 ? 'Staking' : 'Voting', }); -const blockWithRewards = (count: number): BlockData => ({ - blockTime: null, - blockhash: blockhash('11111111111111111111111111111111'), - parentSlot: 0n, - previousBlockhash: blockhash('11111111111111111111111111111111'), +const blockWithRewards = (count: number) => ({ + ...makeBlock([]), rewards: Array.from({ length: count }, (_, index) => sampleReward(index)), - transactions: [], }); export const WithRewards: Story = { diff --git a/app/components/block/__stories__/fixtures.ts b/app/components/block/__stories__/fixtures.ts new file mode 100644 index 0000000000..d913dce524 --- /dev/null +++ b/app/components/block/__stories__/fixtures.ts @@ -0,0 +1,17 @@ +// Account addresses for the synthetic blocks (valid base58, so no 0, O, I, l). 13 entries so the +// BlockAccountsCard list exceeds the initial 10 rows and the "Load More" control shows. +export const ACCOUNT_IDS = [ + '11111111111111111111111111111111', + 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', + 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb', + 'So11111111111111111111111111111111111111112', + 'SysvarRent111111111111111111111111111111111', + 'SysvarC1ock11111111111111111111111111111111', + 'Stake11111111111111111111111111111111111111', + 'Vote111111111111111111111111111111111111111', + 'BPFLoaderUpgradeab1e11111111111111111111111', + 'ComputeBudget111111111111111111111111111111', + 'AddressLookupTab1e1111111111111111111111111', + 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL', + 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s', +]; diff --git a/app/components/common/__stories__/Account.stories.tsx b/app/components/common/__stories__/Account.stories.tsx index ebf8150148..59ba42685a 100644 --- a/app/components/common/__stories__/Account.stories.tsx +++ b/app/components/common/__stories__/Account.stories.tsx @@ -1,24 +1,20 @@ -import { Account } from '@providers/accounts'; +import { makeAccount } from '@entities/account/__fixtures__/account'; import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { OverviewCard } from '@/app/shared/ui/OverviewCard'; import { AccountAddressRow, AccountBalanceRow, AccountHeader } from '../Account'; -const sampleAccount: Account = { - data: {}, - executable: false, +const sampleAccount = makeAccount({ lamports: 4_200_000_000, - owner: new PublicKey('11111111111111111111111111111111'), pubkey: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), space: 0, -}; +}); const meta = { decorators: [withCluster, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Common/Account', } satisfies Meta; diff --git a/app/components/common/__stories__/Address.stories.tsx b/app/components/common/__stories__/Address.stories.tsx index 9c372d0fe7..8ef493890d 100644 --- a/app/components/common/__stories__/Address.stories.tsx +++ b/app/components/common/__stories__/Address.stories.tsx @@ -1,5 +1,5 @@ import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { Address } from '../Address'; @@ -9,7 +9,6 @@ const pubkey = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'); const meta: Meta = { component: Address, decorators: [withCluster, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Common/Address', }; diff --git a/app/components/common/__stories__/ErrorCard.responsive.stories.tsx b/app/components/common/__stories__/ErrorCard.responsive.stories.tsx index ddb0ad7347..4fe4cd7f04 100644 --- a/app/components/common/__stories__/ErrorCard.responsive.stories.tsx +++ b/app/components/common/__stories__/ErrorCard.responsive.stories.tsx @@ -1,16 +1,14 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { ErrorCard } from '../ErrorCard'; +import * as Base from './ErrorCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. // ErrorCard switches button layout under the md breakpoint (full-width on mobile, inline on md+). const meta: Meta = { component: ErrorCard, decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Common/ErrorCard@Media', }; @@ -18,11 +16,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - retry: () => {}, - subtext: 'Please check your network connection', - text: 'Failed to fetch', -}; +const args = Base.WithSubtext.args; export const Mobile: Story = { args, diff --git a/app/components/common/__stories__/InfoTooltip.responsive.stories.tsx b/app/components/common/__stories__/InfoTooltip.responsive.stories.tsx index d449bdd76d..d7fe47e63d 100644 --- a/app/components/common/__stories__/InfoTooltip.responsive.stories.tsx +++ b/app/components/common/__stories__/InfoTooltip.responsive.stories.tsx @@ -1,14 +1,12 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { InfoTooltip } from '../InfoTooltip'; +import * as Base from './InfoTooltip.stories'; const meta: Meta = { component: InfoTooltip, decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Common/InfoTooltip@Media', }; @@ -16,10 +14,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - children: Hover for more info, - text: 'This is the tooltip text shown on hover.', -}; +const args = Base.Default.args; export const Mobile: Story = { args, diff --git a/app/components/common/__stories__/InstructionDetails.stories.tsx b/app/components/common/__stories__/InstructionDetails.stories.tsx index 6597f845fb..c638a81474 100644 --- a/app/components/common/__stories__/InstructionDetails.stories.tsx +++ b/app/components/common/__stories__/InstructionDetails.stories.tsx @@ -1,5 +1,5 @@ import { gen } from '@__fixtures__/gen'; -import { buildTokenTransferCheckedIx } from '@features/receipt/model/__fixtures__/builders'; +import { buildTokenTransferCheckedIx } from '@entities/transaction-data/__fixtures__/parsed-transactions'; import { mockConfirmedSignatureInfo } from '@storybook-config/__fixtures__/account-history'; import type { Meta, StoryObj } from '@storybook-config/types'; diff --git a/app/components/common/__stories__/KitAddress.stories.tsx b/app/components/common/__stories__/KitAddress.stories.tsx index 5ecacbdeeb..faee93e0ce 100644 --- a/app/components/common/__stories__/KitAddress.stories.tsx +++ b/app/components/common/__stories__/KitAddress.stories.tsx @@ -1,6 +1,6 @@ import { address } from '@solana/kit'; import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { KitAddress } from '../KitAddress'; @@ -8,7 +8,6 @@ import { KitAddress } from '../KitAddress'; const meta: Meta = { component: KitAddress, decorators: [withCluster, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Common/KitAddress', }; diff --git a/app/components/common/__stories__/LoadingCard.responsive.stories.tsx b/app/components/common/__stories__/LoadingCard.responsive.stories.tsx index f2066df09c..7c05bbacb7 100644 --- a/app/components/common/__stories__/LoadingCard.responsive.stories.tsx +++ b/app/components/common/__stories__/LoadingCard.responsive.stories.tsx @@ -1,4 +1,4 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { LoadingCard } from '../LoadingCard'; @@ -7,9 +7,6 @@ import { LoadingCard } from '../LoadingCard'; const meta: Meta = { component: LoadingCard, decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Common/LoadingCard@Media', }; diff --git a/app/components/common/__stories__/NFTArt.responsive.stories.tsx b/app/components/common/__stories__/NFTArt.responsive.stories.tsx index 9988d3a0c0..5ddc806827 100644 --- a/app/components/common/__stories__/NFTArt.responsive.stories.tsx +++ b/app/components/common/__stories__/NFTArt.responsive.stories.tsx @@ -1,16 +1,11 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import { NFTImageContent } from '../NFTArt'; - -const SAMPLE_URI = 'https://arweave.net/sample-image.png'; +import * as Base from './NFTArt.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta = { decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Common/NFTArt@Media', } satisfies Meta; @@ -20,15 +15,15 @@ type Story = StoryObj; export const Mobile: Story = { globals: { viewport: { value: 'iphonex' } }, - render: () => , + render: Base.WithUri.render, }; export const TabletPortrait: Story = { globals: { viewport: { value: 'ipad' } }, - render: () => , + render: Base.WithUri.render, }; export const TabletLandscape: Story = { globals: { viewport: { isRotated: true, value: 'ipad' } }, - render: () => , + render: Base.WithUri.render, }; diff --git a/app/components/common/__stories__/VerifiedProgramBadge.stories.tsx b/app/components/common/__stories__/VerifiedProgramBadge.stories.tsx index 11d1c180b9..cf58457f61 100644 --- a/app/components/common/__stories__/VerifiedProgramBadge.stories.tsx +++ b/app/components/common/__stories__/VerifiedProgramBadge.stories.tsx @@ -2,7 +2,6 @@ import { toConnectableUrl } from '@entities/cluster'; import type { ClusterState } from '@providers/cluster'; import { PublicKey } from '@solana/web3.js'; import { MockClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; -import { nextjsParameters } from '@storybook-config/decorators'; import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; import { Cluster, clusterSelection, ClusterStatus, clusterUrl } from '@utils/cluster'; import { hashProgramData } from '@utils/verified-builds'; @@ -78,7 +77,6 @@ const withUnsupportedCluster: Decorator = Story => ( const meta: Meta = { args: { programData, pubkey }, component: VerifiedProgramBadge, - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Common/VerifiedProgramBadge', }; diff --git a/app/components/common/__tests__/VerifiedProgramBadge.spec.tsx b/app/components/common/__tests__/VerifiedProgramBadge.spec.tsx index 053ea53783..25c1813c89 100644 --- a/app/components/common/__tests__/VerifiedProgramBadge.spec.tsx +++ b/app/components/common/__tests__/VerifiedProgramBadge.spec.tsx @@ -1,4 +1,5 @@ /* eslint-disable no-restricted-syntax -- test assertions use RegExp for pattern matching */ +import { makeProgramDataInfo } from '@entities/account/__fixtures__/account'; import { PublicKey } from '@solana/web3.js'; import { render, screen } from '@testing-library/react'; import React from 'react'; @@ -21,11 +22,7 @@ vi.mock('@/app/utils/verified-builds', async importOriginal => ({ import { useCluster } from '@/app/providers/cluster'; import { useIsProgramVerified } from '@/app/utils/verified-builds'; -const mockProgramData = { - authority: new PublicKey('11111111111111111111111111111111'), - data: ['deadbeef', 'base64'] as [string, 'base64'], - slot: 123, -}; +const mockProgramData = makeProgramDataInfo(); const mockPubkey = new PublicKey('cmtDvXumGCrqC1Age74AVPhSRVXJMd8PJS91L8KbNCK'); describe('VerifiedProgramBadge (mocked useIsProgramVerified)', () => { diff --git a/app/components/inspector/__stories__/AccountsCard.stories.tsx b/app/components/inspector/__stories__/AccountsCard.stories.tsx index 94cf9c2eba..6caac2fc37 100644 --- a/app/components/inspector/__stories__/AccountsCard.stories.tsx +++ b/app/components/inspector/__stories__/AccountsCard.stories.tsx @@ -1,14 +1,13 @@ /* eslint-disable no-restricted-syntax -- storybook play functions use RegExp for pattern matching */ +import { makeAccount } from '@entities/account/__fixtures__/account'; import { PublicKey, VersionedMessage } from '@solana/web3.js'; import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; import { mockVersionedMessage } from '@storybook-config/__fixtures__/messages'; -import { MockClusterProvider as ClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; -import { nextjsParameters, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withAccountsState, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import React from 'react'; import { expect, within } from 'storybook/test'; -import { DispatchContext, FetchersContext, State, StateContext } from '@/app/providers/accounts'; +import { State } from '@/app/providers/accounts'; import { FetchStatus } from '@/app/providers/cache'; import { MAINNET_BETA_URL } from '@/app/utils/cluster'; @@ -16,11 +15,6 @@ import { AccountsCard } from '../AccountsCard'; const TOKEN_PROGRAM_PUBKEY = new PublicKey(TOKEN_PROGRAM_ADDRESS); -// No-op function for mock fetchers -const noop = () => { - // intentionally empty -}; - // Create a message without lookups const createMessage = (): VersionedMessage => { const staticAccountKeys = [PublicKey.default, TOKEN_PROGRAM_PUBKEY]; @@ -38,55 +32,30 @@ const createMessage = (): VersionedMessage => { }); }; -// Mock provider with accounts -function MockAccountsProvider({ children }: { children: React.ReactNode }) { - const mockState: State = { - entries: { - [PublicKey.default.toBase58()]: { - data: { - data: {}, - executable: false, - lamports: 1_000_000_000, - owner: PublicKey.default, - pubkey: PublicKey.default, - space: 0, - }, - status: FetchStatus.Fetched, - }, - [TOKEN_PROGRAM_ADDRESS]: { - data: { - data: {}, - executable: true, - lamports: 5_000_000_000, - owner: new PublicKey('BPFLoaderUpgradeab1e11111111111111111111111'), - pubkey: TOKEN_PROGRAM_PUBKEY, - space: 36, - }, - status: FetchStatus.Fetched, +const accountsState: State = { + entries: { + [PublicKey.default.toBase58()]: { + data: makeAccount({ space: 0 }), + status: FetchStatus.Fetched, + }, + [TOKEN_PROGRAM_ADDRESS]: { + data: { + data: {}, + executable: true, + lamports: 5_000_000_000, + owner: new PublicKey('BPFLoaderUpgradeab1e11111111111111111111111'), + pubkey: TOKEN_PROGRAM_PUBKEY, + space: 36, }, + status: FetchStatus.Fetched, }, - url: MAINNET_BETA_URL, - }; - - const mockFetchers = { - parsed: { fetch: noop }, - raw: { fetch: noop }, - skip: { fetch: noop }, - }; - - return ( - - - {children} - - - ); -} + }, + url: MAINNET_BETA_URL, +}; const meta = { component: AccountsCard, decorators: [withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Inspector/AccountsCard', } satisfies Meta; @@ -98,15 +67,7 @@ export const Default: Story = { args: { message: createMessage(), }, - decorators: [ - Story => ( - - - - - - ), - ], + decorators: [withAccountsState(accountsState)], play: async ({ canvasElement }) => { const canvas = within(canvasElement); diff --git a/app/components/inspector/__stories__/AddressTableLookupsCard.responsive.stories.tsx b/app/components/inspector/__stories__/AddressTableLookupsCard.responsive.stories.tsx index 594eecc42d..86fbdfd19b 100644 --- a/app/components/inspector/__stories__/AddressTableLookupsCard.responsive.stories.tsx +++ b/app/components/inspector/__stories__/AddressTableLookupsCard.responsive.stories.tsx @@ -1,82 +1,13 @@ -import { DispatchContext, FetchersContext, type State, StateContext } from '@providers/accounts'; -import { FetchStatus } from '@providers/cache'; -import { AddressLookupTableProgram, PublicKey } from '@solana/web3.js'; -import { mockVersionedMessage } from '@storybook-config/__fixtures__/messages'; -import { MockClusterProvider as ClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; -import { nextjsParameters, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; -import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; -import React from 'react'; - -import { MAINNET_BETA_URL } from '@/app/utils/cluster'; +import { withTokenInfoBatch } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import type { Meta, StoryObj } from '@storybook-config/types'; import { AddressTableLookupsCard } from '../AddressTableLookupsCard'; - -const LOOKUP_TABLE_KEY = new PublicKey('AddressLookupTab1e1111111111111111111111111'); -const RESOLVED_A = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'); -const RESOLVED_B = new PublicKey('So11111111111111111111111111111111111111112'); - -const noop = () => undefined; - -const message = mockVersionedMessage({ - addressTableLookups: [{ accountKey: LOOKUP_TABLE_KEY, readonlyIndexes: [1], writableIndexes: [0] }], - header: { numReadonlySignedAccounts: 0, numReadonlyUnsignedAccounts: 0, numRequiredSignatures: 0 }, - staticAccountKeys: [], -}); - -const resolvedState: State = { - entries: { - [LOOKUP_TABLE_KEY.toBase58()]: { - data: { - data: { - parsed: { - parsed: { - info: { - addresses: [RESOLVED_A, RESOLVED_B], - authority: undefined, - deactivationSlot: '18446744073709551615', - lastExtendedSlot: '0', - lastExtendedSlotStartIndex: 0, - }, - type: 'lookupTable', - }, - program: 'address-lookup-table', - space: 568, - }, - } as any, - executable: false, - lamports: 1_000_000_000, - owner: AddressLookupTableProgram.programId, - pubkey: LOOKUP_TABLE_KEY, - space: 568, - }, - status: FetchStatus.Fetched, - }, - }, - url: MAINNET_BETA_URL, -}; - -const withResolved: Decorator = Story => ( - - - - - - - - - -); +import * as Base from './AddressTableLookupsCard.stories'; const meta: Meta = { component: AddressTableLookupsCard, - decorators: [withTokenInfoBatch, withResolved, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withTokenInfoBatch, withViewportFromGlobal], tags: ['autodocs', 'test'], title: 'Components/Inspector/AddressTableLookupsCard@Media', }; @@ -84,8 +15,8 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { message }; +const { args, decorators } = Base.WithResolvedAddresses; -export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; -export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; -export const TabletLandscape: Story = { args, globals: { viewport: { isRotated: true, value: 'ipad' } } }; +export const Mobile: Story = { args, decorators, globals: { viewport: { value: 'iphonex' } } }; +export const TabletPortrait: Story = { args, decorators, globals: { viewport: { value: 'ipad' } } }; +export const TabletLandscape: Story = { args, decorators, globals: { viewport: { isRotated: true, value: 'ipad' } } }; diff --git a/app/components/inspector/__stories__/AddressTableLookupsCard.stories.tsx b/app/components/inspector/__stories__/AddressTableLookupsCard.stories.tsx index 6efe3d0661..3b65cfb065 100644 --- a/app/components/inspector/__stories__/AddressTableLookupsCard.stories.tsx +++ b/app/components/inspector/__stories__/AddressTableLookupsCard.stories.tsx @@ -1,11 +1,9 @@ -import { DispatchContext, FetchersContext, type State, StateContext } from '@providers/accounts'; +import type { State } from '@providers/accounts'; import { FetchStatus } from '@providers/cache'; import { AddressLookupTableProgram, PublicKey } from '@solana/web3.js'; import { mockVersionedMessage } from '@storybook-config/__fixtures__/messages'; -import { MockClusterProvider as ClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; -import { nextjsParameters, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withAccountsState, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import React from 'react'; import { MAINNET_BETA_URL } from '@/app/utils/cluster'; @@ -15,29 +13,11 @@ const LOOKUP_TABLE_KEY = new PublicKey('AddressLookupTab1e1111111111111111111111 const RESOLVED_A = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'); const RESOLVED_B = new PublicKey('So11111111111111111111111111111111111111112'); -const noop = () => undefined; - const createAccountsState = (entries: State['entries']): State => ({ entries, url: MAINNET_BETA_URL, }); -function MockProvider({ children, state }: { children: React.ReactNode; state: State }) { - return ( - - - - - {children} - - - - - ); -} - const messageWithLookups = mockVersionedMessage({ addressTableLookups: [ { @@ -86,7 +66,6 @@ const resolvedState = createAccountsState({ const meta = { component: AddressTableLookupsCard, decorators: [withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Inspector/AddressTableLookupsCard', } satisfies Meta; @@ -96,13 +75,7 @@ type Story = StoryObj; export const WithResolvedAddresses: Story = { args: { message: messageWithLookups }, - decorators: [ - Story => ( - - - - ), - ], + decorators: [withAccountsState(resolvedState)], }; const messageNoLookups = mockVersionedMessage({ @@ -112,11 +85,5 @@ const messageNoLookups = mockVersionedMessage({ export const Empty: Story = { args: { message: messageNoLookups }, - decorators: [ - Story => ( - - - - ), - ], + decorators: [withAccountsState(createAccountsState({}))], }; diff --git a/app/components/inspector/__stories__/AddressWithContext.responsive.stories.tsx b/app/components/inspector/__stories__/AddressWithContext.responsive.stories.tsx index e1e30f411d..f4f53d42da 100644 --- a/app/components/inspector/__stories__/AddressWithContext.responsive.stories.tsx +++ b/app/components/inspector/__stories__/AddressWithContext.responsive.stories.tsx @@ -1,6 +1,6 @@ import { gen } from '@__fixtures__/gen'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { AddressWithContext } from '../AddressWithContext'; @@ -9,10 +9,6 @@ import { AddressWithContext } from '../AddressWithContext'; const meta = { component: AddressWithContext, decorators: [withClusterAndAccounts, withTokenInfoBatch, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Inspector/AddressWithContext@Media', } satisfies Meta; diff --git a/app/components/inspector/__stories__/AddressWithContext.stories.tsx b/app/components/inspector/__stories__/AddressWithContext.stories.tsx index 8f838a747e..1f3526518e 100644 --- a/app/components/inspector/__stories__/AddressWithContext.stories.tsx +++ b/app/components/inspector/__stories__/AddressWithContext.stories.tsx @@ -1,5 +1,5 @@ import { gen } from '@__fixtures__/gen'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { AddressWithContext, createFeePayerValidator, programValidator } from '../AddressWithContext'; @@ -7,7 +7,6 @@ import { AddressWithContext, createFeePayerValidator, programValidator } from '. const meta = { component: AddressWithContext, decorators: [withClusterAndAccounts, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Inspector/AddressWithContext', } satisfies Meta; diff --git a/app/components/inspector/__stories__/RawInputCard.responsive.stories.tsx b/app/components/inspector/__stories__/RawInputCard.responsive.stories.tsx index 90da78a5f9..beb1f56d5c 100644 --- a/app/components/inspector/__stories__/RawInputCard.responsive.stories.tsx +++ b/app/components/inspector/__stories__/RawInputCard.responsive.stories.tsx @@ -1,5 +1,4 @@ -import { nextjsParameters } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { fn } from 'storybook/test'; @@ -9,10 +8,6 @@ import { RawInput } from '../RawInputCard'; const meta = { component: RawInput, decorators: [withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Inspector/RawInputCard@Media', } satisfies Meta; diff --git a/app/components/inspector/__stories__/RawInputCard.stories.tsx b/app/components/inspector/__stories__/RawInputCard.stories.tsx index 6ad4285b08..48428aa845 100644 --- a/app/components/inspector/__stories__/RawInputCard.stories.tsx +++ b/app/components/inspector/__stories__/RawInputCard.stories.tsx @@ -1,4 +1,3 @@ -import { nextjsParameters } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { fn } from 'storybook/test'; @@ -6,7 +5,6 @@ import { RawInput } from '../RawInputCard'; const meta = { component: RawInput, - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Inspector/RawInputCard', } satisfies Meta; diff --git a/app/components/inspector/__stories__/SignaturesCard.responsive.stories.tsx b/app/components/inspector/__stories__/SignaturesCard.responsive.stories.tsx index 32b89499e0..852d9a2f21 100644 --- a/app/components/inspector/__stories__/SignaturesCard.responsive.stories.tsx +++ b/app/components/inspector/__stories__/SignaturesCard.responsive.stories.tsx @@ -1,35 +1,14 @@ -import { DEFAULT_SIGNATURE } from '@__fixtures__/gen'; -import { PublicKey } from '@solana/web3.js'; -import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; -import { mockVersionedMessage } from '@storybook-config/__fixtures__/messages'; -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { TransactionSignatures } from '../SignaturesCard'; +import * as Base from './SignaturesCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. -const SIGNER_2 = new PublicKey(TOKEN_PROGRAM_ADDRESS); -const BOGUS_SIGNATURE = DEFAULT_SIGNATURE; - -const baseMessage = mockVersionedMessage({ - header: { - numReadonlySignedAccounts: 0, - numReadonlyUnsignedAccounts: 0, - numRequiredSignatures: 2, - }, - staticAccountKeys: [PublicKey.default, SIGNER_2], -}); - -const rawMessage = new Uint8Array(64); - const meta = { component: TransactionSignatures, decorators: [withViewportFromGlobal, withCluster, withTokenInfoBatch], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Inspector/SignaturesCard@Media', } satisfies Meta; @@ -37,11 +16,7 @@ const meta = { export default meta; type Story = StoryObj; -const args = { - message: baseMessage, - rawMessage, - signatures: [BOGUS_SIGNATURE, BOGUS_SIGNATURE], -}; +const args = Base.Invalid.args; export const Mobile: Story = { args, diff --git a/app/components/inspector/__stories__/SignaturesCard.stories.tsx b/app/components/inspector/__stories__/SignaturesCard.stories.tsx index ffc42e96ca..8a4c0c63d6 100644 --- a/app/components/inspector/__stories__/SignaturesCard.stories.tsx +++ b/app/components/inspector/__stories__/SignaturesCard.stories.tsx @@ -1,6 +1,6 @@ import { PublicKey } from '@solana/web3.js'; import { mockVersionedMessage } from '@storybook-config/__fixtures__/messages'; -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { TransactionSignatures } from '../SignaturesCard'; @@ -22,7 +22,6 @@ const rawMessage = new Uint8Array(64); const meta = { component: TransactionSignatures, decorators: [withCluster, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Inspector/SignaturesCard', } satisfies Meta; diff --git a/app/components/inspector/__stories__/SimulationHint.stories.tsx b/app/components/inspector/__stories__/SimulationHint.stories.tsx index 251f1cadeb..6a8075eed2 100644 --- a/app/components/inspector/__stories__/SimulationHint.stories.tsx +++ b/app/components/inspector/__stories__/SimulationHint.stories.tsx @@ -1,4 +1,3 @@ -import { nextjsParameters } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import type { SimulationState } from '@/app/features/instruction-simulation/model/use-simulation'; @@ -7,7 +6,6 @@ import { SimulationHint } from '../SimulationHint'; const meta: Meta = { component: SimulationHint, - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Inspector/SimulationHint', }; diff --git a/app/components/inspector/__tests__/AccountsCard-raw-data.spec.tsx b/app/components/inspector/__tests__/AccountsCard-raw-data.spec.tsx index e0e396e446..265c7b1c46 100644 --- a/app/components/inspector/__tests__/AccountsCard-raw-data.spec.tsx +++ b/app/components/inspector/__tests__/AccountsCard-raw-data.spec.tsx @@ -12,29 +12,15 @@ vi.mock('@/app/entities/cluster/api/fetch-genesis-hash', () => ({ const mockGetMultipleAccounts = vi.fn(); const mockGetAccountInfo = vi.fn(); -const mockRpc = () => ({ - getAccountInfo: (...args: unknown[]) => ({ - send: async () => ({ value: await mockGetAccountInfo(...args) }), - }), - getMultipleAccounts: (...args: unknown[]) => ({ - send: async () => ({ value: await mockGetMultipleAccounts(...args) }), - }), -}); - -vi.mock('@entities/cluster/@x/account', async () => { - const actual = await vi.importActual('@entities/cluster/@x/account'); - return { ...actual, getRpc: vi.fn(() => mockRpc()) }; -}); - -vi.mock('@entities/cluster', async () => { - const actual = await vi.importActual('@entities/cluster'); - return { ...actual, getRpc: vi.fn(() => mockRpc()) }; -}); +vi.mock('@/app/entities/cluster/api/get-rpc', () => ({ + getRpc: () => rpcValueStub({ getAccountInfo: mockGetAccountInfo, getMultipleAccounts: mockGetMultipleAccounts }), +})); import { DEFAULT_BLOCKHASH, gen } from '@__fixtures__/gen'; import { Message, MessageV0, PublicKey, type VersionedMessage } from '@solana/web3.js'; import React from 'react'; +import { rpcValueStub } from '@/app/__tests__/mock-rpc'; import * as stubs from '@/app/__tests__/mock-stubs'; import * as mock from '@/app/__tests__/mocks'; import { AccountsProvider, useFetchAccountInfo } from '@/app/providers/accounts'; diff --git a/app/components/inspector/__tests__/InstructionsSection-ProgramRow.spec.tsx b/app/components/inspector/__tests__/InstructionsSection-ProgramRow.spec.tsx index 94620c54bb..291869b8cc 100644 --- a/app/components/inspector/__tests__/InstructionsSection-ProgramRow.spec.tsx +++ b/app/components/inspector/__tests__/InstructionsSection-ProgramRow.spec.tsx @@ -1,5 +1,6 @@ import { gen } from '@__fixtures__/gen'; -import { type MessageV0, PublicKey, SystemProgram, TransactionInstruction, TransactionMessage } from '@solana/web3.js'; +import { compileV0Message } from '@entities/transaction-data/__fixtures__/wire-transactions'; +import { PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js'; import { ASSOCIATED_TOKEN_PROGRAM_ADDRESS, TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; @@ -15,22 +16,9 @@ import { instructionParserDispatcher } from '@/app/tx/instruction-parser-dispatc import { InstructionsSection } from '../InstructionsSection'; -vi.mock('swr', () => ({ - __esModule: true, - default: vi.fn(() => ({ - data: undefined, - error: undefined, - isLoading: false, - isValidating: false, - mutate: vi.fn(), - })), -})); +vi.mock('swr', async () => (await import('@/app/__tests__/swr-idle')).idleSwrModule); -vi.mock('next/navigation', () => ({ - usePathname: vi.fn(() => '/'), - useRouter: vi.fn(() => ({ push: vi.fn(), replace: vi.fn() })), - useSearchParams: vi.fn(() => new URLSearchParams()), -})); +vi.mock('next/navigation', () => import('@/app/__tests__/next-navigation')); vi.mock('next/link', () => ({ __esModule: true, @@ -86,7 +74,7 @@ function renderSection(ix: TransactionInstruction) { - + @@ -94,11 +82,3 @@ function renderSection(ix: TransactionInstruction) { , ); } - -function buildMessage(ix: TransactionInstruction): MessageV0 { - return new TransactionMessage({ - instructions: [ix], - payerKey: PAYER, - recentBlockhash: PublicKey.default.toBase58(), - }).compileToV0Message(); -} diff --git a/app/components/inspector/__tests__/InstructionsSection-VendoredDecoders.spec.tsx b/app/components/inspector/__tests__/InstructionsSection-VendoredDecoders.spec.tsx index 3a5cce57f6..2144a9daa8 100644 --- a/app/components/inspector/__tests__/InstructionsSection-VendoredDecoders.spec.tsx +++ b/app/components/inspector/__tests__/InstructionsSection-VendoredDecoders.spec.tsx @@ -1,12 +1,14 @@ /* eslint-disable no-restricted-syntax -- test assertions use RegExp for pattern matching */ import { gen } from '@__fixtures__/gen'; +import { makeInstruction } from '@__fixtures__/instruction'; +import { compileV0Message } from '@entities/transaction-data/__fixtures__/wire-transactions'; import { MANGO_PROGRAM_IDS } from '@explorer/decoder-mango'; import { OPEN_BOOK_PROGRAM_IDS, SERUM_DEX_V3_PROGRAM_IDS } from '@explorer/decoder-serum'; import { TOKEN_SWAP_PROGRAM_IDS } from '@explorer/decoder-token-swap'; import { WORMHOLE_PROGRAM_IDS } from '@explorer/decoder-wormhole'; import { getBase58Decoder } from '@solana/kit'; import type { CompiledInnerInstruction } from '@solana/web3.js'; -import { MessageV0, PublicKey, SystemProgram, TransactionInstruction, TransactionMessage } from '@solana/web3.js'; +import { MessageV0, PublicKey, SystemProgram } from '@solana/web3.js'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import React from 'react'; @@ -21,27 +23,9 @@ import { instructionParserDispatcher } from '@/app/tx/instruction-parser-dispatc import { InstructionsSection } from '../InstructionsSection'; -// `useAnchorProgram` reads its IDL through SWR. The mock returns no data, so the instructions -// render through the dispatcher. -vi.mock('swr', () => ({ - __esModule: true, - default: vi.fn(() => ({ - data: undefined, - error: undefined, - isLoading: false, - isValidating: false, - mutate: vi.fn(), - })), -})); +vi.mock('swr', async () => (await import('@/app/__tests__/swr-idle')).idleSwrModule); -// The Token Swap and Wormhole parsers report a tag outside their name table through `Logger.error`. -vi.mock('@/app/shared/lib/logger', () => ({ Logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } })); - -vi.mock('next/navigation', () => ({ - usePathname: vi.fn(() => '/'), - useRouter: vi.fn(() => ({ push: vi.fn(), replace: vi.fn() })), - useSearchParams: vi.fn(() => new URLSearchParams()), -})); +vi.mock('next/navigation', () => import('@/app/__tests__/next-navigation')); vi.mock('next/link', () => ({ __esModule: true, @@ -74,7 +58,7 @@ describe('Inspector InstructionsSection with vendored decoder instructions', () ])( 'should render decoded fields for the OpenBook instruction $title', async ({ data, fields, keyCount, title }) => { - renderSection(buildMessage(makeInstruction(OPEN_BOOK_PROGRAM_IDS.mainnet, hexBytes(data), keyCount))); + renderSection(buildMessage(OPEN_BOOK_PROGRAM_IDS.mainnet, hexBytes(data), keyCount)); expect(await screen.findByText(title)).toBeInTheDocument(); for (const field of fields) { @@ -85,7 +69,7 @@ describe('Inspector InstructionsSection with vendored decoder instructions', () ); test('should show the raw accounts and hex of a decoded OpenBook instruction on request', async () => { - renderSection(buildMessage(makeInstruction(OPEN_BOOK_PROGRAM_IDS.mainnet, hexBytes(CONSUME_EVENTS_DATA), 6))); + renderSection(buildMessage(OPEN_BOOK_PROGRAM_IDS.mainnet, hexBytes(CONSUME_EVENTS_DATA), 6)); expect(await screen.findByText('OpenBook Dex Program: Consume Events')).toBeInTheDocument(); expect(screen.queryByText(/Instruction Data/)).not.toBeInTheDocument(); @@ -98,9 +82,7 @@ describe('Inspector InstructionsSection with vendored decoder instructions', () }); test('should render a deprecated Serum deployment name-only under its program name', async () => { - renderSection( - buildMessage(makeInstruction(SERUM_DEX_V3_PROGRAM_IDS.mainnet, hexBytes(CONSUME_EVENTS_DATA), 6)), - ); + renderSection(buildMessage(SERUM_DEX_V3_PROGRAM_IDS.mainnet, hexBytes(CONSUME_EVENTS_DATA), 6)); expect(await screen.findByText('Serum Dex v3 (deprecated): Consume Events')).toBeInTheDocument(); expect(screen.queryByText('Event Queue')).not.toBeInTheDocument(); @@ -114,7 +96,7 @@ describe('Inspector InstructionsSection with vendored decoder instructions', () { data: [1], programId: TOKEN_SWAP_PROGRAM_IDS[0], title: 'Token Swap: Swap' }, { data: [2], programId: WORMHOLE_PROGRAM_IDS[0], title: 'Wormhole: Post VAA' }, ])('should title the $title instruction by name', async ({ data, programId, title }) => { - renderSection(buildMessage(makeInstruction(programId, data, 1))); + renderSection(buildMessage(programId, data, 1)); expect(await screen.findByText(title)).toBeInTheDocument(); expectNoGenericUnknownCard(); @@ -144,7 +126,7 @@ describe('Inspector InstructionsSection with vendored decoder instructions', () ])( 'should title an unrecognized $name instruction "Unknown" and open its raw view', async ({ data, programId, title }) => { - renderSection(buildMessage(makeInstruction(programId, data, 1))); + renderSection(buildMessage(programId, data, 1)); expect(await screen.findByText(title)).toBeInTheDocument(); // The raw view is the card's whole content, so it opens without a click. @@ -231,24 +213,9 @@ function expectNoGenericUnknownCard() { expect(screen.queryByText('Instruction')).not.toBeInTheDocument(); } -function makeInstruction(programId: string, data: ArrayLike, keyCount: number): TransactionInstruction { - return new TransactionInstruction({ - data: Buffer.from(data), - keys: Array.from({ length: keyCount }, (_, i) => ({ - isSigner: false, - isWritable: false, - pubkey: gen.publicKey(i), - })), - programId: new PublicKey(programId), - }); -} - -function buildMessage(ix: TransactionInstruction): MessageV0 { - return new TransactionMessage({ - instructions: [ix], - payerKey: PAYER, - recentBlockhash: PublicKey.default.toBase58(), - }).compileToV0Message(); +function buildMessage(programId: string, data: Uint8Array | number[], keyCount: number): MessageV0 { + const keys = Array.from({ length: keyCount }, (_, i) => gen.publicKey(i)); + return compileV0Message(PAYER, makeInstruction({ data, keys, programId })); } // A single System Transfer, so every vendored card in the inspector is an inner instruction. diff --git a/app/components/inspector/__tests__/InstructionsSection.spec.tsx b/app/components/inspector/__tests__/InstructionsSection.spec.tsx index 900eee4f10..665faff455 100644 --- a/app/components/inspector/__tests__/InstructionsSection.spec.tsx +++ b/app/components/inspector/__tests__/InstructionsSection.spec.tsx @@ -4,6 +4,7 @@ import { SystemDetailsCard } from '@components/instruction/system/SystemDetailsC // From the literal's own library-free module: the feature no longer re-exports it, and this spec only needs the // program id to build a fixture instruction - not the decoders that `@entities/pmp-account` would pull in. import { PMP_ADDRESS } from '@entities/pmp-account/lib/program-address'; +import { compileV0Message } from '@entities/transaction-data/__fixtures__/wire-transactions'; import { LIGHTHOUSE_ADDRESS, LighthouseDetailsCard } from '@features/decode-instruction-lighthouse'; import { useIdlInstructionDecode } from '@features/decode-instruction-with-idl'; import { MPL_TOKEN_METADATA_PROGRAM_ID } from '@metaplex-foundation/mpl-token-metadata'; @@ -37,17 +38,7 @@ import { instructionParserDispatcher } from '@/app/tx/instruction-parser-dispatc import { InstructionsSection } from '../InstructionsSection'; import { buildMessage, CREATE_ACCOUNT, INNER_INSTRUCTIONS } from './__fixtures__/create-idempotent-tx'; -// The IDL tiers read through SWR. The mock returns no data, so instructions render through the dispatcher. -vi.mock('swr', () => ({ - __esModule: true, - default: vi.fn(() => ({ - data: undefined, - error: undefined, - isLoading: false, - isValidating: false, - mutate: vi.fn(), - })), -})); +vi.mock('swr', async () => (await import('@/app/__tests__/swr-idle')).idleSwrModule); vi.mock('@features/decode-instruction-with-idl', async importOriginal => ({ ...(await importOriginal()), @@ -355,11 +346,7 @@ function buildLighthouseMessage(): MessageV0 { keys: [], programId: new PublicKey(LIGHTHOUSE_ADDRESS), }); - return new TransactionMessage({ - instructions: [ix], - payerKey: Keypair.generate().publicKey, - recentBlockhash: PublicKey.default.toBase58(), - }).compileToV0Message(); + return compileV0Message(Keypair.generate().publicKey, ix); } function buildPmpMessage(data: Uint8Array): MessageV0 { @@ -371,11 +358,7 @@ function buildPmpMessage(data: Uint8Array): MessageV0 { ], programId: new PublicKey(PMP_ADDRESS), }); - return new TransactionMessage({ - instructions: [ix], - payerKey: gen.publicKey(0), - recentBlockhash: PublicKey.default.toBase58(), - }).compileToV0Message(); + return compileV0Message(gen.publicKey(0), ix); } function buildTokenMetadataMessage(data: number[]): MessageV0 { @@ -387,11 +370,7 @@ function buildTokenMetadataMessage(data: number[]): MessageV0 { ], programId: new PublicKey(MPL_TOKEN_METADATA_PROGRAM_ID), }); - return new TransactionMessage({ - instructions: [ix], - payerKey: gen.publicKey(0), - recentBlockhash: PublicKey.default.toBase58(), - }).compileToV0Message(); + return compileV0Message(gen.publicKey(0), ix); } function buildEd25519Message(): MessageV0 { diff --git a/app/components/inspector/__tests__/PermalinkView-InnerInstructions.spec.tsx b/app/components/inspector/__tests__/PermalinkView-InnerInstructions.spec.tsx index 20f1c15ce6..107de391f0 100644 --- a/app/components/inspector/__tests__/PermalinkView-InnerInstructions.spec.tsx +++ b/app/components/inspector/__tests__/PermalinkView-InnerInstructions.spec.tsx @@ -13,16 +13,7 @@ import { instructionParserDispatcher } from '@/app/tx/instruction-parser-dispatc import { PermalinkView } from '../InspectorPage'; import { buildMessage, INNER_INSTRUCTIONS } from './__fixtures__/create-idempotent-tx'; -vi.mock('swr', () => ({ - __esModule: true, - default: vi.fn(() => ({ - data: undefined, - error: undefined, - isLoading: false, - isValidating: false, - mutate: vi.fn(), - })), -})); +vi.mock('swr', async () => (await import('@/app/__tests__/swr-idle')).idleSwrModule); vi.mock('@features/decode-instruction-with-idl', async importOriginal => ({ ...(await importOriginal()), diff --git a/app/components/inspector/__tests__/SignaturesCard.spec.tsx b/app/components/inspector/__tests__/SignaturesCard.spec.tsx index 875a9a1663..a5015c1d8e 100644 --- a/app/components/inspector/__tests__/SignaturesCard.spec.tsx +++ b/app/components/inspector/__tests__/SignaturesCard.spec.tsx @@ -1,13 +1,13 @@ +import { makeInstruction } from '@__fixtures__/instruction'; +import { compileV0Message } from '@entities/transaction-data/__fixtures__/wire-transactions'; import { generateKeyPairSigner, getBase58Decoder, type ReadonlyUint8Array, signBytes } from '@solana/kit'; -import { PublicKey, TransactionInstruction, TransactionMessage } from '@solana/web3.js'; +import { PublicKey } from '@solana/web3.js'; import { render, screen, within } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; import { TransactionSignatures } from '../SignaturesCard'; -vi.mock('@components/common/Address', () => ({ - Address: ({ pubkey }: { pubkey: PublicKey }) => {pubkey.toBase58()}, -})); +vi.mock('@components/common/Address', () => import('@/app/__tests__/address-stub')); vi.mock('@components/common/Signature', () => ({ Signature: ({ signature }: { signature: string }) => {signature}, })); @@ -16,11 +16,7 @@ const base58Decoder = getBase58Decoder(); const { address: signerAddress, keyPair } = await generateKeyPairSigner(); const signerPublicKey = new PublicKey(signerAddress); -const message = new TransactionMessage({ - instructions: [new TransactionInstruction({ data: Buffer.from([1]), keys: [], programId: PublicKey.default })], - payerKey: signerPublicKey, - recentBlockhash: PublicKey.default.toBase58(), -}).compileToV0Message(); +const message = compileV0Message(signerPublicKey, makeInstruction({ data: [1], programId: PublicKey.default })); const rawMessage = message.serialize(); async function signMessage(messageBytes: ReadonlyUint8Array): Promise { diff --git a/app/components/shared/__stories__/Skeletons.responsive.stories.tsx b/app/components/shared/__stories__/Skeletons.responsive.stories.tsx index 183d71b241..4b301bd467 100644 --- a/app/components/shared/__stories__/Skeletons.responsive.stories.tsx +++ b/app/components/shared/__stories__/Skeletons.responsive.stories.tsx @@ -1,13 +1,10 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { RichListSkeleton, SimpleCardSkeleton, StatsTableSkeleton, TableCardSkeleton } from '../Skeletons'; const meta: Meta = { decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Components/Shared/Skeletons@Media', }; diff --git a/app/components/shared/__stories__/TruncatedValue.stories.tsx b/app/components/shared/__stories__/TruncatedValue.stories.tsx index f6a4a3aebc..ff9fe728cf 100644 --- a/app/components/shared/__stories__/TruncatedValue.stories.tsx +++ b/app/components/shared/__stories__/TruncatedValue.stories.tsx @@ -1,4 +1,4 @@ -import type { Meta, StoryObj } from '@storybook-config/types'; +import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; import { TruncatedValue } from '../TruncatedValue'; @@ -6,6 +6,7 @@ import { TruncatedValue } from '../TruncatedValue'; const EXAMPLE_HASH = '7039867918bfbbe1aade33c02140c617247df2bb1528f38c66b642a2253c965b'; const meta = { + args: { value: EXAMPLE_HASH }, component: TruncatedValue, tags: ['autodocs', 'test'], title: 'Components/Shared/TruncatedValue', @@ -15,16 +16,7 @@ export default meta; type Story = StoryObj; export const Default: Story = { - args: { - value: EXAMPLE_HASH, - }, - decorators: [ - Story => ( -
- -
- ), - ], + decorators: [withWidth(1000)], async play({ canvasElement }) { const canvas = within(canvasElement); const [visible] = canvas.getAllByText(EXAMPLE_HASH).filter(el => !el.hasAttribute('aria-hidden')); @@ -33,17 +25,8 @@ export const Default: Story = { }; export const Truncated: Story = { - args: { - value: EXAMPLE_HASH, - }, - decorators: [ - Story => ( - // narrow container should trigger value truncation. -
- -
- ), - ], + // narrow container should trigger value truncation. + decorators: [withWidth(200)], async play({ canvasElement }) { const canvas = within(canvasElement); expect(canvas.getByText('70398…c965b')).toBeInTheDocument(); @@ -51,17 +34,8 @@ export const Truncated: Story = { }; export const TruncatedWithCustomChars: Story = { - args: { - truncation: { enabled: true, midTruncateChars: 8 }, - value: EXAMPLE_HASH, - }, - decorators: [ - Story => ( -
- -
- ), - ], + args: { truncation: { enabled: true, midTruncateChars: 8 } }, + decorators: [withWidth(200)], async play({ canvasElement }) { const canvas = within(canvasElement); expect(canvas.getByText('70398679…253c965b')).toBeInTheDocument(); @@ -69,19 +43,20 @@ export const TruncatedWithCustomChars: Story = { }; export const Linked: Story = { - args: { - href: '/tx/example', - value: EXAMPLE_HASH, - }, - decorators: [ - Story => ( -
- -
- ), - ], + args: { href: '/tx/example' }, + decorators: [withWidth(200)], async play({ canvasElement }) { const canvas = within(canvasElement); expect(canvas.getByRole('link', { name: EXAMPLE_HASH })).toHaveAttribute('href', '/tx/example'); }, }; + +function withWidth(width: number): Decorator { + return function WithWidth(Story) { + return ( +
+ +
+ ); + }; +} diff --git a/app/components/shared/address/stories/AddressLink.stories.tsx b/app/components/shared/address/stories/AddressLink.stories.tsx index 9db0360eb0..5931d57280 100644 --- a/app/components/shared/address/stories/AddressLink.stories.tsx +++ b/app/components/shared/address/stories/AddressLink.stories.tsx @@ -1,10 +1,5 @@ import { address } from '@solana/kit'; -import { - nextjsParameters, - withClipboardMock, - withClipboardMockErrored, - withCluster, -} from '@storybook-config/decorators'; +import { withClipboardMock, withClipboardMockErrored, withCluster } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, userEvent, waitFor, within } from 'storybook/test'; @@ -15,7 +10,6 @@ const SAMPLE_ADDRESS = address('7bTK6Jis8Xpfrs8ZoUfiMDPazTcdPcTWheZFJTA5Z6X4'); const meta: Meta = { component: AddressLink, decorators: [withClipboardMock, withCluster], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Components/Shared/Address/AddressLink', }; diff --git a/app/components/shared/ui/autocomplete.stories.tsx b/app/components/shared/ui/autocomplete.stories.tsx index 5da9c1fdc9..077b08a7ac 100644 --- a/app/components/shared/ui/autocomplete.stories.tsx +++ b/app/components/shared/ui/autocomplete.stories.tsx @@ -29,245 +29,85 @@ export default meta; type Story = StoryObj; export const Default: Story = { - render: () => { - const DefaultStory = () => { - const [value, setValue] = useState(''); - const [inputId, setInputId] = useState(''); - return ( - - - - ); - }; - - return ; - }, + render: () => ( + + ), }; export const GroupedItems: Story = { - render: () => { - const GroupedItemsStory = () => { - const [value, setValue] = useState(''); - const [inputId, setInputId] = useState(''); - return ( - - - - ); - }; - - return ; - }, + render: () => ( + + ), }; export const Loading: Story = { - render: () => { - const LoadingStory = () => { - const [value, setValue] = useState(''); - const [inputId, setInputId] = useState(''); - return ( - - - - ); - }; - - return ; - }, + render: () => ( + + ), }; export const Empty: Story = { - render: () => { - const EmptyStory = () => { - const [value, setValue] = useState(''); - const [inputId, setInputId] = useState(''); - return ( - - - - ); - }; - - return ; - }, + render: () => ( + + ), }; export const CustomLabel: Story = { - render: () => { - const CustomLabelStory = () => { - const [value, setValue] = useState(''); - const [inputId, setInputId] = useState(''); - - const renderItemLabel = (option: AutocompleteItem) => { - return ( - - {option.label} - {option.value === 'other' && } - - ); - }; - - return ( - - - - ); - }; - - return ; - }, + render: () => ( + + ), }; export const CustomContent: Story = { - render: () => { - const CustomContentStory = () => { - const [value, setValue] = useState(''); - const [inputId, setInputId] = useState(''); - - const getIcon = (option: AutocompleteItem) => { - if (option.group === 'Program') { - return ; - } - if (option.group === 'Sysvar') { - return ; - } - if (option.value === 'other') { - return ; - } - return ; - }; - - const renderItemContent = (option: AutocompleteItem) => { - const isProgram = option.group === 'Program'; - const isSysvar = option.group === 'Sysvar'; - const isFeatured = option.value === 'other' || option.keywords?.includes('wallet'); - - return ( -
-
{getIcon(option)}
-
-
- {option.label} - {isFeatured && ( - - Featured - - )} -
-
- - {option.value.slice(0, 20)}... - - {isProgram && ( - - Program - - )} - {isSysvar && ( - - Sysvar - - )} -
-
-
- ); - }; - - return ( - - - - ); - }; - - return ; - }, + render: () => ( + + ), }; -function Layout({ - children, - value, +function AutocompleteStory({ label, description, - inputId, -}: { - children: React.ReactNode; - value: Value; - label: string; - description: string; - inputId: string; -}) { + ...props +}: { label: string; description: string } & Omit< + React.ComponentProps, + 'label' | 'onChange' | 'onInputIdReady' | 'value' +>) { + const [value, setValue] = useState(''); + const [inputId, setInputId] = useState(''); return (
@@ -279,7 +119,7 @@ function Layout({ - {children} +

{description}

@@ -288,6 +128,63 @@ function Layout({ ); } +function renderItemLabel(option: AutocompleteItem) { + return ( + + {option.label} + {option.value === 'other' && } + + ); +} + +function renderItemContent(option: AutocompleteItem) { + const isProgram = option.group === 'Program'; + const isSysvar = option.group === 'Sysvar'; + const isFeatured = option.value === 'other' || option.keywords?.includes('wallet'); + + return ( +
+
{getIcon(option)}
+
+
+ {option.label} + {isFeatured && ( + + Featured + + )} +
+
+ {option.value.slice(0, 20)}... + {isProgram && ( + + Program + + )} + {isSysvar && ( + + Sysvar + + )} +
+
+
+ ); +} + +function getIcon(option: AutocompleteItem) { + if (option.group === 'Program') { + return ; + } + if (option.group === 'Sysvar') { + return ; + } + if (option.value === 'other') { + return ; + } + return ; +} + function getSimpleItems() { return [ { keywords: ['wallet'], label: 'Your wallet', value: 'GoctE2EU5jZqbWg2Ffo5sjCqjrnzW1m76JmWwd84pwtV' }, diff --git a/app/components/shared/ui/badge.responsive.stories.tsx b/app/components/shared/ui/badge.responsive.stories.tsx index 39d7148351..739a406520 100644 --- a/app/components/shared/ui/badge.responsive.stories.tsx +++ b/app/components/shared/ui/badge.responsive.stories.tsx @@ -12,7 +12,6 @@ const meta = { decorators: [withViewportFromGlobal], parameters: { docs: { story: { height: INITIAL_VIEWPORTS.iphonex.styles.height } }, - viewport: { options: INITIAL_VIEWPORTS }, }, tags: ['autodocs', 'test'], title: 'Components/Shared/Badge@Media', diff --git a/app/components/shared/ui/button.responsive.stories.tsx b/app/components/shared/ui/button.responsive.stories.tsx index 46b305ed29..517c5a0c20 100644 --- a/app/components/shared/ui/button.responsive.stories.tsx +++ b/app/components/shared/ui/button.responsive.stories.tsx @@ -11,7 +11,6 @@ const meta = { decorators: [withViewportFromGlobal], parameters: { docs: { story: { height: INITIAL_VIEWPORTS.iphonex.styles.height } }, - viewport: { options: INITIAL_VIEWPORTS }, }, tags: ['autodocs', 'test'], title: 'Components/Shared/Button@Media', diff --git a/app/components/shared/ui/dropdown-menu.stories.tsx b/app/components/shared/ui/dropdown-menu.stories.tsx index 1cd042b365..647d7d1b16 100644 --- a/app/components/shared/ui/dropdown-menu.stories.tsx +++ b/app/components/shared/ui/dropdown-menu.stories.tsx @@ -36,32 +36,13 @@ export const Default: Story = { const trigger = canvas.getByRole('button', { hidden: true, name: /open menu/i }); expect(trigger).toBeInTheDocument(); }, - render: () => ( - - - - - - Option 1 - Option 2 - Option 3 - - - ), + render: () => , }; export const WithIcons: Story = { render: () => ( - - - + Actions @@ -88,12 +69,7 @@ export const WithIcons: Story = { export const WithShortcuts: Story = { render: () => ( - - - + Edit @@ -122,12 +98,7 @@ export const WithShortcuts: Story = { export const WithGroups: Story = { render: () => ( - - - + Account My Account @@ -158,12 +129,7 @@ export const WithCheckboxItems: Story = { return ( - - - + View Options Toggle columns @@ -187,12 +153,7 @@ export const WithRadioItems: Story = { return ( - - - + Encoding: {encoding} Select encoding @@ -210,12 +171,7 @@ export const WithRadioItems: Story = { export const WithSubmenu: Story = { render: () => ( - - - + More Action 1 Action 2 @@ -236,12 +192,7 @@ export const WithSubmenu: Story = { export const DisabledItems: Story = { render: () => ( - - - + Options Enabled action Disabled action @@ -277,21 +228,7 @@ export const OpenByDefault: Story = { const trigger = canvas.getByRole('button', { hidden: true, name: /open menu/i }); expect(trigger).toHaveAttribute('data-state', 'open'); }, - render: () => ( - - - - - - Option 1 - Option 2 - Option 3 - - - ), + render: () => , }; // inset (pl-8) on items/labels and disabled checkbox/radio items — no other story renders these @@ -303,12 +240,7 @@ export const InsetAndDisabledSelectionItems: Story = { }, render: () => ( - - - + Open Menu Inset label Inset item @@ -338,19 +270,29 @@ export const Interactive: Story = { await userEvent.click(trigger); expect(trigger).toHaveAttribute('data-state', 'open'); }, - render: () => ( - - - - + render: () => , +}; + +function OptionsMenu({ trigger, ...props }: React.ComponentProps & { trigger: string }) { + return ( + + {trigger} Option 1 Option 2 Option 3 - ), -}; + ); +} + +function MenuTrigger({ children }: { children: React.ReactNode }) { + return ( + + + + ); +} diff --git a/app/components/shared/ui/sonner/custom.stories.tsx b/app/components/shared/ui/sonner/custom.stories.tsx index 0223e8b505..d5ea187553 100644 --- a/app/components/shared/ui/sonner/custom.stories.tsx +++ b/app/components/shared/ui/sonner/custom.stories.tsx @@ -4,7 +4,7 @@ import { toast as sonnerToast } from 'sonner'; import { expect, fn, within } from 'storybook/test'; import { Button } from '../button'; -import { CustomToast } from './custom'; +import { CustomToast, type CustomToastProps } from './custom'; import { Toaster } from './toaster'; const meta = { @@ -35,32 +35,8 @@ export const Success: Story = { title: 'Wallet Connected', type: 'success', }, - async play({ canvasElement }) { - const canvas = within(canvasElement); - - const title = await canvas.findByText('Wallet Connected'); - expect(title).toBeInTheDocument(); - - const description = await canvas.findByText('Connected to wallet X5s...GnDZ'); - expect(description).toBeInTheDocument(); - - const closeButton = canvas.getAllByRole('button'); - expect(closeButton.length).toBeGreaterThan(0); - }, - render: args => ( -
- - -
- ), + play: ({ canvasElement }) => expectToast(canvasElement, 'Wallet Connected', 'Connected to wallet X5s...GnDZ'), + render: args => , }; export const Error: Story = { @@ -70,32 +46,9 @@ export const Error: Story = { title: 'Transaction Failed', type: 'error', }, - async play({ canvasElement }) { - const canvas = within(canvasElement); - - const title = await canvas.findByText('Transaction Failed'); - expect(title).toBeInTheDocument(); - - const description = await canvas.findByText('Unable to process transaction. Please try again.'); - expect(description).toBeInTheDocument(); - - const closeButton = canvas.getAllByRole('button'); - expect(closeButton.length).toBeGreaterThan(0); - }, - render: args => ( -
- - -
- ), + play: ({ canvasElement }) => + expectToast(canvasElement, 'Transaction Failed', 'Unable to process transaction. Please try again.'), + render: args => , }; export const Info: Story = { @@ -105,32 +58,9 @@ export const Info: Story = { title: 'Processing Transaction', type: 'info', }, - async play({ canvasElement }) { - const canvas = within(canvasElement); - - const title = await canvas.findByText('Processing Transaction'); - expect(title).toBeInTheDocument(); - - const description = await canvas.findByText('Your transaction is being confirmed on the blockchain.'); - expect(description).toBeInTheDocument(); - - const closeButton = canvas.getAllByRole('button'); - expect(closeButton.length).toBeGreaterThan(0); - }, - render: args => ( -
- - -
- ), + play: ({ canvasElement }) => + expectToast(canvasElement, 'Processing Transaction', 'Your transaction is being confirmed on the blockchain.'), + render: args => , }; export const WithLongTitle: Story = { @@ -141,32 +71,8 @@ export const WithLongTitle: Story = { title: 'This is a very long title that demonstrates how the toast component handles text wrapping when the title exceeds the available width', type: 'info', }, - async play({ canvasElement }) { - const canvas = within(canvasElement); - - const title = await canvas.findByText(/This is a very long title/); - expect(title).toBeInTheDocument(); - - const description = await canvas.findByText(/This toast demonstrates/); - expect(description).toBeInTheDocument(); - - const closeButton = canvas.getAllByRole('button'); - expect(closeButton.length).toBeGreaterThan(0); - }, - render: args => ( -
- - -
- ), + play: ({ canvasElement }) => expectToast(canvasElement, /This is a very long title/, /This toast demonstrates/), + render: args => , }; export const WithoutDescription: Story = { @@ -175,29 +81,8 @@ export const WithoutDescription: Story = { title: 'Action Completed', type: 'success', }, - async play({ canvasElement }) { - const canvas = within(canvasElement); - - const title = await canvas.findByText('Action Completed'); - expect(title).toBeInTheDocument(); - - const closeButton = canvas.getAllByRole('button'); - expect(closeButton.length).toBeGreaterThan(0); - }, - render: args => ( -
- - -
- ), + play: ({ canvasElement }) => expectToast(canvasElement, 'Action Completed'), + render: args => , }; export const WithCustomDescription: Story = { @@ -207,21 +92,8 @@ export const WithCustomDescription: Story = { title: 'Transaction Complete', type: 'success', }, - async play({ canvasElement }) { - const canvas = within(canvasElement); - - const title = await canvas.findByText('Transaction Complete'); - expect(title).toBeInTheDocument(); - - const signature = await canvas.findByText(/Transaction signature:/); - expect(signature).toBeInTheDocument(); - - const link = await canvas.findByText('View on Explorer'); - expect(link).toBeInTheDocument(); - - const closeButton = canvas.getAllByRole('button'); - expect(closeButton.length).toBeGreaterThan(0); - }, + play: ({ canvasElement }) => + expectToast(canvasElement, 'Transaction Complete', /Transaction signature:/, 'View on Explorer'), render: args => { const onViewTransaction = fn(); const description = ( @@ -240,19 +112,31 @@ export const WithCustomDescription: Story = {
); - return ( -
- - -
- ); + return ; }, }; + +function ToastWithTrigger({ trigger, ...props }: CustomToastProps & { trigger: string }) { + return ( +
+ + +
+ ); +} + +async function expectToast(canvasElement: HTMLElement, ...texts: (string | RegExp)[]) { + const canvas = within(canvasElement); + for (const text of texts) { + expect(await canvas.findByText(text)).toBeInTheDocument(); + } + expect(canvas.getAllByRole('button').length).toBeGreaterThan(0); +} diff --git a/app/entities/account/__fixtures__/account.ts b/app/entities/account/__fixtures__/account.ts new file mode 100644 index 0000000000..19541a5788 --- /dev/null +++ b/app/entities/account/__fixtures__/account.ts @@ -0,0 +1,26 @@ +import type { Account, UpgradeableLoaderAccountData } from '@providers/accounts'; +import { PublicKey } from '@solana/web3.js'; +import type { ProgramDataAccountInfo } from '@validators/accounts/upgradeable-program'; + +export function makeAccount(overrides: Partial = {}): Account { + return { + data: {}, + executable: false, + lamports: 1_000_000_000, + owner: PublicKey.default, + pubkey: PublicKey.default, + ...overrides, + }; +} + +export function makeProgramAccountData(programData?: ProgramDataAccountInfo): UpgradeableLoaderAccountData { + return { + parsed: { info: { programData: PublicKey.default }, type: 'program' }, + program: 'bpf-upgradeable-loader', + programData, + }; +} + +export function makeProgramDataInfo(): ProgramDataAccountInfo { + return { authority: PublicKey.default, data: ['deadbeef', 'base64'], slot: 123 }; +} diff --git a/app/entities/account/api/__tests__/fetch-account-sizes.test.ts b/app/entities/account/api/__tests__/fetch-account-sizes.test.ts index d43c0f25bd..044b714f00 100644 --- a/app/entities/account/api/__tests__/fetch-account-sizes.test.ts +++ b/app/entities/account/api/__tests__/fetch-account-sizes.test.ts @@ -1,6 +1,8 @@ import { DEFAULT_RPC_URL, gen } from '@__fixtures__/gen'; import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { rpcValueStub } from '@/app/__tests__/mock-rpc'; + import { fetchAccountSizes } from '../fetch-account-sizes'; const ADDRESS_1 = gen.address(1); @@ -8,17 +10,9 @@ const ADDRESS_2 = gen.address(2); const mockGetMultipleAccounts = vi.fn(); -vi.mock('@entities/cluster/@x/account', async () => { - const actual = await vi.importActual('@entities/cluster/@x/account'); - return { - ...actual, - getRpc: vi.fn(() => ({ - getMultipleAccounts: (...args: unknown[]) => ({ - send: async () => ({ value: await mockGetMultipleAccounts(...args) }), - }), - })), - }; -}); +vi.mock('@/app/entities/cluster/api/get-rpc', () => ({ + getRpc: () => rpcValueStub({ getMultipleAccounts: mockGetMultipleAccounts }), +})); describe('fetchAccountSizes', () => { beforeEach(() => { diff --git a/app/entities/account/model/__tests__/selectors.spec.ts b/app/entities/account/model/__tests__/selectors.spec.ts index 9e936db0be..0eb2d72286 100644 --- a/app/entities/account/model/__tests__/selectors.spec.ts +++ b/app/entities/account/model/__tests__/selectors.spec.ts @@ -1,25 +1,14 @@ import { gen } from '@__fixtures__/gen'; +import { makeAccount } from '@entities/account/__fixtures__/account'; import type { Account } from '@providers/accounts'; -import { SystemProgram } from '@solana/web3.js'; import { describe, expect, it } from 'vitest'; import { selectMintDecimals, selectTokenAccountMint } from '../selectors'; const MINT_PUBKEY = gen.publicKey(1); -function makeBaseAccount(): Account { - return { - data: {}, - executable: false, - lamports: 0, - owner: SystemProgram.programId, - pubkey: gen.publicKey(2), - }; -} - function makeMintAccount(decimals: number): Account { - return { - ...makeBaseAccount(), + return makeAccount({ data: { parsed: { parsed: { @@ -35,12 +24,11 @@ function makeMintAccount(decimals: number): Account { program: 'spl-token' as const, }, }, - }; + }); } function makeTokenAccount(mint: string): Account { - return { - ...makeBaseAccount(), + return makeAccount({ data: { parsed: { parsed: { @@ -56,7 +44,7 @@ function makeTokenAccount(mint: string): Account { program: 'spl-token' as const, }, }, - }; + }); } const MINT_ADDRESS = MINT_PUBKEY.toBase58(); @@ -66,7 +54,7 @@ describe('selectMintDecimals', () => { { account: makeMintAccount(9), expected: 9, label: 'mint with 9 decimals' }, { account: makeMintAccount(0), expected: 0, label: 'mint with 0 decimals' }, { account: makeTokenAccount(MINT_ADDRESS), expected: undefined, label: 'token account' }, - { account: makeBaseAccount(), expected: undefined, label: 'unparsed account' }, + { account: makeAccount(), expected: undefined, label: 'unparsed account' }, ])('should return $expected for $label', ({ account, expected }) => { expect(selectMintDecimals(account)).toBe(expected); }); @@ -76,7 +64,7 @@ describe('selectTokenAccountMint', () => { it.each([ { account: makeTokenAccount(MINT_ADDRESS), expected: MINT_ADDRESS, label: 'valid token account' }, { account: makeMintAccount(6), expected: undefined, label: 'mint account' }, - { account: makeBaseAccount(), expected: undefined, label: 'unparsed account' }, + { account: makeAccount(), expected: undefined, label: 'unparsed account' }, ])('should return $expected for $label', ({ account, expected }) => { expect(selectTokenAccountMint(account)).toBe(expected); }); diff --git a/app/entities/account/model/__tests__/use-account-query.spec.ts b/app/entities/account/model/__tests__/use-account-query.spec.ts index cfebd9d01f..2d511c541e 100644 --- a/app/entities/account/model/__tests__/use-account-query.spec.ts +++ b/app/entities/account/model/__tests__/use-account-query.spec.ts @@ -1,8 +1,8 @@ // @vitest-environment jsdom +import { makeAccount } from '@entities/account/__fixtures__/account'; import { Account, FetchersContext, StateContext } from '@providers/accounts'; import { FetchStatus } from '@providers/cache'; -import { PublicKey, SystemProgram } from '@solana/web3.js'; import { renderHook } from '@testing-library/react'; import React from 'react'; import { describe, expect, it, vi } from 'vitest'; @@ -15,16 +15,6 @@ import { useAccountQuery } from '../use-account-query'; const TEST_ADDRESS = NATIVE_MINT_ADDRESS; -function makeAccount(pubkey: string): Account { - return { - data: {}, - executable: false, - lamports: 0, - owner: SystemProgram.programId, - pubkey: new PublicKey(pubkey), - }; -} - function createWrapper(entries: Record = {}, fetchSpy = vi.fn()) { const state = { entries, url: MAINNET_BETA_URL }; const fetchers = { @@ -65,7 +55,7 @@ describe('useAccountQuery', () => { it('should not trigger fetch when cache entry exists', () => { const { wrapper, fetchSpy } = createWrapper({ - [TEST_ADDRESS]: { data: makeAccount(TEST_ADDRESS), status: FetchStatus.Fetched }, + [TEST_ADDRESS]: { data: makeAccount(), status: FetchStatus.Fetched }, }); renderHook(() => useAccountQuery([TEST_ADDRESS], { select: selectLamports }), { wrapper }); @@ -73,8 +63,7 @@ describe('useAccountQuery', () => { }); it('should return selected data when cache entry is fetched', () => { - const account = makeAccount(TEST_ADDRESS); - account.lamports = 42; + const account = makeAccount({ lamports: 42 }); const { wrapper } = createWrapper({ [TEST_ADDRESS]: { data: account, status: FetchStatus.Fetched }, }); @@ -113,7 +102,7 @@ describe('useAccountQuery', () => { }); it('should return undefined from select when data does not match', () => { - const account = makeAccount(TEST_ADDRESS); + const account = makeAccount(); const { wrapper } = createWrapper({ [TEST_ADDRESS]: { data: account, status: FetchStatus.Fetched }, }); @@ -144,7 +133,7 @@ describe('useAccountExpandedInfo', () => { }); it('should return the cached account itself', () => { - const account = makeAccount(TEST_ADDRESS); + const account = makeAccount(); const { wrapper } = createWrapper({ [TEST_ADDRESS]: { data: account, status: FetchStatus.Fetched } }); const { result } = renderHook(() => useAccountExpandedInfo(TEST_ADDRESS, true), { wrapper }); diff --git a/app/entities/account/model/__tests__/use-account-sizes.test.tsx b/app/entities/account/model/__tests__/use-account-sizes.test.tsx index 726d06bfda..0e599261ea 100644 --- a/app/entities/account/model/__tests__/use-account-sizes.test.tsx +++ b/app/entities/account/model/__tests__/use-account-sizes.test.tsx @@ -1,10 +1,10 @@ import { DEFAULT_RPC_URL, gen } from '@__fixtures__/gen'; import { renderHook, waitFor } from '@testing-library/react'; import { Cluster } from '@utils/cluster'; -import React from 'react'; -import { SWRConfig } from 'swr'; import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { rpcValueStub } from '@/app/__tests__/mock-rpc'; +import { FAST_RETRY, settleRetries, swrWrapper } from '@/app/__tests__/swr-hook'; import { Logger } from '@/app/shared/lib/logger'; import { ERROR_RETRY_COUNT, useAccountSizes } from '../use-account-sizes'; @@ -19,17 +19,11 @@ const mockCluster = vi.hoisted(() => ({ current: {} as { cluster: Cluster; url: vi.mock('@providers/cluster', () => ({ useCluster: () => mockCluster.current })); -vi.mock('@entities/cluster/@x/account', async () => { - const actual = await vi.importActual('@entities/cluster/@x/account'); - return { - ...actual, - getRpc: vi.fn(() => ({ - getMultipleAccounts: (...args: unknown[]) => ({ - send: async () => ({ value: await mockGetMultipleAccounts(...args) }), - }), - })), - }; -}); +vi.mock('@/app/entities/cluster/api/get-rpc', () => ({ + getRpc: () => rpcValueStub({ getMultipleAccounts: mockGetMultipleAccounts }), +})); + +const wrapper = swrWrapper(FAST_RETRY); describe('useAccountSizes', () => { beforeEach(() => { @@ -120,11 +114,3 @@ describe('useAccountSizes', () => { function sizedAccounts(addresses: readonly string[]) { return addresses.map((_, index) => ({ data: ['', 'base64'], space: BigInt(100 + index) })); } - -function wrapper({ children }: { children: React.ReactNode }) { - return new Map() }}>{children}; -} - -function settleRetries() { - return new Promise(resolve => setTimeout(resolve, 100)); -} diff --git a/app/entities/account/model/__tests__/use-raw-account-data.test.tsx b/app/entities/account/model/__tests__/use-raw-account-data.test.tsx index 44bd38ecab..071d7fa627 100644 --- a/app/entities/account/model/__tests__/use-raw-account-data.test.tsx +++ b/app/entities/account/model/__tests__/use-raw-account-data.test.tsx @@ -3,6 +3,7 @@ import { renderHook } from '@testing-library/react'; import { act } from 'react'; import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { rpcValueStub } from '@/app/__tests__/mock-rpc'; import { FAST_RETRY, settleRetries, swrWrapper, waitForHook } from '@/app/__tests__/swr-hook'; import { toBase64 } from '@/app/shared/lib/bytes'; @@ -17,17 +18,9 @@ vi.mock('@providers/cluster', () => ({ useCluster: () => ({ url: MOCK_URL }), })); -vi.mock('@entities/cluster/@x/account', async () => { - const actual = await vi.importActual('@entities/cluster/@x/account'); - return { - ...actual, - getRpc: vi.fn(() => ({ - getAccountInfo: (...args: unknown[]) => ({ - send: async () => ({ value: await mockGetAccountInfo(...args) }), - }), - })), - }; -}); +vi.mock('@/app/entities/cluster/api/get-rpc', () => ({ + getRpc: () => rpcValueStub({ getAccountInfo: mockGetAccountInfo }), +})); function accountInfoValue(data: Uint8Array) { return { data: [toBase64(data), 'base64'] }; diff --git a/app/entities/account/model/__tests__/use-refresh-account.spec.tsx b/app/entities/account/model/__tests__/use-refresh-account.spec.tsx index a126db0ae4..51daecfc92 100644 --- a/app/entities/account/model/__tests__/use-refresh-account.spec.tsx +++ b/app/entities/account/model/__tests__/use-refresh-account.spec.tsx @@ -2,10 +2,10 @@ import { PublicKey } from '@solana/web3.js'; import { act, renderHook, waitFor } from '@testing-library/react'; import { Cluster } from '@utils/cluster'; import { getFullTokenInfoSwrKey } from '@utils/token-info'; -import { SWRConfig } from 'swr'; import useSWRImmutable from 'swr/immutable'; import { describe, expect, it, vi } from 'vitest'; +import { settleRetries, swrWrapper } from '@/app/__tests__/swr-hook'; import { accountRefreshKey } from '@/app/shared/lib/account-refresh-key'; import { rawAccountDataKey } from '../use-raw-account-data'; @@ -38,7 +38,7 @@ describe('useRefreshAccount', () => { ], ])('should not refetch %s', async (_, key) => { const fetcher = await refreshWith(key); - await act(() => new Promise(resolve => setTimeout(resolve, 50))); + await act(() => settleRetries()); expect(fetcher).toHaveBeenCalledTimes(1); }); @@ -51,7 +51,7 @@ async function refreshWith(key: readonly unknown[]) { useSWRImmutable(key, fetcher); return useRefreshAccount(); }, - { wrapper }, + { wrapper: swrWrapper() }, ); await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1)); @@ -61,7 +61,3 @@ async function refreshWith(key: readonly unknown[]) { const MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const OTHER = new PublicKey('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB'); - -function wrapper({ children }: { children: React.ReactNode }) { - return new Map() }}>{children}; -} diff --git a/app/entities/block-data/api/__tests__/fetch-block.spec.ts b/app/entities/block-data/api/__tests__/fetch-block.spec.ts index db44800b9e..c4e7597d95 100644 --- a/app/entities/block-data/api/__tests__/fetch-block.spec.ts +++ b/app/entities/block-data/api/__tests__/fetch-block.spec.ts @@ -12,7 +12,7 @@ import { stubRpcFetch } from '@/app/__tests__/rpc-fetch'; import { LEGACY_BLOCK_RESPONSE, V1_BLOCK_RESPONSE } from '../../__fixtures__/block-responses'; import { fetchBlock } from '../fetch-block'; -vi.mock('@solana/kit', async importOriginal => await importOriginal()); +vi.unmock('@solana/kit'); const URL = 'https://mock.rpc'; const SLOT = 440_572_822; diff --git a/app/entities/cluster/api/__tests__/fetch-genesis-hash.spec.ts b/app/entities/cluster/api/__tests__/fetch-genesis-hash.spec.ts index 63b7d5a28e..a3e9bec5a2 100644 --- a/app/entities/cluster/api/__tests__/fetch-genesis-hash.spec.ts +++ b/app/entities/cluster/api/__tests__/fetch-genesis-hash.spec.ts @@ -1,8 +1,6 @@ import { createSolanaRpc } from '@solana/kit'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -vi.mock('@solana/kit', () => ({ createSolanaRpc: vi.fn() })); - import { UPSTREAM_TIMEOUT_MS } from '@/app/shared/lib/timeouts'; import { fetchGenesisHash } from '../fetch-genesis-hash'; diff --git a/app/entities/cluster/api/__tests__/rpc-bigint-params.spec.ts b/app/entities/cluster/api/__tests__/rpc-bigint-params.spec.ts index ebd0ba76db..1f6a6fe1df 100644 --- a/app/entities/cluster/api/__tests__/rpc-bigint-params.spec.ts +++ b/app/entities/cluster/api/__tests__/rpc-bigint-params.spec.ts @@ -7,7 +7,7 @@ import { getRpc } from '../get-rpc'; // The wire format under test is produced by kit's real request serializer, so undo the global // createSolanaRpc mock from test-setup.specs.ts; the fetch stub keeps the request off the network. -vi.mock('@solana/kit', () => vi.importActual('@solana/kit')); +vi.unmock('@solana/kit'); // A global `BigInt.prototype.toJSON` patch runs before kit's replacer inside JSON.stringify, // turning every bigint RPC param into a JSON string that the RPC rejects with -32602 diff --git a/app/entities/cluster/model/__tests__/cluster-provider.spec.tsx b/app/entities/cluster/model/__tests__/cluster-provider.spec.tsx index ac4e247b9d..74f1d7600c 100644 --- a/app/entities/cluster/model/__tests__/cluster-provider.spec.tsx +++ b/app/entities/cluster/model/__tests__/cluster-provider.spec.tsx @@ -1,12 +1,9 @@ +import { createSolanaRpc } from '@solana/kit'; import { render, screen, waitFor } from '@testing-library/react'; import { createStore, Provider } from 'jotai'; import { SWRConfig } from 'swr'; import { beforeEach, describe, expect, it, vi } from 'vitest'; -vi.mock('@solana/kit', () => ({ createSolanaRpc: vi.fn() })); - -import { createSolanaRpc } from '@solana/kit'; - import { ClusterStatus } from '../../lib/cluster'; import { ClusterProvider } from '../cluster-provider'; import { useCluster } from '../use-cluster'; diff --git a/app/entities/cluster/model/__tests__/use-cluster-resource-search.spec.ts b/app/entities/cluster/model/__tests__/use-cluster-resource-search.spec.ts index 4a82000c80..ae252e913f 100644 --- a/app/entities/cluster/model/__tests__/use-cluster-resource-search.spec.ts +++ b/app/entities/cluster/model/__tests__/use-cluster-resource-search.spec.ts @@ -11,9 +11,7 @@ import { useClusterResourceSearch } from '../use-cluster-resource-search'; const RESOURCE_ID = 'test-resource-id'; -vi.mock('next/navigation', () => ({ - useSearchParams: vi.fn(() => new URLSearchParams()), -})); +vi.mock('next/navigation', () => import('@/app/__tests__/next-navigation')); describe('useClusterResourceSearch', () => { beforeEach(() => { diff --git a/app/entities/compute-unit/lib/__tests__/compute-units-schedule.spec.ts b/app/entities/compute-unit/lib/__tests__/compute-units-schedule.spec.ts index e6c9890fe6..781fb43924 100644 --- a/app/entities/compute-unit/lib/__tests__/compute-units-schedule.spec.ts +++ b/app/entities/compute-unit/lib/__tests__/compute-units-schedule.spec.ts @@ -1,6 +1,7 @@ import { makeBlockTransaction } from '@entities/block-data/__fixtures__/block-builders'; -import { address } from '@solana/kit'; +import { address, type ReadonlyUint8Array } from '@solana/kit'; import { ComputeBudgetProgram } from '@solana/web3.js'; +import { getSetComputeUnitLimitInstructionDataEncoder } from '@solana-program/compute-budget'; import { Cluster } from '@utils/cluster'; import { alloc, writeUint32LE } from '@/app/shared/lib/bytes'; @@ -185,7 +186,7 @@ describe('estimateRequestedComputeUnits', () => { const createMockTransaction = ( instructions: Array<{ programId: string; - data: Uint8Array; + data: ReadonlyUint8Array; }>, ): Parameters[0] => { const staticAccounts = [...new Set(instructions.map(ix => ix.programId))].map(address); @@ -206,9 +207,7 @@ describe('estimateRequestedComputeUnits', () => { describe('with explicit compute budget', () => { it('should return compute units from SetComputeUnitLimit instruction', () => { const computeUnits = 300_000; - const data = alloc(5); - data[0] = 2; // SetComputeUnitLimit instruction type - writeUint32LE(data, computeUnits, 1); + const data = getSetComputeUnitLimitInstructionDataEncoder().encode({ units: computeUnits }); const tx = createMockTransaction([ { @@ -238,13 +237,8 @@ describe('estimateRequestedComputeUnits', () => { }); it('should prioritize first compute budget instruction found', () => { - const data1 = alloc(5); - data1[0] = 2; - writeUint32LE(data1, 100_000, 1); - - const data2 = alloc(5); - data2[0] = 2; - writeUint32LE(data2, 200_000, 1); + const data1 = getSetComputeUnitLimitInstructionDataEncoder().encode({ units: 100_000 }); + const data2 = getSetComputeUnitLimitInstructionDataEncoder().encode({ units: 200_000 }); const tx = createMockTransaction([ { @@ -366,9 +360,7 @@ describe('estimateRequestedComputeUnits', () => { }); it('should handle compute budget with other instructions', () => { - const data = alloc(5); - data[0] = 2; // SetComputeUnitLimit - writeUint32LE(data, 500_000, 1); + const data = getSetComputeUnitLimitInstructionDataEncoder().encode({ units: 500_000 }); const tx = createMockTransaction([ { @@ -391,9 +383,7 @@ describe('estimateRequestedComputeUnits', () => { const createV1Transaction = (transactionConfig?: { computeUnitLimit?: number; }): Parameters[0] => { - const data = alloc(5); - data[0] = 2; // SetComputeUnitLimit - writeUint32LE(data, 999_999, 1); + const data = getSetComputeUnitLimitInstructionDataEncoder().encode({ units: 999_999 }); const programAddress = address(ComputeBudgetProgram.programId.toBase58()); const configValues = diff --git a/app/entities/compute-unit/ui/__stories__/BaseCUProfilingCard.stories.tsx b/app/entities/compute-unit/ui/__stories__/BaseCUProfilingCard.stories.tsx index 8ad1ede8dc..94155d7309 100644 --- a/app/entities/compute-unit/ui/__stories__/BaseCUProfilingCard.stories.tsx +++ b/app/entities/compute-unit/ui/__stories__/BaseCUProfilingCard.stories.tsx @@ -1,5 +1,6 @@ import type { Meta, StoryObj } from '@storybook-config/types'; +import { cuData } from '../../__fixtures__/cu-data'; import { BaseCUProfilingCard } from '../BaseCUProfilingCard'; const meta: Meta = { @@ -16,18 +17,8 @@ type Story = StoryObj; export const TwoInstructions: Story = { args: { instructions: [ - { - computeUnits: 45000, - defaultUnits: 150, - programId: '11111111111111111111111111111111', - scheduledUnits: 200000, - }, - { - computeUnits: 45000, - defaultUnits: 0, - programId: '22222222222222222222222222222222', - scheduledUnits: 200000, - }, + cuData({ computeUnits: 45000, defaultUnits: 150, programId: '11111111111111111111111111111111' }), + cuData({ computeUnits: 45000, programId: '22222222222222222222222222222222' }), ], }, }; @@ -37,30 +28,24 @@ export const TwoInstructions: Story = { export const WithInstructionNames: Story = { args: { instructions: [ - { + cuData({ computeUnits: 105, - defaultUnits: 0, name: 'Transfer Checked', programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', programName: 'Token Program', - scheduledUnits: 200000, - }, - { + }), + cuData({ computeUnits: 150, - defaultUnits: 0, name: 'Set Compute Unit Price', programId: 'ComputeBudget111111111111111111111111111111', programName: 'Compute Budget Program', - scheduledUnits: 200000, - }, - { + }), + cuData({ computeUnits: 150, - defaultUnits: 0, name: 'Set Compute Unit Limit', programId: 'ComputeBudget111111111111111111111111111111', programName: 'Compute Budget Program', - scheduledUnits: 200000, - }, + }), ], unitsConsumed: 405, }, @@ -70,22 +55,18 @@ export const WithInstructionNames: Story = { export const WithLongInstructionNames: Story = { args: { instructions: [ - { + cuData({ computeUnits: 120000, - defaultUnits: 0, name: 'Shared Accounts Route With Token Ledger', programId: 'JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4', programName: 'Jupiter Aggregator V6', - scheduledUnits: 200000, - }, - { + }), + cuData({ computeUnits: 40000, - defaultUnits: 0, name: 'Create Idempotent', programId: 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL', programName: 'Associated Token Account Program', - scheduledUnits: 200000, - }, + }), ], unitsConsumed: 160000, }, @@ -95,66 +76,16 @@ export const WithLongInstructionNames: Story = { export const TenInstructions: Story = { args: { instructions: [ - { - computeUnits: 100000, - defaultUnits: 0, - programId: 'Program1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', - scheduledUnits: 200000, - }, - { - computeUnits: 85000, - defaultUnits: 0, - programId: 'Program2xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', - scheduledUnits: 200000, - }, - { - computeUnits: 70000, - defaultUnits: 0, - programId: 'Program3xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', - scheduledUnits: 200000, - }, - { - computeUnits: 55000, - defaultUnits: 0, - programId: 'Program4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', - scheduledUnits: 200000, - }, - { - computeUnits: 40000, - defaultUnits: 0, - programId: 'Program5xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', - scheduledUnits: 200000, - }, - { - computeUnits: 30000, - defaultUnits: 0, - programId: 'Program6xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', - scheduledUnits: 200000, - }, - { - computeUnits: 20000, - defaultUnits: 0, - programId: 'Program7xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', - scheduledUnits: 200000, - }, - { - computeUnits: 15000, - defaultUnits: 0, - programId: 'Program8xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', - scheduledUnits: 200000, - }, - { - computeUnits: 10000, - defaultUnits: 0, - programId: 'Program9xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', - scheduledUnits: 200000, - }, - { - computeUnits: 5000, - defaultUnits: 0, - programId: 'Program10xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', - scheduledUnits: 200000, - }, + cuData({ computeUnits: 100000, programId: 'Program1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }), + cuData({ computeUnits: 85000, programId: 'Program2xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }), + cuData({ computeUnits: 70000, programId: 'Program3xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }), + cuData({ computeUnits: 55000, programId: 'Program4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }), + cuData({ computeUnits: 40000, programId: 'Program5xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }), + cuData({ computeUnits: 30000, programId: 'Program6xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }), + cuData({ computeUnits: 20000, programId: 'Program7xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }), + cuData({ computeUnits: 15000, programId: 'Program8xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }), + cuData({ computeUnits: 10000, programId: 'Program9xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }), + cuData({ computeUnits: 5000, programId: 'Program10xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }), ], }, }; @@ -162,24 +93,14 @@ export const TenInstructions: Story = { export const WithZeroComputeUnits: Story = { args: { instructions: [ - { - computeUnits: 50000, - defaultUnits: 150, - programId: '11111111111111111111111111111111', - scheduledUnits: 200000, - }, - { + cuData({ computeUnits: 50000, defaultUnits: 150, programId: '11111111111111111111111111111111' }), + cuData({ computeUnits: 0, defaultUnits: 1200, programId: 'AddressLookupTab1e1111111111111111111111111', scheduledUnits: 1200, - }, - { - computeUnits: 30000, - defaultUnits: 0, - programId: '33333333333333333333333333333333', - scheduledUnits: 200000, - }, + }), + cuData({ computeUnits: 30000, programId: '33333333333333333333333333333333' }), ], unitsConsumed: 51200, }, diff --git a/app/entities/domain/api/__tests__/fetch-ans-domains.test.ts b/app/entities/domain/api/__tests__/fetch-ans-domains.test.ts index 0c04287506..e96a5c0edf 100644 --- a/app/entities/domain/api/__tests__/fetch-ans-domains.test.ts +++ b/app/entities/domain/api/__tests__/fetch-ans-domains.test.ts @@ -1,4 +1,4 @@ -import { type Address, address } from '@solana/kit'; +import { type Address, address, createSolanaRpc } from '@solana/kit'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { makeAnsNameRecordData, makeTldHouseData } from '../../__tests__/fixtures'; @@ -23,16 +23,9 @@ vi.mock('@utils/cluster', () => ({ serverClusterUrl: () => 'https://unused.test', })); -vi.mock('@solana/kit', async importOriginal => { - const actual = await importOriginal(); - return { - ...actual, - createSolanaRpc: () => ({ - getMultipleAccounts: mockGetMultipleAccounts, - getProgramAccounts: mockGetProgramAccounts, - }), - }; -}); +vi.mocked(createSolanaRpc).mockImplementation( + () => ({ getMultipleAccounts: mockGetMultipleAccounts, getProgramAccounts: mockGetProgramAccounts }) as never, +); const { fetchAnsDomains } = await import('../fetch-ans-domains'); diff --git a/app/entities/domain/ui/__stories__/BaseDomainsCard.responsive.stories.tsx b/app/entities/domain/ui/__stories__/BaseDomainsCard.responsive.stories.tsx index 02d1e2dbe3..1cdd0aaf41 100644 --- a/app/entities/domain/ui/__stories__/BaseDomainsCard.responsive.stories.tsx +++ b/app/entities/domain/ui/__stories__/BaseDomainsCard.responsive.stories.tsx @@ -1,16 +1,12 @@ -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BaseDomainsCard } from '../BaseDomainsCard'; +import * as Base from './BaseDomainsCard.stories'; const meta: Meta = { component: BaseDomainsCard, - decorators: [withClusterAndAccounts, withTokenInfoBatch, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [...Base.default.decorators, withViewportFromGlobal], tags: ['autodocs', 'test'], title: 'Entities/Domain/BaseDomainsCard@Media', }; @@ -18,12 +14,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - domains: [ - { address: '5ASxtmcPKDeD8NoE5QpskizPokqDdX1qHFiqZb1spLdo', name: 'example.sns' }, - { address: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', name: 'bob.sns' }, - ], -}; +const args = Base.MultipleDomains.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/entities/domain/ui/__stories__/BaseDomainsCard.stories.tsx b/app/entities/domain/ui/__stories__/BaseDomainsCard.stories.tsx index 43b3306ddb..3f2b476314 100644 --- a/app/entities/domain/ui/__stories__/BaseDomainsCard.stories.tsx +++ b/app/entities/domain/ui/__stories__/BaseDomainsCard.stories.tsx @@ -1,4 +1,4 @@ -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; @@ -8,7 +8,6 @@ const meta = { component: BaseDomainsCard, decorators: [withClusterAndAccounts, withTokenInfoBatch], parameters: { - ...nextjsParameters, docs: { description: { component: [ diff --git a/app/entities/idl/model/__tests__/use-program-idl-names.spec.tsx b/app/entities/idl/model/__tests__/use-program-idl-names.spec.tsx index 2ccbd585e4..aa708511ac 100644 --- a/app/entities/idl/model/__tests__/use-program-idl-names.spec.tsx +++ b/app/entities/idl/model/__tests__/use-program-idl-names.spec.tsx @@ -1,6 +1,7 @@ import { renderHook } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { reported } from '@/app/__tests__/rpc-errors'; import { swrWrapper, waitForHook } from '@/app/__tests__/swr-hook'; import { Logger } from '@/app/shared/lib/logger'; import { Cluster } from '@/app/utils/cluster'; @@ -107,10 +108,7 @@ describe('useProgramIdlNames', () => { await waitForHook(() => expect(result.current.size).toBe(1)); expect(Logger.warn).toHaveBeenCalledWith( expect.stringContaining('IDL fetch failed'), - expect.objectContaining({ - sentry: true, - sentryExtras: expect.objectContaining({ programId: SECOND }), - }), + reported({ programId: SECOND }), ); }); diff --git a/app/entities/instruction-card/__tests__/DecodedInstructionCard.spec.tsx b/app/entities/instruction-card/__tests__/DecodedInstructionCard.spec.tsx index f4a5e6222d..df8e1e0910 100644 --- a/app/entities/instruction-card/__tests__/DecodedInstructionCard.spec.tsx +++ b/app/entities/instruction-card/__tests__/DecodedInstructionCard.spec.tsx @@ -1,5 +1,5 @@ import { gen } from '@__fixtures__/gen'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; +import { TransactionInstruction } from '@solana/web3.js'; import { fireEvent, render, screen, within } from '@testing-library/react'; import React from 'react'; import { describe, expect, it, vi } from 'vitest'; @@ -11,11 +11,7 @@ import { toRawInstructionNode } from '../model/node'; import { type InstructionSurface, InstructionSurfaceProvider } from '../model/surface'; import { DECODED_TABLE_COLUMNS, DecodedInstructionCard } from '../ui/DecodedInstructionCard'; -vi.mock('@/app/components/common/Address', () => ({ - Address: ({ pubkey, fallbackText }: { pubkey: PublicKey; fallbackText?: string }) => ( -
{fallbackText ?? pubkey.toBase58()}
- ), -})); +vi.mock('@/app/components/common/Address', () => import('@/app/__tests__/address-stub')); const STUB_SURFACE: InstructionSurface = { Card: () => undefined, diff --git a/app/entities/instruction-card/__tests__/InstructionAddress.spec.tsx b/app/entities/instruction-card/__tests__/InstructionAddress.spec.tsx index 9710ad4bcc..8a71d50576 100644 --- a/app/entities/instruction-card/__tests__/InstructionAddress.spec.tsx +++ b/app/entities/instruction-card/__tests__/InstructionAddress.spec.tsx @@ -9,11 +9,7 @@ import { address as addressField } from '../model/fields'; import { InstructionAddress } from '../ui/InstructionAddress'; import { InstructionFieldRows } from '../ui/InstructionFields'; -vi.mock('next/navigation', () => ({ - usePathname: vi.fn(() => '/'), - useRouter: vi.fn(() => ({ push: vi.fn(), replace: vi.fn() })), - useSearchParams: vi.fn(() => new URLSearchParams()), -})); +vi.mock('next/navigation', () => import('@/app/__tests__/next-navigation')); vi.mock('@entities/token-info', () => ({ useTokenInfo: (fetch: boolean | undefined) => (fetch ? { name: 'USD Coin', symbol: 'USDC' } : undefined), diff --git a/app/entities/instruction-card/ui/__stories__/BaseInstructionCard.responsive.stories.tsx b/app/entities/instruction-card/ui/__stories__/BaseInstructionCard.responsive.stories.tsx index 1497f66f2c..576080153d 100644 --- a/app/entities/instruction-card/ui/__stories__/BaseInstructionCard.responsive.stories.tsx +++ b/app/entities/instruction-card/ui/__stories__/BaseInstructionCard.responsive.stories.tsx @@ -1,26 +1,13 @@ -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; -import { nextjsParameters, withCluster, withScrollAnchor, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withCluster, withScrollAnchor, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import { BaseTable } from '@/app/shared/ui/Table'; - -import { toInstructionNode } from '../../model/node'; import { BaseInstructionCard } from '../BaseInstructionCard'; - -const sampleIx = new TransactionInstruction({ - data: Buffer.from([1, 2, 3, 4]), - keys: [{ isSigner: true, isWritable: true, pubkey: new PublicKey('11111111111111111111111111111111') }], - programId: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), -}); +import * as Base from './BaseInstructionCard.stories'; const meta: Meta = { component: BaseInstructionCard, decorators: [withCluster, withScrollAnchor, withTokenInfoBatch, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Entities/Instruction Card/BaseInstructionCard@Media', }; @@ -28,19 +15,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - children: ( - - Instruction details go here - - ), - collapsible: false, - node: toInstructionNode({ index: 0, ix: sampleIx }), - rawSource: { kind: 'none' }, - result: { err: null }, - title: 'Token Transfer', - validateProgram: false, -} as const; +const args = { ...Base.default.args, ...Base.Success.args }; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/entities/instruction-card/ui/__stories__/BaseInstructionCard.stories.tsx b/app/entities/instruction-card/ui/__stories__/BaseInstructionCard.stories.tsx index 6af35534cf..7a85ee7acd 100644 --- a/app/entities/instruction-card/ui/__stories__/BaseInstructionCard.stories.tsx +++ b/app/entities/instruction-card/ui/__stories__/BaseInstructionCard.stories.tsx @@ -1,6 +1,5 @@ import { type ParsedInstruction, PublicKey, TransactionInstruction } from '@solana/web3.js'; import { - nextjsParameters, withCluster, withClusterAndAccounts, withScrollAnchor, @@ -20,7 +19,6 @@ const meta = { args: { collapsible: false, rawSource: { kind: 'none' }, result: { err: null }, validateProgram: false }, component: BaseInstructionCard, decorators: [withCluster, withScrollAnchor, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Entities/Instruction Card/BaseInstructionCard', } satisfies Meta; diff --git a/app/entities/instruction-card/ui/__stories__/BaseRawDetails.stories.tsx b/app/entities/instruction-card/ui/__stories__/BaseRawDetails.stories.tsx index 57dad84e0e..86c516f93c 100644 --- a/app/entities/instruction-card/ui/__stories__/BaseRawDetails.stories.tsx +++ b/app/entities/instruction-card/ui/__stories__/BaseRawDetails.stories.tsx @@ -1,6 +1,6 @@ import { PublicKey, TransactionInstruction } from '@solana/web3.js'; import { MockClusterProvider as ClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; -import { nextjsParameters, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import React from 'react'; import { expect, within } from 'storybook/test'; @@ -65,7 +65,6 @@ const meta = { ), withTokenInfoBatch, ], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Entities/Instruction Card/BaseRawDetails', } satisfies Meta; diff --git a/app/entities/instruction-card/ui/__stories__/BaseRawParsedDetails.stories.tsx b/app/entities/instruction-card/ui/__stories__/BaseRawParsedDetails.stories.tsx index 98b6063e29..0a1a7d5485 100644 --- a/app/entities/instruction-card/ui/__stories__/BaseRawParsedDetails.stories.tsx +++ b/app/entities/instruction-card/ui/__stories__/BaseRawParsedDetails.stories.tsx @@ -1,5 +1,5 @@ import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withCardTableField } from '@storybook-config/decorators'; +import { withCardTableField } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BaseTable } from '@/app/shared/ui/Table'; @@ -22,7 +22,6 @@ const sampleIx = { const meta: Meta = { component: BaseRawParsedDetails, decorators: [withCardTableField], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Entities/Instruction Card/BaseRawParsedDetails', }; diff --git a/app/entities/instruction-card/ui/__stories__/ProgramField.stories.tsx b/app/entities/instruction-card/ui/__stories__/ProgramField.stories.tsx index 8e518668e1..0c6fb6559b 100644 --- a/app/entities/instruction-card/ui/__stories__/ProgramField.stories.tsx +++ b/app/entities/instruction-card/ui/__stories__/ProgramField.stories.tsx @@ -1,7 +1,7 @@ /* eslint-disable no-restricted-syntax -- storybook play functions use RegExp for pattern matching */ import { TOKEN_PROGRAM_ID } from '@providers/accounts/tokens'; import { SystemProgram } from '@solana/web3.js'; -import { nextjsParameters, withCardTableField, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withCardTableField, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; @@ -10,7 +10,6 @@ import { ProgramField } from '../ProgramField'; const meta = { component: ProgramField, decorators: [withCardTableField, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Entities/Instruction Card/Field/ProgramField', } satisfies Meta; diff --git a/app/entities/nft/lib/__tests__/make-nft-data.ts b/app/entities/nft/__fixtures__/make-nft-data.ts similarity index 83% rename from app/entities/nft/lib/__tests__/make-nft-data.ts rename to app/entities/nft/__fixtures__/make-nft-data.ts index 8fa3edb478..91a5b0db3f 100644 --- a/app/entities/nft/lib/__tests__/make-nft-data.ts +++ b/app/entities/nft/__fixtures__/make-nft-data.ts @@ -2,7 +2,7 @@ import type { Metadata } from '@metaplex-foundation/mpl-token-metadata'; import { none, publicKey, some } from '@metaplex-foundation/umi'; import { PublicKey } from '@solana/web3.js'; -import type { EditionInfo, NFTData, NftJson } from '../types'; +import type { EditionInfo, NFTData, NftJson } from '../lib/types'; export function makeMetadata(overrides: Partial = {}): Metadata { return { @@ -32,6 +32,8 @@ export function makeNftData( overrides: { name?: string; symbol?: string; + isMutable?: boolean; + primarySaleHappened?: boolean; editionInfo?: EditionInfo; collection?: { key: string; verified: boolean } | null; creators?: Array<{ address: string; verified: boolean; share: number }> | null; @@ -41,18 +43,21 @@ export function makeNftData( const { name = 'Test NFT', symbol = 'TNFT', + isMutable = true, + primarySaleHappened = false, editionInfo = { edition: undefined, masterEdition: undefined }, collection = null, creators = null, - json, } = overrides; return { editionInfo, - json: json ?? { image: 'https://example.com/image.png', name }, + json: 'json' in overrides ? overrides.json : { image: 'https://example.com/image.png', name }, metadata: makeMetadata({ collection: collection ? some({ ...collection, key: publicKey(collection.key) }) : none(), creators: creators ? some(creators.map(c => ({ ...c, address: publicKey(c.address) }))) : none(), + isMutable, name, + primarySaleHappened, symbol, tokenStandard: some(0), }), diff --git a/app/entities/nft/lib/__tests__/is-metaplex-nft.spec.ts b/app/entities/nft/lib/__tests__/is-metaplex-nft.spec.ts index 4e483a0c8c..2ec326bb12 100644 --- a/app/entities/nft/lib/__tests__/is-metaplex-nft.spec.ts +++ b/app/entities/nft/lib/__tests__/is-metaplex-nft.spec.ts @@ -3,11 +3,10 @@ import { some } from '@metaplex-foundation/umi'; import { describe, expect, it } from 'vitest'; import { isMetaplexNFT } from '@/app/entities/nft'; +import { makeMetadata } from '@/app/entities/nft/__fixtures__/make-nft-data'; import type { TokenProgramData } from '@/app/providers/accounts'; import type { MintAccountInfo } from '@/app/validators/accounts/token'; -import { makeMetadata } from './make-nft-data'; - function makeMintInfo(overrides: Partial = {}): MintAccountInfo { return { decimals: 0, diff --git a/app/entities/pmp-account/__fixtures__/pmp-account.ts b/app/entities/pmp-account/__fixtures__/pmp-account.ts index 074c45a4f1..d876aa1c12 100644 --- a/app/entities/pmp-account/__fixtures__/pmp-account.ts +++ b/app/entities/pmp-account/__fixtures__/pmp-account.ts @@ -25,6 +25,12 @@ export const DOC = '{"name":"company","version":"1.0.0"}'; /** The same document as `DOC`, indented - a `Format.Json` payload is re-serialised before it reaches the card. */ export const DOC_PRETTY = '{\n "name": "company",\n "version": "1.0.0"\n}'; +export const IDL_DOC = JSON.stringify({ + instructions: [{ name: 'initialize' }], + name: 'company_program', + version: '1.0.0', +}); + // `encoding` tells `packDirectData` how to read `content`, so Utf8 is the only choice for a text document. export function pack(content: string, compression: Compression): Uint8Array { return packDirectData({ compression, content, encoding: Encoding.Utf8 }).data as Uint8Array; diff --git a/app/entities/slot-time/model/__tests__/use-slot-time.spec.tsx b/app/entities/slot-time/model/__tests__/use-slot-time.spec.tsx index f697134aad..48a5ae0f56 100644 --- a/app/entities/slot-time/model/__tests__/use-slot-time.spec.tsx +++ b/app/entities/slot-time/model/__tests__/use-slot-time.spec.tsx @@ -3,6 +3,7 @@ import { Cluster, ClusterStatus } from '@utils/cluster'; import { type SWRConfiguration } from 'swr'; import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { reported } from '@/app/__tests__/rpc-errors'; import { type ClusterContext, clusterContext, @@ -175,10 +176,7 @@ describe('useSlotTime', () => { expect(Logger.warn).toHaveBeenCalledTimes(1); expect(Logger.warn).toHaveBeenCalledWith( expect.any(String), - expect.objectContaining({ - sentry: true, - sentryExtras: expect.objectContaining({ cluster: Cluster.Mainnet, status: 400 }), - }), + reported({ cluster: Cluster.Mainnet, status: 400 }), ); // The bot gate ahead of the route refuses visitors it misjudges, and this fires once per visitor // with no CDN in front of it: one gate misfiring must not set the error rate on its own. @@ -205,13 +203,7 @@ describe('useSlotTime', () => { expect(Logger.warn).toHaveBeenCalledTimes(1); expect(Logger.warn).toHaveBeenCalledWith( expect.any(String), - expect.objectContaining({ - sentry: true, - sentryExtras: expect.objectContaining({ - cluster: Cluster.Mainnet, - parseError: expect.any(String), - }), - }), + reported({ cluster: Cluster.Mainnet, parseError: expect.any(String) }), ); // A captive portal or an interstitial proxy answers for the route this way, once per visitor with // no CDN in front of it: someone else's middlebox must not set the error rate. diff --git a/app/entities/stake-rewards/api/__tests__/is-stake-account.spec.ts b/app/entities/stake-rewards/api/__tests__/is-stake-account.spec.ts index 15382e1f23..4e96011900 100644 --- a/app/entities/stake-rewards/api/__tests__/is-stake-account.spec.ts +++ b/app/entities/stake-rewards/api/__tests__/is-stake-account.spec.ts @@ -1,5 +1,5 @@ import { gen } from '@__fixtures__/gen'; -import { address } from '@solana/kit'; +import { address, createSolanaRpc } from '@solana/kit'; import { STAKE_PROGRAM_ADDRESS } from '@solana-program/stake'; import { SYSTEM_PROGRAM_ADDRESS } from '@solana-program/system'; import { beforeEach, describe, expect, it, vi } from 'vitest'; @@ -9,14 +9,9 @@ import { isStakeAccount } from '../is-stake-account'; const ADDRESS = address(gen.address(0)); const RPC_URL = 'https://rpc.example'; -const mocks = vi.hoisted(() => ({ getAccountInfo: vi.fn() })); +const mocks = { getAccountInfo: vi.fn() }; -// The global kit mock in `test-setup.specs.ts` serves an RPC stub without `getAccountInfo`; per its -// own note, tests needing other methods override it locally. -vi.mock('@solana/kit', async () => { - const actual = await vi.importActual('@solana/kit'); - return { ...actual, createSolanaRpc: vi.fn(() => ({ getAccountInfo: mocks.getAccountInfo })) }; -}); +vi.mocked(createSolanaRpc).mockImplementation(() => ({ getAccountInfo: mocks.getAccountInfo }) as never); describe('isStakeAccount', () => { beforeEach(() => { diff --git a/app/entities/token-info/__fixtures__/token-info.ts b/app/entities/token-info/__fixtures__/token-info.ts index 24d0f656b0..eda9b25744 100644 --- a/app/entities/token-info/__fixtures__/token-info.ts +++ b/app/entities/token-info/__fixtures__/token-info.ts @@ -1,5 +1,5 @@ import type { TokenInfo } from '../lib/types'; -export function tokenInfo(address: string, verified = false): TokenInfo { - return { address, decimals: 6, logoURI: null, name: address, symbol: address, verified }; +export function tokenInfo(address: string, verified = false, overrides: Partial = {}): TokenInfo { + return { address, decimals: 6, logoURI: null, name: address, symbol: address, verified, ...overrides }; } diff --git a/app/entities/token-info/api/__tests__/fetch-token-mints.spec.ts b/app/entities/token-info/api/__tests__/fetch-token-mints.spec.ts index b2364f7fe6..fa35189db8 100644 --- a/app/entities/token-info/api/__tests__/fetch-token-mints.spec.ts +++ b/app/entities/token-info/api/__tests__/fetch-token-mints.spec.ts @@ -1,19 +1,12 @@ +import { tokenInfo } from '@entities/token-info/__fixtures__/token-info'; import { PublicKey } from '@solana/web3.js'; import { Cluster } from '@utils/cluster'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TokenInfoHttpError, TokenInfoInvalidResponseError } from '../../lib/errors'; -import { type TokenInfo } from '../../lib/types'; import { getTokenInfo, getTokenInfos } from '../fetch-token-mints'; -const mockToken: TokenInfo = { - address: PublicKey.default.toBase58(), - decimals: 9, - logoURI: null, - name: 'Wrapped SOL', - symbol: 'SOL', - verified: true, -}; +const mockToken = tokenInfo(PublicKey.default.toBase58(), true); describe('getTokenInfos', () => { const originalFetch = global.fetch; @@ -189,10 +182,10 @@ describe('getTokenInfos', () => { const onError = vi.fn(); const withoutVerified = { address: mockToken.address, - decimals: 9, + decimals: mockToken.decimals, logoURI: null, - name: 'Wrapped SOL', - symbol: 'SOL', + name: mockToken.name, + symbol: mockToken.symbol, }; vi.mocked(global.fetch).mockResolvedValueOnce({ diff --git a/app/entities/token-info/model/__tests__/token-info-batch-provider.cache.spec.tsx b/app/entities/token-info/model/__tests__/token-info-batch-provider.cache.spec.tsx index aafb5053ab..c4a1abd806 100644 --- a/app/entities/token-info/model/__tests__/token-info-batch-provider.cache.spec.tsx +++ b/app/entities/token-info/model/__tests__/token-info-batch-provider.cache.spec.tsx @@ -13,9 +13,7 @@ vi.mock('../../api/fetch-token-infos-from-api', async importOriginal => ({ // The specs setup (test-setup.specs.ts) globally no-ops useTokenInfoBatch to prevent network. This suite // asserts real batch behavior, so restore the actual provider for this file only. -vi.mock('@/app/entities/token-info/model/token-info-batch-provider', async () => - vi.importActual('@/app/entities/token-info/model/token-info-batch-provider'), -); +vi.unmock('@/app/entities/token-info/model/token-info-batch-provider'); import { TokenInfoBatchProvider, useTokenInfoBatch } from '../token-info-batch-provider'; diff --git a/app/entities/token-receipt/__fixtures__/formatted-receipt.ts b/app/entities/token-receipt/__fixtures__/formatted-receipt.ts index 7ddd38e842..20270cbc43 100644 --- a/app/entities/token-receipt/__fixtures__/formatted-receipt.ts +++ b/app/entities/token-receipt/__fixtures__/formatted-receipt.ts @@ -1,4 +1,4 @@ -import type { FormattedReceipt } from '../types'; +import type { FormattedReceipt, FormattedReceiptToken } from '../types'; export function buildFormattedReceipt(overrides: Partial = {}): FormattedReceipt { return { @@ -13,3 +13,14 @@ export function buildFormattedReceipt(overrides: Partial = {}) ...overrides, }; } + +export function buildFormattedTokenReceipt(overrides: Partial = {}): FormattedReceiptToken { + return { + ...buildFormattedReceipt(), + kind: 'token', + mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', + symbol: 'USDC', + total: { formatted: '143.25', raw: 143.25, unit: 'USDC' }, + ...overrides, + }; +} diff --git a/app/entities/token-receipt/__tests__/lib.spec.ts b/app/entities/token-receipt/__tests__/lib.spec.ts index 2d1f7681e3..465b810214 100644 --- a/app/entities/token-receipt/__tests__/lib.spec.ts +++ b/app/entities/token-receipt/__tests__/lib.spec.ts @@ -1,19 +1,11 @@ import { describe, expect, it } from 'vitest'; -import { buildFormattedReceipt } from '../__fixtures__/formatted-receipt'; +import { buildFormattedReceipt, buildFormattedTokenReceipt } from '../__fixtures__/formatted-receipt'; import { getReceiptAmount, getReceiptMint, getReceiptSymbol } from '../lib'; -import type { FormattedReceiptToken } from '../types'; const SOL_RECEIPT = buildFormattedReceipt({ total: { formatted: '1.5', raw: 1_500_000_000, unit: 'SOL' } }); -const TOKEN_FIELDS: Partial = { - kind: 'token', - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - symbol: 'USDC', - total: { formatted: '143.25', raw: 143.25, unit: 'USDC' }, -}; - -const TOKEN_RECEIPT = buildFormattedReceipt(TOKEN_FIELDS); +const TOKEN_RECEIPT = buildFormattedTokenReceipt(); describe('getReceiptMint', () => { it('should return undefined for SOL receipts', () => { @@ -25,7 +17,7 @@ describe('getReceiptMint', () => { }); it('should return undefined for token receipts without mint', () => { - const receipt = buildFormattedReceipt({ ...TOKEN_FIELDS, mint: undefined }); + const receipt = buildFormattedTokenReceipt({ mint: undefined }); expect(getReceiptMint(receipt)).toBeUndefined(); }); }); @@ -40,7 +32,7 @@ describe('getReceiptSymbol', () => { }); it('should return undefined for token receipts without symbol', () => { - const receipt = buildFormattedReceipt({ ...TOKEN_FIELDS, symbol: undefined }); + const receipt = buildFormattedTokenReceipt({ symbol: undefined }); expect(getReceiptSymbol(receipt)).toBeUndefined(); }); }); diff --git a/app/features/receipt/model/__fixtures__/builders.ts b/app/entities/transaction-data/__fixtures__/parsed-transactions.ts similarity index 80% rename from app/features/receipt/model/__fixtures__/builders.ts rename to app/entities/transaction-data/__fixtures__/parsed-transactions.ts index c0fd967238..f51009cb03 100644 --- a/app/features/receipt/model/__fixtures__/builders.ts +++ b/app/entities/transaction-data/__fixtures__/parsed-transactions.ts @@ -1,4 +1,4 @@ -import { DEFAULT_SIGNATURE } from '@__fixtures__/gen'; +import { DEFAULT_BLOCKHASH, DEFAULT_SIGNATURE } from '@__fixtures__/gen'; import { type ParsedInnerInstruction, type ParsedInstruction, @@ -12,8 +12,6 @@ import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; const SYSTEM_PROGRAM = SystemProgram.programId; const TOKEN_PROGRAM = new PublicKey(TOKEN_PROGRAM_ADDRESS); -const DEFAULT_BLOCKHASH = 'AHK7TnmvzPAk4WsmWqVgL7v6YccGkANoWUmrSY7aQDzw'; - export function buildSolTransferIx(opts: { source: PublicKey; destination: PublicKey; @@ -113,35 +111,42 @@ export type ParsedTokenBalance = { uiTokenAmount: { amount: string; decimals: number; uiAmount: number; uiAmountString: string }; }; +type AccountKey = PublicKey | { pubkey: PublicKey; signer?: boolean; writable?: boolean }; + export function buildParsedTransaction(opts: { - accountKeys: PublicKey[]; + accountKeys?: AccountKey[]; instructions: (ParsedInstruction | PartiallyDecodedInstruction)[]; innerInstructions?: ParsedInnerInstruction[]; postTokenBalances?: ParsedTokenBalance[]; fee?: number; blockTime?: number; + logMessages?: string[]; + meta?: null; + slot?: number; }): ParsedTransactionWithMeta { + const accountKeys = opts.accountKeys ?? []; + const meta = { + computeUnitsConsumed: 1200, + err: null, + fee: opts.fee ?? 5000, + innerInstructions: opts.innerInstructions ?? [], + logMessages: opts.logMessages ?? [], + postBalances: accountKeys.map(() => 0), + postTokenBalances: opts.postTokenBalances ?? [], + preBalances: accountKeys.map(() => 0), + preTokenBalances: opts.postTokenBalances ?? [], + }; return { blockTime: opts.blockTime ?? 1768831450, - meta: { - computeUnitsConsumed: 1200, - err: null, - fee: opts.fee ?? 5000, - innerInstructions: opts.innerInstructions ?? [], - logMessages: [], - postBalances: opts.accountKeys.map(() => 0), - postTokenBalances: opts.postTokenBalances ?? [], - preBalances: opts.accountKeys.map(() => 0), - preTokenBalances: opts.postTokenBalances ?? [], - }, - slot: 436228237, + meta: opts.meta === null ? null : meta, + slot: opts.slot ?? 436228237, transaction: { message: { - accountKeys: opts.accountKeys.map((pubkey, i) => ({ - pubkey, + accountKeys: accountKeys.map((key, i) => ({ signer: i === 0, source: 'transaction', writable: true, + ...(key instanceof PublicKey ? { pubkey: key } : key), })), instructions: opts.instructions, recentBlockhash: DEFAULT_BLOCKHASH, diff --git a/app/entities/transaction-data/__fixtures__/wire-transactions.ts b/app/entities/transaction-data/__fixtures__/wire-transactions.ts index 58d46aedaa..0b0ceae02c 100644 --- a/app/entities/transaction-data/__fixtures__/wire-transactions.ts +++ b/app/entities/transaction-data/__fixtures__/wire-transactions.ts @@ -14,7 +14,13 @@ import { setTransactionMessageLoadedAccountsDataSizeLimit, setTransactionMessagePriorityFeeLamports, } from '@solana/kit'; -import { PublicKey, SystemProgram, TransactionMessage } from '@solana/web3.js'; +import { + type MessageV0, + PublicKey, + SystemProgram, + type TransactionInstruction, + TransactionMessage, +} from '@solana/web3.js'; export const FEE_PAYER = address(gen.address(1)); export const RECIPIENT = address(gen.address(2)); @@ -66,6 +72,14 @@ export function createWeb3TransactionMessage(): TransactionMessage { }); } +export function compileV0Message(payer: PublicKey, instruction: TransactionInstruction): MessageV0 { + return new TransactionMessage({ + instructions: [instruction], + payerKey: payer, + recentBlockhash: PublicKey.default.toBase58(), + }).compileToV0Message(); +} + /** * Wire bytes of an unsigned legacy or v0 transaction. * diff --git a/app/entities/transaction-data/api/__tests__/fetch-raw-transaction.spec.ts b/app/entities/transaction-data/api/__tests__/fetch-raw-transaction.spec.ts index 533e93c18e..483f7b5004 100644 --- a/app/entities/transaction-data/api/__tests__/fetch-raw-transaction.spec.ts +++ b/app/entities/transaction-data/api/__tests__/fetch-raw-transaction.spec.ts @@ -1,5 +1,4 @@ import { gen } from '@__fixtures__/gen'; -import type * as SolanaKit from '@solana/kit'; import { describe, expect, it, vi } from 'vitest'; import { stubRpcFetch } from '@/app/__tests__/rpc-fetch'; @@ -15,7 +14,7 @@ import { fetchRawTransaction } from '../fetch-raw-transaction'; // The global setup stubs `createSolanaRpc` so no test reaches the network; these tests exercise the // real client against a stubbed `fetch` instead. -vi.mock('@solana/kit', async () => await vi.importActual('@solana/kit')); +vi.unmock('@solana/kit'); const URL = 'https://mock.rpc'; const SIGNATURE = gen.signature(1); diff --git a/app/entities/transaction-data/api/__tests__/fetch-transaction-details.spec.ts b/app/entities/transaction-data/api/__tests__/fetch-transaction-details.spec.ts index 0d094e99b0..99902d7fb1 100644 --- a/app/entities/transaction-data/api/__tests__/fetch-transaction-details.spec.ts +++ b/app/entities/transaction-data/api/__tests__/fetch-transaction-details.spec.ts @@ -1,5 +1,4 @@ import { gen } from '@__fixtures__/gen'; -import type * as SolanaKit from '@solana/kit'; import { SystemProgram } from '@solana/web3.js'; import { describe, expect, it, vi } from 'vitest'; @@ -9,7 +8,7 @@ import { fetchTransactionDetails } from '../fetch-transaction-details'; // The global setup stubs `createSolanaRpc` so no test reaches the network; these tests exercise the // real client against a stubbed `fetch` instead. -vi.mock('@solana/kit', async () => await vi.importActual('@solana/kit')); +vi.unmock('@solana/kit'); const URL = 'https://mock.rpc'; const SIGNATURE = gen.signature(1); diff --git a/app/entities/transaction-data/api/__tests__/find-transaction-cluster.spec.ts b/app/entities/transaction-data/api/__tests__/find-transaction-cluster.spec.ts index 89acebc408..dfbbae1f1d 100644 --- a/app/entities/transaction-data/api/__tests__/find-transaction-cluster.spec.ts +++ b/app/entities/transaction-data/api/__tests__/find-transaction-cluster.spec.ts @@ -9,13 +9,7 @@ import { findTransactionCluster } from '../find-transaction-cluster'; const mockSend = vi.fn(); const mockGetSignatureStatuses = vi.fn(() => ({ send: mockSend })); -vi.mock('@solana/kit', async () => { - const actual = await vi.importActual('@solana/kit'); - return { - ...actual, - createSolanaRpc: vi.fn(() => ({ getSignatureStatuses: mockGetSignatureStatuses })), - }; -}); +vi.mocked(createSolanaRpc).mockImplementation(() => ({ getSignatureStatuses: mockGetSignatureStatuses }) as never); const SIGNATURE = gen.signature(1); diff --git a/app/entities/transaction-data/lib/__tests__/encoding.spec.ts b/app/entities/transaction-data/lib/__tests__/encoding.spec.ts index eaa7ab0650..3f1bddcdc2 100644 --- a/app/entities/transaction-data/lib/__tests__/encoding.spec.ts +++ b/app/entities/transaction-data/lib/__tests__/encoding.spec.ts @@ -1,6 +1,10 @@ -import { gen } from '@__fixtures__/gen'; +import { + createWeb3TransactionMessage, + FEE_PAYER, + RECIPIENT, +} from '@entities/transaction-data/__fixtures__/wire-transactions'; import { getBase58Encoder } from '@solana/kit'; -import { PublicKey, SystemProgram, TransactionMessage, VersionedMessage } from '@solana/web3.js'; +import { PublicKey, SystemProgram, VersionedMessage } from '@solana/web3.js'; import { describe, expect, it } from 'vitest'; import { encodeTransactionData } from '../encoding'; @@ -11,36 +15,13 @@ const BASE58_ENCODER = getBase58Encoder(); // The production code uses only Uint8Array for browser compatibility. describe('transaction-data encoding', () => { - const FROM_PUBKEY = gen.publicKey(1); - const TO_PUBKEY = gen.publicKey(2); - const TRANSFER_AMOUNT = 1_000_000n; - - const createTransferInstruction = () => - SystemProgram.transfer({ - fromPubkey: FROM_PUBKEY, - lamports: TRANSFER_AMOUNT, - toPubkey: TO_PUBKEY, - }); - - const createLegacyMessage = (): Uint8Array => { - const message = new TransactionMessage({ - instructions: [createTransferInstruction()], - payerKey: FROM_PUBKEY, - recentBlockhash: PublicKey.default.toBase58(), - }).compileToLegacyMessage(); + const FROM_PUBKEY = new PublicKey(FEE_PAYER); + const TO_PUBKEY = new PublicKey(RECIPIENT); + const TRANSFER_AMOUNT = 1n; - return message.serialize(); - }; + const createLegacyMessage = (): Uint8Array => createWeb3TransactionMessage().compileToLegacyMessage().serialize(); - const createV0Message = (): Uint8Array => { - const message = new TransactionMessage({ - instructions: [createTransferInstruction()], - payerKey: FROM_PUBKEY, - recentBlockhash: PublicKey.default.toBase58(), - }).compileToV0Message(); - - return message.serialize(); - }; + const createV0Message = (): Uint8Array => createWeb3TransactionMessage().compileToV0Message().serialize(); const verifyDecodedMessage = (decoded: Uint8Array) => { const message = VersionedMessage.deserialize(decoded); diff --git a/app/entities/transaction-data/lib/__tests__/instruction-summary.spec.ts b/app/entities/transaction-data/lib/__tests__/instruction-summary.spec.ts index eb3be5b54d..8d1498b418 100644 --- a/app/entities/transaction-data/lib/__tests__/instruction-summary.spec.ts +++ b/app/entities/transaction-data/lib/__tests__/instruction-summary.spec.ts @@ -1,3 +1,4 @@ +import { buildParsedTransaction } from '@entities/transaction-data/__fixtures__/parsed-transactions'; import { address, appendTransactionMessageInstructions, @@ -15,7 +16,6 @@ import { import { ComputeBudgetProgram, ParsedInstruction, - ParsedTransactionWithMeta, PartiallyDecodedInstruction, PublicKey, SystemProgram, @@ -178,7 +178,7 @@ describe('getInstructionSummaries', () => { programId: SystemProgram.programId, } as unknown as ParsedInstruction; const version = 1; - const results = getInstructionSummaries(makeTxWithMeta([ix], version)); + const results = getInstructionSummaries(makeTx([ix], version)); expect(results).toEqual([{ name: 'Transfer', programName: 'System Program' }]); }); @@ -289,34 +289,11 @@ describe('resolveNamesFromData', () => { }); }); -function makeTx(instructions: (ParsedInstruction | PartiallyDecodedInstruction)[]): ParsedTransactionWithMeta { - return { - meta: null, - transaction: { - message: { - accountKeys: [], - instructions, - }, - signatures: [], - }, - } as unknown as ParsedTransactionWithMeta; -} - -function makeTxWithMeta( +function makeTx( instructions: (ParsedInstruction | PartiallyDecodedInstruction)[], - version: TransactionWithMeta['version'], + version?: TransactionWithMeta['version'], ): TransactionWithMeta { - return { - meta: null, - transaction: { - message: { - accountKeys: [], - instructions, - }, - signatures: [], - }, - version, - } as unknown as TransactionWithMeta; + return { ...buildParsedTransaction({ instructions, meta: null }), version }; } describe('getCompiledInstructionSummaries', () => { diff --git a/app/entities/transfer-instruction/__fixtures__/load-fixture.ts b/app/entities/transfer-instruction/__fixtures__/load-fixture.ts index 2e927be469..def6ce2eb9 100644 --- a/app/entities/transfer-instruction/__fixtures__/load-fixture.ts +++ b/app/entities/transfer-instruction/__fixtures__/load-fixture.ts @@ -1,4 +1,4 @@ -import { type ParsedTransactionWithMeta, PublicKey } from '@solana/web3.js'; +import { adaptParsedTransaction } from '@entities/transaction-data'; import devnetMultiSolMemoRaw from './devnet-multi-sol-memo-5PQcQh7w63DzgaSaovT5nLgyfciWm6fkyeBHwADoaVuesk8KAuwEK1v9gnruPfmoN4HseWMnPuZy5xjfxLazx5wt.json'; import devnetSingleSolMemoRaw from './devnet-single-sol-memo-2EhgNdNDaH2ArsoEChEFYMnNzu6qerQpqFP5auGQHXUDEz5CH4mGF1t3ga4tKsVrio3SSPDxSv8HYmURQu1TPTkJ.json'; @@ -9,61 +9,15 @@ import mainnetSingleSolRaw from './mainnet-single-sol-2kHbPUGzehenUXQbBfAVZGcuTr import mainnetSingleUsdcRaw from './mainnet-single-usdc-4LXpF3MCdp69iFmD27Sn812UNpqFPHM4qXH7Y12E964p9GHXvwMe1XEmyasogVT2N4XEctdQQLf1sHY6Gvsa5sFX.json'; import surfpoolMultiTransferRaw from './surfpool-multi-transfer-3p9fzShSPEC5ocZ52UqQBszEKrr6m1w5QwCFrChwQBgQAKbAG1dgMraQuXKtZhSvg6sSHZzaQvDjhh8wKCWL6f9D.json'; -type WireInstruction = { programId: string; [extra: string]: unknown }; -type WireAccountKey = { pubkey: string; [extra: string]: unknown }; -type WireInnerGroup = { index: number; instructions: WireInstruction[] }; +type RpcResponse = { result: Parameters[0] }; -type WireParsedTransaction = { - blockTime: number; - slot: number; - version: number | 'legacy'; - meta: { - innerInstructions: WireInnerGroup[]; - [extra: string]: unknown; - }; - transaction: { - message: { - accountKeys: WireAccountKey[]; - instructions: WireInstruction[]; - recentBlockhash: string; - }; - signatures: string[]; - }; -}; +const hydrate = ({ result }: RpcResponse) => adaptParsedTransaction(result); -type WireRpcResponse = { result: WireParsedTransaction }; - -const hydrateInstruction = (ix: WireInstruction) => ({ ...ix, programId: new PublicKey(ix.programId) }); - -function hydrate({ result }: WireRpcResponse): ParsedTransactionWithMeta { - return { - ...result, - meta: { - ...result.meta, - innerInstructions: result.meta.innerInstructions.map(g => ({ - ...g, - instructions: g.instructions.map(hydrateInstruction), - })), - }, - transaction: { - ...result.transaction, - message: { - ...result.transaction.message, - accountKeys: result.transaction.message.accountKeys.map(k => ({ - ...k, - pubkey: new PublicKey(k.pubkey), - })), - instructions: result.transaction.message.instructions.map(hydrateInstruction), - }, - }, - } as ParsedTransactionWithMeta; -} - -export const surfpoolMultiTransferTx = hydrate(surfpoolMultiTransferRaw as unknown as WireRpcResponse); -export const mainnetSingleSolTx = hydrate(mainnetSingleSolRaw as unknown as WireRpcResponse); -export const mainnetSingleUsdcTx = hydrate(mainnetSingleUsdcRaw as unknown as WireRpcResponse); -export const devnetSingleSolMemoTx = hydrate(devnetSingleSolMemoRaw as unknown as WireRpcResponse); -export const mainnetMultiSolTx = hydrate(mainnetMultiSolRaw as unknown as WireRpcResponse); -export const devnetMultiSolMemoTx = hydrate(devnetMultiSolMemoRaw as unknown as WireRpcResponse); -export const devnetTransferWithSeedTx = hydrate(devnetTransferWithSeedRaw as unknown as WireRpcResponse); -export const devnetSolWithAtaRentTx = hydrate(devnetSolWithAtaRentRaw as unknown as WireRpcResponse); +export const surfpoolMultiTransferTx = hydrate(surfpoolMultiTransferRaw as unknown as RpcResponse); +export const mainnetSingleSolTx = hydrate(mainnetSingleSolRaw as unknown as RpcResponse); +export const mainnetSingleUsdcTx = hydrate(mainnetSingleUsdcRaw as unknown as RpcResponse); +export const devnetSingleSolMemoTx = hydrate(devnetSingleSolMemoRaw as unknown as RpcResponse); +export const mainnetMultiSolTx = hydrate(mainnetMultiSolRaw as unknown as RpcResponse); +export const devnetMultiSolMemoTx = hydrate(devnetMultiSolMemoRaw as unknown as RpcResponse); +export const devnetTransferWithSeedTx = hydrate(devnetTransferWithSeedRaw as unknown as RpcResponse); +export const devnetSolWithAtaRentTx = hydrate(devnetSolWithAtaRentRaw as unknown as RpcResponse); diff --git a/app/features/account-share/api/__tests__/get-program-provenance.spec.ts b/app/features/account-share/api/__tests__/get-program-provenance.spec.ts index 2abfa303b8..0cc250ac3f 100644 --- a/app/features/account-share/api/__tests__/get-program-provenance.spec.ts +++ b/app/features/account-share/api/__tests__/get-program-provenance.spec.ts @@ -10,7 +10,6 @@ const mocks = vi.hoisted(() => ({ vi.mock('@entities/idl/server', () => ({ resolveProgramIdls: mocks.resolveProgramIdls })); vi.mock('@solana/security-txt', () => ({ fetchSecurityTxt: mocks.fetchSecurityTxt })); -vi.mock('@/app/shared/lib/logger', () => ({ Logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } })); import { getProgramProvenance, verifiedBuildState, type VerifiedLookup } from '../get-program-provenance'; diff --git a/app/features/account-share/model/__tests__/get-account-share-data.spec.ts b/app/features/account-share/model/__tests__/get-account-share-data.spec.ts index 04e4cc7453..ddb4c9265b 100644 --- a/app/features/account-share/model/__tests__/get-account-share-data.spec.ts +++ b/app/features/account-share/model/__tests__/get-account-share-data.spec.ts @@ -30,7 +30,6 @@ vi.mock('../../api/get-program-provenance', () => ({ getProgramProvenance: mocks.getProgramProvenance, verifiedBuildState: mocks.verifiedBuildState, })); -vi.mock('@/app/shared/lib/logger', () => ({ Logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } })); import { getAccountShareData } from '../get-account-share-data'; diff --git a/app/features/account-share/ui/__stories__/BaseAccountImage.stories.tsx b/app/features/account-share/ui/__stories__/BaseAccountImage.stories.tsx index 18b6069c4f..35f552e382 100644 --- a/app/features/account-share/ui/__stories__/BaseAccountImage.stories.tsx +++ b/app/features/account-share/ui/__stories__/BaseAccountImage.stories.tsx @@ -1,6 +1,6 @@ import { gen } from '@__fixtures__/gen'; import { truncateAddress } from '@entities/address'; -import { IMAGE_SIZE } from '@shared/lib/og/image-size'; +import { withOgImageFrame } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; @@ -48,13 +48,7 @@ const meta: Meta = { }, args: { glows: GLOWS }, component: BaseAccountImage, - decorators: [ - Story => ( -
- -
- ), - ], + decorators: [withOgImageFrame], tags: ['autodocs', 'test'], title: 'Features/AccountShare/BaseAccountImage', }; diff --git a/app/features/account/ui/__stories__/RawAccountRows.stories.tsx b/app/features/account/ui/__stories__/RawAccountRows.stories.tsx deleted file mode 100644 index 76842fcb6f..0000000000 --- a/app/features/account/ui/__stories__/RawAccountRows.stories.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import { gen } from '@__fixtures__/gen'; -import type { Account } from '@providers/accounts'; -import { nextjsParameters, withCardTableField, withTokenInfoBatch } from '@storybook-config/decorators'; -import type { Meta, StoryObj } from '@storybook-config/types'; - -import { BaseRawAccountRows } from '@/app/shared/ui/BaseRawAccountRows'; - -const mockAccount: Account = { - data: {}, - executable: false, - lamports: 1_500_000_000, - owner: gen.publicKey(0), - pubkey: gen.publicKey(1), - space: 165, -}; - -const mockRawData = new Uint8Array([ - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, - 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, -]); - -const meta: Meta = { - component: BaseRawAccountRows, - decorators: [withCardTableField, withTokenInfoBatch], - parameters: nextjsParameters, - tags: ['autodocs', 'test'], - title: 'Features/Account/BaseRawAccountRows', -}; - -export default meta; -type Story = StoryObj; - -/** Raw data loaded and displayed as hex. */ -export const WithData: Story = { - args: { - account: mockAccount, - isLoading: false, - rawData: mockRawData, - }, -}; - -/** Loading state before raw data arrives. */ -export const Loading: Story = { - args: { - account: mockAccount, - isLoading: true, - }, -}; - -/** Account not found on chain. */ -export const NotFound: Story = { - args: { - account: mockAccount, - isLoading: false, - }, -}; - -/** Account with zero data bytes. */ -export const EmptyData: Story = { - args: { - account: { ...mockAccount, space: 0 }, - isLoading: false, - rawData: new Uint8Array(0), - }, -}; - -/** Executable program account. */ -export const Executable: Story = { - args: { - account: { ...mockAccount, executable: true, space: 36 }, - isLoading: false, - rawData: mockRawData, - }, -}; diff --git a/app/features/account/ui/__tests__/AccountCard.spec.tsx b/app/features/account/ui/__tests__/AccountCard.spec.tsx index 26210e175c..f016754293 100644 --- a/app/features/account/ui/__tests__/AccountCard.spec.tsx +++ b/app/features/account/ui/__tests__/AccountCard.spec.tsx @@ -1,3 +1,4 @@ +import { makeAccount } from '@entities/account/__fixtures__/account'; import type { Account } from '@providers/accounts'; import { type CacheEntry, FetchStatus } from '@providers/cache'; import { PublicKey } from '@solana/web3.js'; @@ -44,14 +45,7 @@ describe('AccountCard', () => { }); }); -const ACCOUNT: Account = { - data: {}, - executable: false, - lamports: 1, - owner: PublicKey.default, - pubkey: new PublicKey(1), - space: 0, -}; +const ACCOUNT = makeAccount({ pubkey: new PublicKey(1), space: 0 }); function renderCard() { render( diff --git a/app/features/alpenglow/api/__tests__/fetch-ag-genesis-cert.spec.ts b/app/features/alpenglow/api/__tests__/fetch-ag-genesis-cert.spec.ts index df663c9cfb..61b4525206 100644 --- a/app/features/alpenglow/api/__tests__/fetch-ag-genesis-cert.spec.ts +++ b/app/features/alpenglow/api/__tests__/fetch-ag-genesis-cert.spec.ts @@ -1,11 +1,11 @@ -import type * as SolanaKit from '@solana/kit'; import { getBase58Encoder } from '@solana/kit'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; // The spec setup stubs `createSolanaRpc`, but these tests cover what kit does with a node's // answer, so this file uses the real one and fakes the transport instead. -vi.mock('@solana/kit', async () => await vi.importActual('@solana/kit')); +vi.unmock('@solana/kit'); +import { stubRpcFetch } from '@/app/__tests__/rpc-fetch'; import { toConnectableUrl } from '@/app/entities/cluster/lib/connectable-url'; import { Logger } from '@/app/shared/lib/logger'; import { UPSTREAM_TIMEOUT_MS } from '@/app/shared/lib/timeouts'; @@ -20,50 +20,28 @@ const CERT = { signature: { bitmap: [255, 3], signature: [1, 2, 3] }, }; -const fetchMock = vi.fn(); - -/** A real `Response`, so no test can pass against a shape `fetch` would never hand kit. */ -function respondWith(body: unknown, { status = 200 }: { status?: number } = {}) { - fetchMock.mockResolvedValueOnce(new Response(JSON.stringify(body), { status })); -} - -function respondWithRaw(body: string, { status = 200 }: { status?: number } = {}) { - fetchMock.mockResolvedValueOnce(new Response(body, { status })); -} - -function rpcError(error: unknown) { - return { error, id: '0', jsonrpc: '2.0' }; -} - -function rpcResult(result: unknown) { - return { id: '0', jsonrpc: '2.0', result }; -} - -beforeEach(() => { - vi.stubGlobal('fetch', fetchMock); -}); +const { fetchMock, requestBody, respondWith, respondWithError } = stubRpcFetch(); afterEach(() => { - vi.unstubAllGlobals(); vi.clearAllMocks(); }); describe('fetchAgGenesisCert', () => { it('should post the getAgGenesisCert call with no arguments', async () => { - respondWith(rpcResult(null)); + respondWith(null); await fetchAgGenesisCert(URL); const [url, init] = fetchMock.mock.calls[0]; expect(url).toBe(URL); expect(init.method).toBe('POST'); - expect(JSON.parse(init.body)).toMatchObject({ jsonrpc: '2.0', method: 'getAgGenesisCert', params: [] }); + expect(requestBody()).toMatchObject({ jsonrpc: '2.0', method: 'getAgGenesisCert', params: [] }); }); // An accepted connection that never answers would otherwise hang forever. it('should bound the wait on the node', async () => { const timeout = vi.spyOn(AbortSignal, 'timeout'); - respondWith(rpcResult(null)); + respondWith(null); await fetchAgGenesisCert(URL); @@ -73,13 +51,13 @@ describe('fetchAgGenesisCert', () => { }); it('should read a null result as an absent certificate', async () => { - respondWith(rpcResult(null)); + respondWith(null); await expect(fetchAgGenesisCert(URL)).resolves.toEqual({ kind: 'absent' }); }); it('should read a certificate as a completed migration', async () => { - respondWith(rpcResult(CERT)); + respondWith(CERT); await expect(fetchAgGenesisCert(URL)).resolves.toEqual({ cert: { blockId: BLOCK_ID, slot: 460_012_345n }, @@ -91,7 +69,7 @@ describe('fetchAgGenesisCert', () => { ['the dedicated code', { code: -32601, message: 'Method not found' }], ['an internal error naming the method', { code: -32603, message: 'Method not found' }], ])('should read %s as the node not implementing the call', async (_label, error) => { - respondWith(rpcError(error)); + respondWithError(error); await expect(fetchAgGenesisCert(URL)).resolves.toEqual({ kind: 'unsupported' }); }); @@ -99,7 +77,7 @@ describe('fetchAgGenesisCert', () => { // Some providers answer an unsupported method with a 404, and kit throws on the status before // the body is read, so the status is the only signal available. it('should read a 404 as the node not implementing the call', async () => { - respondWith(rpcError({ code: -32603, message: 'Method not found' }), { status: 404 }); + respondWithError({ code: -32603, message: 'Method not found' }, 404); await expect(fetchAgGenesisCert(URL)).resolves.toEqual({ kind: 'unsupported' }); }); @@ -107,14 +85,14 @@ describe('fetchAgGenesisCert', () => { // Some endpoints rate-limit this method alone while still serving others. Retrying makes the // limit worse. it('should return a rate limit as a settled answer rather than throw', async () => { - respondWith(rpcError({ code: 429, message: 'Too many requests' }), { status: 429 }); + respondWithError({ code: 429, message: 'Too many requests' }, 429); await expect(fetchAgGenesisCert(URL)).resolves.toEqual({ kind: 'refused' }); }); // A bare 429 carries no JSON body, so the status is the only signal. it('should return a 429 with an HTML body as a refusal', async () => { - respondWithRaw('rate limited', { status: 429 }); + fetchMock.mockResolvedValueOnce(new Response('rate limited', { status: 429 })); await expect(fetchAgGenesisCert(URL)).resolves.toEqual({ kind: 'refused' }); }); @@ -124,38 +102,38 @@ describe('fetchAgGenesisCert', () => { ['401', 401], ['403', 403], ])('should carry an HTTP %s as a refusal, not a failure', async (_label, status) => { - respondWith(rpcError({ message: 'unauthorized' }), { status }); + respondWithError({ message: 'unauthorized' }, status); await expect(fetchAgGenesisCert(URL)).resolves.toEqual({ kind: 'refused' }); }); // A rate-limited node can still return a cached response, so the status is the stronger signal. it('should prefer a 429 status over a cached response body', async () => { - respondWith(rpcResult(null), { status: 429 }); + respondWith(null, 429); await expect(fetchAgGenesisCert(URL)).resolves.toEqual({ kind: 'refused' }); }); // A rate limit can be raised, unlike an unsupported method. it('should log a refusal but not an unsupported method', async () => { - respondWith(rpcError({ code: 429, message: 'Too many requests' }), { status: 429 }); + respondWithError({ code: 429, message: 'Too many requests' }, 429); await fetchAgGenesisCert(URL); expect(Logger.warn).toHaveBeenCalledWith(expect.stringContaining('refused'), expect.anything()); vi.clearAllMocks(); - respondWith(rpcError({ code: -32601, message: 'Method not found' })); + respondWithError({ code: -32601, message: 'Method not found' }); await fetchAgGenesisCert(URL); expect(Logger.warn).not.toHaveBeenCalled(); }); it('should throw on an RPC error unrelated to the method', async () => { - respondWith(rpcError({ code: -32005, message: 'Node is unhealthy' })); + respondWithError({ code: -32005, message: 'Node is unhealthy' }); await expect(fetchAgGenesisCert(URL)).rejects.toThrow('Node is unhealthy'); }); it('should throw on a 5xx', async () => { - respondWithRaw('', { status: 503 }); + fetchMock.mockResolvedValueOnce(new Response('', { status: 503 })); await expect(fetchAgGenesisCert(URL)).rejects.toThrow('503'); }); @@ -163,20 +141,20 @@ describe('fetchAgGenesisCert', () => { // The node will answer the same way next time, so throwing would spend the retry budget on one // unchanging body. it.each([ - ['a block id the parser refuses', rpcResult({ block: { blockId: [1, 2, 3], slot: 1 } })], - ['a bare string', rpcResult('not-a-cert')], - ['an object with no block', rpcResult({ signature: { bitmap: [], signature: [] } })], - ['an array', rpcResult([1, 2, 3])], - ['no result field at all', { id: '0', jsonrpc: '2.0' }], - ])('should carry an answer that is %s as unreadable, not a failure', async (_label, body) => { - respondWith(body); + ['a block id the parser refuses', { block: { blockId: [1, 2, 3], slot: 1 } }], + ['a bare string', 'not-a-cert'], + ['an object with no block', { signature: { bitmap: [], signature: [] } }], + ['an array', [1, 2, 3]], + ['no result field at all', undefined], + ])('should carry an answer that is %s as unreadable, not a failure', async (_label, result) => { + respondWith(result); await expect(fetchAgGenesisCert(URL)).resolves.toEqual({ kind: 'unreadable' }); }); // Unlike an unsupported method, a malformed certificate is a bug worth logging. it('should record an unreadable certificate', async () => { - respondWith(rpcResult({ block: { blockId: [1, 2, 3], slot: 1 } })); + respondWith({ block: { blockId: [1, 2, 3], slot: 1 } }); await fetchAgGenesisCert(URL); diff --git a/app/features/alpenglow/model/__tests__/use-alpenglow-status.spec.tsx b/app/features/alpenglow/model/__tests__/use-alpenglow-status.spec.tsx index f9a37a74dc..83338783a4 100644 --- a/app/features/alpenglow/model/__tests__/use-alpenglow-status.spec.tsx +++ b/app/features/alpenglow/model/__tests__/use-alpenglow-status.spec.tsx @@ -1,11 +1,11 @@ import { act, renderHook } from '@testing-library/react'; -import { Cluster, ClusterStatus } from '@utils/cluster'; +import { Cluster } from '@utils/cluster'; import { type SWRConfiguration } from 'swr'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { type ClusterContext, - clusterContext, + connectedTo, FAST_RETRY, refocusTab, swrWrapper, @@ -239,7 +239,3 @@ function answerWith(answer: AgGenesisCertAnswer) { function renderStatus(overrides: SWRConfiguration = {}) { return renderHook(() => useAlpenglowStatus(), { wrapper: swrWrapper({ ...FAST_RETRY, ...overrides }) }); } - -function connectedTo(cluster: Cluster, url: string) { - return clusterContext({ cluster, connectableUrl: url, status: ClusterStatus.Connected, url }); -} diff --git a/app/features/alpenglow/ui/__stories__/BaseAlpenglowCard.stories.tsx b/app/features/alpenglow/ui/__stories__/BaseAlpenglowCard.stories.tsx index 37d7ebba67..5625149180 100644 --- a/app/features/alpenglow/ui/__stories__/BaseAlpenglowCard.stories.tsx +++ b/app/features/alpenglow/ui/__stories__/BaseAlpenglowCard.stories.tsx @@ -1,4 +1,4 @@ -import { nextjsParameters, withCluster } from '@storybook-config/decorators'; +import { withCluster } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { Cluster } from '@utils/cluster'; @@ -13,7 +13,6 @@ const MIGRATED: AlpenglowUpgrade = { const meta = { component: BaseAlpenglowCard, decorators: [withCluster], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/Alpenglow/AlpenglowCard', } satisfies Meta; diff --git a/app/features/cluster-switcher/ui/__stories__/ClusterModal.responsive.stories.tsx b/app/features/cluster-switcher/ui/__stories__/ClusterModal.responsive.stories.tsx index 1a147d2f3c..eb9b011b41 100644 --- a/app/features/cluster-switcher/ui/__stories__/ClusterModal.responsive.stories.tsx +++ b/app/features/cluster-switcher/ui/__stories__/ClusterModal.responsive.stories.tsx @@ -1,51 +1,14 @@ -import { useClusterModal } from '@entities/cluster'; -import { - createNextjsParameters, - nextjsParameters, - withClusterModalOpen, - withClusterState, -} from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import { Cluster, ClusterStatus } from '@utils/cluster'; -import React from 'react'; -import type { SavedCluster } from '../../lib/cluster-storage'; import { ClusterModal } from '../ClusterModal'; -import { withSavedClusters } from './switcher-panel'; - -const CUSTOM_URL = 'https://my-node.example/rpc?api-key=not-a-real-key'; - -const SAVED: SavedCluster[] = [ - { name: 'My Local', url: 'http://localhost:8899' }, - { name: 'Staging', url: 'https://staging.example.com/rpc?api-key=not-a-real-key' }, - { - name: 'A cluster name long enough to truncate', - url: 'https://a-deliberately-long-hostname.rpc.provider.example.com:8899', - }, -]; - -function ClusterModalWithReopen() { - const [, setShow] = useClusterModal(); - return ( - <> - - - - ); -} +import * as Base from './ClusterModal.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta = { component: ClusterModal, - decorators: [withClusterModalOpen, withSavedClusters([]), withViewportFromGlobal], - parameters: { - ...nextjsParameters, - docs: { story: { height: INITIAL_VIEWPORTS.ipad.styles.height } }, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [...Base.default.decorators, withViewportFromGlobal], + parameters: Base.default.parameters, tags: ['autodocs', 'test'], title: 'Features/ClusterSwitcher/ClusterModal@Media', } satisfies Meta; @@ -53,7 +16,7 @@ const meta = { export default meta; type Story = StoryObj; -const render = () => ; +const { render } = Base.Default; export const Mobile: Story = { globals: { viewport: { value: 'iphonex' } }, @@ -73,20 +36,8 @@ export const TabletLandscape: Story = { // The tallest the panel gets, on the shortest viewport: the case the scrolling body exists for, since // the developer settings at the bottom stay reachable only because the body scrolls. export const MobileCustomCluster: Story = { - decorators: [ - withClusterState({ - cluster: Cluster.Custom, - customUrl: CUSTOM_URL, - modalOpen: true, - status: ClusterStatus.Connected, - }), - withSavedClusters(SAVED), - ], + decorators: Base.CustomCluster.decorators, globals: { viewport: { value: 'iphonex' } }, - parameters: { - ...createNextjsParameters({ query: { cluster: 'custom', customUrl: CUSTOM_URL } }), - docs: { story: { height: INITIAL_VIEWPORTS.ipad.styles.height } }, - viewport: { options: INITIAL_VIEWPORTS }, - }, - render, + parameters: Base.CustomCluster.parameters, + render: Base.CustomCluster.render, }; diff --git a/app/features/cluster-switcher/ui/__stories__/ClusterModal.stories.tsx b/app/features/cluster-switcher/ui/__stories__/ClusterModal.stories.tsx index 5a73537bd4..ed858ec19b 100644 --- a/app/features/cluster-switcher/ui/__stories__/ClusterModal.stories.tsx +++ b/app/features/cluster-switcher/ui/__stories__/ClusterModal.stories.tsx @@ -1,10 +1,5 @@ import { useClusterModal } from '@entities/cluster'; -import { - createNextjsParameters, - nextjsParameters, - withClusterModalOpen, - withClusterState, -} from '@storybook-config/decorators'; +import { createNextjsParameters, withClusterModalOpen, withClusterState } from '@storybook-config/decorators'; import { INITIAL_VIEWPORTS } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { Cluster, ClusterStatus } from '@utils/cluster'; @@ -49,7 +44,6 @@ const meta = { component: ClusterModal, decorators: [withClusterModalOpen, withSavedClusters([])], parameters: { - ...nextjsParameters, docs: { story: { height: INITIAL_VIEWPORTS.ipad.styles.height } }, }, tags: ['autodocs', 'test'], diff --git a/app/features/cluster-switcher/ui/__stories__/ClusterModalDeveloperSettings.responsive.stories.tsx b/app/features/cluster-switcher/ui/__stories__/ClusterModalDeveloperSettings.responsive.stories.tsx index 3aab67bb3d..9319dc32d1 100644 --- a/app/features/cluster-switcher/ui/__stories__/ClusterModalDeveloperSettings.responsive.stories.tsx +++ b/app/features/cluster-switcher/ui/__stories__/ClusterModalDeveloperSettings.responsive.stories.tsx @@ -1,4 +1,4 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { ClusterModalDeveloperSettings } from '../ClusterModalDeveloperSettings'; @@ -6,9 +6,6 @@ import { ClusterModalDeveloperSettings } from '../ClusterModalDeveloperSettings' const meta = { component: ClusterModalDeveloperSettings, decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Features/ClusterSwitcher/ClusterModalDeveloperSettings@Media', } satisfies Meta; diff --git a/app/features/cookie/ui/__stories__/CookieConsent.stories.tsx b/app/features/cookie/ui/__stories__/CookieConsent.stories.tsx index 84faa9b2e1..ed8cd8160e 100644 --- a/app/features/cookie/ui/__stories__/CookieConsent.stories.tsx +++ b/app/features/cookie/ui/__stories__/CookieConsent.stories.tsx @@ -11,9 +11,6 @@ const meta = { // preview block collapses. Render each story in its own sized iframe so the // card is contained and visible in full per block. docs: { story: { height: '220px', inline: false } }, - nextjs: { - appDirectory: true, - }, }, tags: ['autodocs', 'test'], title: 'Features/Cookie/CookieConsent', diff --git a/app/features/cu-profiling/ui/__tests__/CUProfilingSection.spec.tsx b/app/features/cu-profiling/ui/__tests__/CUProfilingSection.spec.tsx index ea12350527..872b48dbcb 100644 --- a/app/features/cu-profiling/ui/__tests__/CUProfilingSection.spec.tsx +++ b/app/features/cu-profiling/ui/__tests__/CUProfilingSection.spec.tsx @@ -1,8 +1,8 @@ +import { buildParsedTransaction } from '@entities/transaction-data/__fixtures__/parsed-transactions'; import { getBase58Decoder } from '@solana/kit'; import { ComputeBudgetProgram, type ParsedInstruction, - type ParsedTransactionWithMeta, type PartiallyDecodedInstruction, PublicKey, } from '@solana/web3.js'; @@ -201,11 +201,7 @@ function mockTransaction( logLines: string[][], ): void { useProgramIdlNames.mockReturnValue(new Map()); - const transactionWithMeta = { - meta: { computeUnitsConsumed: 405, err: null, logMessages: logLines.flat() }, - slot: SLOT, - transaction: { message: { accountKeys: [], instructions } }, - } as unknown as ParsedTransactionWithMeta; + const transactionWithMeta = buildParsedTransaction({ instructions, logMessages: logLines.flat(), slot: SLOT }); useTransactionDetails.mockReturnValue({ data: { transactionWithMeta } }); } diff --git a/app/features/decode-account-pmp/ui/__fixtures__/pmp-account-fixtures.ts b/app/features/decode-account-pmp/ui/__fixtures__/pmp-account-fixtures.ts index 280964c46a..7d47a633f3 100644 --- a/app/features/decode-account-pmp/ui/__fixtures__/pmp-account-fixtures.ts +++ b/app/features/decode-account-pmp/ui/__fixtures__/pmp-account-fixtures.ts @@ -14,18 +14,13 @@ export { type BufferHeaderOverrides, DOC, DOC_PRETTY, + IDL_DOC, metadataAccountData, pack, } from '@entities/pmp-account/__fixtures__/pmp-account'; export const YAML_DOC = 'name: orbit\nversion: 1.0.0\n'; -export const IDL_DOC = JSON.stringify({ - instructions: [{ name: 'initialize' }], - name: 'company_program', - version: '1.0.0', -}); - /** One byte past the render cap, so unpacking it always lands on the `oversized` arm. */ export const OVERSIZED_DOC = 'x'.repeat(PMP_DECODED_RENDER_CAP_BYTES + 1); diff --git a/app/features/decode-account-pmp/ui/__stories__/BaseBufferAccountCard.stories.tsx b/app/features/decode-account-pmp/ui/__stories__/BaseBufferAccountCard.stories.tsx index 5cbce4bed7..59d36d79ff 100644 --- a/app/features/decode-account-pmp/ui/__stories__/BaseBufferAccountCard.stories.tsx +++ b/app/features/decode-account-pmp/ui/__stories__/BaseBufferAccountCard.stories.tsx @@ -1,6 +1,6 @@ import { gen } from '@__fixtures__/gen'; import { Compression, DataSource, Encoding, Format } from '@solana-program/program-metadata'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { resolveBufferConfigFromBytes } from '../../lib/config-resolution/resolve-buffer-config-from-bytes'; @@ -25,7 +25,6 @@ function bufferArgsFor(body: Uint8Array) { const meta = { component: BaseBufferAccountCard, decorators: [withClusterAndAccounts, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/DecodeAccountPmp/BaseBufferAccountCard', } satisfies Meta; diff --git a/app/features/decode-account-pmp/ui/__stories__/BaseMetadataAccountCard.stories.tsx b/app/features/decode-account-pmp/ui/__stories__/BaseMetadataAccountCard.stories.tsx index 007f1a212e..382ea67872 100644 --- a/app/features/decode-account-pmp/ui/__stories__/BaseMetadataAccountCard.stories.tsx +++ b/app/features/decode-account-pmp/ui/__stories__/BaseMetadataAccountCard.stories.tsx @@ -1,6 +1,6 @@ import { decodePmpPayload } from '@entities/pmp-account'; import { Compression } from '@solana-program/program-metadata'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { gzip } from 'pako'; @@ -30,7 +30,6 @@ function argsFor(raw: Uint8Array) { const meta = { component: BaseMetadataAccountCard, decorators: [withClusterAndAccounts, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/DecodeAccountPmp/BaseMetadataAccountCard', } satisfies Meta; diff --git a/app/features/decode-account-pmp/ui/__stories__/PmpAccountNoticeCard.stories.tsx b/app/features/decode-account-pmp/ui/__stories__/PmpAccountNoticeCard.stories.tsx index cadaf7f676..de7a401ecf 100644 --- a/app/features/decode-account-pmp/ui/__stories__/PmpAccountNoticeCard.stories.tsx +++ b/app/features/decode-account-pmp/ui/__stories__/PmpAccountNoticeCard.stories.tsx @@ -1,5 +1,4 @@ import { PMP_EMPTY_DISCRIMINATOR } from '@entities/pmp-account'; -import { nextjsParameters } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { bufferAccountData, readAs } from '../__fixtures__/pmp-account-fixtures'; @@ -8,7 +7,6 @@ import { PmpAccountNoticeCard } from '../PmpAccountNoticeCard'; // No cluster or token decorators: this card renders alert text only, with no `Address` or `Signature` inside it. const meta = { component: PmpAccountNoticeCard, - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/DecodeAccountPmp/PmpAccountNoticeCard', } satisfies Meta; diff --git a/app/features/decode-account-pmp/ui/__tests__/BaseBufferAccountCard.spec.tsx b/app/features/decode-account-pmp/ui/__tests__/BaseBufferAccountCard.spec.tsx index d933f2a206..e13f965d0f 100644 --- a/app/features/decode-account-pmp/ui/__tests__/BaseBufferAccountCard.spec.tsx +++ b/app/features/decode-account-pmp/ui/__tests__/BaseBufferAccountCard.spec.tsx @@ -17,9 +17,7 @@ import { BaseBufferAccountCard } from '../BaseBufferAccountCard'; // Both render address-shaped links that reach for the active cluster, which has no provider here. The rows under // test are the config enums, so stubbing them keeps this spec to the precedence question. -vi.mock('@components/common/Address', () => ({ - Address: ({ pubkey }: { pubkey: { toBase58(): string } }) =>
{pubkey.toBase58()}
, -})); +vi.mock('@components/common/Address', () => import('@/app/__tests__/address-stub')); vi.mock('@components/common/Signature', () => ({ Signature: ({ signature }: { signature: string }) => {signature}, diff --git a/app/features/decode-account-pmp/ui/__tests__/PmpAccountCard.spec.tsx b/app/features/decode-account-pmp/ui/__tests__/PmpAccountCard.spec.tsx index 905d64c4dd..4fac6da097 100644 --- a/app/features/decode-account-pmp/ui/__tests__/PmpAccountCard.spec.tsx +++ b/app/features/decode-account-pmp/ui/__tests__/PmpAccountCard.spec.tsx @@ -31,9 +31,7 @@ vi.mock('@/app/shared/lib/analytics', async importOriginal => ({ trackEvent: vi.fn(), })); -vi.mock('@components/common/Address', () => ({ - Address: ({ pubkey }: { pubkey: { toBase58(): string } }) =>
{pubkey.toBase58()}
, -})); +vi.mock('@components/common/Address', () => import('@/app/__tests__/address-stub')); vi.mock('@providers/cluster', () => ({ useCluster: () => ({ url: 'https://api.devnet.solana.com' }) })); diff --git a/app/features/decode-instruction-bpf-loader/lib/__tests__/bpf-loader-parser.spec.ts b/app/features/decode-instruction-bpf-loader/lib/__tests__/bpf-loader-parser.spec.ts index da7faef48f..4655edad92 100644 --- a/app/features/decode-instruction-bpf-loader/lib/__tests__/bpf-loader-parser.spec.ts +++ b/app/features/decode-instruction-bpf-loader/lib/__tests__/bpf-loader-parser.spec.ts @@ -3,8 +3,6 @@ import { AccountRole, type Address, address } from '@solana/kit'; import { type ParsedInstruction, PublicKey, TransactionInstruction } from '@solana/web3.js'; import { beforeEach, describe, expect, it, vi } from 'vitest'; -vi.mock('@/app/shared/lib/logger', () => ({ Logger: { error: vi.fn() } })); - import { Logger } from '@/app/shared/lib/logger'; import { bpfLoaderInstructionParser } from '../bpf-loader-client'; diff --git a/app/features/decode-instruction-ed25519/ui/__stories__/Ed25519DetailsCard.responsive.stories.tsx b/app/features/decode-instruction-ed25519/ui/__stories__/Ed25519DetailsCard.responsive.stories.tsx index 0f7ef2ab8f..242881cf4d 100644 --- a/app/features/decode-instruction-ed25519/ui/__stories__/Ed25519DetailsCard.responsive.stories.tsx +++ b/app/features/decode-instruction-ed25519/ui/__stories__/Ed25519DetailsCard.responsive.stories.tsx @@ -1,52 +1,12 @@ -import { instructionDataOf, toInstructionNode, toRawInstructionNode } from '@entities/instruction-card'; -import { createInstructionParserDispatcher, isParsedInstruction } from '@entities/instruction-parser'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; -import { - nextjsParameters, - withCluster, - withMockTransactions, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import { invariant } from '@/app/shared/lib/invariant'; - -import { ed25519InstructionParser } from '../../lib/ed25519-client'; import { Ed25519DetailsCard } from '../Ed25519DetailsCard'; - -const ix = new TransactionInstruction({ - data: Buffer.from('01000c0001004c0001006e008a000100', 'hex'), - keys: [], - programId: new PublicKey('Ed25519SigVerify111111111111111111111111111'), -}); - -const surroundingIx = new TransactionInstruction({ - data: Buffer.alloc(256), - keys: [], - programId: new PublicKey('11111111111111111111111111111111'), -}); - -const siblingData = instructionDataOf( - [ix, surroundingIx].map((instruction, index) => toInstructionNode({ index, ix: instruction })), -); +import * as Base from './Ed25519DetailsCard.stories'; const meta: Meta = { component: Ed25519DetailsCard, - decorators: [ - withCluster, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, - withMockTransactions, - withViewportFromGlobal, - ], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [...Base.default.decorators, withViewportFromGlobal], tags: ['autodocs', 'test'], title: 'Components/Instruction/Ed25519DetailsCard@Media', }; @@ -54,14 +14,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const dispatched = createInstructionParserDispatcher([ed25519InstructionParser]).fromTransactionInstruction(ix); -invariant(isParsedInstruction(dispatched), 'the fixture decodes as an ed25519 instruction'); - -const args = { - node: toRawInstructionNode({ index: 0, ix }), - parsed: dispatched.parsed, - siblingData, -}; +const args = Base.SingleSignature.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/features/decode-instruction-ed25519/ui/__stories__/Ed25519DetailsCard.stories.tsx b/app/features/decode-instruction-ed25519/ui/__stories__/Ed25519DetailsCard.stories.tsx index fd5b70aad2..ee34ea2ef1 100644 --- a/app/features/decode-instruction-ed25519/ui/__stories__/Ed25519DetailsCard.stories.tsx +++ b/app/features/decode-instruction-ed25519/ui/__stories__/Ed25519DetailsCard.stories.tsx @@ -8,14 +8,7 @@ import { } from '@entities/instruction-card'; import { createInstructionParserDispatcher, isParsedInstruction } from '@entities/instruction-parser'; import { PublicKey, TransactionInstruction } from '@solana/web3.js'; -import { - nextjsParameters, - withCluster, - withMockTransactions, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; +import { instructionCardDecorators } from '@storybook-config/decorators'; import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; import { invariant } from '@/app/shared/lib/invariant'; @@ -55,13 +48,12 @@ const withFailedInstructionSurface: Decorator = Story => ( ); -const meta: Meta = { +const meta = { component: Ed25519DetailsCard, - decorators: [withCluster, withScrollAnchor, withTokenInfoBatch, withTxInstructionSurface, withMockTransactions], - parameters: nextjsParameters, + decorators: instructionCardDecorators, tags: ['autodocs', 'test'], title: 'Components/Instruction/Ed25519DetailsCard', -}; +} satisfies Meta; export default meta; type Story = StoryObj; diff --git a/app/features/decode-instruction-lighthouse/ui/__stories__/LighthouseDetailsCard.responsive.stories.tsx b/app/features/decode-instruction-lighthouse/ui/__stories__/LighthouseDetailsCard.responsive.stories.tsx index b2ebfe0a08..9d71abaf14 100644 --- a/app/features/decode-instruction-lighthouse/ui/__stories__/LighthouseDetailsCard.responsive.stories.tsx +++ b/app/features/decode-instruction-lighthouse/ui/__stories__/LighthouseDetailsCard.responsive.stories.tsx @@ -1,56 +1,14 @@ -import { toRawInstructionNode } from '@entities/instruction-card'; -import { PublicKey, type TransactionInstruction } from '@solana/web3.js'; -import { - nextjsParameters, - withCluster, - withMockTransactions, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import { toKitInstruction } from '@/app/shared/lib/web3js-compat'; - -import { LIGHTHOUSE_ADDRESS } from '../../lib/constants'; -import { parseLighthouseInstruction } from '../../lib/lighthouse-parser'; import { LighthouseDetailsCard } from '../LighthouseDetailsCard'; +import * as Base from './LighthouseDetailsCard.stories'; -const raw = { - data: Buffer.from([5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), - keys: [ - { - isSigner: false, - isWritable: false, - pubkey: new PublicKey('AUuYypaXez7kXWWWYecmsb89prMCnba6g2tBWm3BxKQV'), - }, - ], - programId: new PublicKey(LIGHTHOUSE_ADDRESS), -} as unknown as TransactionInstruction; - -const parsed = parseLighthouseInstruction(toKitInstruction(raw)); -if (!parsed) throw new Error('fixture failed to parse as a Lighthouse instruction'); - -const args = { - node: toRawInstructionNode({ index: 0, ix: raw }), - parsed, -}; +const args = Base.AssertAccountInfo.args; const meta: Meta = { component: LighthouseDetailsCard, - decorators: [ - withCluster, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, - withMockTransactions, - withViewportFromGlobal, - ], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [...Base.default.decorators, withViewportFromGlobal], tags: ['autodocs', 'test'], title: 'Components/Instruction/LighthouseDetailsCard@Media', }; diff --git a/app/features/decode-instruction-lighthouse/ui/__stories__/LighthouseDetailsCard.stories.tsx b/app/features/decode-instruction-lighthouse/ui/__stories__/LighthouseDetailsCard.stories.tsx index 510f3d1e9b..8d830ae334 100644 --- a/app/features/decode-instruction-lighthouse/ui/__stories__/LighthouseDetailsCard.stories.tsx +++ b/app/features/decode-instruction-lighthouse/ui/__stories__/LighthouseDetailsCard.stories.tsx @@ -1,13 +1,6 @@ import { toRawInstructionNode } from '@entities/instruction-card'; import { PublicKey, type TransactionInstruction } from '@solana/web3.js'; -import { - nextjsParameters, - withCluster, - withMockTransactions, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; +import { instructionCardDecorators } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { toKitInstruction } from '@/app/shared/lib/web3js-compat'; @@ -48,13 +41,12 @@ const assertAccountInfoIx = { programId: new PublicKey(LIGHTHOUSE_ADDRESS), } as unknown as TransactionInstruction; -const meta: Meta = { +const meta = { component: LighthouseDetailsCard, - decorators: [withCluster, withScrollAnchor, withTokenInfoBatch, withTxInstructionSurface, withMockTransactions], - parameters: nextjsParameters, + decorators: instructionCardDecorators, tags: ['autodocs', 'test'], title: 'Components/Instruction/LighthouseDetailsCard', -}; +} satisfies Meta; export default meta; type Story = StoryObj; diff --git a/app/features/decode-instruction-lighthouse/ui/__tests__/LighthouseDetailsCard.test.tsx b/app/features/decode-instruction-lighthouse/ui/__tests__/LighthouseDetailsCard.test.tsx index a63032f785..c8b13d1de6 100644 --- a/app/features/decode-instruction-lighthouse/ui/__tests__/LighthouseDetailsCard.test.tsx +++ b/app/features/decode-instruction-lighthouse/ui/__tests__/LighthouseDetailsCard.test.tsx @@ -17,11 +17,7 @@ import { LIGHTHOUSE_ADDRESS } from '../../lib/constants'; import { parseLighthouseInstruction } from '../../lib/lighthouse-parser'; import { LighthouseDetailsCard } from '../LighthouseDetailsCard'; -vi.mock('@/app/components/common/Address', () => ({ - Address: ({ pubkey, fallbackText }: { pubkey: PublicKey; fallbackText?: string }) => ( -
{fallbackText ?? pubkey.toBase58()}
- ), -})); +vi.mock('@/app/components/common/Address', () => import('@/app/__tests__/address-stub')); vi.mock('@/app/components/common/Copyable', () => ({ Copyable: ({ text, children }: { text: string; children: React.ReactNode }) => ( diff --git a/app/features/decode-instruction-pmp/lib/__tests__/decode-pmp-instruction.spec.ts b/app/features/decode-instruction-pmp/lib/__tests__/decode-pmp-instruction.spec.ts index 477a56dd2f..ef98dcd116 100644 --- a/app/features/decode-instruction-pmp/lib/__tests__/decode-pmp-instruction.spec.ts +++ b/app/features/decode-instruction-pmp/lib/__tests__/decode-pmp-instruction.spec.ts @@ -1,5 +1,6 @@ import { gen } from '@__fixtures__/gen'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; +import { makeInstruction } from '@__fixtures__/instruction'; +import { PublicKey } from '@solana/web3.js'; import { Compression, DataSource, @@ -21,13 +22,7 @@ const FOREIGN_BUFFER = gen.publicKey(1); const METADATA_PDA = gen.publicKey(2); const DOC_BYTES = new TextEncoder().encode('{"name":"company"}'); -function makeIx(data: Uint8Array, accounts: PublicKey[] = []): TransactionInstruction { - return new TransactionInstruction({ - data: Buffer.from(data), - keys: accounts.map(pubkey => ({ isSigner: false, isWritable: false, pubkey })), - programId: PMP, - }); -} +const makeIx = (data: Uint8Array, keys?: PublicKey[]) => makeInstruction({ data, keys, programId: PMP }); describe('isProgramMetadataInstruction', () => { it('should accept an instruction targeting the PMP program', () => { @@ -35,11 +30,7 @@ describe('isProgramMetadataInstruction', () => { }); it('should reject an instruction targeting another program', () => { - const ix = new TransactionInstruction({ - data: Buffer.from([0]), - keys: [], - programId: PublicKey.default, - }); + const ix = makeInstruction({ data: [0], programId: PublicKey.default }); expect(isProgramMetadataInstruction(ix)).toBe(false); }); diff --git a/app/features/decode-instruction-pmp/ui/__stories__/PmpDetailsCard.stories.tsx b/app/features/decode-instruction-pmp/ui/__stories__/PmpDetailsCard.stories.tsx index 2049c978c0..16b7f81fe4 100644 --- a/app/features/decode-instruction-pmp/ui/__stories__/PmpDetailsCard.stories.tsx +++ b/app/features/decode-instruction-pmp/ui/__stories__/PmpDetailsCard.stories.tsx @@ -1,52 +1,33 @@ import { gen } from '@__fixtures__/gen'; +import { makeInstruction } from '@__fixtures__/instruction'; import { toRawInstructionNode } from '@entities/instruction-card'; +import { bufferAccountData, IDL_DOC, pack } from '@entities/pmp-account/__fixtures__/pmp-account'; import { PmpDetailsCard } from '@features/decode-instruction-pmp'; import type { Account, State } from '@providers/accounts'; import { FetchStatus } from '@providers/cache'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; +import { PublicKey, type TransactionInstruction } from '@solana/web3.js'; import { Compression, DataSource, Encoding, Format, - getBufferEncoder, getInitializeInstructionDataEncoder, getSetDataInstructionDataEncoder, getWriteInstructionDataEncoder, packDirectData, PROGRAM_METADATA_PROGRAM_ADDRESS, } from '@solana-program/program-metadata'; -import { - nextjsParameters, - withCluster, - withMockTransactions, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; +import { instructionCardDecorators } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { gzip } from 'pako'; const PROGRAM_ID = new PublicKey(PROGRAM_METADATA_PROGRAM_ADDRESS); -const IDL_DOC = JSON.stringify({ - instructions: [{ name: 'initialize' }], - name: 'company_program', - version: '1.0.0', -}); - // Account addresses are labelled positionally from the card's static name table, so any keys work here. Seeded // so the rendered addresses stay pixel-stable across runs. -function makeIx(data: Uint8Array, accountCount: number): TransactionInstruction { - return new TransactionInstruction({ - data: Buffer.from(data), - keys: Array.from({ length: accountCount }, (_, index) => ({ - isSigner: false, - isWritable: true, - pubkey: gen.publicKey(index), - })), - programId: PROGRAM_ID, - }); +function makeIx(data: Uint8Array, accountCount: number) { + const keys = Array.from({ length: accountCount }, (_, index) => gen.publicKey(index)); + return makeInstruction({ data, keys, programId: PROGRAM_ID, writable: true }); } function setDataIx({ @@ -75,8 +56,7 @@ function setDataIx({ const meta = { component: PmpDetailsCard, - decorators: [withCluster, withScrollAnchor, withTokenInfoBatch, withTxInstructionSurface, withMockTransactions], - parameters: nextjsParameters, + decorators: instructionCardDecorators, tags: ['autodocs', 'test'], title: 'Features/DecodeInstructionPmp/PmpDetailsCard', } satisfies Meta; @@ -251,16 +231,8 @@ function setDataFromBufferIx({ compression, format }: { compression: Compression return ix; } -/** The library's own encoder, so the fixture carries the real 96-byte Buffer header. */ function bufferAccountEntry(content: string, compression: Compression): State['entries'] { - const packed = packDirectData({ compression, content, encoding: Encoding.Utf8 }); - const raw = getBufferEncoder().encode({ - authority: PROGRAM_METADATA_PROGRAM_ADDRESS, - canonical: true, - data: packed.data, - program: PROGRAM_METADATA_PROGRAM_ADDRESS, - seed: 'idl', - }) as Uint8Array; + const raw = bufferAccountData(pack(content, compression)); const data: Account = { data: { raw }, diff --git a/app/features/decode-instruction-pmp/ui/__tests__/PmpDetailsCard.payload.spec.tsx b/app/features/decode-instruction-pmp/ui/__tests__/PmpDetailsCard.payload.spec.tsx index 0e5698b0ac..b7f12e3bab 100644 --- a/app/features/decode-instruction-pmp/ui/__tests__/PmpDetailsCard.payload.spec.tsx +++ b/app/features/decode-instruction-pmp/ui/__tests__/PmpDetailsCard.payload.spec.tsx @@ -50,9 +50,7 @@ vi.mock('@providers/accounts', () => ({ useFetchAccountInfo: () => mockFetchAccountInfo, })); -vi.mock('@/app/components/common/Address', () => ({ - Address: ({ pubkey }: { pubkey: { toBase58(): string } }) =>
{pubkey.toBase58()}
, -})); +vi.mock('@/app/components/common/Address', () => import('@/app/__tests__/address-stub')); const STUB_SURFACE: InstructionSurface = { Card: () => undefined, diff --git a/app/features/decode-instruction-pmp/ui/__tests__/PmpDetailsCard.spec.tsx b/app/features/decode-instruction-pmp/ui/__tests__/PmpDetailsCard.spec.tsx index 27a8bd63d7..943e08dba2 100644 --- a/app/features/decode-instruction-pmp/ui/__tests__/PmpDetailsCard.spec.tsx +++ b/app/features/decode-instruction-pmp/ui/__tests__/PmpDetailsCard.spec.tsx @@ -1,4 +1,5 @@ import { gen } from '@__fixtures__/gen'; +import { makeInstruction } from '@__fixtures__/instruction'; import { InstructionNodeCard } from '@components/instruction/InstructionNodeCard'; import { inspectorSurface, @@ -35,11 +36,7 @@ vi.mock('../../lib/decode-pmp-instruction', async importOriginal => { return { decodePmpContentInstruction: vi.fn(actual.decodePmpContentInstruction) }; }); -vi.mock('@/app/components/common/Address', () => ({ - Address: ({ pubkey, fallbackText }: { pubkey: PublicKey; fallbackText?: string }) => ( -
{fallbackText ?? pubkey.toBase58()}
- ), -})); +vi.mock('@/app/components/common/Address', () => import('@/app/__tests__/address-stub')); vi.mock('@/app/components/common/Copyable', () => ({ Copyable: ({ children }: { children: React.ReactNode }) =>
{children}
, @@ -51,13 +48,7 @@ const FOREIGN_BUFFER = gen.publicKey(1); const METADATA_PDA = gen.publicKey(2); const DOC = '{"name":"company","version":"1.0.0"}'; -function makeIx(data: Uint8Array, accounts: PublicKey[]): TransactionInstruction { - return new TransactionInstruction({ - data: Buffer.from(data), - keys: accounts.map(pubkey => ({ isSigner: false, isWritable: true, pubkey })), - programId: PMP, - }); -} +const makeIx = (data: Uint8Array, keys: PublicKey[]) => makeInstruction({ data, keys, programId: PMP, writable: true }); const SURFACE: InstructionSurface = { ...inspectorSurface({ Card: InstructionNodeCard, instructionData: () => undefined }), diff --git a/app/features/decode-instruction-sas/lib/__tests__/sas-parser.spec.ts b/app/features/decode-instruction-sas/lib/__tests__/sas-parser.spec.ts index 341cbf4ba8..6a590c4968 100644 --- a/app/features/decode-instruction-sas/lib/__tests__/sas-parser.spec.ts +++ b/app/features/decode-instruction-sas/lib/__tests__/sas-parser.spec.ts @@ -1,6 +1,7 @@ +import { makeInstruction } from '@__fixtures__/instruction'; import { createInstructionParserDispatcher, isParsedInstruction } from '@entities/instruction-parser'; import { AccountRole, type Address, address } from '@solana/kit'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; +import { PublicKey } from '@solana/web3.js'; import { describe, expect, it } from 'vitest'; import { solanaAttestationInstructionParser } from '../sas-client'; @@ -74,9 +75,6 @@ describe('solanaAttestationInstructionParser', () => { }); function transactionInstruction(data: Uint8Array, accounts: Address[]) { - return new TransactionInstruction({ - data: Buffer.from(data), - keys: accounts.map(account => ({ isSigner: false, isWritable: false, pubkey: new PublicKey(account) })), - programId: new PublicKey(SOLANA_ATTESTATION_SERVICE_PROGRAM_ADDRESS), - }); + const keys = accounts.map(account => new PublicKey(account)); + return makeInstruction({ data, keys, programId: SOLANA_ATTESTATION_SERVICE_PROGRAM_ADDRESS }); } diff --git a/app/features/decode-instruction-sas/ui/__stories__/SolanaAttestationDetailsCard.responsive.stories.tsx b/app/features/decode-instruction-sas/ui/__stories__/SolanaAttestationDetailsCard.responsive.stories.tsx index 116eed8d44..cd45161308 100644 --- a/app/features/decode-instruction-sas/ui/__stories__/SolanaAttestationDetailsCard.responsive.stories.tsx +++ b/app/features/decode-instruction-sas/ui/__stories__/SolanaAttestationDetailsCard.responsive.stories.tsx @@ -1,51 +1,12 @@ -import { gen } from '@__fixtures__/gen'; -import { toRawInstructionNode } from '@entities/instruction-card'; -import { createInstructionParserDispatcher, isParsedInstruction } from '@entities/instruction-parser'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; -import { - nextjsParameters, - withCluster, - withMockTransactions, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import { solanaAttestationInstructionParser } from '../../lib/sas-client'; import { SolanaAttestationDetailsCard } from '../SolanaAttestationDetailsCard'; - -// CreateCredential data layout: u8 discriminator + u32 name length + u32 signers length (9 bytes -// minimum for empty values). Requires 4 accounts (payer, credential, authority, systemProgram). -const raw = new TransactionInstruction({ - data: Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0]), - keys: [ - { isSigner: true, isWritable: true, pubkey: gen.publicKey(1) }, - { isSigner: false, isWritable: true, pubkey: gen.publicKey(2) }, - { isSigner: true, isWritable: false, pubkey: gen.publicKey(3) }, - { isSigner: false, isWritable: false, pubkey: new PublicKey('11111111111111111111111111111111') }, - ], - programId: new PublicKey('22zoJMtdu4tQc2PzL74ZUT7FrwgB1Udec8DdW4yw4BdG'), -}); -const dispatched = createInstructionParserDispatcher([solanaAttestationInstructionParser]).fromTransactionInstruction( - raw, -); +import * as Base from './SolanaAttestationDetailsCard.stories'; const meta: Meta = { component: SolanaAttestationDetailsCard, - decorators: [ - withCluster, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, - withMockTransactions, - withViewportFromGlobal, - ], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [...Base.default.decorators, withViewportFromGlobal], tags: ['autodocs', 'test'], title: 'Features/DecodeInstructionSas/SolanaAttestationDetailsCard@Media', }; @@ -53,10 +14,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - node: toRawInstructionNode({ index: 0, ix: raw }), - parsed: isParsedInstruction(dispatched) ? dispatched.parsed : undefined, -}; +const args = Base.Default.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/features/decode-instruction-sas/ui/__stories__/SolanaAttestationDetailsCard.stories.tsx b/app/features/decode-instruction-sas/ui/__stories__/SolanaAttestationDetailsCard.stories.tsx index 244becd8f6..8334193a1d 100644 --- a/app/features/decode-instruction-sas/ui/__stories__/SolanaAttestationDetailsCard.stories.tsx +++ b/app/features/decode-instruction-sas/ui/__stories__/SolanaAttestationDetailsCard.stories.tsx @@ -2,14 +2,7 @@ import { gen } from '@__fixtures__/gen'; import { toRawInstructionNode } from '@entities/instruction-card'; import { createInstructionParserDispatcher, isParsedInstruction } from '@entities/instruction-parser'; import { PublicKey, TransactionInstruction } from '@solana/web3.js'; -import { - nextjsParameters, - withCluster, - withMockTransactions, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; +import { instructionCardDecorators } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { solanaAttestationInstructionParser } from '../../lib/sas-client'; @@ -32,13 +25,12 @@ const dispatched = createInstructionParserDispatcher([solanaAttestationInstructi raw, ); -const meta: Meta = { +const meta = { component: SolanaAttestationDetailsCard, - decorators: [withCluster, withScrollAnchor, withTokenInfoBatch, withTxInstructionSurface, withMockTransactions], - parameters: nextjsParameters, + decorators: instructionCardDecorators, tags: ['autodocs', 'test'], title: 'Features/DecodeInstructionSas/SolanaAttestationDetailsCard', -}; +} satisfies Meta; export default meta; type Story = StoryObj; diff --git a/app/features/decode-instruction-sas/ui/__tests__/SolanaAttestationDetailsCard.spec.tsx b/app/features/decode-instruction-sas/ui/__tests__/SolanaAttestationDetailsCard.spec.tsx index 163056ef98..ce4b5ed012 100644 --- a/app/features/decode-instruction-sas/ui/__tests__/SolanaAttestationDetailsCard.spec.tsx +++ b/app/features/decode-instruction-sas/ui/__tests__/SolanaAttestationDetailsCard.spec.tsx @@ -1,4 +1,5 @@ import { gen } from '@__fixtures__/gen'; +import { makeInstruction } from '@__fixtures__/instruction'; import { toRawInstructionNode } from '@entities/instruction-card'; import { createInstructionParserDispatcher, isParsedInstruction } from '@entities/instruction-parser'; import { PublicKey, TransactionInstruction } from '@solana/web3.js'; @@ -122,14 +123,9 @@ describe('SolanaAttestationDetailsCard', () => { }); }); -function sasInstruction(data: number[], accountCount: number): TransactionInstruction { - const keys = [...ACCOUNTS, SYSTEM_PROGRAM].slice(0, accountCount).map(pubkey => ({ - isSigner: false, - isWritable: false, - pubkey: new PublicKey(pubkey), - })); - - return new TransactionInstruction({ data: Buffer.from(data), keys, programId: SAS_PROGRAM_ID }); +function sasInstruction(data: number[], accountCount: number) { + const keys = [...ACCOUNTS, SYSTEM_PROGRAM].slice(0, accountCount).map(pubkey => new PublicKey(pubkey)); + return makeInstruction({ data, keys, programId: SAS_PROGRAM_ID }); } function renderCard(raw: TransactionInstruction, dispatched = dispatcher.fromTransactionInstruction(raw)) { diff --git a/app/features/decode-instruction-with-idl/__fixtures__/anchor-programs.ts b/app/features/decode-instruction-with-idl/__fixtures__/anchor-programs.ts new file mode 100644 index 0000000000..5e46535118 --- /dev/null +++ b/app/features/decode-instruction-with-idl/__fixtures__/anchor-programs.ts @@ -0,0 +1,14 @@ +import { gen } from '@__fixtures__/gen'; +import { makeInstruction } from '@__fixtures__/instruction'; +import { type Idl, Program } from '@coral-xyz/anchor'; +import anchor030Devi from '@entities/idl/mocks/anchor/anchor-0.30.1-devi51mZmdwUJGU9hjN27vEz64Gps7uUefqxg27EAtH.json'; +import { getProvider } from '@entities/idl/model/anchor/anchor-provider'; + +export const ammV3Program = new Program(anchor030Devi as Idl, getProvider('https://api.devnet.solana.com')); + +// update_reward_infos has no args and one pool_state account, so it is the smallest instruction to decode. +export const UPDATE_REWARD_INFOS_DISCRIMINATOR = [163, 172, 224, 52, 11, 154, 106, 223]; + +export function ammV3Instruction(data: Uint8Array | number[], key = gen.publicKey(1)) { + return makeInstruction({ data, keys: [key], programId: ammV3Program.programId, writable: true }); +} diff --git a/app/features/decode-instruction-with-idl/lib/__tests__/decode-anchor-instruction.spec.ts b/app/features/decode-instruction-with-idl/lib/__tests__/decode-anchor-instruction.spec.ts index cbcc9f83f2..83252f30d8 100644 --- a/app/features/decode-instruction-with-idl/lib/__tests__/decode-anchor-instruction.spec.ts +++ b/app/features/decode-instruction-with-idl/lib/__tests__/decode-anchor-instruction.spec.ts @@ -1,38 +1,11 @@ -import { AnchorProvider, Idl, Program } from '@coral-xyz/anchor'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; import { describe, expect, it } from 'vitest'; -import anchor030Devi from '@/app/entities/idl/mocks/anchor/anchor-0.30.1-devi51mZmdwUJGU9hjN27vEz64Gps7uUefqxg27EAtH.json'; - +import { ammV3Instruction, ammV3Program, UPDATE_REWARD_INFOS_DISCRIMINATOR } from '../../__fixtures__/anchor-programs'; import { decodeAnchorInstruction } from '../decode-anchor-instruction'; -// A real Program built from the bundled amm_v3 IDL fixture; the provider is a noop because decoding only -// touches the IDL + Borsh coders, never the network. -const noopWallet = { - publicKey: PublicKey.default, - signAllTransactions: async (txs: T[]) => txs, - signTransaction: async (tx: T) => tx, -}; -const mockProvider = { - connection: { commitment: 'confirmed', rpcEndpoint: 'https://api.devnet.solana.com' }, - opts: { preflightCommitment: 'confirmed' }, - wallet: noopWallet, -} as unknown as AnchorProvider; -const anchorProgram = new Program(anchor030Devi as Idl, mockProvider); - -// update_reward_infos: empty args + a single pool_state account — smallest reproducible instruction. -const UPDATE_REWARD_INFOS_DISCRIMINATOR = Uint8Array.from([163, 172, 224, 52, 11, 154, 106, 223]); - -const buildInstruction = (data: Uint8Array) => - new TransactionInstruction({ - data: Buffer.from(data), - keys: [{ isSigner: false, isWritable: true, pubkey: PublicKey.unique() }], - programId: anchorProgram.programId, - }); - describe('decodeAnchorInstruction', () => { it('should decode a known instruction into its name, definition, accounts, and title', () => { - const decoded = decodeAnchorInstruction(anchorProgram, buildInstruction(UPDATE_REWARD_INFOS_DISCRIMINATOR)); + const decoded = decodeAnchorInstruction(ammV3Program, ammV3Instruction(UPDATE_REWARD_INFOS_DISCRIMINATOR)); expect(decoded.decodedIxData).toBeDefined(); expect(decoded.ixDef).toBeDefined(); @@ -44,7 +17,7 @@ describe('decodeAnchorInstruction', () => { }); it('should leave the decode fields undefined for bytes that match no discriminator', () => { - const decoded = decodeAnchorInstruction(anchorProgram, buildInstruction(new Uint8Array(8))); + const decoded = decodeAnchorInstruction(ammV3Program, ammV3Instruction(new Uint8Array(8))); expect(decoded.decodedIxData).toBeUndefined(); expect(decoded.ixAccounts).toBeUndefined(); diff --git a/app/features/decode-instruction-with-idl/ui/__stories__/AnchorDetailsCard.responsive.stories.tsx b/app/features/decode-instruction-with-idl/ui/__stories__/AnchorDetailsCard.responsive.stories.tsx index 5afba220d9..0bad2ceb81 100644 --- a/app/features/decode-instruction-with-idl/ui/__stories__/AnchorDetailsCard.responsive.stories.tsx +++ b/app/features/decode-instruction-with-idl/ui/__stories__/AnchorDetailsCard.responsive.stories.tsx @@ -1,48 +1,13 @@ -import { gen } from '@__fixtures__/gen'; -import { AnchorProvider, Idl, Program } from '@coral-xyz/anchor'; -import { toRawInstructionNode } from '@entities/instruction-card'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; -import { - nextjsParameters, - withMockTransactions, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import anchor030Devi from '@/app/entities/idl/mocks/anchor/anchor-0.30.1-devi51mZmdwUJGU9hjN27vEz64Gps7uUefqxg27EAtH.json'; - -import { decodeAnchorInstruction } from '../../lib/decode-anchor-instruction'; import { AnchorDetailsCard } from '../AnchorDetailsCard'; - -const url = 'https://api.devnet.solana.com'; -const noopWallet = { - publicKey: PublicKey.default, - signAllTransactions: async (txs: T[]) => txs, - signTransaction: async (tx: T) => tx, -}; -const mockProvider = { - connection: { commitment: 'confirmed', rpcEndpoint: url }, - opts: { preflightCommitment: 'confirmed' }, - wallet: noopWallet, -} as unknown as AnchorProvider; -const anchorProgram = new Program(anchor030Devi as Idl, mockProvider); - -const ix = new TransactionInstruction({ - data: Buffer.from([163, 172, 224, 52, 11, 154, 106, 223]), - keys: [{ isSigner: false, isWritable: true, pubkey: gen.publicKey(1) }], - programId: anchorProgram.programId, -}); +import * as Base from './AnchorDetailsCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta = { component: AnchorDetailsCard, - decorators: [withTxInstructionSurface, withMockTransactions, withTokenInfoBatch, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [...Base.default.decorators, withViewportFromGlobal], tags: ['autodocs', 'test'], // TODO(decode-instruction-with-idl): rename to a feature-scoped title once the Storybook tree migration off // the Dashkit layout lands; kept stable here to avoid churning the tree mid-move. @@ -52,11 +17,7 @@ const meta = { export default meta; type Story = StoryObj; -const args = { - decoded: decodeAnchorInstruction(anchorProgram, ix), - node: toRawInstructionNode({ index: 0, ix }), - program: anchorProgram, -}; +const args = Base.UpdateRewardInfos.args; export const Mobile: Story = { args, diff --git a/app/features/decode-instruction-with-idl/ui/__stories__/AnchorDetailsCard.stories.tsx b/app/features/decode-instruction-with-idl/ui/__stories__/AnchorDetailsCard.stories.tsx index 53f7032570..b37bdb1d45 100644 --- a/app/features/decode-instruction-with-idl/ui/__stories__/AnchorDetailsCard.stories.tsx +++ b/app/features/decode-instruction-with-idl/ui/__stories__/AnchorDetailsCard.stories.tsx @@ -1,50 +1,15 @@ import { gen } from '@__fixtures__/gen'; -import { AnchorProvider, Idl, Program } from '@coral-xyz/anchor'; import { toRawInstructionNode } from '@entities/instruction-card'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; -import { - nextjsParameters, - withMockTransactions, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; +import { instructionCardDecorators } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import anchor030Devi from '@/app/entities/idl/mocks/anchor/anchor-0.30.1-devi51mZmdwUJGU9hjN27vEz64Gps7uUefqxg27EAtH.json'; - +import { ammV3Instruction, ammV3Program, UPDATE_REWARD_INFOS_DISCRIMINATOR } from '../../__fixtures__/anchor-programs'; import { decodeAnchorInstruction } from '../../lib/decode-anchor-instruction'; import { AnchorDetailsCard } from '../AnchorDetailsCard'; -// Construct a real Anchor Program instance from the bundled amm_v3 IDL fixture; the AccountInfo -// fetches inside the card no-op because the storybook accounts fetcher is a noop, but the BorshInstructionCoder -// can decode synthetic instruction data built from the IDL discriminators below. -const url = 'https://api.devnet.solana.com'; -const noopWallet = { - publicKey: PublicKey.default, - signAllTransactions: async (txs: T[]) => txs, - signTransaction: async (tx: T) => tx, -}; -const mockProvider = { - connection: { commitment: 'confirmed', rpcEndpoint: url }, - opts: { preflightCommitment: 'confirmed' }, - wallet: noopWallet, -} as unknown as AnchorProvider; -const anchorProgram = new Program(anchor030Devi as Idl, mockProvider); - -// update_reward_infos has empty args + a single pool_state account — smallest reproducible instruction. -const UPDATE_REWARD_INFOS_DISCRIMINATOR = Uint8Array.from([163, 172, 224, 52, 11, 154, 106, 223]); - -const buildInstruction = (data: Uint8Array, keys: PublicKey[]) => - new TransactionInstruction({ - data: Buffer.from(data), - keys: keys.map(pubkey => ({ isSigner: false, isWritable: true, pubkey })), - programId: anchorProgram.programId, - }); - const meta = { component: AnchorDetailsCard, - decorators: [withTxInstructionSurface, withMockTransactions, withTokenInfoBatch], - parameters: nextjsParameters, + decorators: instructionCardDecorators, tags: ['autodocs', 'test'], // TODO(decode-instruction-with-idl): rename to a feature-scoped title once the Storybook tree migration off // the Dashkit layout lands; kept stable here to avoid churning the tree mid-move. @@ -54,21 +19,21 @@ const meta = { export default meta; type Story = StoryObj; -const updateRewardInfosIx = buildInstruction(UPDATE_REWARD_INFOS_DISCRIMINATOR, [gen.publicKey(1)]); +const updateRewardInfosIx = ammV3Instruction(UPDATE_REWARD_INFOS_DISCRIMINATOR); export const UpdateRewardInfos: Story = { args: { - decoded: decodeAnchorInstruction(anchorProgram, updateRewardInfosIx), + decoded: decodeAnchorInstruction(ammV3Program, updateRewardInfosIx), node: toRawInstructionNode({ index: 0, ix: updateRewardInfosIx }), - program: anchorProgram, + program: ammV3Program, }, }; // Synthetic data matches no known discriminator, so the card renders the "Failed to decode" row. -const failedToDecodeIx = buildInstruction(new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]), [gen.publicKey(2)]); +const failedToDecodeIx = ammV3Instruction([0, 0, 0, 0, 0, 0, 0, 0], gen.publicKey(2)); export const FailedToDecode: Story = { args: { - decoded: decodeAnchorInstruction(anchorProgram, failedToDecodeIx), + decoded: decodeAnchorInstruction(ammV3Program, failedToDecodeIx), node: toRawInstructionNode({ index: 1, ix: failedToDecodeIx }), - program: anchorProgram, + program: ammV3Program, }, }; diff --git a/app/features/decode-instruction-with-idl/ui/__stories__/CodamaInstructionCard.responsive.stories.tsx b/app/features/decode-instruction-with-idl/ui/__stories__/CodamaInstructionCard.responsive.stories.tsx index c339b0a33d..a924f5c19b 100644 --- a/app/features/decode-instruction-with-idl/ui/__stories__/CodamaInstructionCard.responsive.stories.tsx +++ b/app/features/decode-instruction-with-idl/ui/__stories__/CodamaInstructionCard.responsive.stories.tsx @@ -1,40 +1,12 @@ -import { toRawInstructionNode } from '@entities/instruction-card'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; -import { - nextjsParameters, - withCluster, - withMockTransactions, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { CodamaInstructionCard } from '../CodamaInstructionCard'; - -const sampleIx = new TransactionInstruction({ - data: Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]), - keys: [{ isSigner: true, isWritable: true, pubkey: new PublicKey('11111111111111111111111111111111') }], - programId: new PublicKey('CodamaProgramx111111111111111111111111111x1'), -}); - -const fallbackParsedIx = { path: [{ kind: 'unknownNode' }] } as any; +import * as Base from './CodamaInstructionCard.stories'; const meta: Meta = { component: CodamaInstructionCard, - decorators: [ - withCluster, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, - withMockTransactions, - withViewportFromGlobal, - ], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [...Base.default.decorators, withViewportFromGlobal], tags: ['autodocs', 'test'], // TODO(decode-instruction-with-idl): rename to a feature-scoped title once the Storybook tree migration off // the Dashkit layout lands; kept stable here to avoid churning the tree mid-move. @@ -44,7 +16,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { node: toRawInstructionNode({ index: 0, ix: sampleIx }), parsedIx: fallbackParsedIx }; +const args = Base.UnknownFallback.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/features/decode-instruction-with-idl/ui/__stories__/CodamaInstructionCard.stories.tsx b/app/features/decode-instruction-with-idl/ui/__stories__/CodamaInstructionCard.stories.tsx index 4d8f2c9c74..85636c8708 100644 --- a/app/features/decode-instruction-with-idl/ui/__stories__/CodamaInstructionCard.stories.tsx +++ b/app/features/decode-instruction-with-idl/ui/__stories__/CodamaInstructionCard.stories.tsx @@ -1,13 +1,6 @@ import { toRawInstructionNode } from '@entities/instruction-card'; import { PublicKey, TransactionInstruction } from '@solana/web3.js'; -import { - nextjsParameters, - withCluster, - withMockTransactions, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; +import { instructionCardDecorators } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { CodamaInstructionCard } from '../CodamaInstructionCard'; @@ -26,15 +19,14 @@ const sampleIx = new TransactionInstruction({ // parsedIx routes through the UnknownDetailsCard fallback inside CodamaInstructionCard. const fallbackParsedIx = { path: [{ kind: 'unknownNode' }] } as any; -const meta: Meta = { +const meta = { component: CodamaInstructionCard, - decorators: [withCluster, withScrollAnchor, withTokenInfoBatch, withTxInstructionSurface, withMockTransactions], - parameters: nextjsParameters, + decorators: instructionCardDecorators, tags: ['autodocs', 'test'], // TODO(decode-instruction-with-idl): rename to a feature-scoped title once the Storybook tree migration off // the Dashkit layout lands; kept stable here to avoid churning the tree mid-move. title: 'Components/Instruction/CodamaInstructionDetailsCard', -}; +} satisfies Meta; export default meta; type Story = StoryObj; diff --git a/app/features/decode-instruction-with-idl/ui/__stories__/IdlInstructionCard.stories.tsx b/app/features/decode-instruction-with-idl/ui/__stories__/IdlInstructionCard.stories.tsx index 1fa09a3e8b..0a847d7d53 100644 --- a/app/features/decode-instruction-with-idl/ui/__stories__/IdlInstructionCard.stories.tsx +++ b/app/features/decode-instruction-with-idl/ui/__stories__/IdlInstructionCard.stories.tsx @@ -1,21 +1,16 @@ +import { gen } from '@__fixtures__/gen'; +import { makeInstruction } from '@__fixtures__/instruction'; // Repo's stored PMP Codama IDL mock (not kept in sync with the published IDL) — drives the real decode path. import pmpIdl from '@entities/idl/mocks/codama/codama-1.0.0-ProgM6JCCvbYkfKqJYHePx4xxSUSqJp7rh8Lyv7nk7S.json'; import { toRawInstructionNode } from '@entities/instruction-card'; import { address } from '@solana/kit'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; +import { PublicKey } from '@solana/web3.js'; import { getAllocateInstructionDataEncoder, getSetAuthorityInstructionDataEncoder, PROGRAM_METADATA_PROGRAM_ADDRESS, } from '@solana-program/program-metadata'; -import { - nextjsParameters, - withCluster, - withMockTransactions, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; +import { instructionCardDecorators } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; @@ -27,22 +22,14 @@ const url = 'https://api.devnet.solana.com'; // Account names are resolved from the IDL by position, so any keys work — only the count and the // (real) instruction data matter for decoding. -function makeIx(data: Buffer, accountCount: number): TransactionInstruction { - return new TransactionInstruction({ - data, - keys: Array.from({ length: accountCount }, () => ({ - isSigner: false, - isWritable: false, - pubkey: PublicKey.unique(), - })), - programId: PROGRAM_ID, - }); +function makeIx(data: Buffer, accountCount: number) { + const keys = Array.from({ length: accountCount }, (_, index) => gen.publicKey(index)); + return makeInstruction({ data, keys, programId: PROGRAM_ID }); } const meta = { component: IdlInstructionCard, - decorators: [withCluster, withScrollAnchor, withTokenInfoBatch, withTxInstructionSurface, withMockTransactions], - parameters: nextjsParameters, + decorators: instructionCardDecorators, tags: ['autodocs', 'test'], // TODO(decode-instruction-with-idl): rename to a feature-scoped title once the Storybook tree migration off // the Dashkit layout lands; kept stable here to avoid churning the tree mid-move. diff --git a/app/features/decode-instruction-with-idl/ui/__tests__/AnchorDetailsCard.spec.tsx b/app/features/decode-instruction-with-idl/ui/__tests__/AnchorDetailsCard.spec.tsx index d9f643e0e4..e06b41853d 100644 --- a/app/features/decode-instruction-with-idl/ui/__tests__/AnchorDetailsCard.spec.tsx +++ b/app/features/decode-instruction-with-idl/ui/__tests__/AnchorDetailsCard.spec.tsx @@ -1,6 +1,5 @@ import { gen } from '@__fixtures__/gen'; import { InstructionNodeCard } from '@components/instruction/InstructionNodeCard'; -import { AnchorProvider, Idl, Program } from '@coral-xyz/anchor'; import { inspectorSurface, InstructionSurfaceProvider, @@ -17,34 +16,24 @@ import React from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { readCell } from '@/app/__tests__/card-harness'; -import anchor030Devi from '@/app/entities/idl/mocks/anchor/anchor-0.30.1-devi51mZmdwUJGU9hjN27vEz64Gps7uUefqxg27EAtH.json'; import { ClusterProvider } from '@/app/providers/cluster'; import { TransactionsProvider } from '@/app/providers/transactions'; +import { + ammV3Instruction, + ammV3Program as program, + UPDATE_REWARD_INFOS_DISCRIMINATOR, +} from '../../__fixtures__/anchor-programs'; import { decodeAnchorInstruction } from '../../lib/decode-anchor-instruction'; import { AnchorDetailsCard } from '../AnchorDetailsCard'; -vi.mock('next/navigation', () => ({ - usePathname: vi.fn(), - useRouter: vi.fn(() => ({ push: vi.fn() })), - useSearchParams: vi.fn(() => ({ get: vi.fn(), has: vi.fn(), toString: () => '' })), -})); +vi.mock('next/navigation', () => import('@/app/__tests__/next-navigation')); vi.mock('@providers/transactions', async importOriginal => { const actual = await importOriginal(); return { ...actual, useTransactionDetails: vi.fn(actual.useTransactionDetails) }; }); -const program = new Program( - anchor030Devi as Idl, - { - connection: { commitment: 'confirmed', rpcEndpoint: 'https://api.devnet.solana.com' }, - opts: {}, - wallet: { publicKey: PublicKey.default }, - } as unknown as AnchorProvider, -); - -const UPDATE_REWARD_INFOS_DISCRIMINATOR = [163, 172, 224, 52, 11, 154, 106, 223]; const CONFIG_CHANGE_EVENT_DISCRIMINATOR = [247, 189, 7, 119, 106, 112, 95, 151]; const CONFIG_CHANGE_EVENT = Buffer.from([...CONFIG_CHANGE_EVENT_DISCRIMINATOR, ...new Array(80).fill(0)]).toString( 'base64', @@ -61,7 +50,7 @@ describe('AnchorDetailsCard', () => { ['tx page', 0], ['inspector', 1], ] as const)('should draw the frame of the %s', (surface, collapseButtons) => { - renderCard(makeIx(UPDATE_REWARD_INFOS_DISCRIMINATOR), { surface }); + renderCard(ammV3Instruction(UPDATE_REWARD_INFOS_DISCRIMINATOR), { surface }); expect(screen.getByText('Amm V3: Update Reward Infos')).toBeInTheDocument(); expect(screen.queryAllByRole('button', { name: 'Collapse' })).toHaveLength(collapseButtons); @@ -70,7 +59,7 @@ describe('AnchorDetailsCard', () => { it.each(['tx page', 'inspector'] as const)( 'should draw one Program row on the %s when the instruction decodes', surface => { - renderCard(makeIx(UPDATE_REWARD_INFOS_DISCRIMINATOR), { surface }); + renderCard(ammV3Instruction(UPDATE_REWARD_INFOS_DISCRIMINATOR), { surface }); expect(screen.getByText('Account Name')).toBeInTheDocument(); expect(screen.getAllByText('Program')).toHaveLength(1); @@ -81,7 +70,7 @@ describe('AnchorDetailsCard', () => { it.each(['tx page', 'inspector'] as const)( 'should draw one Program row on the %s when the instruction does not decode', surface => { - renderCard(makeIx([0, 0, 0, 0, 0, 0, 0, 0]), { surface }); + renderCard(ammV3Instruction([0, 0, 0, 0, 0, 0, 0, 0]), { surface }); expect(readCell('Error')).toBe('Failed to decode account data according to the public Anchor interface'); expect(screen.getAllByText('Program')).toHaveLength(1); @@ -90,7 +79,7 @@ describe('AnchorDetailsCard', () => { ); it.each(['tx page', 'inspector'] as const)('should pass the child index to the frame of the %s', surface => { - renderCard(makeIx(UPDATE_REWARD_INFOS_DISCRIMINATOR), { childIndex: 2, surface }); + renderCard(ammV3Instruction(UPDATE_REWARD_INFOS_DISCRIMINATOR), { childIndex: 2, surface }); expect(screen.getByText('#1.3')).toBeInTheDocument(); }); @@ -108,7 +97,7 @@ describe('AnchorDetailsCard', () => { [other, program.programId], ); - renderCard(makeIx(UPDATE_REWARD_INFOS_DISCRIMINATOR), { index: 1, surface: 'tx page' }); + renderCard(ammV3Instruction(UPDATE_REWARD_INFOS_DISCRIMINATOR), { index: 1, surface: 'tx page' }); expect(screen.getByText('Events')).toBeInTheDocument(); expect(screen.getByText('Unknown Event')).toBeInTheDocument(); @@ -129,7 +118,7 @@ describe('AnchorDetailsCard', () => { [parent], ); - renderCard(makeIx(UPDATE_REWARD_INFOS_DISCRIMINATOR), { childIndex: 0, surface: 'tx page' }); + renderCard(ammV3Instruction(UPDATE_REWARD_INFOS_DISCRIMINATOR), { childIndex: 0, surface: 'tx page' }); expect(screen.getByText('Config Change Event')).toBeInTheDocument(); expect(screen.queryByText('Unknown Event')).not.toBeInTheDocument(); @@ -147,7 +136,7 @@ describe('AnchorDetailsCard', () => { ], [parent], ); - renderCard(makeIx(UPDATE_REWARD_INFOS_DISCRIMINATOR), { childIndex: 0, surface: 'tx page' }); + renderCard(ammV3Instruction(UPDATE_REWARD_INFOS_DISCRIMINATOR), { childIndex: 0, surface: 'tx page' }); expect(screen.getByText('Field Name')).toBeInTheDocument(); await userEvent.click(screen.getByRole('button', { name: 'Raw' })); @@ -170,7 +159,7 @@ describe('AnchorDetailsCard', () => { [parent], ); - renderCard(makeIx(UPDATE_REWARD_INFOS_DISCRIMINATOR), { childIndex: 0, surface: 'tx page' }); + renderCard(ammV3Instruction(UPDATE_REWARD_INFOS_DISCRIMINATOR), { childIndex: 0, surface: 'tx page' }); expect(screen.getByText('#1.1 · event 1')).toBeInTheDocument(); }); @@ -188,7 +177,7 @@ describe('AnchorDetailsCard', () => { [program.programId], ); - renderCard(makeIx(UPDATE_REWARD_INFOS_DISCRIMINATOR), { surface: 'tx page' }); + renderCard(ammV3Instruction(UPDATE_REWARD_INFOS_DISCRIMINATOR), { surface: 'tx page' }); expect(screen.getByText('Amm V3: Update Reward Infos')).toBeInTheDocument(); expect(screen.queryByText('Events')).not.toBeInTheDocument(); @@ -204,7 +193,7 @@ describe('AnchorDetailsCard', () => { [program.programId], ); - renderCard(makeIx(UPDATE_REWARD_INFOS_DISCRIMINATOR), { surface: 'tx page' }); + renderCard(ammV3Instruction(UPDATE_REWARD_INFOS_DISCRIMINATOR), { surface: 'tx page' }); expect(screen.getByText('Amm V3: Update Reward Infos')).toBeInTheDocument(); expect(screen.queryByText('Events')).not.toBeInTheDocument(); @@ -218,14 +207,6 @@ function expectProgramLink() { ); } -function makeIx(data: number[]) { - return new TransactionInstruction({ - data: Buffer.from(data), - keys: [{ isSigner: false, isWritable: true, pubkey: gen.publicKey(1) }], - programId: program.programId, - }); -} - function mockTransactionLogs(logMessages: string[], programIds: PublicKey[]) { const transactionWithMeta = { meta: { logMessages }, diff --git a/app/features/decode-instruction-with-idl/ui/__tests__/CodamaInstructionCard.spec.tsx b/app/features/decode-instruction-with-idl/ui/__tests__/CodamaInstructionCard.spec.tsx index deb0b01cfb..9199baf7cf 100644 --- a/app/features/decode-instruction-with-idl/ui/__tests__/CodamaInstructionCard.spec.tsx +++ b/app/features/decode-instruction-with-idl/ui/__tests__/CodamaInstructionCard.spec.tsx @@ -40,11 +40,7 @@ vi.mock('@entities/instruction-card', async importOriginal => ({ UnknownDetailsCard: () =>
, })); -vi.mock('@/app/components/common/Address', () => ({ - Address: ({ pubkey, fallbackText }: { pubkey: PublicKey; fallbackText?: string }) => ( -
{fallbackText ?? pubkey.toBase58()}
- ), -})); +vi.mock('@/app/components/common/Address', () => import('@/app/__tests__/address-stub')); const PROGRAM = gen.publicKey(0); const AUTHORITY = gen.address(1); diff --git a/app/features/decode-instruction-zk-elgamal-proof/ui/__tests__/ZkElGamalProofDetailsCard.spec.tsx b/app/features/decode-instruction-zk-elgamal-proof/ui/__tests__/ZkElGamalProofDetailsCard.spec.tsx index 7cb298d4f7..8584fcf58a 100644 --- a/app/features/decode-instruction-zk-elgamal-proof/ui/__tests__/ZkElGamalProofDetailsCard.spec.tsx +++ b/app/features/decode-instruction-zk-elgamal-proof/ui/__tests__/ZkElGamalProofDetailsCard.spec.tsx @@ -1,3 +1,4 @@ +import { makeInstruction } from '@__fixtures__/instruction'; import { toInstructionNode } from '@entities/instruction-card'; import { createInstructionParserDispatcher, isParsedInstruction } from '@entities/instruction-parser'; import { PublicKey, TransactionInstruction } from '@solana/web3.js'; @@ -70,12 +71,8 @@ describe('ZkElGamalProofDetailsCard', () => { }); }); -function instruction(data: number[], keys: string[] = []): TransactionInstruction { - return new TransactionInstruction({ - data: Buffer.from(data), - keys: keys.map(key => ({ isSigner: false, isWritable: false, pubkey: new PublicKey(key) })), - programId: PROGRAM_ID, - }); +function instruction(data: number[], keys: string[] = []) { + return makeInstruction({ data, keys: keys.map(key => new PublicKey(key)), programId: PROGRAM_ID }); } function renderCard(ix: TransactionInstruction) { diff --git a/app/features/feature-gate/ui/__stories__/BaseFeatureGateImage.stories.tsx b/app/features/feature-gate/ui/__stories__/BaseFeatureGateImage.stories.tsx index df16547a42..a0c019bb47 100644 --- a/app/features/feature-gate/ui/__stories__/BaseFeatureGateImage.stories.tsx +++ b/app/features/feature-gate/ui/__stories__/BaseFeatureGateImage.stories.tsx @@ -1,4 +1,4 @@ -import { IMAGE_SIZE } from '@shared/lib/og/image-size'; +import { withOgImageFrame } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; @@ -16,13 +16,7 @@ const meta: Meta = { }, }, component: BaseFeatureGateImage, - decorators: [ - Story => ( -
- -
- ), - ], + decorators: [withOgImageFrame], tags: ['autodocs', 'test'], title: 'Features/FeatureGate/BaseFeatureGateImage', }; diff --git a/app/features/feature-gate/ui/__stories__/FeatureGateTable.responsive.stories.tsx b/app/features/feature-gate/ui/__stories__/FeatureGateTable.responsive.stories.tsx index cf94d0fad1..e87ebb65d6 100644 --- a/app/features/feature-gate/ui/__stories__/FeatureGateTable.responsive.stories.tsx +++ b/app/features/feature-gate/ui/__stories__/FeatureGateTable.responsive.stories.tsx @@ -1,42 +1,13 @@ -import { gen } from '@__fixtures__/gen'; -import { address } from '@solana/kit'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import { Cluster } from '@utils/cluster'; import type { ActivatedFeature } from '../../lib/partition-features'; -import { EmptyStateCard, FeatureGateTable } from '../FeatureGateTable'; - -const baseFields = { - comms_required: null, - description: 'Activates a new behavior on the network. Click the row to expand the full description.', - devnet_activation_epoch: 700, - mainnet_activation_epoch: 850, - min_agave_versions: ['1.18.0'], - min_fd_versions: [], - min_jito_versions: [], - owners: ['Solana Labs'], - planned_testnet_order: null, - testnet_activation_epoch: 680, -}; - -const activated: ActivatedFeature[] = [ - { - ...baseFields, - clusterActivationEpoch: 850, - key: address(gen.address(1)), - otherActivations: [{ cluster: Cluster.Devnet, epoch: 700 }], - simdEntries: [{ link: 'https://github.com/example', simd: '148' }], - title: 'MoveStake and MoveLamports', - }, -]; +import { FeatureGateTable } from '../FeatureGateTable'; +import * as Base from './FeatureGateTable.stories'; const meta: Meta> = { component: FeatureGateTable, decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Features/FeatureGate/FeatureGateTable@Media', }; @@ -44,15 +15,7 @@ const meta: Meta> = { export default meta; type Story = StoryObj>; -const args = { - cluster: Cluster.Mainnet, - emptyState: No activated features., - features: activated, - secondColumn: { - header: 'Activation', - render: (feature: ActivatedFeature) => {feature.clusterActivationEpoch}, - }, -}; +const args = Base.ActivatedRows.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/features/feature-gate/ui/__stories__/FeatureGatesView.stories.tsx b/app/features/feature-gate/ui/__stories__/FeatureGatesView.stories.tsx index a80b61fae0..5d001a98ba 100644 --- a/app/features/feature-gate/ui/__stories__/FeatureGatesView.stories.tsx +++ b/app/features/feature-gate/ui/__stories__/FeatureGatesView.stories.tsx @@ -1,6 +1,5 @@ import { toConnectableUrl } from '@entities/cluster'; import { defaultEpochInfo, MockClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; -import { nextjsParameters } from '@storybook-config/decorators'; import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; import { Cluster, clusterSelection, clusterUrl } from '@utils/cluster'; import { expect, within } from 'storybook/test'; @@ -45,7 +44,6 @@ const SLOT_TIME_KEY = unstable_serialize([ const meta: Meta = { component: FeatureGatesView, decorators: [atEpoch(1075n)], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/FeatureGate/FeatureGatesView', }; diff --git a/app/features/feature-gate/ui/__stories__/UpcomingFeatures.responsive.stories.tsx b/app/features/feature-gate/ui/__stories__/UpcomingFeatures.responsive.stories.tsx index 7f56fe1ac3..a5cef0c0a6 100644 --- a/app/features/feature-gate/ui/__stories__/UpcomingFeatures.responsive.stories.tsx +++ b/app/features/feature-gate/ui/__stories__/UpcomingFeatures.responsive.stories.tsx @@ -1,5 +1,5 @@ -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { UpcomingFeatures } from '../UpcomingFeatures'; @@ -8,10 +8,6 @@ import { UpcomingFeatures } from '../UpcomingFeatures'; const meta = { component: UpcomingFeatures, decorators: [withViewportFromGlobal, withCluster, withTokenInfoBatch], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Features/FeatureGate/UpcomingFeatures@Media', } satisfies Meta; diff --git a/app/features/feature-gate/ui/__stories__/UpcomingFeatures.stories.tsx b/app/features/feature-gate/ui/__stories__/UpcomingFeatures.stories.tsx index c3965926ea..66ba6ef935 100644 --- a/app/features/feature-gate/ui/__stories__/UpcomingFeatures.stories.tsx +++ b/app/features/feature-gate/ui/__stories__/UpcomingFeatures.stories.tsx @@ -1,4 +1,4 @@ -import { nextjsParameters, withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withCluster, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { UpcomingFeatures } from '../UpcomingFeatures'; @@ -6,7 +6,6 @@ import { UpcomingFeatures } from '../UpcomingFeatures'; const meta = { component: UpcomingFeatures, decorators: [withCluster, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/FeatureGate/UpcomingFeatures', } satisfies Meta; diff --git a/app/features/idl/formatted-idl/ui/__stories__/AnchorFormattedIdl.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/AnchorFormattedIdl.stories.tsx index 2c1fc91eca..ba1bb5f01a 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/AnchorFormattedIdl.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/AnchorFormattedIdl.stories.tsx @@ -12,9 +12,6 @@ const meta = { story: 'Format and render Anchor IDL', }, }, - nextjs: { - appDirectory: true, - }, }, tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/AnchorFormattedIdl', diff --git a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlAccounts.responsive.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlAccounts.responsive.stories.tsx index 3cf7952e42..f5f7ffcd74 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlAccounts.responsive.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlAccounts.responsive.stories.tsx @@ -1,15 +1,12 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BaseIdlAccounts } from '../BaseIdlAccounts'; +import * as Base from './BaseIdlAccounts.stories'; const meta: Meta = { component: BaseIdlAccounts, decorators: [withViewportFromGlobal], - parameters: { - nextjs: { appDirectory: true }, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/BaseIdlAccounts@Media', }; @@ -17,22 +14,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - data: [ - { - docs: ['Stores user information and balance'], - fieldType: { - fields: [ - { name: 'owner', type: 'publicKey' }, - { name: 'balance', type: 'u64' }, - { name: 'active', type: 'bool' }, - ], - kind: 'struct' as const, - }, - name: 'UserAccount', - }, - ], -}; +const args = Base.SimpleAccounts.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlAccounts.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlAccounts.stories.tsx index 5e64d5e7e5..46a5890252 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlAccounts.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlAccounts.stories.tsx @@ -4,11 +4,6 @@ import { BaseIdlAccounts } from '../BaseIdlAccounts'; const meta = { component: BaseIdlAccounts, - parameters: { - nextjs: { - appDirectory: true, - }, - }, tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/BaseIdlAccounts', } satisfies Meta; diff --git a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlConstants.responsive.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlConstants.responsive.stories.tsx index 0f061873ee..a72ce44ee0 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlConstants.responsive.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlConstants.responsive.stories.tsx @@ -1,15 +1,12 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BaseIdlConstants } from '../BaseIdlConstants'; +import * as Base from './BaseIdlConstants.stories'; const meta: Meta = { component: BaseIdlConstants, decorators: [withViewportFromGlobal], - parameters: { - nextjs: { appDirectory: true }, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/BaseIdlConstants@Media', }; @@ -17,22 +14,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - data: [ - { - docs: ['Maximum number of users allowed'], - name: 'MAX_USERS', - type: 'u16', - value: '1000', - }, - { - docs: ['Minimum deposit amount in lamports'], - name: 'MIN_DEPOSIT', - type: 'u64', - value: '10000000', - }, - ], -}; +const args = Base.NumericConstants.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlConstants.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlConstants.stories.tsx index 525604528a..e6e2aa423c 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlConstants.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlConstants.stories.tsx @@ -5,13 +5,6 @@ import { SearchHighlightProvider } from '../SearchHighlightContext'; const meta = { component: BaseIdlConstants, - decorators: [ - Story => ( -
- -
- ), - ], tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/BaseIdlConstants', } satisfies Meta; @@ -120,9 +113,7 @@ export const WithSearchTerm: Story = { decorators: [ Story => ( -
- -
+
), ], diff --git a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlErrors.responsive.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlErrors.responsive.stories.tsx index 1526bff051..8b1143ea2f 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlErrors.responsive.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlErrors.responsive.stories.tsx @@ -1,15 +1,12 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BaseIdlErrors } from '../BaseIdlErrors'; +import * as Base from './BaseIdlErrors.stories'; const meta: Meta = { component: BaseIdlErrors, decorators: [withViewportFromGlobal], - parameters: { - nextjs: { appDirectory: true }, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/BaseIdlErrors@Media', }; @@ -17,20 +14,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - data: [ - { - code: '100', - message: 'The provided owner is not valid for this operation', - name: 'InvalidOwner', - }, - { - code: '101', - message: 'The account has insufficient funds for this operation', - name: 'InsufficientFunds', - }, - ], -}; +const args = Base.BasicErrors.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlErrors.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlErrors.stories.tsx index 51c339e40e..216ab256de 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlErrors.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlErrors.stories.tsx @@ -4,13 +4,6 @@ import { BaseIdlErrors } from '../BaseIdlErrors'; const meta = { component: BaseIdlErrors, - decorators: [ - Story => ( -
- -
- ), - ], tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/BaseIdlErrors', } satisfies Meta; diff --git a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlEvents.responsive.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlEvents.responsive.stories.tsx index 53d5337b11..949f20b0e3 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlEvents.responsive.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlEvents.responsive.stories.tsx @@ -1,15 +1,12 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BaseIdlEvents } from '../BaseIdlEvents'; +import * as Base from './BaseIdlEvents.stories'; const meta: Meta = { component: BaseIdlEvents, decorators: [withViewportFromGlobal], - parameters: { - nextjs: { appDirectory: true }, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/BaseIdlEvents@Media', }; @@ -17,22 +14,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - data: [ - { - docs: ['Emitted when an NFT is sold on the marketplace'], - fieldType: { - fields: [ - { docs: ['NFT mint address'], name: 'tokenMint', type: 'publicKey' }, - { name: 'seller', type: 'publicKey' }, - { docs: ['Sale price in lamports'], name: 'price', type: 'u64' }, - ], - kind: 'struct' as const, - }, - name: 'MarketItemSold', - }, - ], -}; +const args = Base.BasicEvents.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlEvents.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlEvents.stories.tsx index 30c377f54e..b51e630573 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlEvents.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlEvents.stories.tsx @@ -4,13 +4,6 @@ import { BaseIdlEvents } from '../BaseIdlEvents'; const meta = { component: BaseIdlEvents, - decorators: [ - Story => ( -
- -
- ), - ], tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/BaseIdlEvents', } satisfies Meta; diff --git a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlFields.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlFields.stories.tsx index 9ea59c3a6e..910063baa8 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlFields.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlFields.stories.tsx @@ -4,11 +4,6 @@ import { BaseIdlFields } from '../BaseIdlFields'; const meta = { component: BaseIdlFields, - parameters: { - nextjs: { - appDirectory: true, - }, - }, tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/BaseIdlFields', } satisfies Meta; diff --git a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlInstructions.responsive.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlInstructions.responsive.stories.tsx index 28aceaac3f..dfb9605205 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlInstructions.responsive.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlInstructions.responsive.stories.tsx @@ -1,15 +1,12 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BaseIdlInstructions } from '../BaseIdlInstructions'; +import * as Base from './BaseIdlInstructions.stories'; const meta: Meta = { component: BaseIdlInstructions, decorators: [withViewportFromGlobal], - parameters: { - nextjs: { appDirectory: true }, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/BaseIdlInstructions@Media', }; @@ -17,19 +14,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - data: [ - { - accounts: [ - { docs: ['Account that can update the data'], name: 'authority', signer: true, writable: false }, - { docs: ['Account to initialize'], name: 'newAccount', signer: false, writable: true }, - ], - args: [{ docs: ['Initial value'], name: 'data', type: 'u64' }], - docs: ['Initialize a new account'], - name: 'initialize', - }, - ], -}; +const args = Base.SimpleInstructions.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlInstructions.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlInstructions.stories.tsx index 2a20accf01..b5b1aaf4da 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlInstructions.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlInstructions.stories.tsx @@ -4,11 +4,6 @@ import { BaseIdlInstructions } from '../BaseIdlInstructions'; const meta = { component: BaseIdlInstructions, - parameters: { - nextjs: { - appDirectory: true, - }, - }, tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/BaseIdlInstructions', } satisfies Meta; diff --git a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlPdas.responsive.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlPdas.responsive.stories.tsx index 8f637d6af5..52884d99dc 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlPdas.responsive.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlPdas.responsive.stories.tsx @@ -1,15 +1,12 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BaseIdlPdas } from '../BaseIdlPdas'; +import * as Base from './BaseIdlPdas.stories'; const meta: Meta = { component: BaseIdlPdas, decorators: [withViewportFromGlobal], - parameters: { - nextjs: { appDirectory: true }, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/BaseIdlPdas@Media', }; @@ -17,22 +14,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - data: [ - { - docs: ['This PDA has defined seeds.'], - name: 'SeededPDA', - seeds: [ - { - docs: ['Seed for the PDA'], - kind: 'type' as const, - name: 'seed1', - type: 'bytes', - }, - ], - }, - ], -}; +const args = Base.PdasWithSeeds.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlPdas.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlPdas.stories.tsx index 6238c3054e..04f21c2484 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlPdas.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlPdas.stories.tsx @@ -4,11 +4,6 @@ import { BaseIdlPdas } from '../BaseIdlPdas'; const meta = { component: BaseIdlPdas, - parameters: { - nextjs: { - appDirectory: true, - }, - }, tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/BaseIdlPdas', } satisfies Meta; diff --git a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlTypes.responsive.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlTypes.responsive.stories.tsx index 6ef832c0f2..95316c6d73 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlTypes.responsive.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlTypes.responsive.stories.tsx @@ -1,15 +1,12 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BaseIdlTypes } from '../BaseIdlTypes'; +import * as Base from './BaseIdlTypes.stories'; const meta: Meta = { component: BaseIdlTypes, decorators: [withViewportFromGlobal], - parameters: { - nextjs: { appDirectory: true }, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/BaseIdlTypes@Media', }; @@ -17,22 +14,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - data: [ - { - docs: ['Complete market state'], - fieldType: { - fields: [ - { name: 'id', type: 'u64' }, - { name: 'owner', type: 'publicKey' }, - { docs: ['Market configuration'], name: 'config', type: 'MarketConfig' }, - ], - kind: 'struct' as const, - }, - name: 'MarketState', - }, - ], -}; +const args = Base.StructTypes.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlTypes.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlTypes.stories.tsx index 8dd6131045..d8b9406b66 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/BaseIdlTypes.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/BaseIdlTypes.stories.tsx @@ -4,11 +4,6 @@ import { BaseIdlTypes } from '../BaseIdlTypes'; const meta = { component: BaseIdlTypes, - parameters: { - nextjs: { - appDirectory: true, - }, - }, tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/BaseIdlTypes', } satisfies Meta; diff --git a/app/features/idl/formatted-idl/ui/__stories__/CodamaFormattedIdl.stories.tsx b/app/features/idl/formatted-idl/ui/__stories__/CodamaFormattedIdl.stories.tsx index bc14352c46..f57fdba895 100644 --- a/app/features/idl/formatted-idl/ui/__stories__/CodamaFormattedIdl.stories.tsx +++ b/app/features/idl/formatted-idl/ui/__stories__/CodamaFormattedIdl.stories.tsx @@ -14,9 +14,6 @@ const meta = { story: 'Format and render Codama IDL', }, }, - nextjs: { - appDirectory: true, - }, }, tags: ['autodocs', 'test'], title: 'Features/IDL/Formatted IDL/CodamaFormattedIdl', diff --git a/app/features/idl/interactive-idl/model/__mocks__/anchor/anchor-0.30.0-voting-AXcxp15oz1L4YYtqZo6Qt6EkUj1jtLR6wXYqaJvn4oye.json b/app/features/idl/interactive-idl/model/__mocks__/anchor/anchor-0.30.0-voting-AXcxp15oz1L4YYtqZo6Qt6EkUj1jtLR6wXYqaJvn4oye.json deleted file mode 100644 index e26930c6bc..0000000000 --- a/app/features/idl/interactive-idl/model/__mocks__/anchor/anchor-0.30.0-voting-AXcxp15oz1L4YYtqZo6Qt6EkUj1jtLR6wXYqaJvn4oye.json +++ /dev/null @@ -1 +0,0 @@ -{"address":"AXcxp15oz1L4YYtqZo6Qt6EkUj1jtLR6wXYqaJvn4oye","instructions":[{"accounts":[{"name":"signer","signer":true,"writable":true},{"name":"poll","pda":{"seeds":[{"kind":"arg","path":"poll_id"}]},"writable":true},{"name":"candidate","pda":{"seeds":[{"kind":"arg","path":"poll_id"},{"kind":"arg","path":"candidate_name"}]},"writable":true}],"args":[{"name":"candidate_name","type":"string"},{"name":"_poll_id","type":"u64"}],"discriminator":[210,107,118,204,255,97,112,26],"name":"initialize_candidate"},{"accounts":[{"name":"poll","pda":{"seeds":[{"kind":"arg","path":"poll_id"}]},"writable":true}],"args":[{"name":"poll_id","type":"u64"}],"discriminator":[193,22,99,197,18,33,115,117],"name":"initialize_poll"}],"metadata":{"name":"voting","spec":"0.1.0","version":"0.1.0"}} diff --git a/app/features/idl/interactive-idl/model/__tests__/use-pdas.spec.ts b/app/features/idl/interactive-idl/model/__tests__/use-pdas.spec.ts index 04865516ad..1eb2eeb4a8 100644 --- a/app/features/idl/interactive-idl/model/__tests__/use-pdas.spec.ts +++ b/app/features/idl/interactive-idl/model/__tests__/use-pdas.spec.ts @@ -10,8 +10,7 @@ import { invariant } from '@/app/shared/lib/invariant'; import { Logger } from '@/app/shared/lib/logger'; import votingIdl029 from '../__mocks__/anchor/anchor-0.29.0-voting-AXcxp15oz1L4YYtqZo6Qt6EkUj1jtLR6wXYqaJvn4oye.json'; -import votingIdl030 from '../__mocks__/anchor/anchor-0.30.0-voting-AXcxp15oz1L4YYtqZo6Qt6EkUj1jtLR6wXYqaJvn4oye.json'; -import votingIdl030Variations from '../__mocks__/anchor/anchor-0.30.0-voting-variations-AXcxp15oz1L4YYtqZo6Qt6EkUj1jtLR6wXYqaJvn4oye.json'; +import votingIdl030 from '../__mocks__/anchor/anchor-0.30.0-voting-variations-AXcxp15oz1L4YYtqZo6Qt6EkUj1jtLR6wXYqaJvn4oye.json'; import donateIdl0301 from '../__mocks__/anchor/anchor-0.30.1-donate-DRLYxueWz6iymdsaRCER6iv6v9zL7gFWANwDL2V5VUx1.json'; import codamaVotingIdl from '../__mocks__/codama/codama-voting.json'; import { computePdas } from '../pda-generator/compute-pdas'; @@ -167,7 +166,7 @@ describe('computePdas', () => { // 0.30 variations tests - nested groups it('should skip nested account groups', async () => { - const pdas = await pdasFor(votingIdl030Variations, 'instruction_with_nested', { arguments: { pollId: '999' } }); + const pdas = await pdasFor(votingIdl030, 'instruction_with_nested', { arguments: { pollId: '999' } }); expect(Object.keys(pdas)).toEqual(['poll']); expect(pdas.poll.generated).toEqual(expect.any(String)); @@ -176,7 +175,7 @@ describe('computePdas', () => { // 0.30 variations tests it('should handle account seeds', async () => { const accountPubkey = PublicKey.default.toString(); - const pdas = await pdasFor(votingIdl030Variations, 'instruction_with_account_seed', { + const pdas = await pdasFor(votingIdl030, 'instruction_with_account_seed', { accounts: { authority: accountPubkey }, }); @@ -186,7 +185,7 @@ describe('computePdas', () => { }); it('should handle const seeds', async () => { - const pdas = await pdasFor(votingIdl030Variations, 'instruction_with_const_seed'); + const pdas = await pdasFor(votingIdl030, 'instruction_with_const_seed'); expect(pdas.pdaAccount.generated).not.toBeNull(); expect(pdas.pdaAccount.seeds).toHaveLength(1); @@ -194,7 +193,7 @@ describe('computePdas', () => { }); it('should return null when account seed value is missing', async () => { - const pdas = await pdasFor(votingIdl030Variations, 'instruction_with_account_seed'); + const pdas = await pdasFor(votingIdl030, 'instruction_with_account_seed'); expect(pdas.pdaAccount.generated).toBeNull(); expect(pdas.pdaAccount.seeds).toHaveLength(1); diff --git a/app/features/idl/interactive-idl/model/form-prefill/providers/__tests__/use-pda-prefill.spec.ts b/app/features/idl/interactive-idl/model/form-prefill/providers/__tests__/use-pda-prefill.spec.ts index 2e40131d24..b031ae2193 100644 --- a/app/features/idl/interactive-idl/model/form-prefill/providers/__tests__/use-pda-prefill.spec.ts +++ b/app/features/idl/interactive-idl/model/form-prefill/providers/__tests__/use-pda-prefill.spec.ts @@ -4,8 +4,7 @@ import type { SupportedIdl } from '@entities/idl'; import { act, renderHook } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; -import votingIdl030 from '../../../__mocks__/anchor/anchor-0.30.0-voting-AXcxp15oz1L4YYtqZo6Qt6EkUj1jtLR6wXYqaJvn4oye.json'; -import votingIdl030Variations from '../../../__mocks__/anchor/anchor-0.30.0-voting-variations-AXcxp15oz1L4YYtqZo6Qt6EkUj1jtLR6wXYqaJvn4oye.json'; +import votingIdl030 from '../../../__mocks__/anchor/anchor-0.30.0-voting-variations-AXcxp15oz1L4YYtqZo6Qt6EkUj1jtLR6wXYqaJvn4oye.json'; import { findInstruction } from '../../../__tests__/utils'; import type { PdaGenerationResult } from '../../../pda-generator/types'; import { usePdaPrefill } from '../use-pda-prefill'; @@ -99,7 +98,7 @@ describe('usePdaPrefill', () => { }); it('should handle nested PDA accounts', () => { - const { createForm, mockInstruction } = setup(votingIdl030Variations, 'instruction_with_nested'); + const { createForm, mockInstruction } = setup(votingIdl030, 'instruction_with_nested'); const { form, fieldNames } = createForm(); renderHook(() => @@ -118,7 +117,7 @@ describe('usePdaPrefill', () => { }); it('should not fill non-PDA accounts', () => { - const { createForm, mockInstruction } = setup(votingIdl030Variations, 'instruction_with_non_pda'); + const { createForm, mockInstruction } = setup(votingIdl030, 'instruction_with_non_pda'); const { form, fieldNames } = createForm(); const setValueSpy = vi.spyOn(form, 'setValue'); diff --git a/app/features/idl/interactive-idl/ui/__stories__/InstructionExecutionActivity.stories.tsx b/app/features/idl/interactive-idl/ui/__stories__/InstructionExecutionActivity.stories.tsx index 360feeb5cb..5623c18c6e 100644 --- a/app/features/idl/interactive-idl/ui/__stories__/InstructionExecutionActivity.stories.tsx +++ b/app/features/idl/interactive-idl/ui/__stories__/InstructionExecutionActivity.stories.tsx @@ -3,6 +3,7 @@ import { parsedBaseLogs, parsedErrorLogs } from '@entities/program-logs/model/mo import { withCluster } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; +import type { BroadcastFailedResult } from '../../model/transaction/types'; import { InstructionExecutionActivity } from '../InstructionActivity'; const FINISHED_AT = new Date('2026-01-01T00:00:00Z'); @@ -16,6 +17,17 @@ const LONG_ERROR = const BASE_LOGS = { parsed: parsedBaseLogs, raw: baseLogs }; const ERROR_LOGS = { parsed: parsedErrorLogs, raw: errorLogs }; +const BROADCAST_FAILED: BroadcastFailedResult = { + finishedAt: FINISHED_AT, + kind: 'execution', + logs: ERROR_LOGS, + message: 'AnchorError occurred. Error Code: ConstraintHasOne. Error Number: 2001.', + phase: 'broadcast_failed', + serializedTxMessage: SERIALIZED, + signature: SIGNATURE, + status: 'error', +}; + const meta = { component: InstructionExecutionActivity, decorators: [withCluster], @@ -47,49 +59,16 @@ export const Success: Story = { /** Tx was broadcast but failed on-chain — Error status header with a tx link. */ export const BroadcastFailed: Story = { - args: { - lastResult: { - finishedAt: FINISHED_AT, - kind: 'execution', - logs: ERROR_LOGS, - message: 'AnchorError occurred. Error Code: ConstraintHasOne. Error Number: 2001.', - phase: 'broadcast_failed', - serializedTxMessage: SERIALIZED, - signature: SIGNATURE, - status: 'error', - }, - }, + args: { lastResult: BROADCAST_FAILED }, }; export const BroadcastFailedEmptyMessage: Story = { - args: { - lastResult: { - finishedAt: FINISHED_AT, - kind: 'execution', - logs: ERROR_LOGS, - message: '', - phase: 'broadcast_failed', - serializedTxMessage: SERIALIZED, - signature: SIGNATURE, - status: 'error', - }, - }, + args: { lastResult: { ...BROADCAST_FAILED, message: '' } }, }; /** Long error message — the note wraps below the signature box. */ export const BroadcastFailedLongError: Story = { - args: { - lastResult: { - finishedAt: FINISHED_AT, - kind: 'execution', - logs: ERROR_LOGS, - message: LONG_ERROR, - phase: 'broadcast_failed', - serializedTxMessage: SERIALIZED, - signature: SIGNATURE, - status: 'error', - }, - }, + args: { lastResult: { ...BROADCAST_FAILED, message: LONG_ERROR } }, }; /** Local failure before broadcast, with a serialized message — error note + inspector link. */ diff --git a/app/features/idl/interactive-idl/ui/__stories__/InstructionSimulationActivity.stories.tsx b/app/features/idl/interactive-idl/ui/__stories__/InstructionSimulationActivity.stories.tsx index 4e0b64889a..1ba40bec87 100644 --- a/app/features/idl/interactive-idl/ui/__stories__/InstructionSimulationActivity.stories.tsx +++ b/app/features/idl/interactive-idl/ui/__stories__/InstructionSimulationActivity.stories.tsx @@ -3,6 +3,7 @@ import { parsedBaseLogs, parsedErrorLogs } from '@entities/program-logs/model/mo import { withCluster } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; +import type { RpcSimulationFailedResult } from '../../model/transaction/types'; import { InstructionSimulationActivity } from '../InstructionActivity'; const FINISHED_AT = new Date('2026-01-01T00:00:00Z'); @@ -15,6 +16,17 @@ const LONG_ERROR = const BASE_LOGS = { parsed: parsedBaseLogs, raw: baseLogs }; const ERROR_LOGS = { parsed: parsedErrorLogs, raw: errorLogs }; +const RPC_SIMULATION_FAILED: RpcSimulationFailedResult = { + finishedAt: FINISHED_AT, + kind: 'simulation', + logs: ERROR_LOGS, + message: + 'Error Message: A has one constraint was violated. The provided account does not match the expected owner.', + phase: 'rpc_simulation_failed', + serializedTxMessage: SERIALIZED, + status: 'error', +}; + const meta = { component: InstructionSimulationActivity, decorators: [withCluster], @@ -47,46 +59,15 @@ export const Success: Story = { }; export const RpcSimulationFailed: Story = { - args: { - lastSimulation: { - finishedAt: FINISHED_AT, - kind: 'simulation', - logs: ERROR_LOGS, - message: - 'Error Message: A has one constraint was violated. The provided account does not match the expected owner.', - phase: 'rpc_simulation_failed', - serializedTxMessage: SERIALIZED, - status: 'error', - }, - }, + args: { lastSimulation: RPC_SIMULATION_FAILED }, }; export const RpcSimulationFailedEmptyMessage: Story = { - args: { - lastSimulation: { - finishedAt: FINISHED_AT, - kind: 'simulation', - logs: ERROR_LOGS, - message: '', - phase: 'rpc_simulation_failed', - serializedTxMessage: SERIALIZED, - status: 'error', - }, - }, + args: { lastSimulation: { ...RPC_SIMULATION_FAILED, message: '' } }, }; export const RpcSimulationFailedLongError: Story = { - args: { - lastSimulation: { - finishedAt: FINISHED_AT, - kind: 'simulation', - logs: ERROR_LOGS, - message: LONG_ERROR, - phase: 'rpc_simulation_failed', - serializedTxMessage: SERIALIZED, - status: 'error', - }, - }, + args: { lastSimulation: { ...RPC_SIMULATION_FAILED, message: LONG_ERROR } }, }; /** Local failure before/during the simulate call, no serialized message — error note, no link. */ diff --git a/app/features/idl/ui/__stories__/IdlCard.responsive.stories.tsx b/app/features/idl/ui/__stories__/IdlCard.responsive.stories.tsx index 1279b6bc6e..1e86503b7f 100644 --- a/app/features/idl/ui/__stories__/IdlCard.responsive.stories.tsx +++ b/app/features/idl/ui/__stories__/IdlCard.responsive.stories.tsx @@ -1,19 +1,14 @@ -import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withClipboardMock, withCluster } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { IdlCard } from '../IdlCard'; +import * as Base from './IdlCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. // Storybook resolves IDL hooks to no-IDL → empty state with upload instructions. const meta = { component: IdlCard, - decorators: [withViewportFromGlobal, withCluster, withClipboardMock], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withViewportFromGlobal, ...Base.default.decorators], tags: ['autodocs', 'test'], title: 'Features/IDL/IdlCard@Media', } satisfies Meta; @@ -21,7 +16,7 @@ const meta = { export default meta; type Story = StoryObj; -const args = { programId: PublicKey.default.toBase58() }; +const args = Base.NoIdl.args; export const Mobile: Story = { args, diff --git a/app/features/idl/ui/__stories__/IdlCard.stories.tsx b/app/features/idl/ui/__stories__/IdlCard.stories.tsx index 5b30805059..33e195ef4f 100644 --- a/app/features/idl/ui/__stories__/IdlCard.stories.tsx +++ b/app/features/idl/ui/__stories__/IdlCard.stories.tsx @@ -1,4 +1,4 @@ -import { nextjsParameters, withClipboardMock, withCluster } from '@storybook-config/decorators'; +import { withClipboardMock, withCluster } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { IdlCard } from '../IdlCard'; @@ -9,7 +9,6 @@ import { IdlCard } from '../IdlCard'; const meta = { component: IdlCard, decorators: [withCluster, withClipboardMock], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/IDL/IdlCard', } satisfies Meta; diff --git a/app/features/idl/ui/__stories__/IdlInstructionSection.stories.tsx b/app/features/idl/ui/__stories__/IdlInstructionSection.stories.tsx index 91b27a8b39..0010e0879e 100644 --- a/app/features/idl/ui/__stories__/IdlInstructionSection.stories.tsx +++ b/app/features/idl/ui/__stories__/IdlInstructionSection.stories.tsx @@ -1,4 +1,4 @@ -import { nextjsParameters, withClipboardMock } from '@storybook-config/decorators'; +import { withClipboardMock } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { IdlInstructionSection } from '../IdlInstructionSection'; @@ -6,7 +6,6 @@ import { IdlInstructionSection } from '../IdlInstructionSection'; const meta = { component: IdlInstructionSection, decorators: [withClipboardMock], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/IDL/IdlInstructionSection', } satisfies Meta; diff --git a/app/features/idl/ui/__stories__/IdlRenderer.stories.tsx b/app/features/idl/ui/__stories__/IdlRenderer.stories.tsx index 583b678bda..9a1af79fe8 100644 --- a/app/features/idl/ui/__stories__/IdlRenderer.stories.tsx +++ b/app/features/idl/ui/__stories__/IdlRenderer.stories.tsx @@ -1,14 +1,12 @@ import type { AnchorIdl, CodamaIdl } from '@entities/idl'; import codamaIdlMock from '@entities/idl/mocks/codama/codama-1.0.0-ProgM6JCCvbYkfKqJYHePx4xxSUSqJp7rh8Lyv7nk7S.json'; import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { IdlRenderer } from '../IdlRenderer'; const meta: Meta = { component: IdlRenderer, - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/IDL/IdlRenderer', }; diff --git a/app/features/idl/ui/__tests__/IdlCard.spec.tsx b/app/features/idl/ui/__tests__/IdlCard.spec.tsx index 70023192c2..f380939d63 100644 --- a/app/features/idl/ui/__tests__/IdlCard.spec.tsx +++ b/app/features/idl/ui/__tests__/IdlCard.spec.tsx @@ -3,7 +3,7 @@ import { gen } from '@__fixtures__/gen'; import type { Idl } from '@coral-xyz/anchor'; import { Keypair, PublicKey } from '@solana/web3.js'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; -import { usePathname, useRouter, useSearchParams } from 'next/navigation'; +import { useSearchParams } from 'next/navigation'; import { vi } from 'vitest'; import type { ProgramIdlPair, ProgramIdls, SupportedIdl } from '@/app/entities/idl'; @@ -20,11 +20,7 @@ const mocks = vi.hoisted(() => ({ useProgramIdls: vi.fn() })); // the `@entities/idl` barrel, which re-exports this module). vi.mock('@/app/entities/idl/model/use-program-idls', () => ({ useProgramIdls: mocks.useProgramIdls })); -vi.mock('next/navigation', () => ({ - usePathname: vi.fn(), - useRouter: vi.fn(), - useSearchParams: vi.fn(), -})); +vi.mock('next/navigation', () => import('@/app/__tests__/next-navigation')); const DEFAULT_ADDRESS = PublicKey.default.toBase58(); const PMP_PDA = gen.vanityAddress('PMP'); @@ -119,14 +115,6 @@ describe('IdlCard', () => { has: (_query?: string) => false, toString: () => '', }); - - (usePathname as ReturnType).mockReturnValue('/'); - - (useRouter as ReturnType).mockReturnValue({ - push: vi.fn(), - refresh: vi.fn(), - replace: vi.fn(), - }); }); test('should render the PMP IDL (no source tabs) when a program-metadata IDL exists', async () => { diff --git a/app/features/instruction-program-mango/__tests__/mango-parser.spec.ts b/app/features/instruction-program-mango/__tests__/mango-parser.spec.ts index 5b6a264248..f7bdec4205 100644 --- a/app/features/instruction-program-mango/__tests__/mango-parser.spec.ts +++ b/app/features/instruction-program-mango/__tests__/mango-parser.spec.ts @@ -1,16 +1,17 @@ +import { makeInstruction } from '@__fixtures__/instruction'; import { createInstructionParserDispatcher } from '@entities/instruction-parser'; import { MANGO_PROGRAM_IDS } from '@explorer/decoder-mango'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; import { describe, expect, it } from 'vitest'; import { mangoInstructionParsers } from '../lib/mango-client'; import { MANGO_PROGRAM_LABEL } from '../lib/mango-parser'; const dispatcher = createInstructionParserDispatcher(mangoInstructionParsers); +const makeIx = (data: number[]) => makeInstruction({ data, programId: MANGO_PROGRAM_IDS.mainnet }); describe('parseMangoInstruction', () => { it('should resolve a known discriminator to its name', () => { - expect(dispatcher.fromTransactionInstruction(makeInstruction([2, 0, 0, 0]))).toMatchObject({ + expect(dispatcher.fromTransactionInstruction(makeIx([2, 0, 0, 0]))).toMatchObject({ parsed: { info: {}, type: 'Deposit' }, program: MANGO_PROGRAM_LABEL, }); @@ -20,7 +21,7 @@ describe('parseMangoInstruction', () => { { data: [255, 255, 0, 0], label: 'a discriminator outside the name table' }, { data: [], label: 'an instruction without data' }, ])('should leave $label unparsed', ({ data }) => { - expect(dispatcher.fromTransactionInstruction(makeInstruction(data))).toMatchObject({ + expect(dispatcher.fromTransactionInstruction(makeIx(data))).toMatchObject({ programLabel: MANGO_PROGRAM_LABEL, unknown: true, }); @@ -30,11 +31,3 @@ describe('parseMangoInstruction', () => { expect(dispatcher.getInstructionParser(programId)?.programLabel).toBe(MANGO_PROGRAM_LABEL); }); }); - -function makeInstruction(data: number[]): TransactionInstruction { - return new TransactionInstruction({ - data: Buffer.from(data), - keys: [], - programId: new PublicKey(MANGO_PROGRAM_IDS.mainnet), - }); -} diff --git a/app/features/instruction-program-serum/__tests__/serum-parser.spec.ts b/app/features/instruction-program-serum/__tests__/serum-parser.spec.ts index d83af0fa34..9fcef89345 100644 --- a/app/features/instruction-program-serum/__tests__/serum-parser.spec.ts +++ b/app/features/instruction-program-serum/__tests__/serum-parser.spec.ts @@ -9,8 +9,6 @@ import { Logger } from '@/app/shared/lib/logger'; import { serumInstructionParsers } from '../lib/serum-client'; import { parseSerumInstruction, SERUM_PROGRAM_LABEL } from '../lib/serum-parser'; -vi.mock('@/app/shared/lib/logger', () => ({ Logger: { error: vi.fn() } })); - const MARKET = address('FagABcRBhZH27JDtu6A1Jo9woXyoznP28QujLkxkN9Hj'); const EVENT_QUEUE = address('7txXZZD6Um59YoLMF7XUNimbMjsqsWhc7g2EniiTrmp1'); const OPEN_ORDERS = address('GgU1RSCbCTNfjPqBGnR7NBDZoLQwB7oEjnHqzGtcCLBH'); diff --git a/app/features/instruction-program-serum/ui/__stories__/SerumDetailsCard.responsive.stories.tsx b/app/features/instruction-program-serum/ui/__stories__/SerumDetailsCard.responsive.stories.tsx index 3300338e52..e207da91a6 100644 --- a/app/features/instruction-program-serum/ui/__stories__/SerumDetailsCard.responsive.stories.tsx +++ b/app/features/instruction-program-serum/ui/__stories__/SerumDetailsCard.responsive.stories.tsx @@ -1,60 +1,14 @@ -import { gen } from '@__fixtures__/gen'; -import { toInstructionNode } from '@entities/instruction-card'; -import { createInstructionParserDispatcher, isParsedInstruction } from '@entities/instruction-parser'; -import { OPEN_BOOK_PROGRAM_IDS } from '@explorer/decoder-serum'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; -import { - nextjsParameters, - withCluster, - withMockTransactions, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import { invariant } from '@/app/shared/lib/invariant'; - -import { serumInstructionParsers } from '../../lib/serum-client'; import { SerumDetailsCard } from '../SerumDetailsCard'; +import * as Base from './SerumDetailsCard.stories'; -// New Order v3 data from mainnet tx 2fHxffhsx9pJ… (sell, ioc, limit price 50000). -const NEW_ORDER_V3_DATA = - '000a0000000100000050c30000000000000400000000000000400d03000000000000000000010000000000000000000000ffff'; - -const raw = new TransactionInstruction({ - data: Buffer.from(NEW_ORDER_V3_DATA, 'hex'), - keys: Array.from({ length: 12 }, (_, i) => ({ - isSigner: false, - isWritable: false, - pubkey: gen.publicKey(i), - })), - programId: new PublicKey(OPEN_BOOK_PROGRAM_IDS.mainnet), -}); - -const dispatched = createInstructionParserDispatcher(serumInstructionParsers).fromTransactionInstruction(raw); -invariant(dispatched, 'the OpenBook program id is registered'); - -const args = { - node: toInstructionNode({ index: 0, ix: raw }), - parsed: isParsedInstruction(dispatched) ? dispatched.parsed : undefined, -}; +const args = Base.NewOrderV3.args; const meta: Meta = { component: SerumDetailsCard, - decorators: [ - withCluster, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, - withMockTransactions, - withViewportFromGlobal, - ], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [...Base.default.decorators, withViewportFromGlobal], tags: ['autodocs', 'test'], title: 'Features/InstructionProgramSerum/SerumDetailsCard@Media', }; diff --git a/app/features/instruction-program-serum/ui/__stories__/SerumDetailsCard.stories.tsx b/app/features/instruction-program-serum/ui/__stories__/SerumDetailsCard.stories.tsx index 7648e2311a..62a641f897 100644 --- a/app/features/instruction-program-serum/ui/__stories__/SerumDetailsCard.stories.tsx +++ b/app/features/instruction-program-serum/ui/__stories__/SerumDetailsCard.stories.tsx @@ -1,16 +1,9 @@ import { gen } from '@__fixtures__/gen'; +import { makeInstruction } from '@__fixtures__/instruction'; import { toInstructionNode } from '@entities/instruction-card'; import { createInstructionParserDispatcher, isParsedInstruction } from '@entities/instruction-parser'; import { OPEN_BOOK_PROGRAM_IDS } from '@explorer/decoder-serum'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; -import { - nextjsParameters, - withCluster, - withMockTransactions, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; +import { instructionCardDecorators } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { invariant } from '@/app/shared/lib/invariant'; @@ -25,15 +18,8 @@ const NEW_ORDER_V3_DATA = const dispatcher = createInstructionParserDispatcher(serumInstructionParsers); function storyArgs(data: Buffer, keyCount: number) { - const raw = new TransactionInstruction({ - data, - keys: Array.from({ length: keyCount }, (_, i) => ({ - isSigner: false, - isWritable: false, - pubkey: gen.publicKey(i), - })), - programId: new PublicKey(OPEN_BOOK_PROGRAM_IDS.mainnet), - }); + const keys = Array.from({ length: keyCount }, (_, i) => gen.publicKey(i)); + const raw = makeInstruction({ data, keys, programId: OPEN_BOOK_PROGRAM_IDS.mainnet }); const dispatched = dispatcher.fromTransactionInstruction(raw); invariant(dispatched, 'the OpenBook program id is registered'); return { @@ -42,13 +28,12 @@ function storyArgs(data: Buffer, keyCount: number) { }; } -const meta: Meta = { +const meta = { component: SerumDetailsCard, - decorators: [withCluster, withScrollAnchor, withTokenInfoBatch, withTxInstructionSurface, withMockTransactions], - parameters: nextjsParameters, + decorators: instructionCardDecorators, tags: ['autodocs', 'test'], title: 'Features/InstructionProgramSerum/SerumDetailsCard', -}; +} satisfies Meta; export default meta; type Story = StoryObj; diff --git a/app/features/instruction-program-serum/ui/__tests__/SerumDetailsCard.spec.tsx b/app/features/instruction-program-serum/ui/__tests__/SerumDetailsCard.spec.tsx index 5c753b894a..1a613ca937 100644 --- a/app/features/instruction-program-serum/ui/__tests__/SerumDetailsCard.spec.tsx +++ b/app/features/instruction-program-serum/ui/__tests__/SerumDetailsCard.spec.tsx @@ -1,9 +1,10 @@ /* eslint-disable no-restricted-syntax -- test assertions use RegExp for pattern matching */ import { gen } from '@__fixtures__/gen'; +import { makeInstruction } from '@__fixtures__/instruction'; import { toInstructionNode } from '@entities/instruction-card'; import { createInstructionParserDispatcher, isParsedInstruction } from '@entities/instruction-parser'; import { OPEN_BOOK_PROGRAM_IDS, SERUM_DEX_V3_PROGRAM_IDS } from '@explorer/decoder-serum'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; +import { TransactionInstruction } from '@solana/web3.js'; import { screen, waitFor } from '@testing-library/react'; import { vi } from 'vitest'; @@ -24,7 +25,7 @@ const dispatcher = createInstructionParserDispatcher(serumInstructionParsers); describe('@features/instruction-program-serum', () => { describe('SerumDetailsCard', () => { test('should render decoded fields for a New Order v3 instruction', async () => { - renderCard(makeInstruction(NEW_ORDER_V3_DATA, 12)); + renderCard(makeIx(NEW_ORDER_V3_DATA, 12)); // waitFor's act() boundary absorbs ClusterProvider's post-mount dispatch await waitFor(() => { @@ -45,7 +46,7 @@ describe('@features/instruction-program-serum', () => { test('should stack every open-orders account into one row for a Consume Events instruction', async () => { // 6 keys: openOrders = keys[0..1], market = keys[2], eventQueue = keys[3] - renderCard(makeInstruction(CONSUME_EVENTS_DATA, 6)); + renderCard(makeIx(CONSUME_EVENTS_DATA, 6)); // waitFor's act() boundary absorbs ClusterProvider's post-mount dispatch await waitFor(() => { @@ -60,7 +61,7 @@ describe('@features/instruction-program-serum', () => { }); test('should omit the Open Orders row for a Consume Events instruction with no open-orders account', async () => { - renderCard(makeInstruction(CONSUME_EVENTS_DATA, 4)); + renderCard(makeIx(CONSUME_EVENTS_DATA, 4)); // waitFor's act() boundary absorbs ClusterProvider's post-mount dispatch await waitFor(() => { @@ -70,7 +71,7 @@ describe('@features/instruction-program-serum', () => { }); test('should fall back to the raw card with an "Unknown" title for undecodable data', async () => { - renderCard(makeInstruction('00ff000000', 0)); + renderCard(makeIx('00ff000000', 0)); // waitFor's act() boundary absorbs ClusterProvider's post-mount dispatch await waitFor(() => { @@ -80,7 +81,7 @@ describe('@features/instruction-program-serum', () => { }); test('should render a deprecated Serum deployment name-only under its program name', async () => { - renderCard(makeInstruction(CONSUME_EVENTS_DATA, 6, SERUM_DEX_V3_PROGRAM_IDS.mainnet)); + renderCard(makeIx(CONSUME_EVENTS_DATA, 6, SERUM_DEX_V3_PROGRAM_IDS.mainnet)); // waitFor's act() boundary absorbs ClusterProvider's post-mount dispatch await waitFor(() => { @@ -90,7 +91,7 @@ describe('@features/instruction-program-serum', () => { }); test('should title an instruction on a deprecated deployment "Unknown" when its code is unrecognized', async () => { - renderCard(makeInstruction('00ff000000', 0, SERUM_DEX_V3_PROGRAM_IDS.mainnet)); + renderCard(makeIx('00ff000000', 0, SERUM_DEX_V3_PROGRAM_IDS.mainnet)); // waitFor's act() boundary absorbs ClusterProvider's post-mount dispatch await waitFor(() => { @@ -99,7 +100,7 @@ describe('@features/instruction-program-serum', () => { }); test('should title a named code with no vendored layout from the name table', async () => { - renderCard(makeInstruction('0007000000', 0)); + renderCard(makeIx('0007000000', 0)); // waitFor's act() boundary absorbs ClusterProvider's post-mount dispatch await waitFor(() => { @@ -109,7 +110,7 @@ describe('@features/instruction-program-serum', () => { }); test('should title a recognized code with a truncated payload by name', async () => { - renderCard(makeInstruction('000a00000001', 0)); + renderCard(makeIx('000a00000001', 0)); // waitFor's act() boundary absorbs ClusterProvider's post-mount dispatch await waitFor(() => { @@ -119,20 +120,9 @@ describe('@features/instruction-program-serum', () => { }); }); -function makeInstruction( - dataHex: string, - keyCount: number, - programId: string = OPEN_BOOK_PROGRAM_IDS.mainnet, -): TransactionInstruction { - return new TransactionInstruction({ - data: Buffer.from(dataHex, 'hex'), - keys: Array.from({ length: keyCount }, (_, i) => ({ - isSigner: false, - isWritable: false, - pubkey: gen.publicKey(i), - })), - programId: new PublicKey(programId), - }); +function makeIx(dataHex: string, keyCount: number, programId: string = OPEN_BOOK_PROGRAM_IDS.mainnet) { + const keys = Array.from({ length: keyCount }, (_, i) => gen.publicKey(i)); + return makeInstruction({ data: Buffer.from(dataHex, 'hex'), keys, programId }); } function renderCard(raw: TransactionInstruction) { diff --git a/app/features/instruction-program-token-swap/__tests__/token-swap-parser.spec.ts b/app/features/instruction-program-token-swap/__tests__/token-swap-parser.spec.ts index 9a729ffec4..5d3c2cb4c1 100644 --- a/app/features/instruction-program-token-swap/__tests__/token-swap-parser.spec.ts +++ b/app/features/instruction-program-token-swap/__tests__/token-swap-parser.spec.ts @@ -1,6 +1,6 @@ +import { makeInstruction } from '@__fixtures__/instruction'; import { createInstructionParserDispatcher } from '@entities/instruction-parser'; import { TOKEN_SWAP_PROGRAM_IDS } from '@explorer/decoder-token-swap'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { Logger } from '@/app/shared/lib/logger'; @@ -8,9 +8,8 @@ import { Logger } from '@/app/shared/lib/logger'; import { tokenSwapInstructionParsers } from '../lib/token-swap-client'; import { TOKEN_SWAP_PROGRAM_LABEL } from '../lib/token-swap-parser'; -vi.mock('@/app/shared/lib/logger', () => ({ Logger: { error: vi.fn() } })); - const dispatcher = createInstructionParserDispatcher(tokenSwapInstructionParsers); +const makeIx = (data: number[]) => makeInstruction({ data, programId: TOKEN_SWAP_PROGRAM_IDS[0] }); describe('parseTokenSwapInstruction', () => { beforeEach(() => { @@ -18,7 +17,7 @@ describe('parseTokenSwapInstruction', () => { }); it('should resolve a known tag to its name', () => { - expect(dispatcher.fromTransactionInstruction(makeInstruction([1]))).toMatchObject({ + expect(dispatcher.fromTransactionInstruction(makeIx([1]))).toMatchObject({ parsed: { info: {}, type: 'Swap' }, program: TOKEN_SWAP_PROGRAM_LABEL, }); @@ -26,7 +25,7 @@ describe('parseTokenSwapInstruction', () => { }); it('should leave a tag outside the name table unparsed and report it', () => { - expect(dispatcher.fromTransactionInstruction(makeInstruction([255]))).toMatchObject({ + expect(dispatcher.fromTransactionInstruction(makeIx([255]))).toMatchObject({ programLabel: TOKEN_SWAP_PROGRAM_LABEL, unknown: true, }); @@ -34,11 +33,3 @@ describe('parseTokenSwapInstruction', () => { expect(Logger.error).toHaveBeenCalledOnce(); }); }); - -function makeInstruction(data: number[]): TransactionInstruction { - return new TransactionInstruction({ - data: Buffer.from(data), - keys: [], - programId: new PublicKey(TOKEN_SWAP_PROGRAM_IDS[0]), - }); -} diff --git a/app/features/instruction-program-wormhole/__tests__/wormhole-parser.spec.ts b/app/features/instruction-program-wormhole/__tests__/wormhole-parser.spec.ts index 63b9379027..db1b2887c0 100644 --- a/app/features/instruction-program-wormhole/__tests__/wormhole-parser.spec.ts +++ b/app/features/instruction-program-wormhole/__tests__/wormhole-parser.spec.ts @@ -1,6 +1,6 @@ +import { makeInstruction } from '@__fixtures__/instruction'; import { createInstructionParserDispatcher } from '@entities/instruction-parser'; import { WORMHOLE_PROGRAM_IDS } from '@explorer/decoder-wormhole'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { Logger } from '@/app/shared/lib/logger'; @@ -8,9 +8,8 @@ import { Logger } from '@/app/shared/lib/logger'; import { wormholeInstructionParsers } from '../lib/wormhole-client'; import { WORMHOLE_PROGRAM_LABEL } from '../lib/wormhole-parser'; -vi.mock('@/app/shared/lib/logger', () => ({ Logger: { error: vi.fn() } })); - const dispatcher = createInstructionParserDispatcher(wormholeInstructionParsers); +const makeIx = (data: number[]) => makeInstruction({ data, programId: WORMHOLE_PROGRAM_IDS[0] }); describe('parseWormholeInstruction', () => { beforeEach(() => { @@ -18,7 +17,7 @@ describe('parseWormholeInstruction', () => { }); it('should resolve a known tag to its name', () => { - expect(dispatcher.fromTransactionInstruction(makeInstruction([2]))).toMatchObject({ + expect(dispatcher.fromTransactionInstruction(makeIx([2]))).toMatchObject({ parsed: { info: {}, type: 'Post VAA' }, program: WORMHOLE_PROGRAM_LABEL, }); @@ -26,7 +25,7 @@ describe('parseWormholeInstruction', () => { }); it('should leave a tag outside the name table unparsed and report it', () => { - expect(dispatcher.fromTransactionInstruction(makeInstruction([255]))).toMatchObject({ + expect(dispatcher.fromTransactionInstruction(makeIx([255]))).toMatchObject({ programLabel: WORMHOLE_PROGRAM_LABEL, unknown: true, }); @@ -34,11 +33,3 @@ describe('parseWormholeInstruction', () => { expect(Logger.error).toHaveBeenCalledOnce(); }); }); - -function makeInstruction(data: number[]): TransactionInstruction { - return new TransactionInstruction({ - data: Buffer.from(data), - keys: [], - programId: new PublicKey(WORMHOLE_PROGRAM_IDS[0]), - }); -} diff --git a/app/features/instruction-simulation/ui/__stories__/BaseSimulatorCUProfilingCard.stories.tsx b/app/features/instruction-simulation/ui/__stories__/BaseSimulatorCUProfilingCard.stories.tsx index 7e2b5546f8..7f7ba1a776 100644 --- a/app/features/instruction-simulation/ui/__stories__/BaseSimulatorCUProfilingCard.stories.tsx +++ b/app/features/instruction-simulation/ui/__stories__/BaseSimulatorCUProfilingCard.stories.tsx @@ -1,5 +1,4 @@ import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { Cluster } from '@utils/cluster'; @@ -10,7 +9,6 @@ const TOKEN_PROGRAM = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA const meta: Meta = { component: BaseSimulatorCUProfilingCard, - parameters: { ...nextjsParameters }, tags: ['autodocs', 'test'], // TODO(dashkit): rename to match BaseSimulatorCUProfilingCard once the Dashkit migration lands. Kept // as-is so the Storybook tree does not churn mid-migration. diff --git a/app/features/instruction-simulation/ui/__stories__/SimulatedBadge.stories.tsx b/app/features/instruction-simulation/ui/__stories__/SimulatedBadge.stories.tsx index 624ad24f31..f4979946a2 100644 --- a/app/features/instruction-simulation/ui/__stories__/SimulatedBadge.stories.tsx +++ b/app/features/instruction-simulation/ui/__stories__/SimulatedBadge.stories.tsx @@ -1,11 +1,9 @@ -import { nextjsParameters } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { SimulatedBadge } from '../SimulatedBadge'; const meta: Meta = { component: SimulatedBadge, - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/InstructionSimulation/SimulatedBadge', }; diff --git a/app/features/instruction-simulation/ui/__stories__/SimulationCard.responsive.stories.tsx b/app/features/instruction-simulation/ui/__stories__/SimulationCard.responsive.stories.tsx index f7bc48ae00..eec663b3af 100644 --- a/app/features/instruction-simulation/ui/__stories__/SimulationCard.responsive.stories.tsx +++ b/app/features/instruction-simulation/ui/__stories__/SimulationCard.responsive.stories.tsx @@ -1,22 +1,13 @@ -import { mockVersionedMessage } from '@storybook-config/__fixtures__/messages'; -import { nextjsParameters, withCluster } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { SimulatorCard } from '../SimulationCard'; +import * as Base from './SimulationCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. -const idleMessage = mockVersionedMessage({ - serialize: () => new Uint8Array(), -}); - const meta = { component: SimulatorCard, - decorators: [withViewportFromGlobal, withCluster], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withViewportFromGlobal, ...Base.default.decorators], tags: ['autodocs', 'test'], title: 'Features/InstructionSimulation/SimulationCard@Media', } satisfies Meta; @@ -24,10 +15,7 @@ const meta = { export default meta; type Story = StoryObj; -const args = { - message: idleMessage, - showTokenBalanceChanges: false, -}; +const args = Base.Idle.args; export const Mobile: Story = { args, diff --git a/app/features/instruction-simulation/ui/__stories__/SimulationCard.stories.tsx b/app/features/instruction-simulation/ui/__stories__/SimulationCard.stories.tsx index 30e6362c63..dc6be9cd24 100644 --- a/app/features/instruction-simulation/ui/__stories__/SimulationCard.stories.tsx +++ b/app/features/instruction-simulation/ui/__stories__/SimulationCard.stories.tsx @@ -1,5 +1,5 @@ import { mockVersionedMessage } from '@storybook-config/__fixtures__/messages'; -import { nextjsParameters, withCluster } from '@storybook-config/decorators'; +import { withCluster } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { SimulatorCard } from '../SimulationCard'; @@ -13,7 +13,6 @@ const idleMessage = mockVersionedMessage({ const meta = { component: SimulatorCard, decorators: [withCluster], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/InstructionSimulation/SimulationCard', } satisfies Meta; diff --git a/app/features/instruction-simulation/ui/__stories__/SolBalanceChangesCard.responsive.stories.tsx b/app/features/instruction-simulation/ui/__stories__/SolBalanceChangesCard.responsive.stories.tsx index 996b8b47b7..1a2379ba26 100644 --- a/app/features/instruction-simulation/ui/__stories__/SolBalanceChangesCard.responsive.stories.tsx +++ b/app/features/instruction-simulation/ui/__stories__/SolBalanceChangesCard.responsive.stories.tsx @@ -1,33 +1,12 @@ -import { gen } from '@__fixtures__/gen'; -import { PublicKey } from '@solana/web3.js'; -import { SYSTEM_PROGRAM_ADDRESS } from '@solana-program/system'; -import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import BN from 'bn.js'; -import type { SolBalanceChange } from '../../lib/types'; import { SolBalanceChangesCard } from '../SolBalanceChangesCard'; - -const ALICE = gen.publicKey(1).toBase58(); - -function change(pubkey: string, delta: string, preBalance: string, postBalance: string): SolBalanceChange { - return { - delta: new BN(delta), - postBalance: new BN(postBalance), - preBalance: new BN(preBalance), - pubkey: new PublicKey(pubkey), - }; -} +import * as Base from './SolBalanceChangesCard.stories'; const meta: Meta = { component: SolBalanceChangesCard, - decorators: [withClusterAndAccounts, withTokenInfoBatch, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [...Base.default.decorators, withViewportFromGlobal], tags: ['autodocs', 'test'], title: 'Features/InstructionSimulation/SolBalanceChangesCard@Media', }; @@ -35,13 +14,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - balanceChanges: [ - change(ALICE, '-2000000000', '5000000000', '3000000000'), - change(TOKEN_PROGRAM_ADDRESS, '1500000000', '1000000000', '2500000000'), - change(SYSTEM_PROGRAM_ADDRESS, '500000000', '0', '500000000'), - ], -}; +const args = Base.MultipleChanges.args; export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; diff --git a/app/features/instruction-simulation/ui/__stories__/SolBalanceChangesCard.stories.tsx b/app/features/instruction-simulation/ui/__stories__/SolBalanceChangesCard.stories.tsx index 21e952a09a..dd8c3239da 100644 --- a/app/features/instruction-simulation/ui/__stories__/SolBalanceChangesCard.stories.tsx +++ b/app/features/instruction-simulation/ui/__stories__/SolBalanceChangesCard.stories.tsx @@ -2,7 +2,7 @@ import { gen } from '@__fixtures__/gen'; import { PublicKey } from '@solana/web3.js'; import { SYSTEM_PROGRAM_ADDRESS } from '@solana-program/system'; import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import BN from 'bn.js'; import { expect, within } from 'storybook/test'; @@ -15,7 +15,6 @@ const ALICE = gen.publicKey(1).toBase58(); const meta = { component: SolBalanceChangesCard, decorators: [withClusterAndAccounts, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/InstructionSimulation/SolBalanceChangesCard', } satisfies Meta; diff --git a/app/features/instruction-simulation/ui/__tests__/SolBalanceChangesCard.spec.tsx b/app/features/instruction-simulation/ui/__tests__/SolBalanceChangesCard.spec.tsx index f7afbe0b8b..34b19f4dce 100644 --- a/app/features/instruction-simulation/ui/__tests__/SolBalanceChangesCard.spec.tsx +++ b/app/features/instruction-simulation/ui/__tests__/SolBalanceChangesCard.spec.tsx @@ -11,9 +11,7 @@ import { SolBalanceChangesCard } from '../SolBalanceChangesCard'; const ARBITRARY_KEY = Keypair.generate().publicKey.toBase58(); -vi.mock('@components/common/Address', () => ({ - Address: ({ pubkey }: { pubkey: PublicKey }) =>
{pubkey.toBase58()}
, -})); +vi.mock('@components/common/Address', () => import('@/app/__tests__/address-stub')); vi.mock('@components/common/BalanceDelta', () => ({ BalanceDelta: ({ delta, isSol }: { delta: BN; isSol: boolean }) => ( diff --git a/app/features/mcp-docs/ui/__stories__/McpDocsOverviewView.responsive.stories.tsx b/app/features/mcp-docs/ui/__stories__/McpDocsOverviewView.responsive.stories.tsx index 3b845e2b2b..4324880df7 100644 --- a/app/features/mcp-docs/ui/__stories__/McpDocsOverviewView.responsive.stories.tsx +++ b/app/features/mcp-docs/ui/__stories__/McpDocsOverviewView.responsive.stories.tsx @@ -1,15 +1,13 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { McpDocsOverviewView } from '../McpDocsOverviewView'; +import * as Base from './McpDocsOverviewView.stories'; const meta: Meta = { component: McpDocsOverviewView, decorators: [withViewportFromGlobal], - parameters: { - layout: 'fullscreen', - viewport: { options: INITIAL_VIEWPORTS }, - }, + parameters: Base.default.parameters, tags: ['autodocs', 'test'], title: 'Features/McpDocs/Overview@Media', }; diff --git a/app/features/metadata/mocks.ts b/app/features/metadata/mocks.ts index b869fb145e..e2590c01e7 100644 --- a/app/features/metadata/mocks.ts +++ b/app/features/metadata/mocks.ts @@ -29,10 +29,11 @@ export function getMockAccountWithNFTData(): Account { } as unknown as Account; // Account type is incomplete and incorrect for some fields, fixing it would require a lot of unrelated changes } -export function getMockAccountWithTokenMetadata(): Account { +export function getMockAccountWithTokenMetadata(nftData?: NFTData): Account { return { data: { parsed: { + nftData, parsed: { info: { decimals: 6, @@ -56,30 +57,7 @@ export function getMockAccountWithTokenMetadata(): Account { } export function getMockAccountWithTokenMetadataAndMetaplexMetadata(): Account { - return { - data: { - parsed: { - nftData: getNftData(), - parsed: { - info: { - decimals: 6, - extensions: getTokenExtension(), - freezeAuthority: '2apBGMsS6ti9RyF5TwQTDswXBWskiJP2LD4cUEDqYJjk', - isInitialized: true, - mintAuthority: 'FtrZqgM9begkaLHq3f4hGEUrAK1jjJpkc8hZ1hVk3EDN', - supply: '997647954721900', - }, - type: 'mint', - }, - program: 'spl-token-2022', - }, - }, - executable: false, - lamports: 2064720952, - owner: new PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'), - pubkey: new PublicKey('2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo'), - space: 866, - }; + return getMockAccountWithTokenMetadata(getNftData()); } export function getMockAccountWithCompressedNft(): Account { diff --git a/app/features/metadata/ui/__stories__/MetadataCard.stories.tsx b/app/features/metadata/ui/__stories__/MetadataCard.stories.tsx index fadb1dfbee..3578073a6a 100644 --- a/app/features/metadata/ui/__stories__/MetadataCard.stories.tsx +++ b/app/features/metadata/ui/__stories__/MetadataCard.stories.tsx @@ -9,18 +9,6 @@ import { MetadataCard } from '../MetadataCard'; const meta = { component: MetadataCard, - decorators: [ - Story => ( -
- -
- ), - ], - parameters: { - nextjs: { - appDirectory: true, - }, - }, tags: ['autodocs', 'test'], title: 'Features/Metadata/MetadataCard', } satisfies Meta; diff --git a/app/features/mpl-token-metadata/__fixtures__/instructions.ts b/app/features/mpl-token-metadata/__fixtures__/instructions.ts new file mode 100644 index 0000000000..4eb7bfc01b --- /dev/null +++ b/app/features/mpl-token-metadata/__fixtures__/instructions.ts @@ -0,0 +1,30 @@ +import { gen } from '@__fixtures__/gen'; +import { makeInstruction } from '@__fixtures__/instruction'; +import { + getCreateMetadataAccountV3InstructionDataSerializer, + MPL_TOKEN_METADATA_PROGRAM_ID, +} from '@metaplex-foundation/mpl-token-metadata'; +import { none } from '@metaplex-foundation/umi'; +import type { PublicKey } from '@solana/web3.js'; + +export const KEYS = Array.from({ length: 20 }, (_, n) => gen.publicKey(n + 1)); + +export function tokenMetadataInstruction(data: Uint8Array | number[], keys: PublicKey[] = []) { + return makeInstruction({ data, keys, programId: MPL_TOKEN_METADATA_PROGRAM_ID }); +} + +export function createMetadataAccountV3Data({ sellerFeeBasisPoints = 500, uri = 'https://example.com/nft.json' } = {}) { + return getCreateMetadataAccountV3InstructionDataSerializer().serialize({ + collectionDetails: none(), + data: { + collection: none(), + creators: none(), + name: 'My NFT', + sellerFeeBasisPoints, + symbol: 'MNFT', + uri, + uses: none(), + }, + isMutable: true, + }); +} diff --git a/app/features/mpl-token-metadata/__tests__/metaplex-token-metadata-parser.spec.ts b/app/features/mpl-token-metadata/__tests__/metaplex-token-metadata-parser.spec.ts index 1f85e5cc84..5ce1981960 100644 --- a/app/features/mpl-token-metadata/__tests__/metaplex-token-metadata-parser.spec.ts +++ b/app/features/mpl-token-metadata/__tests__/metaplex-token-metadata-parser.spec.ts @@ -1,39 +1,24 @@ import { getCreateMasterEditionV3InstructionDataSerializer, - getCreateMetadataAccountV3InstructionDataSerializer, getUpdateMetadataAccountV2InstructionDataSerializer, } from '@metaplex-foundation/mpl-token-metadata'; -import { MPL_TOKEN_METADATA_PROGRAM_ID } from '@metaplex-foundation/mpl-token-metadata'; import { none, publicKey as umiPublicKey, some } from '@metaplex-foundation/umi'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; +import { PublicKey } from '@solana/web3.js'; import { describe, expect, test } from 'vitest'; import { type KitInstruction, toKitInstruction } from '@/app/shared/lib/web3js-compat'; +import { createMetadataAccountV3Data, KEYS, tokenMetadataInstruction } from '../__fixtures__/instructions'; import { identifyInstructionType, parseMetaplexTokenMetadataInstruction } from '../lib/metaplex-token-metadata-parser'; -const PROGRAM_ID = new PublicKey(MPL_TOKEN_METADATA_PROGRAM_ID); - -// Generated test public keys (byte-filled for readability) -const KEY_A = new PublicKey(new Uint8Array(32).fill(1)); -const KEY_B = new PublicKey(new Uint8Array(32).fill(2)); -const KEY_C = new PublicKey(new Uint8Array(32).fill(3)); -const KEY_D = new PublicKey(new Uint8Array(32).fill(4)); -const KEY_E = PublicKey.default; +const [KEY_A, KEY_B, KEY_C, KEY_D, KEY_E] = KEYS; // Hoisted serializers — construction allocates nested objects, so share across tests -const createMetadataV3Serializer = getCreateMetadataAccountV3InstructionDataSerializer(); const updateMetadataV2Serializer = getUpdateMetadataAccountV2InstructionDataSerializer(); const createMasterEditionV3Serializer = getCreateMasterEditionV3InstructionDataSerializer(); function makeIx(data: Uint8Array | Buffer, keys: PublicKey[] = []): KitInstruction { - return toKitInstruction( - new TransactionInstruction({ - data: Buffer.from(data), - keys: keys.map(pubkey => ({ isSigner: false, isWritable: false, pubkey })), - programId: PROGRAM_ID, - }), - ); + return toKitInstruction(tokenMetadataInstruction(data, keys)); } function assertParsed(val: T | null | undefined): T { @@ -179,28 +164,10 @@ describe('parseMetaplexTokenMetadataInstruction', () => { ); describe('createMetadataAccountV3', () => { - function buildData(name: string, symbol: string, uri: string, basisPoints: number, isMutable: boolean) { - return Buffer.from( - createMetadataV3Serializer.serialize({ - collectionDetails: none(), - data: { - collection: none(), - creators: none(), - name, - sellerFeeBasisPoints: basisPoints, - symbol, - uri, - uses: none(), - }, - isMutable, - }), - ); - } - test('should decode data fields and map account keys', () => { // keys: metadata[0], mint[1], mintAuthority[2], payer[3], updateAuthority[4] const keys = [KEY_A, KEY_B, KEY_C, KEY_D, KEY_E]; - const ix = makeIx(buildData('My NFT', 'MNFT', 'https://example.com/nft', 500, true), keys); + const ix = makeIx(createMetadataAccountV3Data({ uri: 'https://example.com/nft' }), keys); const result = assertParsed(parseMetaplexTokenMetadataInstruction(ix)); expect(result.type).toBe('createMetadataAccountV3'); diff --git a/app/features/mpl-token-metadata/ui/__stories__/MetaplexTokenMetadataDetailsCard.stories.tsx b/app/features/mpl-token-metadata/ui/__stories__/MetaplexTokenMetadataDetailsCard.stories.tsx index 833ccb14b7..d683afdd7c 100644 --- a/app/features/mpl-token-metadata/ui/__stories__/MetaplexTokenMetadataDetailsCard.stories.tsx +++ b/app/features/mpl-token-metadata/ui/__stories__/MetaplexTokenMetadataDetailsCard.stories.tsx @@ -6,32 +6,21 @@ import { } from '@entities/instruction-parser'; import { getCreateMasterEditionV3InstructionDataSerializer, - getCreateMetadataAccountV3InstructionDataSerializer, getUpdateMetadataAccountV2InstructionDataSerializer, } from '@metaplex-foundation/mpl-token-metadata'; -import { MPL_TOKEN_METADATA_PROGRAM_ID } from '@metaplex-foundation/mpl-token-metadata'; import { none, some } from '@metaplex-foundation/umi'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; -import { - nextjsParameters, - withTokenInfoBatch, - withTransactions, - withTxInstructionSurface, -} from '@storybook-config/decorators'; +import type { PublicKey } from '@solana/web3.js'; +import { instructionCardDecorators } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; import { invariant } from '@/app/shared/lib/invariant'; +import { createMetadataAccountV3Data, KEYS, tokenMetadataInstruction } from '../../__fixtures__/instructions'; import { metaplexTokenMetadataInstructionParser } from '../../lib/metaplex-token-metadata-client'; import { MetaplexTokenMetadataDetailsCard } from '../MetaplexTokenMetadataDetailsCard'; -const PROGRAM_ID = new PublicKey(MPL_TOKEN_METADATA_PROGRAM_ID); -const KEY_A = new PublicKey(new Uint8Array(32).fill(1)); -const KEY_B = new PublicKey(new Uint8Array(32).fill(2)); -const KEY_C = new PublicKey(new Uint8Array(32).fill(3)); -const KEY_D = new PublicKey(new Uint8Array(32).fill(4)); -const KEY_E = PublicKey.default; +const [KEY_A, KEY_B, KEY_C, KEY_D, KEY_E] = KEYS; const dispatcher = createInstructionParserDispatcher([metaplexTokenMetadataInstructionParser]); @@ -40,11 +29,7 @@ function makeIx( data: Uint8Array | Buffer, keys: PublicKey[] = [], ): { node: InstructionNode; parsed: ParsedInstructionInfo | undefined } { - const raw = new TransactionInstruction({ - data: Buffer.from(data), - keys: keys.map(pubkey => ({ isSigner: false, isWritable: false, pubkey })), - programId: PROGRAM_ID, - }); + const raw = tokenMetadataInstruction(data, keys); const dispatched = dispatcher.fromTransactionInstruction(raw); invariant(dispatched, 'the token metadata program is registered'); return { @@ -53,16 +38,12 @@ function makeIx( }; } -const createMetadataV3Serializer = getCreateMetadataAccountV3InstructionDataSerializer(); const updateMetadataV2Serializer = getUpdateMetadataAccountV2InstructionDataSerializer(); const createMasterEditionV3Serializer = getCreateMasterEditionV3InstructionDataSerializer(); const meta = { component: MetaplexTokenMetadataDetailsCard, - decorators: [withTxInstructionSurface, withTransactions, withTokenInfoBatch], - parameters: { - ...nextjsParameters, - }, + decorators: instructionCardDecorators, tags: ['autodocs', 'test'], title: 'Features/MplTokenMetadata/MetaplexTokenMetadataDetailsCard', } satisfies Meta; @@ -71,25 +52,7 @@ export default meta; type Story = StoryObj; export const CreateMetadataAccountV3: Story = { - args: makeIx( - 0, - Buffer.from( - createMetadataV3Serializer.serialize({ - collectionDetails: none(), - data: { - collection: none(), - creators: none(), - name: 'My NFT', - sellerFeeBasisPoints: 500, - symbol: 'MNFT', - uri: 'https://example.com/nft.json', - uses: none(), - }, - isMutable: true, - }), - ), - [KEY_A, KEY_B, KEY_C, KEY_D, KEY_E], - ), + args: makeIx(0, createMetadataAccountV3Data(), [KEY_A, KEY_B, KEY_C, KEY_D, KEY_E]), play: async ({ canvasElement }) => { const canvas = within(canvasElement); await expect(canvas.getByText('Token Metadata Program: Create Metadata Account V3')).toBeInTheDocument(); diff --git a/app/features/mpl-token-metadata/ui/__tests__/MetaplexTokenMetadataDetailsCard.spec.tsx b/app/features/mpl-token-metadata/ui/__tests__/MetaplexTokenMetadataDetailsCard.spec.tsx index 30a8bb61c9..1ffce2acdb 100644 --- a/app/features/mpl-token-metadata/ui/__tests__/MetaplexTokenMetadataDetailsCard.spec.tsx +++ b/app/features/mpl-token-metadata/ui/__tests__/MetaplexTokenMetadataDetailsCard.spec.tsx @@ -1,15 +1,13 @@ -import { gen } from '@__fixtures__/gen'; import { InstructionNodeCard } from '@components/instruction/InstructionNodeCard'; import { inspectorSurface, InstructionSurfaceProvider, toInstructionNode } from '@entities/instruction-card'; import { createInstructionParserDispatcher, isParsedInstruction } from '@entities/instruction-parser'; import { getCreateMasterEditionV3InstructionDataSerializer, - getCreateMetadataAccountV3InstructionDataSerializer, getUpdateMetadataAccountV2InstructionDataSerializer, MPL_TOKEN_METADATA_PROGRAM_ID, } from '@metaplex-foundation/mpl-token-metadata'; import { none, publicKey as umiPublicKey, some } from '@metaplex-foundation/umi'; -import { PublicKey, TransactionInstruction } from '@solana/web3.js'; +import { PublicKey } from '@solana/web3.js'; import { screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { afterEach, describe, expect, it, vi } from 'vitest'; @@ -18,6 +16,7 @@ import { type CardRow, readCardRows, renderTxCard, renderWithProviders } from '@ import { invariant } from '@/app/shared/lib/invariant'; import { Logger } from '@/app/shared/lib/logger'; +import { createMetadataAccountV3Data, KEYS, tokenMetadataInstruction } from '../../__fixtures__/instructions'; import { metaplexTokenMetadataInstructionParser } from '../../lib/metaplex-token-metadata-client'; import { MetaplexTokenMetadataDetailsCard } from '../MetaplexTokenMetadataDetailsCard'; @@ -26,9 +25,7 @@ vi.mock('next/navigation', () => import('@/app/__tests__/next-navigation')); const dispatcher = createInstructionParserDispatcher([metaplexTokenMetadataInstructionParser]); const PROGRAM_ID = new PublicKey(MPL_TOKEN_METADATA_PROGRAM_ID); const PROGRAM_ROW: CardRow = ['Program', PROGRAM_ID.toBase58()]; -const KEYS = Array.from({ length: 20 }, (_, n) => gen.publicKey(n + 1)); -const createMetadataV3 = getCreateMetadataAccountV3InstructionDataSerializer(); const updateMetadataV2 = getUpdateMetadataAccountV2InstructionDataSerializer(); const createMasterEditionV3 = getCreateMasterEditionV3InstructionDataSerializer(); @@ -41,7 +38,7 @@ describe('MetaplexTokenMetadataDetailsCard', () => { { render: renderTxCard, surface: 'tx page' }, { render: renderInspectorCard, surface: 'inspector' }, ])('should render the Create Metadata Account V3 rows on the $surface surface', async ({ render }) => { - render(card(createMetadataAccountV3Data(500), KEYS)); + render(card(createMetadataAccountV3Data(), KEYS)); await waitFor(() => { expect(readCardRows()).toEqual([ @@ -66,7 +63,7 @@ describe('MetaplexTokenMetadataDetailsCard', () => { { basisPoints: 250, royalty: '2.50%' }, { basisPoints: 1234, royalty: '12.34%' }, ])('should show $basisPoints basis points as a $royalty royalty', async ({ basisPoints, royalty }) => { - renderTxCard(card(createMetadataAccountV3Data(basisPoints), KEYS)); + renderTxCard(card(createMetadataAccountV3Data({ sellerFeeBasisPoints: basisPoints }), KEYS)); await waitFor(() => { expect(readCardRows()).toContainEqual(['Royalty', royalty]); @@ -228,11 +225,7 @@ const PRINT_LABELS = [ ]; function card(data: Uint8Array | number[], keys: PublicKey[]) { - const raw = new TransactionInstruction({ - data: Buffer.from(data), - keys: keys.map(pubkey => ({ isSigner: false, isWritable: false, pubkey })), - programId: PROGRAM_ID, - }); + const raw = tokenMetadataInstruction(data, keys); const dispatched = dispatcher.fromTransactionInstruction(raw); invariant(dispatched, 'the token metadata program is registered'); @@ -253,19 +246,3 @@ function renderInspectorCard(ui: JSX.Element) { , ); } - -function createMetadataAccountV3Data(sellerFeeBasisPoints: number) { - return createMetadataV3.serialize({ - collectionDetails: none(), - data: { - collection: none(), - creators: none(), - name: 'My NFT', - sellerFeeBasisPoints, - symbol: 'MNFT', - uri: 'https://example.com/nft.json', - uses: none(), - }, - isMutable: true, - }); -} diff --git a/app/features/nftoken/api/__tests__/fetch-collection-nfts.spec.ts b/app/features/nftoken/api/__tests__/fetch-collection-nfts.spec.ts index 3f1c3bfd27..12d5f3717f 100644 --- a/app/features/nftoken/api/__tests__/fetch-collection-nfts.spec.ts +++ b/app/features/nftoken/api/__tests__/fetch-collection-nfts.spec.ts @@ -1,8 +1,8 @@ -import type * as SolanaKit from '@solana/kit'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; -vi.mock('@solana/kit', async () => await vi.importActual('@solana/kit')); +vi.unmock('@solana/kit'); +import { stubRpcFetch } from '@/app/__tests__/rpc-fetch'; import { toConnectableUrl } from '@/app/entities/cluster/lib/connectable-url'; import { Logger } from '@/app/shared/lib/logger'; import { UPSTREAM_TIMEOUT_MS } from '@/app/shared/lib/timeouts'; @@ -14,14 +14,9 @@ const URL = toConnectableUrl('https://mock.rpc'); const NFTOKEN_PROGRAM = 'nftokf9qcHSYkVSP3P2gUMmV6d4AwjMueXgUu43HyLL'; const NFT_DISCRIMINATOR_BASE58 = '6dycNg3Aybe'; -const fetchMock = vi.fn(); - -beforeEach(() => { - vi.stubGlobal('fetch', fetchMock); -}); +const { fetchMock, requestBody, respondWithError } = stubRpcFetch(); afterEach(() => { - vi.unstubAllGlobals(); vi.restoreAllMocks(); vi.clearAllMocks(); }); @@ -32,7 +27,7 @@ describe('fetchCollectionNfts', () => { await fetchCollectionNfts(URL, COLLECTION); - expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toMatchObject({ + expect(requestBody()).toMatchObject({ method: 'getProgramAccounts', params: [ NFTOKEN_PROGRAM, @@ -104,25 +99,25 @@ describe('fetchCollectionNfts', () => { }); it('should return unsupported for the method-not-found code with any node message', async () => { - respondWithRpcError({ code: -32601, message: 'getProgramAccounts is disabled' }); + respondWithError({ code: -32601, message: 'getProgramAccounts is disabled' }); await expect(fetchCollectionNfts(URL, COLLECTION)).resolves.toEqual({ kind: 'unsupported' }); }); it('should throw on any other JSON-RPC error code so the caller retries', async () => { - respondWithRpcError({ code: -32005, message: 'Node is behind by 42 slots' }); + respondWithError({ code: -32005, message: 'Node is behind by 42 slots' }); await expect(fetchCollectionNfts(URL, COLLECTION)).rejects.toThrow(); }); it('should return unsupported for an internal error whose message names a missing method', async () => { - respondWithRpcError({ code: -32603, message: 'Method not found' }); + respondWithError({ code: -32603, message: 'Method not found' }); await expect(fetchCollectionNfts(URL, COLLECTION)).resolves.toEqual({ kind: 'unsupported' }); }); it('should throw on an internal error with any other message so the caller retries', async () => { - respondWithRpcError({ code: -32603, message: 'Internal error' }); + respondWithError({ code: -32603, message: 'Internal error' }); await expect(fetchCollectionNfts(URL, COLLECTION)).rejects.toThrow(); }); @@ -170,7 +165,3 @@ function respondWithAccounts(accounts: readonly { base64: string; pubkey: string ); fetchMock.mockResolvedValueOnce(new Response(`{"id":"0","jsonrpc":"2.0","result":[${result.join(',')}]}`)); } - -function respondWithRpcError(error: { code: number; message: string }) { - fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ error, id: '0', jsonrpc: '2.0' }))); -} diff --git a/app/features/nftoken/ui/__stories__/BaseNftokenCollectionGrid.stories.tsx b/app/features/nftoken/ui/__stories__/BaseNftokenCollectionGrid.stories.tsx index e9cd26989e..fe831f7cc0 100644 --- a/app/features/nftoken/ui/__stories__/BaseNftokenCollectionGrid.stories.tsx +++ b/app/features/nftoken/ui/__stories__/BaseNftokenCollectionGrid.stories.tsx @@ -1,4 +1,3 @@ -import { nextjsParameters } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { fn } from 'storybook/test'; @@ -9,7 +8,6 @@ import { BaseNftokenTile } from '../BaseNftokenTile'; const meta = { component: BaseNftokenCollectionGrid, - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/NFToken/NftokenCollectionGrid', } satisfies Meta; diff --git a/app/features/nftoken/ui/__stories__/BaseNftokenHeader.responsive.stories.tsx b/app/features/nftoken/ui/__stories__/BaseNftokenHeader.responsive.stories.tsx index fe42c225e1..461894fc40 100644 --- a/app/features/nftoken/ui/__stories__/BaseNftokenHeader.responsive.stories.tsx +++ b/app/features/nftoken/ui/__stories__/BaseNftokenHeader.responsive.stories.tsx @@ -1,16 +1,12 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import solanaHero from '@/app/components/shared/ui/image/__stories__/solana_hero_generated.jpg'; - import { BaseNftokenHeader } from '../BaseNftokenHeader'; +import * as Base from './BaseNftokenHeader.stories'; const meta = { component: BaseNftokenHeader, decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Features/NFToken/NftokenHeader@Media', } satisfies Meta; @@ -18,11 +14,7 @@ const meta = { export default meta; type Story = StoryObj; -const args = { - kind: 'nft', - metadata: { kind: 'loaded', metadata: { image: solanaHero.src, name: 'Genesis: friends.glow' } }, - mutable: true, -} as const; +const args = Base.NftMutable.args; export const Mobile: Story = { args, diff --git a/app/features/nftoken/ui/__stories__/BaseNftokenTile.stories.tsx b/app/features/nftoken/ui/__stories__/BaseNftokenTile.stories.tsx index 4f0f2df557..dbc2ecb3c6 100644 --- a/app/features/nftoken/ui/__stories__/BaseNftokenTile.stories.tsx +++ b/app/features/nftoken/ui/__stories__/BaseNftokenTile.stories.tsx @@ -1,4 +1,3 @@ -import { nextjsParameters } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import solanaHero from '@/app/components/shared/ui/image/__stories__/solana_hero_generated.jpg'; @@ -7,7 +6,6 @@ import { BaseNftokenTile } from '../BaseNftokenTile'; const meta = { component: BaseNftokenTile, - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/NFToken/NftokenTile', } satisfies Meta; diff --git a/app/features/nftoken/ui/__tests__/NftokenAccountHeader.spec.tsx b/app/features/nftoken/ui/__tests__/NftokenAccountHeader.spec.tsx index 3014ac9e8f..ec052f5678 100644 --- a/app/features/nftoken/ui/__tests__/NftokenAccountHeader.spec.tsx +++ b/app/features/nftoken/ui/__tests__/NftokenAccountHeader.spec.tsx @@ -1,9 +1,9 @@ import type { Account } from '@providers/accounts'; import { act, render, screen } from '@testing-library/react'; -import { type ReactNode } from 'react'; -import { SWRConfig } from 'swr'; import { afterEach, describe, expect, it, vi } from 'vitest'; +import { swrWrapper } from '@/app/__tests__/swr-hook'; + import { accountBytes, collectionAccount, @@ -73,9 +73,5 @@ describe('NftokenAccountHeader', () => { function renderHeader(account: Account) { const nftoken = parseNftokenAccount(account); if (!nftoken) throw new Error('the fixture does not decode'); - return render(, { wrapper: Providers }); -} - -function Providers({ children }: { children: ReactNode }) { - return new Map() }}>{children}; + return render(, { wrapper: swrWrapper({ dedupingInterval: 0 }) }); } diff --git a/app/features/nftoken/ui/__tests__/NftokenAccountSection.spec.tsx b/app/features/nftoken/ui/__tests__/NftokenAccountSection.spec.tsx index d7d570d3a1..221b8dc305 100644 --- a/app/features/nftoken/ui/__tests__/NftokenAccountSection.spec.tsx +++ b/app/features/nftoken/ui/__tests__/NftokenAccountSection.spec.tsx @@ -1,10 +1,10 @@ import type { Account } from '@providers/accounts'; -import type { PublicKey } from '@solana/web3.js'; import { act, fireEvent, render, screen } from '@testing-library/react'; import { type ReactNode } from 'react'; -import { SWRConfig } from 'swr'; import { afterEach, describe, expect, it, vi } from 'vitest'; +import { swrWrapper } from '@/app/__tests__/swr-hook'; + import { accountBytes, COLLECTION, @@ -37,9 +37,7 @@ vi.mock('@features/account', () => ({ ), })); vi.mock('@components/account/UnknownAccountCard', () => ({ UnknownAccountCard: () =>

UnknownAccountCard

})); -vi.mock('@components/common/Address', () => ({ - Address: ({ pubkey }: { pubkey: PublicKey }) => {pubkey.toBase58()}, -})); +vi.mock('@/app/components/common/Address', () => import('@/app/__tests__/address-stub')); vi.mock('../../api/fetch-collection-nfts', () => ({ fetchCollectionNfts: mocks.fetchCollectionNfts })); vi.mock('../../api/fetch-nftoken-metadata', () => ({ fetchNftokenMetadata: mocks.fetchNftokenMetadata })); @@ -194,7 +192,7 @@ function expectRow(label: string, value: string) { } function renderSection(account: Account) { - return render(, { wrapper: Providers }); + return render(, { wrapper: swrWrapper({ dedupingInterval: 0 }) }); } function renderSectionWithHeader(account: Account) { @@ -205,10 +203,6 @@ function renderSectionWithHeader(account: Account) { , - { wrapper: Providers }, + { wrapper: swrWrapper({ dedupingInterval: 0 }) }, ); } - -function Providers({ children }: { children: ReactNode }) { - return new Map() }}>{children}; -} diff --git a/app/features/nicknames/ui/__stories__/NicknameEditor.responsive.stories.tsx b/app/features/nicknames/ui/__stories__/NicknameEditor.responsive.stories.tsx index f890c33602..be0cd34d06 100644 --- a/app/features/nicknames/ui/__stories__/NicknameEditor.responsive.stories.tsx +++ b/app/features/nicknames/ui/__stories__/NicknameEditor.responsive.stories.tsx @@ -1,20 +1,15 @@ -import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; -import { withAutoFocusReleased } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withFixedContainer, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import { fn } from 'storybook/test'; import { NicknameEditor } from '../NicknameEditor'; +import * as Base from './NicknameEditor.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta = { + args: Base.default.args, component: NicknameEditor, - decorators: [withAutoFocusReleased, withFixedContainer, withViewportFromGlobal], - parameters: { - layout: 'fullscreen', // NicknameEditor renders as a position:fixed overlay; fullscreen removes the canvas padding so it anchors to the iframe viewport. - nextjs: { appDirectory: true }, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [...Base.default.decorators, withViewportFromGlobal], + parameters: Base.default.parameters, tags: ['autodocs', 'test'], title: 'Features/Nicknames/NicknameEditor@Media', } satisfies Meta; @@ -22,11 +17,7 @@ const meta = { export default meta; type Story = StoryObj; -const args = { - address: TOKEN_PROGRAM_ADDRESS, - onClose: fn(), - open: true, -}; +const args = Base.LongAddress.args; export const Mobile: Story = { args, diff --git a/app/features/nicknames/ui/__stories__/NicknameEditor.stories.tsx b/app/features/nicknames/ui/__stories__/NicknameEditor.stories.tsx index 3a31fa351f..71ad0f2fbd 100644 --- a/app/features/nicknames/ui/__stories__/NicknameEditor.stories.tsx +++ b/app/features/nicknames/ui/__stories__/NicknameEditor.stories.tsx @@ -19,9 +19,6 @@ const meta = { }, }, layout: 'fullscreen', // NicknameEditor renders as a position:fixed overlay; fullscreen removes the canvas padding so it anchors to the iframe viewport. - nextjs: { - appDirectory: true, - }, }, tags: ['autodocs', 'test'], title: 'Features/Nicknames/NicknameEditor', diff --git a/app/features/receipt/lib/__tests__/__fixtures__/pdf-mocks.ts b/app/features/receipt/__fixtures__/pdf-mocks.ts similarity index 88% rename from app/features/receipt/lib/__tests__/__fixtures__/pdf-mocks.ts rename to app/features/receipt/__fixtures__/pdf-mocks.ts index 6fa0c54536..be09cd98f4 100644 --- a/app/features/receipt/lib/__tests__/__fixtures__/pdf-mocks.ts +++ b/app/features/receipt/__fixtures__/pdf-mocks.ts @@ -1,4 +1,8 @@ -import { buildFormattedReceipt } from '@entities/token-receipt/__fixtures__/formatted-receipt'; +import { DEFAULT_SIGNATURE } from '@__fixtures__/gen'; +import { + buildFormattedReceipt, + buildFormattedTokenReceipt, +} from '@entities/token-receipt/__fixtures__/formatted-receipt'; import { vi } from 'vitest'; export const mockTextField = vi.fn(function () { @@ -71,19 +75,16 @@ export function stubSvgRasterizationUnsupported(): void { }); } -export const SIGNATURE = '5UfDuX7hXbGjGHqPXRGaHdSecretSignature1234567890abcdef'; -export const RECEIPT_URL = 'https://explorer.solana.com/receipt/5UfDuX7hXbGjGHqPXRGaHdSecretSignature1234567890abcdef'; +export const SIGNATURE = DEFAULT_SIGNATURE; +export const RECEIPT_URL = `https://explorer.solana.com/receipt/${SIGNATURE}`; export const CLUSTER_LABEL = 'Mainnet'; export const PDF_OPTS = { clusterLabel: CLUSTER_LABEL, receiptUrl: RECEIPT_URL, signature: SIGNATURE } as const; export const SOL_RECEIPT = buildFormattedReceipt(); -export const USDC_RECEIPT = buildFormattedReceipt({ - kind: 'token', +export const USDC_RECEIPT = buildFormattedTokenReceipt({ memo: undefined, - mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', - symbol: 'USDC', total: { formatted: '125.50', raw: 125.5, unit: 'USDC' }, }); diff --git a/app/features/receipt/ui/__stories__/receipt-fixtures.ts b/app/features/receipt/__fixtures__/receipts.ts similarity index 60% rename from app/features/receipt/ui/__stories__/receipt-fixtures.ts rename to app/features/receipt/__fixtures__/receipts.ts index 7a4ec782f5..a553d4f4a4 100644 --- a/app/features/receipt/ui/__stories__/receipt-fixtures.ts +++ b/app/features/receipt/__fixtures__/receipts.ts @@ -1,25 +1,17 @@ +import { gen } from '@__fixtures__/gen'; + import { Cluster } from '@/app/utils/cluster'; -import { formatReceiptData } from '../../model/receipt-data'; -import type { Receipt } from '../../model/types'; -import type { FormattedExtendedReceipt, FormattedReceipt } from '../../types'; +import { formatReceiptData } from '../model/receipt-data'; +import type { Receipt, ReceiptToken } from '../model/types'; +import { messageForReason } from '../receipt-page'; +import type { FormattedExtendedReceipt, FormattedReceipt } from '../types'; const CLUSTER = Cluster.Mainnet; -// Fixed literal addresses so screenshot captures are deterministic (was Keypair.generate()). -const SENDER = 'UM1jjYaM2Y4BDSdCw3AiELrP6HDpz62VjUHcHVJosix'; -const RECEIVER = 'UMxTDTS9cXEBVNkNmtaPKY4gZwwNrsLb6K7XiT3MnHP'; -const EXTRA_RECEIVERS = [ - 'UNuAhNHxEFQ2AT8MvxGKyCTuBW7TCRddJYRYVJSEr1p', - 'UPqtBH9dACJEh67Whonp2FczN8p8mci2tBicQpTDFb1', - 'UQnbfC1RmvU5NAVVrsUo2idHawqHdsPYoeS6LXk3RsS', - 'URjK96HJoqgNoA5vzFEyTvSTCDKw3yAnyCQP95LjdLq', - 'USg2d197RZrDUETv9JvxUPSkR2M5vTxCo1qyLUqFKR8', - 'UTck4LGQp2t9zBnXr99NfoKSkgiEHRzyiYnndSoMHsV', - 'UUZTYF8DRm3zfGAX1CqMgGKjyVjP9vnPYNENprKKHpU', - 'UVVydGP1WgMd5BfpNnrWzun5S6zHgmNvbNfmZVCUhSZ', - 'UWSh7BEp8QXTkG3oXrYW1NnNev1SZGALRC7MktiShPY', -]; +const SENDER = gen.address(1); +const RECEIVER = gen.address(2); +const EXTRA_RECEIVERS = Array.from({ length: 9 }, (_, i) => gen.address(i + 3)); const raw = { date: 1737100062, @@ -129,70 +121,37 @@ export const receiptMultiTransfer9: FormattedReceipt = formatReceiptData( CLUSTER, ); -export const receiptMultiTokenTransfer: FormattedReceipt = formatReceiptData( - { - date: raw.date, - fee: 10001, - logoURI: USDC_LOGO, - mint: USDC_MINT, - receiver: raw.receiver, - sender: raw.sender, - symbol: 'USDC', - total: 1.000841, - transfers: [ - { receiver: EXTRA_RECEIVERS[0], sender: raw.sender, total: 1 }, - { receiver: EXTRA_RECEIVERS[1], sender: raw.sender, total: 0.000841 }, - ], - type: 'token', - }, - CLUSTER, -); +const multiTokenTransfer: ReceiptToken = { + date: raw.date, + fee: 10001, + logoURI: USDC_LOGO, + mint: USDC_MINT, + receiver: raw.receiver, + sender: raw.sender, + symbol: 'USDC', + total: 1.000841, + transfers: [ + { receiver: EXTRA_RECEIVERS[0], sender: raw.sender, total: 1 }, + { receiver: EXTRA_RECEIVERS[1], sender: raw.sender, total: 0.000841 }, + ], + type: 'token', +}; + +export const receiptMultiTokenTransfer: FormattedReceipt = formatReceiptData(multiTokenTransfer, CLUSTER); export const receiptMultiTokenTransferWithMemo: FormattedReceipt = formatReceiptData( - { - date: raw.date, - fee: 10001, - logoURI: USDC_LOGO, - memo: 'Payroll batch — Q2', - mint: USDC_MINT, - receiver: raw.receiver, - sender: raw.sender, - symbol: 'USDC', - total: 1.000841, - transfers: [ - { receiver: EXTRA_RECEIVERS[0], sender: raw.sender, total: 1 }, - { receiver: EXTRA_RECEIVERS[1], sender: raw.sender, total: 0.000841 }, - ], - type: 'token', - }, + { ...multiTokenTransfer, memo: 'Payroll batch — Q2' }, CLUSTER, ); export const receiptMultiTokenTransferWithLongMemo: FormattedReceipt = formatReceiptData( - { - date: raw.date, - fee: 10001, - logoURI: USDC_LOGO, - memo: longMemoText, - mint: USDC_MINT, - receiver: raw.receiver, - sender: raw.sender, - symbol: 'USDC', - total: 1.000841, - transfers: [ - { receiver: EXTRA_RECEIVERS[0], sender: raw.sender, total: 1 }, - { receiver: EXTRA_RECEIVERS[1], sender: raw.sender, total: 0.000841 }, - ], - type: 'token', - }, + { ...multiTokenTransfer, memo: longMemoText }, CLUSTER, ); -export const mixedMintNoReceiptMessage = - 'Receipts are only available when all token transfers in a transaction use the same mint. This transaction transfers multiple different tokens.'; +export const mixedMintNoReceiptMessage = messageForReason('mixed-mint'); -export const innerInstructionsNoReceiptMessage = - 'Receipts are only available for simple transfers. This transaction contains inner program instructions.'; +export const innerInstructionsNoReceiptMessage = messageForReason('inner-transfers'); export function forBaseReceipt( data: FormattedReceipt, diff --git a/app/features/receipt/__fixtures__/transactions.ts b/app/features/receipt/__fixtures__/transactions.ts new file mode 100644 index 0000000000..d04e591591 --- /dev/null +++ b/app/features/receipt/__fixtures__/transactions.ts @@ -0,0 +1,408 @@ +import { gen } from '@__fixtures__/gen'; +import { + buildParsedTransaction, + buildPartiallyDecodedIx, + buildSolTransferIx, + buildTokenTransferCheckedIx, + type ParsedTokenBalance, +} from '@entities/transaction-data/__fixtures__/parsed-transactions'; +import { ComputeBudgetProgram, PublicKey, SystemProgram } from '@solana/web3.js'; +import { ASSOCIATED_TOKEN_PROGRAM_ADDRESS, TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; +import { TOKEN_2022_PROGRAM_ADDRESS } from '@solana-program/token-2022'; + +export const SENDER = gen.publicKey(1); +export const RECEIVER = gen.publicKey(2); +export const RECEIVER_2 = gen.publicKey(3); +export const MULTISIG_AUTHORITY = gen.publicKey(4); +const FEE_PAYER = gen.publicKey(5); +const MINT = gen.publicKey(6); +const MINT_2 = gen.publicKey(7); +const SOURCE_TOKEN_ACCOUNT = gen.publicKey(8); +const SOURCE_TOKEN_ACCOUNT_2 = gen.publicKey(9); +const DESTINATION_TOKEN_ACCOUNT = gen.publicKey(10); +const DESTINATION_TOKEN_ACCOUNT_2 = gen.publicKey(11); + +const WALLET_HD3F3 = new PublicKey('Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5'); +const WALLET_65MUM = new PublicKey('65MUMxiopKUaZbazs6pRUr9y774mj4Z1TdDgUh3L2Fhk'); +const TOKEN_ACCOUNT_HYSC1 = new PublicKey('HYsC1ge3Yo1sSBFvcEn4otFZEJkitUNZYPsDVTQNacBT'); +const TOKEN_ACCOUNT_3MRB = new PublicKey('3MRBUAxwx7gWoGvAtzxLtzmhzwPDGAEqStKWb8cJnYQX'); +const DEVNET_USDC = new PublicKey('4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'); +const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); + +const TOKEN_PROGRAM = new PublicKey(TOKEN_PROGRAM_ADDRESS); +const TOKEN_2022_PROGRAM = new PublicKey(TOKEN_2022_PROGRAM_ADDRESS); +const COMPUTE_BUDGET_PROGRAM = ComputeBudgetProgram.programId; + +export const mockSingleTransferTransaction = buildParsedTransaction({ + accountKeys: [SENDER, RECEIVER, SystemProgram.programId], + blockTime: 1769070902, + instructions: [buildSolTransferIx({ destination: RECEIVER, lamports: 300000000, source: SENDER })], +}); + +export const mockMultipleTransfersTransaction = buildParsedTransaction({ + accountKeys: [SENDER, RECEIVER, RECEIVER_2, SystemProgram.programId], + instructions: [ + buildSolTransferIx({ destination: RECEIVER, lamports: 80000000, source: SENDER }), + buildSolTransferIx({ destination: RECEIVER_2, lamports: 50000000, source: SENDER }), + buildSolTransferIx({ destination: RECEIVER, lamports: 10000000, source: SENDER }), + ], +}); + +const MEMO_PROGRAM = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'); + +export const mockNoTransferTransaction = buildParsedTransaction({ + accountKeys: [WALLET_HD3F3, MEMO_PROGRAM], + blockTime: 1768828236, + instructions: [{ parsed: 'Payment for invoice #123', program: 'spl-memo', programId: MEMO_PROGRAM }], +}); + +const WALLET_R1CHH = new PublicKey('R1CHHDEeDwxVxjKv2FPd57mVhbUp4aUQvuE49jYF6Vq'); +const JITO_TIP_ADUUK = new PublicKey('ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt'); + +export const mockJitoOnlyTransferTransaction = buildParsedTransaction({ + accountKeys: [WALLET_R1CHH, JITO_TIP_ADUUK, SystemProgram.programId], + blockTime: 1770048279, + instructions: [buildSolTransferIx({ destination: JITO_TIP_ADUUK, lamports: 17343, source: WALLET_R1CHH })], +}); + +export const mockCustomFeePayerTransaction = buildFeePayerSolTransfer({ blockTime: 1769093093, lamports: 500000000 }); + +export const mockZeroTransferTransaction = buildFeePayerSolTransfer({ blockTime: 1769142127, lamports: 0 }); + +function buildFeePayerSolTransfer({ blockTime, lamports }: { blockTime: number; lamports: number }) { + const feePayer = new PublicKey('644RudhReGpiHsNysSVSpDDagrzw5mBCwdHq1ZNwK6zL'); + const receiver = new PublicKey('G2GjouKPJnGi3aGVsHnBu475EGvseiL1QnVHBMkN6wid'); + return buildParsedTransaction({ + accountKeys: [feePayer, { pubkey: WALLET_HD3F3, signer: true }, receiver, SystemProgram.programId], + blockTime, + fee: 10000, + instructions: [buildSolTransferIx({ destination: receiver, lamports, source: WALLET_HD3F3 })], + }); +} + +export const mockUsdcTransferTransaction = buildParsedTransaction({ + accountKeys: [ + WALLET_HD3F3, + TOKEN_ACCOUNT_HYSC1, + TOKEN_ACCOUNT_3MRB, + COMPUTE_BUDGET_PROGRAM, + SystemProgram.programId, + TOKEN_PROGRAM, + ], + blockTime: 1769070184, + instructions: [ + buildTokenTransferCheckedIx({ + amount: '1000000', + authority: WALLET_HD3F3, + decimals: 6, + destinationTokenAccount: TOKEN_ACCOUNT_3MRB, + mint: DEVNET_USDC, + sourceTokenAccount: TOKEN_ACCOUNT_HYSC1, + }), + buildPartiallyDecodedIx({ data: 'KL8Bcb', programId: COMPUTE_BUDGET_PROGRAM }), + ], + postTokenBalances: [ + buildTokenBalance({ accountIndex: 1, amount: '1000000', decimals: 6, mint: DEVNET_USDC, owner: WALLET_65MUM }), + buildTokenBalance({ accountIndex: 2, amount: '19000000', decimals: 6, mint: DEVNET_USDC, owner: WALLET_HD3F3 }), + ], +}); + +export const mockUsdcRegularTransferTransaction = buildParsedTransaction({ + accountKeys: [WALLET_HD3F3, TOKEN_ACCOUNT_HYSC1, TOKEN_ACCOUNT_3MRB, TOKEN_PROGRAM], + blockTime: 1769153097, + instructions: [ + { + parsed: { + info: { + amount: '1000000', + authority: WALLET_HD3F3.toBase58(), + destination: TOKEN_ACCOUNT_3MRB.toBase58(), + source: TOKEN_ACCOUNT_HYSC1.toBase58(), + }, + type: 'transfer', + }, + program: 'spl-token', + programId: TOKEN_PROGRAM, + }, + ], + postTokenBalances: [ + buildTokenBalance({ accountIndex: 1, amount: '2000000', decimals: 6, mint: DEVNET_USDC, owner: WALLET_65MUM }), + buildTokenBalance({ accountIndex: 2, amount: '18000000', decimals: 6, mint: DEVNET_USDC, owner: WALLET_HD3F3 }), + ], +}); + +const JITO_TIP_96GY = new PublicKey('96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5'); + +export const mockUsdcJitoTransferTransaction = buildParsedTransaction({ + accountKeys: [ + WALLET_HD3F3, + TOKEN_ACCOUNT_3MRB, + DEVNET_USDC, + TOKEN_ACCOUNT_HYSC1, + JITO_TIP_96GY, + SystemProgram.programId, + TOKEN_PROGRAM, + ], + blockTime: 1769770869, + instructions: [ + buildTokenTransferCheckedIx({ + amount: '1000000', + authority: WALLET_HD3F3, + decimals: 6, + destinationTokenAccount: TOKEN_ACCOUNT_3MRB, + mint: DEVNET_USDC, + sourceTokenAccount: TOKEN_ACCOUNT_HYSC1, + }), + buildSolTransferIx({ destination: JITO_TIP_96GY, lamports: 10000, source: WALLET_HD3F3 }), + ], + postTokenBalances: [ + buildTokenBalance({ accountIndex: 1, amount: '3000000', decimals: 6, mint: DEVNET_USDC, owner: WALLET_65MUM }), + buildTokenBalance({ accountIndex: 3, amount: '17000000', decimals: 6, mint: DEVNET_USDC, owner: WALLET_HD3F3 }), + ], +}); + +const T22_MINT_AN8H = new PublicKey('AN8h2reVWuPAWXhfJQounhTMqb5bvwVKumX6pMmSK25U'); +const TOKEN_ACCOUNT_AVU46 = new PublicKey('AvU46uNPpHaPewPwqWNqVLgD9TgQRD8uqFpRRi5PkFDS'); +const TOKEN_ACCOUNT_99FC = new PublicKey('99FC9v1Jt7ZDB7fmZtLbYLt7wpYPfVioRy5NJcGrK7ES'); +const ASSOCIATED_TOKEN_PROGRAM = new PublicKey(ASSOCIATED_TOKEN_PROGRAM_ADDRESS); +const T22_AN8H_TOKEN = { decimals: 9, mint: T22_MINT_AN8H, programId: TOKEN_2022_PROGRAM }; + +export const mockToken2022TransferTransaction = buildParsedTransaction({ + accountKeys: [ + WALLET_HD3F3, + TOKEN_ACCOUNT_AVU46, + TOKEN_ACCOUNT_99FC, + SystemProgram.programId, + ASSOCIATED_TOKEN_PROGRAM, + TOKEN_2022_PROGRAM, + COMPUTE_BUDGET_PROGRAM, + ], + blockTime: 1769580206, + instructions: [ + { + parsed: { type: 'createIdempotent' }, + program: 'spl-associated-token-account', + programId: ASSOCIATED_TOKEN_PROGRAM, + }, + buildTokenTransferCheckedIx({ + amount: '100000000000', + authority: WALLET_HD3F3, + decimals: 9, + destinationTokenAccount: TOKEN_ACCOUNT_AVU46, + mint: T22_MINT_AN8H, + sourceTokenAccount: TOKEN_ACCOUNT_99FC, + tokenProgramId: TOKEN_2022_PROGRAM, + }), + buildPartiallyDecodedIx({ data: 'GC3Vaw', programId: COMPUTE_BUDGET_PROGRAM }), + ], + postTokenBalances: [ + buildTokenBalance({ ...T22_AN8H_TOKEN, accountIndex: 1, amount: '100000000000', owner: WALLET_65MUM }), + buildTokenBalance({ ...T22_AN8H_TOKEN, accountIndex: 2, amount: '900000000000', owner: WALLET_HD3F3 }), + ], +}); + +const T22_MINT_7XKX = new PublicKey('7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU'); +const T22_7XKX_TOKEN = { decimals: 0, mint: T22_MINT_7XKX, programId: TOKEN_2022_PROGRAM }; +const TOKEN_2022_TRANSFER = buildTokenTransferCheckedIx({ + amount: '100', + authority: WALLET_HD3F3, + decimals: 0, + destinationTokenAccount: TOKEN_ACCOUNT_HYSC1, + mint: T22_MINT_7XKX, + sourceTokenAccount: TOKEN_ACCOUNT_3MRB, + tokenProgramId: TOKEN_2022_PROGRAM, +}); + +export const mockToken2022Transfer2Transaction = buildParsedTransaction({ + accountKeys: [ + WALLET_HD3F3, + TOKEN_ACCOUNT_HYSC1, + TOKEN_ACCOUNT_3MRB, + COMPUTE_BUDGET_PROGRAM, + SystemProgram.programId, + TOKEN_2022_PROGRAM, + ], + blockTime: 1769200000, + instructions: [ + { ...TOKEN_2022_TRANSFER, parsed: { ...TOKEN_2022_TRANSFER.parsed, type: 'transfer2' } }, + buildPartiallyDecodedIx({ data: 'KL8Bcb', programId: COMPUTE_BUDGET_PROGRAM }), + ], + postTokenBalances: [ + buildTokenBalance({ ...T22_7XKX_TOKEN, accountIndex: 1, amount: '100', owner: WALLET_65MUM }), + buildTokenBalance({ ...T22_7XKX_TOKEN, accountIndex: 2, amount: '900', owner: WALLET_HD3F3 }), + ], +}); + +export const mockUsdcMultisigTransferTransaction = buildParsedTransaction({ + accountKeys: [SENDER, DESTINATION_TOKEN_ACCOUNT, SOURCE_TOKEN_ACCOUNT, TOKEN_PROGRAM], + blockTime: 1769070184, + instructions: [ + { + parsed: { + info: { + destination: DESTINATION_TOKEN_ACCOUNT.toBase58(), + mint: MINT.toBase58(), + multisigAuthority: MULTISIG_AUTHORITY.toBase58(), + source: SOURCE_TOKEN_ACCOUNT.toBase58(), + tokenAmount: { amount: '1000000', decimals: 6, uiAmount: 1, uiAmountString: '1' }, + }, + type: 'transferChecked', + }, + program: 'spl-token', + programId: TOKEN_PROGRAM, + }, + ], + postTokenBalances: [ + buildTokenBalance({ accountIndex: 1, amount: '1000000', decimals: 6, mint: MINT, owner: RECEIVER }), + buildTokenBalance({ accountIndex: 2, amount: '19000000', decimals: 6, mint: MINT, owner: SENDER }), + ], +}); + +const WALLET_BCDW = new PublicKey('BcdwLA62UPEAvRn7AWauMUXKtYMXxdLzTPaSQg5tNaFc'); +const WALLET_C4E3 = new PublicKey('C4E3ZZ4ymQ5wY6o7JkKMeg6Yjj6CQjnaWr6ANvF9mGYY'); +const WALLET_96WO = new PublicKey('96WoyH3JmANSMsQLGC3MKyiGiXCymZyM9SLaWjcRrKuD'); +const TOKEN_ACCOUNT_7SYA = new PublicKey('7SyaSKPkVFrzAgmBCR64ydpLwcvehkCwJKom8NCF4WGM'); +const TOKEN_ACCOUNT_AUJIP = new PublicKey('AUJip4HMnYJD849oU6b8ajGoKuFGoTDfs6s3taDgsb19'); +const TOKEN_ACCOUNT_DC1V = new PublicKey('DC1VbwstSDC7LVi4dmWjr5abd5BHucAk29pQTPKrYnbW'); + +export const mockUsdcMultipleTransfersTransaction = buildParsedTransaction({ + accountKeys: [ + WALLET_BCDW, + { pubkey: WALLET_C4E3, signer: true }, + TOKEN_ACCOUNT_7SYA, + TOKEN_ACCOUNT_AUJIP, + TOKEN_ACCOUNT_DC1V, + COMPUTE_BUDGET_PROGRAM, + TOKEN_PROGRAM, + USDC_MINT, + ], + blockTime: 1777817015, + fee: 10001, + instructions: [ + buildPartiallyDecodedIx({ data: '3DdGGhkhJbjm', programId: COMPUTE_BUDGET_PROGRAM }), + buildPartiallyDecodedIx({ data: 'Fj2Eoy', programId: COMPUTE_BUDGET_PROGRAM }), + buildTokenTransferCheckedIx({ + amount: '1000000', + authority: WALLET_C4E3, + decimals: 6, + destinationTokenAccount: TOKEN_ACCOUNT_DC1V, + mint: USDC_MINT, + sourceTokenAccount: TOKEN_ACCOUNT_AUJIP, + }), + buildTokenTransferCheckedIx({ + amount: '841', + authority: WALLET_C4E3, + decimals: 6, + destinationTokenAccount: TOKEN_ACCOUNT_7SYA, + mint: USDC_MINT, + sourceTokenAccount: TOKEN_ACCOUNT_AUJIP, + }), + ], + postTokenBalances: [ + buildTokenBalance({ accountIndex: 2, amount: '2400572', decimals: 6, mint: USDC_MINT, owner: WALLET_BCDW }), + buildTokenBalance({ accountIndex: 3, amount: '1996478', decimals: 6, mint: USDC_MINT, owner: WALLET_C4E3 }), + buildTokenBalance({ accountIndex: 4, amount: '6955300', decimals: 6, mint: USDC_MINT, owner: WALLET_96WO }), + ], +}); + +export const mockUsdcMultipleTransfersAddresses = { + authority: WALLET_C4E3.toBase58(), + mint: USDC_MINT.toBase58(), + receiver1: WALLET_96WO.toBase58(), + receiver2: WALLET_BCDW.toBase58(), +} as const; + +export const mockMixedMintTransfersTransaction = buildParsedTransaction({ + accountKeys: [ + FEE_PAYER, + DESTINATION_TOKEN_ACCOUNT, + SOURCE_TOKEN_ACCOUNT, + DESTINATION_TOKEN_ACCOUNT_2, + SOURCE_TOKEN_ACCOUNT_2, + TOKEN_PROGRAM, + ], + blockTime: 1777817015, + instructions: [ + buildTokenTransferCheckedIx({ + amount: '1000000', + authority: SENDER, + decimals: 6, + destinationTokenAccount: DESTINATION_TOKEN_ACCOUNT, + mint: MINT, + sourceTokenAccount: SOURCE_TOKEN_ACCOUNT, + }), + buildTokenTransferCheckedIx({ + amount: '500', + authority: SENDER, + decimals: 5, + destinationTokenAccount: DESTINATION_TOKEN_ACCOUNT_2, + mint: MINT_2, + sourceTokenAccount: SOURCE_TOKEN_ACCOUNT_2, + }), + ], + postTokenBalances: [ + buildTokenBalance({ accountIndex: 1, amount: '1000000', decimals: 6, mint: MINT, owner: RECEIVER }), + buildTokenBalance({ accountIndex: 2, amount: '0', decimals: 6, mint: MINT, owner: SENDER }), + buildTokenBalance({ accountIndex: 3, amount: '500', decimals: 5, mint: MINT_2, owner: RECEIVER_2 }), + buildTokenBalance({ accountIndex: 4, amount: '0', decimals: 5, mint: MINT_2, owner: SENDER }), + ], +}); + +export const mockUsdcFpPrecisionTransfersTransaction = buildParsedTransaction({ + accountKeys: [ + FEE_PAYER, + DESTINATION_TOKEN_ACCOUNT, + SOURCE_TOKEN_ACCOUNT, + DESTINATION_TOKEN_ACCOUNT_2, + TOKEN_PROGRAM, + ], + blockTime: 1777817015, + instructions: [ + buildTokenTransferCheckedIx({ + amount: '100000', + authority: SENDER, + decimals: 6, + destinationTokenAccount: DESTINATION_TOKEN_ACCOUNT, + mint: USDC_MINT, + sourceTokenAccount: SOURCE_TOKEN_ACCOUNT, + }), + buildTokenTransferCheckedIx({ + amount: '200000', + authority: SENDER, + decimals: 6, + destinationTokenAccount: DESTINATION_TOKEN_ACCOUNT_2, + mint: USDC_MINT, + sourceTokenAccount: SOURCE_TOKEN_ACCOUNT, + }), + ], + postTokenBalances: [ + buildTokenBalance({ accountIndex: 1, amount: '100000', decimals: 6, mint: USDC_MINT, owner: RECEIVER }), + buildTokenBalance({ accountIndex: 2, amount: '0', decimals: 6, mint: USDC_MINT, owner: SENDER }), + buildTokenBalance({ accountIndex: 3, amount: '200000', decimals: 6, mint: USDC_MINT, owner: RECEIVER_2 }), + ], +}); + +function buildTokenBalance({ + accountIndex, + amount, + decimals, + mint, + owner, + programId = TOKEN_PROGRAM, +}: { + accountIndex: number; + amount: string; + decimals: number; + mint: PublicKey; + owner: PublicKey; + programId?: PublicKey; +}): ParsedTokenBalance { + const uiAmount = Number(amount) / 10 ** decimals; + return { + accountIndex, + mint: mint.toBase58(), + owner: owner.toBase58(), + programId: programId.toBase58(), + uiTokenAmount: { amount, decimals, uiAmount, uiAmountString: String(uiAmount) }, + }; +} diff --git a/app/features/receipt/api/__tests__/get-tx.spec.ts b/app/features/receipt/api/__tests__/get-tx.spec.ts index 0b8c57f370..cdff08f3be 100644 --- a/app/features/receipt/api/__tests__/get-tx.spec.ts +++ b/app/features/receipt/api/__tests__/get-tx.spec.ts @@ -1,10 +1,11 @@ +import { DEFAULT_SIGNATURE as mockSignature } from '@__fixtures__/gen'; import { fetchTransactionDetails } from '@entities/transaction-data'; import { findTransactionCluster } from '@entities/transaction-data/server'; +import { mockSingleTransferTransaction } from '@features/receipt/__fixtures__/transactions'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { Cluster, serverClusterUrl } from '@/app/utils/cluster'; -import { mockSingleTransferTransaction } from '../../mocks/single-transfer'; import { getTx } from '../get-tx'; // Both halves of the read live in the entity now, on separate barrels: the transaction fetch on the @@ -13,8 +14,6 @@ vi.mock('@entities/transaction-data', () => ({ fetchTransactionDetails: vi.fn() vi.mock('@entities/transaction-data/server', () => ({ findTransactionCluster: vi.fn() })); describe('getTx', () => { - const mockSignature = '5yKzCuw1e9d58HcnzSL31cczfXUux2H4Ga5TAR2RcQLE5W8BiTAC9x9MvhLtc4h99sC9XxLEAjhrXyfKezdMkZFV'; - beforeEach(() => { vi.clearAllMocks(); vi.spyOn(console, 'error').mockImplementation(() => {}); diff --git a/app/features/receipt/lib/__tests__/generate-multi-transfer-pdf.spec.ts b/app/features/receipt/lib/__tests__/generate-multi-transfer-pdf.spec.ts index 419aa7cf73..ae4e9a45b3 100644 --- a/app/features/receipt/lib/__tests__/generate-multi-transfer-pdf.spec.ts +++ b/app/features/receipt/lib/__tests__/generate-multi-transfer-pdf.spec.ts @@ -1,8 +1,3 @@ -import { vi } from 'vitest'; - -import type { FormattedReceipt } from '../../types'; -import { generateMultiTransferPdf } from '../generate-multi-transfer-pdf'; -import { loadPdfDeps } from '../generate-receipt-pdf'; import { buildMultiSolReceipt, collectTextFromMock as collectText, @@ -19,11 +14,16 @@ import { SOL_RECEIPT as RECEIPT, stubSvgRasterizationUnsupported, SVG_RASTERIZATION_ERROR, -} from './__fixtures__/pdf-mocks'; +} from '@features/receipt/__fixtures__/pdf-mocks'; +import { vi } from 'vitest'; + +import type { FormattedReceipt } from '../../types'; +import { generateMultiTransferPdf } from '../generate-multi-transfer-pdf'; +import { loadPdfDeps } from '../generate-receipt-pdf'; vi.mock('jspdf', () => ({ jsPDF: mockJsPDF })); vi.mock('qrcode', () => qrcodeModule); -vi.mock('../pdf-fonts', async () => (await import('./__fixtures__/pdf-mocks')).pdfFontsModule); +vi.mock('../pdf-fonts', async () => (await import('@features/receipt/__fixtures__/pdf-mocks')).pdfFontsModule); describe('generateMultiTransferPdf', () => { const mockOnError = vi.fn(); diff --git a/app/features/receipt/lib/__tests__/generate-receipt-csv.spec.ts b/app/features/receipt/lib/__tests__/generate-receipt-csv.spec.ts index f4bb68981c..232d8aa567 100644 --- a/app/features/receipt/lib/__tests__/generate-receipt-csv.spec.ts +++ b/app/features/receipt/lib/__tests__/generate-receipt-csv.spec.ts @@ -1,6 +1,10 @@ // @vitest-environment jsdom -import { buildFormattedReceipt } from '@entities/token-receipt/__fixtures__/formatted-receipt'; +import { DEFAULT_SIGNATURE as SIGNATURE } from '@__fixtures__/gen'; +import { + buildFormattedReceipt, + buildFormattedTokenReceipt, +} from '@entities/token-receipt/__fixtures__/formatted-receipt'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { FormattedReceipt } from '../../types'; @@ -8,8 +12,6 @@ import { buildReceiptCsvRows, generateReceiptCsv } from '../generate-receipt-csv const RECEIPT = buildFormattedReceipt(); -const SIGNATURE = '5UfDuX7hXbGjGHqPXRGaHdSecretSignature1234567890abcdef'; - describe('buildReceiptCsvRows', () => { it('should include all expected fields in correct column order', () => { const [row] = buildReceiptCsvRows(RECEIPT, SIGNATURE); @@ -34,14 +36,7 @@ describe('buildReceiptCsvRows', () => { }); it('should include mint address for token receipts', () => { - const tokenReceipt: FormattedReceipt = { - ...RECEIPT, - kind: 'token', - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - symbol: 'USDC', - total: { formatted: '143.25', raw: 143.25, unit: 'USDC' }, - }; - const [row] = buildReceiptCsvRows(tokenReceipt, SIGNATURE); + const [row] = buildReceiptCsvRows(buildFormattedTokenReceipt(), SIGNATURE); expect(row[6]).toBe('USDC'); expect(row[7]).toBe('4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'); }); @@ -59,13 +54,10 @@ describe('buildReceiptCsvRows', () => { }); it('should sanitize token symbol with formula-injection prefix', () => { - const receipt: FormattedReceipt = { - ...RECEIPT, - kind: 'token', - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', + const receipt = buildFormattedTokenReceipt({ symbol: '=EVIL', total: { formatted: '100', raw: 100, unit: '=EVIL' }, - }; + }); const [row] = buildReceiptCsvRows(receipt, SIGNATURE); expect(row[6]).toBe("'=EVIL"); }); diff --git a/app/features/receipt/lib/__tests__/generate-receipt-pdf.spec.ts b/app/features/receipt/lib/__tests__/generate-receipt-pdf.spec.ts index fcfe3d117f..14e42e5e37 100644 --- a/app/features/receipt/lib/__tests__/generate-receipt-pdf.spec.ts +++ b/app/features/receipt/lib/__tests__/generate-receipt-pdf.spec.ts @@ -1,8 +1,3 @@ -import { vi } from 'vitest'; - -import { generateMultiTransferPdf } from '../generate-multi-transfer-pdf'; -import { generateReceiptPdf, loadPdfDeps } from '../generate-receipt-pdf'; -import { generateSingleTransferPdf } from '../generate-single-transfer-pdf'; import { buildMultiSolReceipt, collectTextFromMock as collectText, @@ -14,11 +9,16 @@ import { SIGNATURE, SOL_RECEIPT, stubSvgRasterizationUnsupported, -} from './__fixtures__/pdf-mocks'; +} from '@features/receipt/__fixtures__/pdf-mocks'; +import { vi } from 'vitest'; + +import { generateMultiTransferPdf } from '../generate-multi-transfer-pdf'; +import { generateReceiptPdf, loadPdfDeps } from '../generate-receipt-pdf'; +import { generateSingleTransferPdf } from '../generate-single-transfer-pdf'; vi.mock('jspdf', () => ({ jsPDF: mockJsPDF })); vi.mock('qrcode', () => qrcodeModule); -vi.mock('../pdf-fonts', async () => (await import('./__fixtures__/pdf-mocks')).pdfFontsModule); +vi.mock('../pdf-fonts', async () => (await import('@features/receipt/__fixtures__/pdf-mocks')).pdfFontsModule); describe('generateReceiptPdf (dispatcher)', () => { const mockOnError = vi.fn(); diff --git a/app/features/receipt/lib/__tests__/generate-single-transfer-pdf.spec.ts b/app/features/receipt/lib/__tests__/generate-single-transfer-pdf.spec.ts index 0f7d22abd3..955aeaba84 100644 --- a/app/features/receipt/lib/__tests__/generate-single-transfer-pdf.spec.ts +++ b/app/features/receipt/lib/__tests__/generate-single-transfer-pdf.spec.ts @@ -1,7 +1,3 @@ -import { vi } from 'vitest'; - -import { loadPdfDeps } from '../generate-receipt-pdf'; -import { generateSingleTransferPdf } from '../generate-single-transfer-pdf'; import { collectTextFromMock as collectText, mockJsPDF, @@ -12,11 +8,15 @@ import { SOL_RECEIPT, stubSvgRasterizationUnsupported, USDC_RECEIPT, -} from './__fixtures__/pdf-mocks'; +} from '@features/receipt/__fixtures__/pdf-mocks'; +import { vi } from 'vitest'; + +import { loadPdfDeps } from '../generate-receipt-pdf'; +import { generateSingleTransferPdf } from '../generate-single-transfer-pdf'; vi.mock('jspdf', () => ({ jsPDF: mockJsPDF })); vi.mock('qrcode', () => qrcodeModule); -vi.mock('../pdf-fonts', async () => (await import('./__fixtures__/pdf-mocks')).pdfFontsModule); +vi.mock('../pdf-fonts', async () => (await import('@features/receipt/__fixtures__/pdf-mocks')).pdfFontsModule); describe('generateSingleTransferPdf', () => { const mockOnError = vi.fn(); diff --git a/app/features/receipt/mocks/addresses.ts b/app/features/receipt/mocks/addresses.ts deleted file mode 100644 index 8d9f3a118b..0000000000 --- a/app/features/receipt/mocks/addresses.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { Keypair } from '@solana/web3.js'; - -export const SENDER = Keypair.generate(); -export const RECEIVER = Keypair.generate(); -export const RECEIVER_2 = Keypair.generate(); -export const MINT = Keypair.generate(); -export const SOURCE_TOKEN_ACCOUNT = Keypair.generate(); -export const DESTINATION_TOKEN_ACCOUNT = Keypair.generate(); -export const FEE_PAYER = Keypair.generate(); -export const MULTISIG_AUTHORITY = Keypair.generate(); diff --git a/app/features/receipt/mocks/custom-fee-payer.ts b/app/features/receipt/mocks/custom-fee-payer.ts deleted file mode 100644 index 194369dadc..0000000000 --- a/app/features/receipt/mocks/custom-fee-payer.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { type ParsedTransactionWithMeta, PublicKey } from '@solana/web3.js'; - -/** - * Mock transaction data for testing a transaction with a custom fee payer. - * - Transfer 0.5 SOL (500,000,000 lamports) from Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5 - * - To: G2GjouKPJnGi3aGVsHnBu475EGvseiL1QnVHBMkN6wid - * - Fee payer: 644RudhReGpiHsNysSVSpDDagrzw5mBCwdHq1ZNwK6zL (pays 10,000 lamports fee) - * - Sender: Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5 (pays transfer amount) - * - * This transaction has 2 signers: the fee payer and the sender. - */ -export const mockCustomFeePayerTransaction = { - blockTime: 1769093093, - meta: { - computeUnitsConsumed: 150, - costUnits: 2501, - err: null, - fee: 10000, - innerInstructions: [], - logMessages: [ - 'Program 11111111111111111111111111111111 invoke [1]', - 'Program 11111111111111111111111111111111 success', - ], - postBalances: [449980000, 64579299131, 590000000, 1], - postTokenBalances: [], - preBalances: [449990000, 65079299131, 90000000, 1], - preTokenBalances: [], - }, - slot: 436905636, - transaction: { - message: { - accountKeys: [ - { - pubkey: new PublicKey('644RudhReGpiHsNysSVSpDDagrzw5mBCwdHq1ZNwK6zL'), - signer: true, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5'), - signer: true, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('G2GjouKPJnGi3aGVsHnBu475EGvseiL1QnVHBMkN6wid'), - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('11111111111111111111111111111111'), - signer: false, - source: 'transaction', - writable: false, - }, - ], - instructions: [ - { - parsed: { - info: { - destination: 'G2GjouKPJnGi3aGVsHnBu475EGvseiL1QnVHBMkN6wid', - lamports: 500000000, - source: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - }, - type: 'transfer', - }, - program: 'system', - programId: new PublicKey('11111111111111111111111111111111'), - }, - ], - recentBlockhash: 'A9Pd86j8WcF63pn1m21njYmVdkhPbb1E5a1vFkzbuSzM', - }, - signatures: [ - '2MDTSo3dg7UxMnMhQVMVT2uVs5HzKrFjgoRmPwM8g951RZLhGeRcxZc9d1StzFR2FAmfKX8kbB5ZTjcu5vpXKAVN', - 'R6YbzNromQCt2kx1YiVGpBT89zNg7zDBKge9yMreUgz5dYDdPWFCi6ffYy2jtvNdn7hEQiMeJKM5NNsRuQf5auy', - ], - }, - version: 'legacy', -} satisfies ParsedTransactionWithMeta; diff --git a/app/features/receipt/mocks/jito-only-transfer.ts b/app/features/receipt/mocks/jito-only-transfer.ts deleted file mode 100644 index faf19c0f92..0000000000 --- a/app/features/receipt/mocks/jito-only-transfer.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { type ParsedTransactionWithMeta, PublicKey } from '@solana/web3.js'; - -/** - * Mock transaction data for testing a Jito-only SOL transfer (single instruction: SOL transfer to a Jito tip account). - * - Transfer 0.000017343 SOL (17,343 lamports) from R1CHHDEeDwxVxjKv2FPd57mVhbUp4aUQvuE49jYF6Vq - * - To: ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt - * - * Sender: R1CHHDEeDwxVxjKv2FPd57mVhbUp4aUQvuE49jYF6Vq - * Receiver: ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt - */ -export const mockJitoOnlyTransferTransaction = { - blockTime: 1770048279, - meta: { - computeUnitsConsumed: 70324, - costUnits: 84616, - err: null, - fee: 5000, - innerInstructions: [], - logMessages: [ - 'Program 11111111111111111111111111111111 invoke [1]', - 'Program 11111111111111111111111111111111 success', - ], - postBalances: [56197667482817, 17343, 1], - postTokenBalances: [], - preBalances: [56197667482817, 0, 1], - preTokenBalances: [], - }, - slot: 397598054, - transaction: { - message: { - accountKeys: [ - { - pubkey: new PublicKey('R1CHHDEeDwxVxjKv2FPd57mVhbUp4aUQvuE49jYF6Vq'), - signer: true, - source: 'transaction' as const, - writable: true, - }, - { - pubkey: new PublicKey('ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt'), - signer: false, - source: 'transaction' as const, - writable: true, - }, - { - pubkey: new PublicKey('11111111111111111111111111111111'), - signer: false, - source: 'transaction' as const, - writable: false, - }, - ], - instructions: [ - { - parsed: { - info: { - destination: 'ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt', - lamports: 17343, - source: 'R1CHHDEeDwxVxjKv2FPd57mVhbUp4aUQvuE49jYF6Vq', - }, - type: 'transfer', - }, - program: 'system', - programId: new PublicKey('11111111111111111111111111111111'), - }, - ], - recentBlockhash: 'sEGK1mZbefsRz5CabeFbvfZL5JhmXYpWmEciY2VA7o9', - }, - signatures: ['2Pp2vWG88BsebGJWn2AbXcLSkjXWUBJN8ZRYcX4gGTaHQe9h79Bsad77wBM4XB4xK4RvdChR4hsXMf8UdhR2s1Po'], - }, - version: 'legacy' as const, -} satisfies ParsedTransactionWithMeta; diff --git a/app/features/receipt/mocks/mixed-mint-transfers.ts b/app/features/receipt/mocks/mixed-mint-transfers.ts deleted file mode 100644 index 5d562bc53a..0000000000 --- a/app/features/receipt/mocks/mixed-mint-transfers.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { TOKEN_PROGRAM_ID } from '@providers/accounts/tokens'; -import { Keypair, type ParsedTransactionWithMeta } from '@solana/web3.js'; - -const FEE_PAYER = Keypair.generate().publicKey; -const AUTHORITY = Keypair.generate().publicKey; -const SOURCE_USDC = Keypair.generate().publicKey; -const SOURCE_BONK = Keypair.generate().publicKey; -const DESTINATION_USDC = Keypair.generate().publicKey; -const DESTINATION_BONK = Keypair.generate().publicKey; -const RECEIVER_USDC = Keypair.generate().publicKey; -const RECEIVER_BONK = Keypair.generate().publicKey; -const USDC_MINT = Keypair.generate().publicKey; -const BONK_MINT = Keypair.generate().publicKey; -const TOKEN_PROGRAM = TOKEN_PROGRAM_ID; - -/** - * Mock transaction containing two token transfers of distinct mints. - * Used to verify the receipt pipeline rejects mixed-mint transactions and - * exposes a "mixed-mint" reason to the UI. - */ -export const mockMixedMintTransfersTransaction = { - blockTime: 1777817015, - meta: { - computeUnitsConsumed: 12700, - err: null, - fee: 5000, - innerInstructions: [], - logMessages: [], - postBalances: [0, 2039280, 2039280, 2039280, 2039280, 1], - postTokenBalances: [ - { - accountIndex: 1, - mint: USDC_MINT.toBase58(), - owner: RECEIVER_USDC.toBase58(), - programId: TOKEN_PROGRAM.toBase58(), - uiTokenAmount: { amount: '1000000', decimals: 6, uiAmount: 1, uiAmountString: '1' }, - }, - { - accountIndex: 2, - mint: USDC_MINT.toBase58(), - owner: AUTHORITY.toBase58(), - programId: TOKEN_PROGRAM.toBase58(), - uiTokenAmount: { amount: '0', decimals: 6, uiAmount: null, uiAmountString: '0' }, - }, - { - accountIndex: 3, - mint: BONK_MINT.toBase58(), - owner: RECEIVER_BONK.toBase58(), - programId: TOKEN_PROGRAM.toBase58(), - uiTokenAmount: { amount: '500', decimals: 5, uiAmount: 0.005, uiAmountString: '0.005' }, - }, - { - accountIndex: 4, - mint: BONK_MINT.toBase58(), - owner: AUTHORITY.toBase58(), - programId: TOKEN_PROGRAM.toBase58(), - uiTokenAmount: { amount: '0', decimals: 5, uiAmount: null, uiAmountString: '0' }, - }, - ], - preBalances: [5000, 2039280, 2039280, 2039280, 2039280, 1], - preTokenBalances: [], - }, - slot: 1, - transaction: { - message: { - accountKeys: [ - { pubkey: FEE_PAYER, signer: true, source: 'transaction', writable: true }, - { pubkey: DESTINATION_USDC, signer: false, source: 'transaction', writable: true }, - { pubkey: SOURCE_USDC, signer: false, source: 'transaction', writable: true }, - { pubkey: DESTINATION_BONK, signer: false, source: 'transaction', writable: true }, - { pubkey: SOURCE_BONK, signer: false, source: 'transaction', writable: true }, - { pubkey: TOKEN_PROGRAM, signer: false, source: 'transaction', writable: false }, - ], - instructions: [ - { - parsed: { - info: { - authority: AUTHORITY.toBase58(), - destination: DESTINATION_USDC.toBase58(), - mint: USDC_MINT.toBase58(), - source: SOURCE_USDC.toBase58(), - tokenAmount: { amount: '1000000', decimals: 6, uiAmount: 1, uiAmountString: '1' }, - }, - type: 'transferChecked', - }, - program: 'spl-token', - programId: TOKEN_PROGRAM, - }, - { - parsed: { - info: { - authority: AUTHORITY.toBase58(), - destination: DESTINATION_BONK.toBase58(), - mint: BONK_MINT.toBase58(), - source: SOURCE_BONK.toBase58(), - tokenAmount: { amount: '500', decimals: 5, uiAmount: 0.005, uiAmountString: '0.005' }, - }, - type: 'transferChecked', - }, - program: 'spl-token', - programId: TOKEN_PROGRAM, - }, - ], - recentBlockhash: '6MgFAucojhVLnxc6bfvjpn72bnCoGRA7runiGiRg7xtv', - }, - signatures: ['mockSignatureForMixedMintTransfersTestOnly'], - }, - version: 'legacy', -} satisfies ParsedTransactionWithMeta; diff --git a/app/features/receipt/mocks/multiple-transfers.ts b/app/features/receipt/mocks/multiple-transfers.ts deleted file mode 100644 index ec4c995b84..0000000000 --- a/app/features/receipt/mocks/multiple-transfers.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { type ParsedTransactionWithMeta, PublicKey } from '@solana/web3.js'; - -import { RECEIVER, RECEIVER_2, SENDER } from './addresses'; - -/** - * Mock transaction data for testing multiple transfers. - * - Transfer 0.08 SOL to RECEIVER - * - Transfer 0.05 SOL to RECEIVER_2 - * - Transfer 0.01 SOL to RECEIVER - * - * Sender: SENDER - */ -export const mockMultipleTransfersTransaction = { - blockTime: 1768831450, - meta: { - computeUnitsConsumed: 450, - err: null, - fee: 5000, - innerInstructions: [], - logMessages: [ - 'Program 11111111111111111111111111111111 invoke [1]', - 'Program 11111111111111111111111111111111 success', - 'Program 11111111111111111111111111111111 invoke [1]', - 'Program 11111111111111111111111111111111 success', - 'Program 11111111111111111111111111111111 invoke [1]', - 'Program 11111111111111111111111111111111 success', - ], - postBalances: [50601134451, 50000000, 90000000, 1], - postTokenBalances: [], - preBalances: [50741139451, 0, 0, 1], - preTokenBalances: [], - }, - slot: 436228237, - transaction: { - message: { - accountKeys: [ - { - pubkey: SENDER.publicKey, - signer: true, - source: 'transaction', - writable: true, - }, - { - pubkey: RECEIVER.publicKey, - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: RECEIVER_2.publicKey, - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('11111111111111111111111111111111'), - signer: false, - source: 'transaction', - writable: false, - }, - ], - instructions: [ - { - parsed: { - info: { - destination: RECEIVER.publicKey.toBase58(), - lamports: 80000000, - source: SENDER.publicKey.toBase58(), - }, - type: 'transfer', - }, - program: 'system', - programId: new PublicKey('11111111111111111111111111111111'), - }, - { - parsed: { - info: { - destination: RECEIVER_2.publicKey.toBase58(), - lamports: 50000000, - source: SENDER.publicKey.toBase58(), - }, - type: 'transfer', - }, - program: 'system', - programId: new PublicKey('11111111111111111111111111111111'), - }, - { - parsed: { - info: { - destination: RECEIVER.publicKey.toBase58(), - lamports: 10000000, - source: SENDER.publicKey.toBase58(), - }, - type: 'transfer', - }, - program: 'system', - programId: new PublicKey('11111111111111111111111111111111'), - }, - ], - recentBlockhash: 'AHK7TnmvzPAk4WsmWqVgL7v6YccGkANoWUmrSY7aQDzw', - }, - signatures: ['5yKzCuw1e9d58HcnzSL31cczfXUux2H4Ga5TAR2RcQLE5W8BiTAC9x9MvhLtc4h99sC9XxLEAjhrXyfKezdMkZFV'], - }, - version: 'legacy', -} satisfies ParsedTransactionWithMeta; diff --git a/app/features/receipt/mocks/no-transfers.ts b/app/features/receipt/mocks/no-transfers.ts deleted file mode 100644 index 376a3e5b7a..0000000000 --- a/app/features/receipt/mocks/no-transfers.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { type ParsedTransactionWithMeta, PublicKey } from '@solana/web3.js'; - -/** - * Mock transaction data for testing a transaction with no transfers (memo only). - * - Memo: "Payment for invoice #123" - * - No SOL transfers - * - * Sender: Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5 - */ -export const mockNoTransferTransaction = { - blockTime: 1768828236, - meta: { - computeUnitsConsumed: 23208, - err: null, - fee: 5000, - innerInstructions: [], - logMessages: [ - 'Program MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr invoke [1]', - 'Program log: Signed by Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - 'Program log: Memo (len 24): "Payment for invoice #123"', - 'Program MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr consumed 23208 of 200000 compute units', - 'Program MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr success', - ], - postBalances: [50741144451, 1055598881], - postTokenBalances: [], - preBalances: [50741149451, 1055598881], - preTokenBalances: [], - }, - slot: 436219969, - transaction: { - message: { - accountKeys: [ - { - pubkey: new PublicKey('Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5'), - signer: true, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'), - signer: false, - source: 'transaction', - writable: false, - }, - ], - instructions: [ - { - parsed: 'Payment for invoice #123', - program: 'spl-memo', - programId: new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'), - }, - ], - recentBlockhash: '2cCRgF4ZSNTCTTZEvPCwpjMmiMrTibXUnKtCUhwJypgW', - }, - signatures: ['5aVj7exPmdLLQyzMo4FMHQEkoRzheXKVBStvZLuZb1xE2vKhqoxup41bzDtp7Xc5N4gRGGqQofJ4Rt1eyKiJTTK8'], - }, - version: 'legacy', -} satisfies ParsedTransactionWithMeta; diff --git a/app/features/receipt/mocks/single-transfer.ts b/app/features/receipt/mocks/single-transfer.ts deleted file mode 100644 index 8b5727a7ef..0000000000 --- a/app/features/receipt/mocks/single-transfer.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { type ParsedTransactionWithMeta, PublicKey } from '@solana/web3.js'; - -import { RECEIVER, SENDER } from './addresses'; - -/** - * Mock transaction data for testing a single SOL transfer. - * - Transfer 0.3 SOL (300,000,000 lamports) from SENDER to RECEIVER - */ -export const mockSingleTransferTransaction = { - blockTime: 1769070902, - meta: { - computeUnitsConsumed: 150, - costUnits: 1481, - err: null, - fee: 5000, - innerInstructions: [], - logMessages: [ - 'Program 11111111111111111111111111111111 invoke [1]', - 'Program 11111111111111111111111111111111 success', - ], - postBalances: [55179299131, 350000000, 1], - postTokenBalances: [], - preBalances: [55479304131, 50000000, 1], - preTokenBalances: [], - }, - slot: 436848066, - transaction: { - message: { - accountKeys: [ - { - pubkey: SENDER.publicKey, - signer: true, - source: 'transaction', - writable: true, - }, - { - pubkey: RECEIVER.publicKey, - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('11111111111111111111111111111111'), - signer: false, - source: 'transaction', - writable: false, - }, - ], - instructions: [ - { - parsed: { - info: { - destination: RECEIVER.publicKey.toBase58(), - lamports: 300000000, - source: SENDER.publicKey.toBase58(), - }, - type: 'transfer', - }, - program: 'system', - programId: new PublicKey('11111111111111111111111111111111'), - }, - ], - recentBlockhash: '6MgFAucojhVLnxc6bfvjpn72bnCoGRA7runiGiRg7xtv', - }, - signatures: ['pBApPVmSKwvLmGahzW7ZKHmqLuPNXpwJR3n37HQ4B279AG4JmfUWJRd9NnaaQAxJZ5npdoFj6r6iZ2cvoYdorFg'], - }, - version: 'legacy', -} satisfies ParsedTransactionWithMeta; diff --git a/app/features/receipt/mocks/token-2022-transfer.ts b/app/features/receipt/mocks/token-2022-transfer.ts deleted file mode 100644 index 15152e6918..0000000000 --- a/app/features/receipt/mocks/token-2022-transfer.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { type ParsedTransactionWithMeta, PublicKey } from '@solana/web3.js'; - -const TOKEN_2022_PROGRAM_ADDRESS = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'; - -/** - * Mock transaction data for testing a Token-2022 transferChecked (with optional CreateIdempotent). - * - Transfer 100 tokens (9 decimals) via Token-2022 program - * - From (source): 99FC9v1Jt7ZDB7fmZtLbYLt7wpYPfVioRy5NJcGrK7ES (sender Hd3f3's ATA) - * - To (destination): AvU46uNPpHaPewPwqWNqVLgD9TgQRD8uqFpRRi5PkFDS (receiver 65MUM's ATA) - * - Authority: Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5 - * - Mint: AN8h2reVWuPAWXhfJQounhTMqb5bvwVKumX6pMmSK25U - * - * Sender: Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5 - * Receiver: 65MUMxiopKUaZbazs6pRUr9y774mj4Z1TdDgUh3L2Fhk - */ -export const mockToken2022TransferTransaction = { - blockTime: 1769580206, - meta: { - computeUnitsConsumed: 18258, - costUnits: 20082, - err: null, - fee: 5000, - innerInstructions: [], - logMessages: [ - 'Program ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL invoke [1]', - 'Program log: CreateIdempotent', - `Program ${TOKEN_2022_PROGRAM_ADDRESS} invoke [2]`, - 'Program log: Instruction: GetAccountDataSize', - `Program ${TOKEN_2022_PROGRAM_ADDRESS} consumed 1155 of 12917 compute units`, - `Program ${TOKEN_2022_PROGRAM_ADDRESS} success`, - 'Program TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb invoke [1]', - 'Program log: Instruction: TransferChecked', - `Program ${TOKEN_2022_PROGRAM_ADDRESS} consumed 1960 of 2110 compute units`, - `Program ${TOKEN_2022_PROGRAM_ADDRESS} success`, - 'Program ComputeBudget111111111111111111111111111111 invoke [1]', - 'Program ComputeBudget111111111111111111111111111111 success', - ], - postBalances: [69073659371, 2074080, 2074080, 1, 1, 1159846, 449960000, 1461600, 934079540], - postTokenBalances: [ - { - accountIndex: 1, - mint: 'AN8h2reVWuPAWXhfJQounhTMqb5bvwVKumX6pMmSK25U', - owner: '65MUMxiopKUaZbazs6pRUr9y774mj4Z1TdDgUh3L2Fhk', - programId: TOKEN_2022_PROGRAM_ADDRESS, - uiTokenAmount: { - amount: '100000000000', - decimals: 9, - uiAmount: 100, - uiAmountString: '100', - }, - }, - { - accountIndex: 2, - mint: 'AN8h2reVWuPAWXhfJQounhTMqb5bvwVKumX6pMmSK25U', - owner: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - programId: TOKEN_2022_PROGRAM_ADDRESS, - uiTokenAmount: { - amount: '900000000000', - decimals: 9, - uiAmount: 900, - uiAmountString: '900', - }, - }, - ], - preBalances: [69075738451, 2074080, 0, 1, 1, 1159846, 449960000, 1461600, 934079540], - preTokenBalances: [ - { - accountIndex: 1, - mint: 'AN8h2reVWuPAWXhfJQounhTMqb5bvwVKumX6pMmSK25U', - owner: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - programId: TOKEN_2022_PROGRAM_ADDRESS, - uiTokenAmount: { - amount: '1000000000000', - decimals: 9, - uiAmount: 1000, - uiAmountString: '1000', - }, - }, - ], - }, - slot: 438171312, - transaction: { - message: { - accountKeys: [ - { - pubkey: new PublicKey('Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5'), - signer: true, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('AvU46uNPpHaPewPwqWNqVLgD9TgQRD8uqFpRRi5PkFDS'), - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('99FC9v1Jt7ZDB7fmZtLbYLt7wpYPfVioRy5NJcGrK7ES'), - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('11111111111111111111111111111111'), - signer: false, - source: 'transaction', - writable: false, - }, - { - pubkey: new PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'), - signer: false, - source: 'transaction', - writable: false, - }, - { - pubkey: new PublicKey(TOKEN_2022_PROGRAM_ADDRESS), - signer: false, - source: 'transaction', - writable: false, - }, - { - pubkey: new PublicKey('ComputeBudget111111111111111111111111111111'), - signer: false, - source: 'transaction', - writable: false, - }, - ], - instructions: [ - { - parsed: { - info: { - account: 'AvU46uNPpHaPewPwqWNqVLgD9TgQRD8uqFpRRi5PkFDS', - mint: 'AN8h2reVWuPAWXhfJQounhTMqb5bvwVKumX6pMmSK25U', - source: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - systemProgram: '11111111111111111111111111111111', - tokenProgram: TOKEN_2022_PROGRAM_ADDRESS, - wallet: '65MUMxiopKUaZbazs6pRUr9y774mj4Z1TdDgUh3L2Fhk', - }, - type: 'createIdempotent', - }, - program: 'spl-associated-token-account', - programId: new PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'), - }, - { - parsed: { - info: { - authority: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - destination: 'AvU46uNPpHaPewPwqWNqVLgD9TgQRD8uqFpRRi5PkFDS', - mint: 'AN8h2reVWuPAWXhfJQounhTMqb5bvwVKumX6pMmSK25U', - source: '99FC9v1Jt7ZDB7fmZtLbYLt7wpYPfVioRy5NJcGrK7ES', - tokenAmount: { - amount: '100000000000', - decimals: 9, - uiAmount: 100, - uiAmountString: '100', - }, - }, - type: 'transferChecked', - }, - program: 'spl-token', - programId: new PublicKey(TOKEN_2022_PROGRAM_ADDRESS), - }, - { - accounts: [], - data: 'GC3Vaw', - programId: new PublicKey('ComputeBudget111111111111111111111111111111'), - }, - ], - recentBlockhash: 'CjznuT7TC4cruwFvAaSeZHP2vC7wtt6YwUyfKWZHv2fY', - }, - signatures: ['2oSMCYeEPGZq5LLrNcDBw8TRq2H7Dxo4uxgHvuJKTWoTyRBGN87uZFTZy7o2iRVmDeB72nvr91dAkwAciiwQWTgL'], - }, - version: 'legacy', -} satisfies ParsedTransactionWithMeta; diff --git a/app/features/receipt/mocks/token-2022-transfer2.ts b/app/features/receipt/mocks/token-2022-transfer2.ts deleted file mode 100644 index 5553acf227..0000000000 --- a/app/features/receipt/mocks/token-2022-transfer2.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { type ParsedTransactionWithMeta, PublicKey } from '@solana/web3.js'; - -const TOKEN_2022_PROGRAM_ADDRESS = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'; - -/** - * Mock transaction data for testing a Token-2022 transfer (transfer2 instruction). - * - Transfer 100 tokens (100 with 0 decimals) via Token-2022 program - * - From (source): 3MRBUAxwx7gWoGvAtzxLtzmhzwPDGAEqStKWb8cJnYQX (sender Hd3f3's ATA) - * - To (destination): HYsC1ge3Yo1sSBFvcEn4otFZEJkitUNZYPsDVTQNacBT (receiver 65MUM's ATA) - * - Authority: Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5 - * - Mint: 7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU (example T22 mint) - * - * Sender: Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5 - * Receiver: 65MUMxiopKUaZbazs6pRUr9y774mj4Z1TdDgUh3L2Fhk - */ -export const mockToken2022Transfer2Transaction = { - blockTime: 1769200000, - meta: { - computeUnitsConsumed: 6500, - costUnits: 8012, - err: null, - fee: 5000, - innerInstructions: [], - logMessages: [ - `Program ${TOKEN_2022_PROGRAM_ADDRESS} invoke [1]`, - 'Program log: Instruction: Transfer (Checked)', - `Program ${TOKEN_2022_PROGRAM_ADDRESS} consumed 6199 of 6500 compute units`, - `Program ${TOKEN_2022_PROGRAM_ADDRESS} success`, - 'Program ComputeBudget111111111111111111111111111111 invoke [1]', - 'Program ComputeBudget111111111111111111111111111111 success', - ], - postBalances: [55479304131, 2039280, 2039280, 1, 8738370969, 188340812685], - postTokenBalances: [ - { - accountIndex: 1, - mint: '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU', - owner: '65MUMxiopKUaZbazs6pRUr9y774mj4Z1TdDgUh3L2Fhk', - programId: TOKEN_2022_PROGRAM_ADDRESS, - uiTokenAmount: { amount: '100', decimals: 0, uiAmount: 100, uiAmountString: '100' }, - }, - { - accountIndex: 2, - mint: '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU', - owner: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - programId: TOKEN_2022_PROGRAM_ADDRESS, - uiTokenAmount: { amount: '900', decimals: 0, uiAmount: 900, uiAmountString: '900' }, - }, - ], - preBalances: [55479309131, 2039280, 2039280, 1, 8738370969, 188340812685], - preTokenBalances: [ - { - accountIndex: 1, - mint: '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU', - owner: '65MUMxiopKUaZbazs6pRUr9y774mj4Z1TdDgUh3L2Fhk', - programId: TOKEN_2022_PROGRAM_ADDRESS, - uiTokenAmount: { amount: '0', decimals: 0, uiAmount: null, uiAmountString: '0' }, - }, - { - accountIndex: 2, - mint: '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU', - owner: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - programId: TOKEN_2022_PROGRAM_ADDRESS, - uiTokenAmount: { amount: '1000', decimals: 0, uiAmount: 1000, uiAmountString: '1000' }, - }, - ], - }, - slot: 437100000, - transaction: { - message: { - accountKeys: [ - { - pubkey: new PublicKey('Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5'), - signer: true, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('HYsC1ge3Yo1sSBFvcEn4otFZEJkitUNZYPsDVTQNacBT'), - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('3MRBUAxwx7gWoGvAtzxLtzmhzwPDGAEqStKWb8cJnYQX'), - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('ComputeBudget111111111111111111111111111111'), - signer: false, - source: 'transaction', - writable: false, - }, - { - pubkey: new PublicKey('11111111111111111111111111111111'), - signer: false, - source: 'transaction', - writable: false, - }, - { - pubkey: new PublicKey(TOKEN_2022_PROGRAM_ADDRESS), - signer: false, - source: 'transaction', - writable: false, - }, - ], - instructions: [ - { - parsed: { - info: { - authority: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - destination: 'HYsC1ge3Yo1sSBFvcEn4otFZEJkitUNZYPsDVTQNacBT', - mint: '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU', - source: '3MRBUAxwx7gWoGvAtzxLtzmhzwPDGAEqStKWb8cJnYQX', - tokenAmount: { amount: '100', decimals: 0, uiAmount: 100, uiAmountString: '100' }, - }, - type: 'transfer2', - }, - program: 'spl-token-2022', - programId: new PublicKey(TOKEN_2022_PROGRAM_ADDRESS), - }, - { - accounts: [], - data: 'KL8Bcb', - programId: new PublicKey('ComputeBudget111111111111111111111111111111'), - }, - ], - recentBlockhash: 'Eo7YPFE1694LpMwhb5RygaJJBfNzbVGz383Y2uErk9uS', - }, - signatures: ['2cQ1xf4meFvQBcmhyAtnXQzWbqNWvy3eQrgWPov3EQbnj2WGpLzChjJrVopFURRCWeNyKe8grXk4hmcv3EFd7iA8'], - }, - version: 'legacy', -} satisfies ParsedTransactionWithMeta; diff --git a/app/features/receipt/mocks/usdc-checked-transfer.ts b/app/features/receipt/mocks/usdc-checked-transfer.ts deleted file mode 100644 index 7a15cf4698..0000000000 --- a/app/features/receipt/mocks/usdc-checked-transfer.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { type ParsedTransactionWithMeta, PublicKey } from '@solana/web3.js'; - -/** - * Mock transaction data for testing a USDC token transfer. - * - Transfer 1 USDC (1,000,000 with 6 decimals) from HYsC1ge3Yo1sSBFvcEn4otFZEJkitUNZYPsDVTQNacBT - * - To: 3MRBUAxwx7gWoGvAtzxLtzmhzwPDGAEqStKWb8cJnYQX - * - Authority: Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5 - * - Mint: 4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU - * - * Sender: Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5 - * Receiver: 65MUMxiopKUaZbazs6pRUr9y774mj4Z1TdDgUh3L2Fhk - */ -export const mockUsdcTransferTransaction = { - blockTime: 1769070184, - meta: { - computeUnitsConsumed: 6349, - costUnits: 8012, - err: null, - fee: 5000, - innerInstructions: [], - logMessages: [ - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]', - 'Program log: Instruction: TransferChecked', - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 6199 of 6349 compute units', - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success', - 'Program ComputeBudget111111111111111111111111111111 invoke [1]', - 'Program ComputeBudget111111111111111111111111111111 success', - ], - postBalances: [55479304131, 2039280, 2039280, 1, 8738370969, 188340812685], - postTokenBalances: [ - { - accountIndex: 1, - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - owner: '65MUMxiopKUaZbazs6pRUr9y774mj4Z1TdDgUh3L2Fhk', - programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - uiTokenAmount: { amount: '1000000', decimals: 6, uiAmount: 1, uiAmountString: '1' }, - }, - { - accountIndex: 2, - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - owner: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - uiTokenAmount: { amount: '19000000', decimals: 6, uiAmount: 19, uiAmountString: '19' }, - }, - ], - preBalances: [55479309131, 2039280, 2039280, 1, 8738370969, 188340812685], - preTokenBalances: [ - { - accountIndex: 1, - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - owner: '65MUMxiopKUaZbazs6pRUr9y774mj4Z1TdDgUh3L2Fhk', - programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - uiTokenAmount: { amount: '0', decimals: 6, uiAmount: null, uiAmountString: '0' }, - }, - { - accountIndex: 2, - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - owner: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - uiTokenAmount: { amount: '20000000', decimals: 6, uiAmount: 20, uiAmountString: '20' }, - }, - ], - }, - slot: 436846205, - transaction: { - message: { - accountKeys: [ - { - pubkey: new PublicKey('Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5'), - signer: true, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('HYsC1ge3Yo1sSBFvcEn4otFZEJkitUNZYPsDVTQNacBT'), - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('3MRBUAxwx7gWoGvAtzxLtzmhzwPDGAEqStKWb8cJnYQX'), - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('ComputeBudget111111111111111111111111111111'), - signer: false, - source: 'transaction', - writable: false, - }, - { - pubkey: new PublicKey('11111111111111111111111111111111'), - signer: false, - source: 'transaction', - writable: false, - }, - { - pubkey: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), - signer: false, - source: 'transaction', - writable: false, - }, - ], - instructions: [ - { - parsed: { - info: { - authority: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - destination: '3MRBUAxwx7gWoGvAtzxLtzmhzwPDGAEqStKWb8cJnYQX', - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - source: 'HYsC1ge3Yo1sSBFvcEn4otFZEJkitUNZYPsDVTQNacBT', - tokenAmount: { amount: '1000000', decimals: 6, uiAmount: 1, uiAmountString: '1' }, - }, - type: 'transferChecked', - }, - program: 'spl-token', - programId: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), - }, - { - accounts: [], - data: 'KL8Bcb', - programId: new PublicKey('ComputeBudget111111111111111111111111111111'), - }, - ], - recentBlockhash: 'Eo7YPFE1694LpMwhb5RygaJJBfNzbVGz383Y2uErk9uS', - }, - signatures: ['2cQ1xf4meFvQBcmhyAtnXQzWbqNWvy3eQrgWPov3EQbnj2WGpLzChjJrVopFURRCWeNyKe8grXk4hmcv3EFd7iA8'], - }, - version: 'legacy', -} satisfies ParsedTransactionWithMeta; diff --git a/app/features/receipt/mocks/usdc-fp-precision-transfers.ts b/app/features/receipt/mocks/usdc-fp-precision-transfers.ts deleted file mode 100644 index e89b0656c7..0000000000 --- a/app/features/receipt/mocks/usdc-fp-precision-transfers.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { Keypair, type ParsedTransactionWithMeta, PublicKey } from '@solana/web3.js'; - -const FEE_PAYER = Keypair.generate().publicKey; -const AUTHORITY = Keypair.generate().publicKey; -const SOURCE = Keypair.generate().publicKey; -const DESTINATION_A = Keypair.generate().publicKey; -const DESTINATION_B = Keypair.generate().publicKey; -const RECEIVER_A = Keypair.generate().publicKey; -const RECEIVER_B = Keypair.generate().publicKey; -const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); -const TOKEN_PROGRAM = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'); - -/** - * Two same-mint USDC transfers chosen to surface the classic float-summation pitfall: - * 0.1 USDC + 0.2 USDC. - * With naive float addition this sums to 0.30000000000000004; the receipt total - * must instead be exactly 0.3 (raw 100_000 + 200_000 = 300_000 base units / 10^6). - */ -export const mockUsdcFpPrecisionTransfersTransaction = { - blockTime: 1777817015, - meta: { - computeUnitsConsumed: 12400, - err: null, - fee: 5000, - innerInstructions: [], - logMessages: [], - postBalances: [0, 2039280, 2039280, 2039280, 1], - postTokenBalances: [ - { - accountIndex: 1, - mint: USDC_MINT.toBase58(), - owner: RECEIVER_A.toBase58(), - programId: TOKEN_PROGRAM.toBase58(), - uiTokenAmount: { amount: '100000', decimals: 6, uiAmount: 0.1, uiAmountString: '0.1' }, - }, - { - accountIndex: 2, - mint: USDC_MINT.toBase58(), - owner: AUTHORITY.toBase58(), - programId: TOKEN_PROGRAM.toBase58(), - uiTokenAmount: { amount: '0', decimals: 6, uiAmount: null, uiAmountString: '0' }, - }, - { - accountIndex: 3, - mint: USDC_MINT.toBase58(), - owner: RECEIVER_B.toBase58(), - programId: TOKEN_PROGRAM.toBase58(), - uiTokenAmount: { amount: '200000', decimals: 6, uiAmount: 0.2, uiAmountString: '0.2' }, - }, - ], - preBalances: [5000, 2039280, 2039280, 2039280, 1], - preTokenBalances: [], - }, - slot: 1, - transaction: { - message: { - accountKeys: [ - { pubkey: FEE_PAYER, signer: true, source: 'transaction', writable: true }, - { pubkey: DESTINATION_A, signer: false, source: 'transaction', writable: true }, - { pubkey: SOURCE, signer: false, source: 'transaction', writable: true }, - { pubkey: DESTINATION_B, signer: false, source: 'transaction', writable: true }, - { pubkey: TOKEN_PROGRAM, signer: false, source: 'transaction', writable: false }, - ], - instructions: [ - { - parsed: { - info: { - authority: AUTHORITY.toBase58(), - destination: DESTINATION_A.toBase58(), - mint: USDC_MINT.toBase58(), - source: SOURCE.toBase58(), - tokenAmount: { amount: '100000', decimals: 6, uiAmount: 0.1, uiAmountString: '0.1' }, - }, - type: 'transferChecked', - }, - program: 'spl-token', - programId: TOKEN_PROGRAM, - }, - { - parsed: { - info: { - authority: AUTHORITY.toBase58(), - destination: DESTINATION_B.toBase58(), - mint: USDC_MINT.toBase58(), - source: SOURCE.toBase58(), - tokenAmount: { amount: '200000', decimals: 6, uiAmount: 0.2, uiAmountString: '0.2' }, - }, - type: 'transferChecked', - }, - program: 'spl-token', - programId: TOKEN_PROGRAM, - }, - ], - recentBlockhash: '6MgFAucojhVLnxc6bfvjpn72bnCoGRA7runiGiRg7xtv', - }, - signatures: ['mockSignatureForFpPrecisionTransfersTestOnly'], - }, - version: 'legacy', -} satisfies ParsedTransactionWithMeta; diff --git a/app/features/receipt/mocks/usdc-jito-transfer.ts b/app/features/receipt/mocks/usdc-jito-transfer.ts deleted file mode 100644 index 742f6a36ca..0000000000 --- a/app/features/receipt/mocks/usdc-jito-transfer.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { type ParsedTransactionWithMeta, PublicKey } from '@solana/web3.js'; - -/** - * Mock transaction data for testing a USDC transfer with a Jito tip. - * - TransferChecked 1 USDC (1,000,000 with 6 decimals) from HYsC1ge3Yo1sSBFvcEn4otFZEJkitUNZYPsDVTQNacBT - * to 3MRBUAxwx7gWoGvAtzxLtzmhzwPDGAEqStKWb8cJnYQX (authority: Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5) - * - System transfer 10,000 lamports (Jito tip) from Hd3f3... to 96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5 - * - * Sender: Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5 - */ -export const mockUsdcJitoTransferTransaction = { - blockTime: 1769770869, - meta: { - computeUnitsConsumed: 6349, - err: null, - fee: 5000, - innerInstructions: [], - logMessages: [ - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]', - 'Program log: Instruction: TransferChecked', - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 6199 of 203000 compute units', - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success', - 'Program 11111111111111111111111111111111 invoke [1]', - 'Program 11111111111111111111111111111111 success', - ], - postBalances: [74063639371, 2039280, 77333564515, 2039280, 1, 193278062685, 8738370969], - postTokenBalances: [ - { - accountIndex: 1, - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - owner: '65MUMxiopKUaZbazs6pRUr9y774mj4Z1TdDgUh3L2Fhk', - programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - uiTokenAmount: { amount: '3000000', decimals: 6, uiAmount: 3, uiAmountString: '3' }, - }, - { - accountIndex: 3, - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - owner: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - uiTokenAmount: { amount: '17000000', decimals: 6, uiAmount: 17, uiAmountString: '17' }, - }, - ], - preBalances: [74063654371, 2039280, 77333554515, 2039280, 1, 193278062685, 8738370969], - preTokenBalances: [ - { - accountIndex: 1, - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - owner: '65MUMxiopKUaZbazs6pRUr9y774mj4Z1TdDgUh3L2Fhk', - programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - uiTokenAmount: { amount: '2000000', decimals: 6, uiAmount: 2, uiAmountString: '2' }, - }, - { - accountIndex: 3, - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - owner: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - uiTokenAmount: { amount: '18000000', decimals: 6, uiAmount: 18, uiAmountString: '18' }, - }, - ], - }, - slot: 438674743, - transaction: { - message: { - accountKeys: [ - { - pubkey: new PublicKey('Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5'), - signer: true, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('3MRBUAxwx7gWoGvAtzxLtzmhzwPDGAEqStKWb8cJnYQX'), - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'), - signer: false, - source: 'transaction', - writable: false, - }, - { - pubkey: new PublicKey('HYsC1ge3Yo1sSBFvcEn4otFZEJkitUNZYPsDVTQNacBT'), - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5'), - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('11111111111111111111111111111111'), - signer: false, - source: 'transaction', - writable: false, - }, - { - pubkey: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), - signer: false, - source: 'transaction', - writable: false, - }, - ], - instructions: [ - { - parsed: { - info: { - authority: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - destination: '3MRBUAxwx7gWoGvAtzxLtzmhzwPDGAEqStKWb8cJnYQX', - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - source: 'HYsC1ge3Yo1sSBFvcEn4otFZEJkitUNZYPsDVTQNacBT', - tokenAmount: { amount: '1000000', decimals: 6, uiAmount: 1, uiAmountString: '1' }, - }, - type: 'transferChecked', - }, - program: 'spl-token', - programId: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), - }, - { - parsed: { - info: { - destination: '96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5', - lamports: 10000, - source: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - }, - type: 'transfer', - }, - program: 'system', - programId: new PublicKey('11111111111111111111111111111111'), - }, - ], - recentBlockhash: '62siRk4B4LEiXWsFs6qXrkb86cZT4LTEiP6upV29Rek', - }, - signatures: ['3XZac8fbGwoyDWjzWYhakLxPqaHYmGM9zG4aNnRKshyCzod5UaQPbjQP2mWaCDADoZ43JrVA3q42xEr5Psuty4at'], - }, - version: 'legacy', -} satisfies ParsedTransactionWithMeta; diff --git a/app/features/receipt/mocks/usdc-multiple-transfers.ts b/app/features/receipt/mocks/usdc-multiple-transfers.ts deleted file mode 100644 index 15aee8778c..0000000000 --- a/app/features/receipt/mocks/usdc-multiple-transfers.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { TOKEN_PROGRAM_ID } from '@providers/accounts/tokens'; -import { ComputeBudgetProgram, type ParsedTransactionWithMeta, PublicKey } from '@solana/web3.js'; - -const FEE_PAYER = new PublicKey('BcdwLA62UPEAvRn7AWauMUXKtYMXxdLzTPaSQg5tNaFc'); -const AUTHORITY = new PublicKey('C4E3ZZ4ymQ5wY6o7JkKMeg6Yjj6CQjnaWr6ANvF9mGYY'); -const DESTINATION_TOKEN_ACCOUNT_2 = new PublicKey('7SyaSKPkVFrzAgmBCR64ydpLwcvehkCwJKom8NCF4WGM'); -const SOURCE_TOKEN_ACCOUNT = new PublicKey('AUJip4HMnYJD849oU6b8ajGoKuFGoTDfs6s3taDgsb19'); -const DESTINATION_TOKEN_ACCOUNT_1 = new PublicKey('DC1VbwstSDC7LVi4dmWjr5abd5BHucAk29pQTPKrYnbW'); -const RECEIVER_1 = new PublicKey('96WoyH3JmANSMsQLGC3MKyiGiXCymZyM9SLaWjcRrKuD'); -const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); - -const COMPUTE_BUDGET = ComputeBudgetProgram.programId; -const TOKEN_PROGRAM = TOKEN_PROGRAM_ID; - -/** - * Mock transaction data captured from mainnet signature - * 4rygbUwG9nN8hKMzMpz5yrgquZWsn2ES2gEfCK1Tzm2seSgRtssVfiKQvo4SnSELybdJWscD8ZPB6zJ4aSWJA6qc. - * - * Two USDC `transferChecked` instructions sharing the same source token account - * (AUJip4H…) and authority (C4E3ZZ4…): - * 1. 1 USDC → DC1Vbws… (owner 96WoyH3J…) - * 2. 0.000841 USDC → 7SyaSKP… (owner BcdwLA62…, also the fee payer) - * Plus two ComputeBudget instructions (price + limit), no inner instructions. - */ -export const mockUsdcMultipleTransfersTransaction = { - blockTime: 1777817015, - meta: { - computeUnitsConsumed: 12700, - costUnits: 15388, - err: null, - fee: 10001, - innerInstructions: [], - logMessages: [ - 'Program ComputeBudget111111111111111111111111111111 invoke [1]', - 'Program ComputeBudget111111111111111111111111111111 success', - 'Program ComputeBudget111111111111111111111111111111 invoke [1]', - 'Program ComputeBudget111111111111111111111111111111 success', - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]', - 'Program log: Instruction: TransferChecked', - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 6200 of 199700 compute units', - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success', - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]', - 'Program log: Instruction: TransferChecked', - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 6200 of 193500 compute units', - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success', - ], - postBalances: [46449694, 0, 2039280, 2039280, 2039280, 1, 5677904863, 497087412985], - postTokenBalances: [ - { - accountIndex: 2, - mint: USDC_MINT.toBase58(), - owner: FEE_PAYER.toBase58(), - programId: TOKEN_PROGRAM.toBase58(), - uiTokenAmount: { amount: '2400572', decimals: 6, uiAmount: 2.400572, uiAmountString: '2.400572' }, - }, - { - accountIndex: 3, - mint: USDC_MINT.toBase58(), - owner: AUTHORITY.toBase58(), - programId: TOKEN_PROGRAM.toBase58(), - uiTokenAmount: { amount: '1996478', decimals: 6, uiAmount: 1.996478, uiAmountString: '1.996478' }, - }, - { - accountIndex: 4, - mint: USDC_MINT.toBase58(), - owner: RECEIVER_1.toBase58(), - programId: TOKEN_PROGRAM.toBase58(), - uiTokenAmount: { amount: '6955300', decimals: 6, uiAmount: 6.9553, uiAmountString: '6.9553' }, - }, - ], - preBalances: [46459695, 0, 2039280, 2039280, 2039280, 1, 5677904863, 497087412985], - preTokenBalances: [ - { - accountIndex: 2, - mint: USDC_MINT.toBase58(), - owner: FEE_PAYER.toBase58(), - programId: TOKEN_PROGRAM.toBase58(), - uiTokenAmount: { amount: '2399731', decimals: 6, uiAmount: 2.399731, uiAmountString: '2.399731' }, - }, - { - accountIndex: 3, - mint: USDC_MINT.toBase58(), - owner: AUTHORITY.toBase58(), - programId: TOKEN_PROGRAM.toBase58(), - uiTokenAmount: { amount: '2997319', decimals: 6, uiAmount: 2.997319, uiAmountString: '2.997319' }, - }, - { - accountIndex: 4, - mint: USDC_MINT.toBase58(), - owner: RECEIVER_1.toBase58(), - programId: TOKEN_PROGRAM.toBase58(), - uiTokenAmount: { amount: '5955300', decimals: 6, uiAmount: 5.9553, uiAmountString: '5.9553' }, - }, - ], - }, - slot: 417327753, - transaction: { - message: { - accountKeys: [ - { pubkey: FEE_PAYER, signer: true, source: 'transaction', writable: true }, - { pubkey: AUTHORITY, signer: true, source: 'transaction', writable: false }, - { pubkey: DESTINATION_TOKEN_ACCOUNT_2, signer: false, source: 'transaction', writable: true }, - { pubkey: SOURCE_TOKEN_ACCOUNT, signer: false, source: 'transaction', writable: true }, - { pubkey: DESTINATION_TOKEN_ACCOUNT_1, signer: false, source: 'transaction', writable: true }, - { pubkey: COMPUTE_BUDGET, signer: false, source: 'transaction', writable: false }, - { pubkey: TOKEN_PROGRAM, signer: false, source: 'transaction', writable: false }, - { pubkey: USDC_MINT, signer: false, source: 'transaction', writable: false }, - ], - instructions: [ - { accounts: [], data: '3DdGGhkhJbjm', programId: COMPUTE_BUDGET }, - { accounts: [], data: 'Fj2Eoy', programId: COMPUTE_BUDGET }, - { - parsed: { - info: { - authority: AUTHORITY.toBase58(), - destination: DESTINATION_TOKEN_ACCOUNT_1.toBase58(), - mint: USDC_MINT.toBase58(), - source: SOURCE_TOKEN_ACCOUNT.toBase58(), - tokenAmount: { amount: '1000000', decimals: 6, uiAmount: 1, uiAmountString: '1' }, - }, - type: 'transferChecked', - }, - program: 'spl-token', - programId: TOKEN_PROGRAM, - }, - { - parsed: { - info: { - authority: AUTHORITY.toBase58(), - destination: DESTINATION_TOKEN_ACCOUNT_2.toBase58(), - mint: USDC_MINT.toBase58(), - source: SOURCE_TOKEN_ACCOUNT.toBase58(), - tokenAmount: { amount: '841', decimals: 6, uiAmount: 0.000841, uiAmountString: '0.000841' }, - }, - type: 'transferChecked', - }, - program: 'spl-token', - programId: TOKEN_PROGRAM, - }, - ], - recentBlockhash: 'B4jEXExD3PdCfnmpmUGt1vUrRx2qA4K7zDhAejkZyGe5', - }, - signatures: [ - '4rygbUwG9nN8hKMzMpz5yrgquZWsn2ES2gEfCK1Tzm2seSgRtssVfiKQvo4SnSELybdJWscD8ZPB6zJ4aSWJA6qc', - '3p4ocQfLHCtXQ4VzA2hJkHkeuP8sCJumvx4hobidyhuq5qV48g7CVqcHtbipjSAs2rke5fkLHruskTTJz2SuqZwd', - ], - }, - version: 'legacy', -} satisfies ParsedTransactionWithMeta; - -// Help tests assert on the same addresses the mock embeds. -export const mockUsdcMultipleTransfersAddresses = { - authority: AUTHORITY.toBase58(), - feePayer: FEE_PAYER.toBase58(), - mint: USDC_MINT.toBase58(), - receiver1: RECEIVER_1.toBase58(), - receiver2: FEE_PAYER.toBase58(), -} as const; diff --git a/app/features/receipt/mocks/usdc-multisig-transfer.ts b/app/features/receipt/mocks/usdc-multisig-transfer.ts deleted file mode 100644 index 84bac743bc..0000000000 --- a/app/features/receipt/mocks/usdc-multisig-transfer.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { type ParsedTransactionWithMeta, PublicKey } from '@solana/web3.js'; - -import { - DESTINATION_TOKEN_ACCOUNT, - MINT, - MULTISIG_AUTHORITY, - RECEIVER, - SENDER, - SOURCE_TOKEN_ACCOUNT, -} from './addresses'; - -const TOKEN_PROGRAM_ID = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'); - -export const mockUsdcMultisigTransferTransaction = { - blockTime: 1769070184, - meta: { - computeUnitsConsumed: 6349, - err: null, - fee: 5000, - innerInstructions: [], - logMessages: [ - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]', - 'Program log: Instruction: TransferChecked', - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success', - ], - postBalances: [55479304131, 2039280, 2039280, 1], - postTokenBalances: [ - { - accountIndex: 1, - mint: MINT.publicKey.toBase58(), - owner: RECEIVER.publicKey.toBase58(), - programId: TOKEN_PROGRAM_ID.toBase58(), - uiTokenAmount: { amount: '1000000', decimals: 6, uiAmount: 1, uiAmountString: '1' }, - }, - { - accountIndex: 2, - mint: MINT.publicKey.toBase58(), - owner: SENDER.publicKey.toBase58(), - programId: TOKEN_PROGRAM_ID.toBase58(), - uiTokenAmount: { amount: '19000000', decimals: 6, uiAmount: 19, uiAmountString: '19' }, - }, - ], - preBalances: [55479309131, 2039280, 2039280, 1], - preTokenBalances: [ - { - accountIndex: 1, - mint: MINT.publicKey.toBase58(), - owner: RECEIVER.publicKey.toBase58(), - programId: TOKEN_PROGRAM_ID.toBase58(), - uiTokenAmount: { amount: '0', decimals: 6, uiAmount: null, uiAmountString: '0' }, - }, - { - accountIndex: 2, - mint: MINT.publicKey.toBase58(), - owner: SENDER.publicKey.toBase58(), - programId: TOKEN_PROGRAM_ID.toBase58(), - uiTokenAmount: { amount: '20000000', decimals: 6, uiAmount: 20, uiAmountString: '20' }, - }, - ], - }, - slot: 436846205, - transaction: { - message: { - accountKeys: [ - { - pubkey: SENDER.publicKey, - signer: true, - source: 'transaction', - writable: true, - }, - { - pubkey: DESTINATION_TOKEN_ACCOUNT.publicKey, - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: SOURCE_TOKEN_ACCOUNT.publicKey, - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: TOKEN_PROGRAM_ID, - signer: false, - source: 'transaction', - writable: false, - }, - ], - instructions: [ - { - parsed: { - info: { - destination: DESTINATION_TOKEN_ACCOUNT.publicKey.toBase58(), - mint: MINT.publicKey.toBase58(), - multisigAuthority: MULTISIG_AUTHORITY.publicKey.toBase58(), - source: SOURCE_TOKEN_ACCOUNT.publicKey.toBase58(), - tokenAmount: { amount: '1000000', decimals: 6, uiAmount: 1, uiAmountString: '1' }, - }, - type: 'transferChecked', - }, - program: 'spl-token', - programId: TOKEN_PROGRAM_ID, - }, - ], - recentBlockhash: 'Eo7YPFE1694LpMwhb5RygaJJBfNzbVGz383Y2uErk9uS', - }, - signatures: ['3xyzMultisigSignature123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP'], - }, - version: 'legacy', -} satisfies ParsedTransactionWithMeta; diff --git a/app/features/receipt/mocks/usdc-regular-transfer.ts b/app/features/receipt/mocks/usdc-regular-transfer.ts deleted file mode 100644 index c41e08578e..0000000000 --- a/app/features/receipt/mocks/usdc-regular-transfer.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { type ParsedTransactionWithMeta, PublicKey } from '@solana/web3.js'; - -/** - * Mock transaction data for testing a USDC token transfer (regular transfer, not transferChecked). - * - Transfer 1 USDC (1,000,000 with 6 decimals) from HYsC1ge3Yo1sSBFvcEn4otFZEJkitUNZYPsDVTQNacBT - * - To: 3MRBUAxwx7gWoGvAtzxLtzmhzwPDGAEqStKWb8cJnYQX - * - Authority: Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5 - * - Mint: 4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU - * - * Sender: Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5 - * Receiver: 65MUMxiopKUaZbazs6pRUr9y774mj4Z1TdDgUh3L2Fhk - */ -export const mockUsdcRegularTransferTransaction = { - blockTime: 1769153097, - meta: { - computeUnitsConsumed: 4644, - costUnits: 6306, - err: null, - fee: 5000, - innerInstructions: [], - logMessages: [ - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA invoke [1]', - 'Program log: Instruction: Transfer', - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA consumed 4644 of 200000 compute units', - 'Program TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA success', - ], - postBalances: [69079294131, 2039280, 2039280, 8738370969], - postTokenBalances: [ - { - accountIndex: 1, - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - owner: '65MUMxiopKUaZbazs6pRUr9y774mj4Z1TdDgUh3L2Fhk', - programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - uiTokenAmount: { amount: '2000000', decimals: 6, uiAmount: 2, uiAmountString: '2' }, - }, - { - accountIndex: 2, - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - owner: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - uiTokenAmount: { amount: '18000000', decimals: 6, uiAmount: 18, uiAmountString: '18' }, - }, - ], - preBalances: [69079299131, 2039280, 2039280, 8738370969], - preTokenBalances: [ - { - accountIndex: 1, - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - owner: '65MUMxiopKUaZbazs6pRUr9y774mj4Z1TdDgUh3L2Fhk', - programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - uiTokenAmount: { amount: '1000000', decimals: 6, uiAmount: 1, uiAmountString: '1' }, - }, - { - accountIndex: 2, - mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', - owner: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - programId: 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', - uiTokenAmount: { amount: '19000000', decimals: 6, uiAmount: 19, uiAmountString: '19' }, - }, - ], - }, - slot: 437061029, - transaction: { - message: { - accountKeys: [ - { - pubkey: new PublicKey('Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5'), - signer: true, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('HYsC1ge3Yo1sSBFvcEn4otFZEJkitUNZYPsDVTQNacBT'), - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('3MRBUAxwx7gWoGvAtzxLtzmhzwPDGAEqStKWb8cJnYQX'), - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), - signer: false, - source: 'transaction', - writable: false, - }, - ], - instructions: [ - { - parsed: { - info: { - amount: '1000000', - authority: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - destination: '3MRBUAxwx7gWoGvAtzxLtzmhzwPDGAEqStKWb8cJnYQX', - source: 'HYsC1ge3Yo1sSBFvcEn4otFZEJkitUNZYPsDVTQNacBT', - }, - type: 'transfer', - }, - program: 'spl-token', - programId: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'), - }, - ], - recentBlockhash: '743Rt1RW3WXopRLzgGBABuUj7p3rEf23fZsBYusicmZJ', - }, - signatures: ['5CBBFXjdu32noWfSdzAdiEBad73ZmMChN17CEFeTLiQQJZBMzL4J9dj7YLcaag8z6xKiBws7GVPeQ7KmUGiozC4Z'], - }, - version: 'legacy', -} satisfies ParsedTransactionWithMeta; diff --git a/app/features/receipt/mocks/zero-transfer.ts b/app/features/receipt/mocks/zero-transfer.ts deleted file mode 100644 index 976018bbf9..0000000000 --- a/app/features/receipt/mocks/zero-transfer.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { type ParsedTransactionWithMeta, PublicKey } from '@solana/web3.js'; - -/** - * Mock transaction data for testing a zero SOL transfer. - * - Transfer 0 SOL (0 lamports) from Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5 - * - To: G2GjouKPJnGi3aGVsHnBu475EGvseiL1QnVHBMkN6wid - * - Fee payer: 644RudhReGpiHsNysSVSpDDagrzw5mBCwdHq1ZNwK6zL (pays 10,000 lamports fee) - * - This represents a transaction with a transfer instruction but zero lamports - * - * This transaction has 2 signers: the fee payer and the sender. - */ -export const mockZeroTransferTransaction = { - blockTime: 1769142127, - meta: { - computeUnitsConsumed: 150, - costUnits: 2501, - err: null, - fee: 10000, - innerInstructions: [], - logMessages: [ - 'Program 11111111111111111111111111111111 invoke [1]', - 'Program 11111111111111111111111111111111 success', - ], - postBalances: [449960000, 69079299131, 1090000000, 1], - postTokenBalances: [], - preBalances: [449970000, 69079299131, 1090000000, 1], - preTokenBalances: [], - }, - slot: 437032620, - transaction: { - message: { - accountKeys: [ - { - pubkey: new PublicKey('644RudhReGpiHsNysSVSpDDagrzw5mBCwdHq1ZNwK6zL'), - signer: true, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5'), - signer: true, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('G2GjouKPJnGi3aGVsHnBu475EGvseiL1QnVHBMkN6wid'), - signer: false, - source: 'transaction', - writable: true, - }, - { - pubkey: new PublicKey('11111111111111111111111111111111'), - signer: false, - source: 'transaction', - writable: false, - }, - ], - instructions: [ - { - parsed: { - info: { - destination: 'G2GjouKPJnGi3aGVsHnBu475EGvseiL1QnVHBMkN6wid', - lamports: 0, - source: 'Hd3f3TdvcEqEEkCE5pV8qZxtw4CRZ82SU8ggYVR3bD5', - }, - type: 'transfer', - }, - program: 'system', - programId: new PublicKey('11111111111111111111111111111111'), - }, - ], - recentBlockhash: '4115TKZYjN5LSvcyQneUfocYYq6oPzzNRNbFQaP1HugH', - }, - signatures: [ - '22xruGxWMALDoVksikb6kyv7wigrqQSEtmM8pbazAjmM3uSnvugvXhcmGhFhWd9uuUJDsegfddznFPC9f5Qpx8cq', - '3EccbwavfrdLFxK6j9bhFxWSLE4HnzM1u4VwuYdTrMrKSmyoZzvx8kYjuyPBVANdBoDqew9o8dxzp1J2p3CMb22w', - ], - }, - version: 'legacy', -} satisfies ParsedTransactionWithMeta; diff --git a/app/features/receipt/model/__tests__/composite-signature.spec.ts b/app/features/receipt/model/__tests__/composite-signature.spec.ts index cbd035d0e8..f8765e727c 100644 --- a/app/features/receipt/model/__tests__/composite-signature.spec.ts +++ b/app/features/receipt/model/__tests__/composite-signature.spec.ts @@ -1,11 +1,10 @@ +import { DEFAULT_SIGNATURE as SIG } from '@__fixtures__/gen'; import { describe, expect, it } from 'vitest'; import { Cluster } from '@/app/utils/cluster'; import { buildCompositeSignature, parseCompositeSignature } from '../composite-signature'; -const SIG = '5yKzCuw1e9d58HcnzSL31cczfXUux2H4Ga5TAR2RcQLE5W8BiTAC9x9MvhLtc4h99sC9XxLEAjhrXyfKezdMkZFV'; - describe('parseCompositeSignature', () => { it.each([ { expected: { signature: SIG }, input: SIG, name: 'signature only' }, diff --git a/app/features/receipt/model/__tests__/create-receipt.spec.ts b/app/features/receipt/model/__tests__/create-receipt.spec.ts index 8f4ddb2fee..d79ba8b69d 100644 --- a/app/features/receipt/model/__tests__/create-receipt.spec.ts +++ b/app/features/receipt/model/__tests__/create-receipt.spec.ts @@ -1,35 +1,8 @@ -import { gen } from '@__fixtures__/gen'; +import { DEFAULT_SIGNATURE as mockSignature, gen } from '@__fixtures__/gen'; import { truncateAddress } from '@entities/address'; import { type TokenInfo, TokenInfoHttpError, TokenInfoInvalidResponseError } from '@entities/token-info'; import { tokenInfo } from '@entities/token-info/__fixtures__/token-info'; import { getTokenInfo } from '@entities/token-info/server'; -import { Keypair, PublicKey, SystemProgram } from '@solana/web3.js'; -import { ASSOCIATED_TOKEN_PROGRAM_ADDRESS, TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; - -import { Logger } from '@/app/shared/lib/logger'; -import { Cluster } from '@/app/utils/cluster'; - -import { getTx } from '../../api/get-tx'; -import { MULTISIG_AUTHORITY, RECEIVER, RECEIVER_2, SENDER } from '../../mocks/addresses'; -import { mockCustomFeePayerTransaction } from '../../mocks/custom-fee-payer'; -import { mockJitoOnlyTransferTransaction } from '../../mocks/jito-only-transfer'; -import { mockMixedMintTransfersTransaction } from '../../mocks/mixed-mint-transfers'; -import { mockMultipleTransfersTransaction } from '../../mocks/multiple-transfers'; -import { mockNoTransferTransaction } from '../../mocks/no-transfers'; -import { mockSingleTransferTransaction } from '../../mocks/single-transfer'; -import { mockToken2022TransferTransaction } from '../../mocks/token-2022-transfer'; -import { mockToken2022Transfer2Transaction } from '../../mocks/token-2022-transfer2'; -import { mockUsdcTransferTransaction } from '../../mocks/usdc-checked-transfer'; -import { mockUsdcFpPrecisionTransfersTransaction } from '../../mocks/usdc-fp-precision-transfers'; -import { mockUsdcJitoTransferTransaction } from '../../mocks/usdc-jito-transfer'; -import { - mockUsdcMultipleTransfersAddresses, - mockUsdcMultipleTransfersTransaction, -} from '../../mocks/usdc-multiple-transfers'; -import { mockUsdcMultisigTransferTransaction } from '../../mocks/usdc-multisig-transfer'; -import { mockUsdcRegularTransferTransaction } from '../../mocks/usdc-regular-transfer'; -import { mockZeroTransferTransaction } from '../../mocks/zero-transfer'; import { buildInnerGroup, buildParsedTransaction, @@ -37,7 +10,37 @@ import { buildSolTransferIx, buildSolTransferWithSeedIx, buildTokenTransferCheckedIx, -} from '../__fixtures__/builders'; +} from '@entities/transaction-data/__fixtures__/parsed-transactions'; +import { + mockCustomFeePayerTransaction, + mockJitoOnlyTransferTransaction, + mockMixedMintTransfersTransaction, + mockMultipleTransfersTransaction, + mockNoTransferTransaction, + mockSingleTransferTransaction, + mockToken2022Transfer2Transaction, + mockToken2022TransferTransaction, + mockUsdcFpPrecisionTransfersTransaction, + mockUsdcJitoTransferTransaction, + mockUsdcMultipleTransfersAddresses, + mockUsdcMultipleTransfersTransaction, + mockUsdcMultisigTransferTransaction, + mockUsdcRegularTransferTransaction, + mockUsdcTransferTransaction, + mockZeroTransferTransaction, + MULTISIG_AUTHORITY, + RECEIVER, + RECEIVER_2, + SENDER, +} from '@features/receipt/__fixtures__/transactions'; +import { PublicKey, SystemProgram } from '@solana/web3.js'; +import { ASSOCIATED_TOKEN_PROGRAM_ADDRESS, TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { Logger } from '@/app/shared/lib/logger'; +import { Cluster } from '@/app/utils/cluster'; + +import { getTx } from '../../api/get-tx'; import { createReceipt } from '../create-receipt'; import { type ReceiptResult } from '../receipt-data'; @@ -54,8 +57,6 @@ function unwrap(result: ReceiptResult) { } describe('createReceipt', () => { - const mockSignature = '5yKzCuw1e9d58HcnzSL31cczfXUux2H4Ga5TAR2RcQLE5W8BiTAC9x9MvhLtc4h99sC9XxLEAjhrXyfKezdMkZFV'; - beforeEach(() => { vi.spyOn(console, 'error').mockImplementation(() => {}); }); @@ -81,10 +82,10 @@ describe('createReceipt', () => { }, network: 'Mainnet', receiver: { - truncated: truncateAddress(RECEIVER.publicKey.toBase58(), 5), + truncated: truncateAddress(RECEIVER.toBase58(), 5), }, sender: { - truncated: truncateAddress(SENDER.publicKey.toBase58(), 5), + truncated: truncateAddress(SENDER.toBase58(), 5), }, total: { formatted: '0.3', @@ -111,18 +112,18 @@ describe('createReceipt', () => { transfers: [ { amount: { formatted: '0.08', raw: 80000000, unit: 'SOL' }, - receiver: { address: RECEIVER.publicKey.toBase58() }, - sender: { address: SENDER.publicKey.toBase58() }, + receiver: { address: RECEIVER.toBase58() }, + sender: { address: SENDER.toBase58() }, }, { amount: { formatted: '0.05', raw: 50000000, unit: 'SOL' }, - receiver: { address: RECEIVER_2.publicKey.toBase58() }, - sender: { address: SENDER.publicKey.toBase58() }, + receiver: { address: RECEIVER_2.toBase58() }, + sender: { address: SENDER.toBase58() }, }, { amount: { formatted: '0.01', raw: 10000000, unit: 'SOL' }, - receiver: { address: RECEIVER.publicKey.toBase58() }, - sender: { address: SENDER.publicKey.toBase58() }, + receiver: { address: RECEIVER.toBase58() }, + sender: { address: SENDER.toBase58() }, }, ], }); @@ -197,13 +198,13 @@ describe('createReceipt', () => { }); it('should create a SOL receipt from a transferWithSeed instruction with the derived source as sender', async () => { - const base = PublicKey.unique(); - const derived = PublicKey.unique(); + const base = gen.publicKey(20); + const derived = gen.publicKey(21); const tx = buildParsedTransaction({ - accountKeys: [base, derived, RECEIVER.publicKey, SystemProgram.programId], + accountKeys: [base, derived, RECEIVER, SystemProgram.programId], instructions: [ buildSolTransferWithSeedIx({ - destination: RECEIVER.publicKey, + destination: RECEIVER, lamports: 50000000, source: derived, sourceBase: base, @@ -218,32 +219,25 @@ describe('createReceipt', () => { expect(receipt).toMatchObject({ kind: 'sol', - receiver: { address: RECEIVER.publicKey.toBase58() }, + receiver: { address: RECEIVER.toBase58() }, sender: { address: derived.toBase58() }, total: { formatted: '0.05', raw: 50000000, unit: 'SOL' }, }); }); it('should aggregate transfer and transferWithSeed instructions into transfers[]', async () => { - const base = PublicKey.unique(); - const derived = PublicKey.unique(); + const base = gen.publicKey(20); + const derived = gen.publicKey(21); const tx = buildParsedTransaction({ - accountKeys: [ - SENDER.publicKey, - base, - derived, - RECEIVER.publicKey, - RECEIVER_2.publicKey, - SystemProgram.programId, - ], + accountKeys: [SENDER, base, derived, RECEIVER, RECEIVER_2, SystemProgram.programId], instructions: [ buildSolTransferIx({ - destination: RECEIVER.publicKey, + destination: RECEIVER, lamports: 80000000, - source: SENDER.publicKey, + source: SENDER, }), buildSolTransferWithSeedIx({ - destination: RECEIVER_2.publicKey, + destination: RECEIVER_2, lamports: 50000000, source: derived, sourceBase: base, @@ -261,12 +255,12 @@ describe('createReceipt', () => { expect(receipt.transfers).toHaveLength(2); expect(receipt.transfers?.[0]).toMatchObject({ amount: { raw: 80000000, unit: 'SOL' }, - receiver: { address: RECEIVER.publicKey.toBase58() }, - sender: { address: SENDER.publicKey.toBase58() }, + receiver: { address: RECEIVER.toBase58() }, + sender: { address: SENDER.toBase58() }, }); expect(receipt.transfers?.[1]).toMatchObject({ amount: { raw: 50000000, unit: 'SOL' }, - receiver: { address: RECEIVER_2.publicKey.toBase58() }, + receiver: { address: RECEIVER_2.toBase58() }, sender: { address: derived.toBase58() }, }); }); @@ -439,8 +433,8 @@ describe('createReceipt', () => { const receipt = unwrap(await createReceipt(mockSignature)); - expect(receipt.sender.address).toBe(MULTISIG_AUTHORITY.publicKey.toBase58()); - expect(receipt.receiver.address).toBe(RECEIVER.publicKey.toBase58()); + expect(receipt.sender.address).toBe(MULTISIG_AUTHORITY.toBase58()); + expect(receipt.receiver.address).toBe(RECEIVER.toBase58()); }); it('should create a multi-transfer token receipt summing totals and exposing per-instruction transfers', async () => { @@ -528,31 +522,25 @@ describe('createReceipt', () => { describe('inner-instruction transfers', () => { it('should build a multi-transfer SOL receipt from inner SystemProgram transfers', async () => { - const wrapperProgram = Keypair.generate().publicKey; + const wrapperProgram = gen.publicKey(20); const tx = buildParsedTransaction({ - accountKeys: [ - SENDER.publicKey, - RECEIVER.publicKey, - RECEIVER_2.publicKey, - SystemProgram.programId, - wrapperProgram, - ], + accountKeys: [SENDER, RECEIVER, RECEIVER_2, SystemProgram.programId, wrapperProgram], innerInstructions: [ buildInnerGroup(0, [ buildSolTransferIx({ - destination: RECEIVER.publicKey, + destination: RECEIVER, lamports: 80000000, - source: SENDER.publicKey, + source: SENDER, }), buildSolTransferIx({ - destination: RECEIVER_2.publicKey, + destination: RECEIVER_2, lamports: 50000000, - source: SENDER.publicKey, + source: SENDER, }), buildSolTransferIx({ - destination: RECEIVER.publicKey, + destination: RECEIVER, lamports: 10000000, - source: SENDER.publicKey, + source: SENDER, }), ]), ], @@ -567,21 +555,21 @@ describe('createReceipt', () => { expect(receipt.transfers).toHaveLength(3); expect(receipt.transfers?.[0]).toMatchObject({ amount: { formatted: '0.08', raw: 80000000, unit: 'SOL' }, - receiver: { address: RECEIVER.publicKey.toBase58() }, - sender: { address: SENDER.publicKey.toBase58() }, + receiver: { address: RECEIVER.toBase58() }, + sender: { address: SENDER.toBase58() }, }); }); it('should build a multi-transfer token receipt from inner transferChecked CPIs', async () => { - const wrapperProgram = Keypair.generate().publicKey; - const feePayer = Keypair.generate().publicKey; - const authority = Keypair.generate().publicKey; - const sourceTokenAccount = Keypair.generate().publicKey; - const destinationTokenAccount1 = Keypair.generate().publicKey; - const destinationTokenAccount2 = Keypair.generate().publicKey; - const receiverOwner1 = Keypair.generate().publicKey; - const receiverOwner2 = Keypair.generate().publicKey; - const mint = Keypair.generate().publicKey; + const wrapperProgram = gen.publicKey(20); + const feePayer = gen.publicKey(21); + const authority = gen.publicKey(22); + const sourceTokenAccount = gen.publicKey(23); + const destinationTokenAccount1 = gen.publicKey(24); + const destinationTokenAccount2 = gen.publicKey(25); + const receiverOwner1 = gen.publicKey(26); + const receiverOwner2 = gen.publicKey(27); + const mint = gen.publicKey(28); const tokenProgram = new PublicKey(TOKEN_PROGRAM_ADDRESS); const accountKeys = [ @@ -657,11 +645,11 @@ describe('createReceipt', () => { // SOL-only counterpart to the USDC + ATA case below: top-level System.transfer to the // recipient + top-level ATA createIdempotent whose inner System.transfer tops up rent. // Only the intentional payment should surface; the rent CPI must be filtered. - const feePayer = Keypair.generate().publicKey; - const recipient = Keypair.generate().publicKey; - const ataAddress = Keypair.generate().publicKey; - const owner = Keypair.generate().publicKey; - const mint = Keypair.generate().publicKey; + const feePayer = gen.publicKey(20); + const recipient = gen.publicKey(21); + const ataAddress = gen.publicKey(22); + const owner = gen.publicKey(23); + const mint = gen.publicKey(24); const ataProgram = new PublicKey(ASSOCIATED_TOKEN_PROGRAM_ADDRESS); const tx = buildParsedTransaction({ @@ -699,12 +687,12 @@ describe('createReceipt', () => { // Realistic combo: send USDC to a fresh ATA. The ATA program's createIdempotent // emits an inner SystemProgram transfer (rent funding) which must NOT be surfaced // — the user-intended payment is the top-level transferChecked. - const feePayer = Keypair.generate().publicKey; - const authority = Keypair.generate().publicKey; - const sourceTokenAccount = Keypair.generate().publicKey; - const destinationTokenAccount = Keypair.generate().publicKey; - const receiverOwner = Keypair.generate().publicKey; - const mint = Keypair.generate().publicKey; + const feePayer = gen.publicKey(20); + const authority = gen.publicKey(21); + const sourceTokenAccount = gen.publicKey(22); + const destinationTokenAccount = gen.publicKey(23); + const receiverOwner = gen.publicKey(24); + const mint = gen.publicKey(25); const tokenProgram = new PublicKey(TOKEN_PROGRAM_ADDRESS); const ataProgram = new PublicKey(ASSOCIATED_TOKEN_PROGRAM_ADDRESS); diff --git a/app/features/receipt/model/__tests__/jito.spec.ts b/app/features/receipt/model/__tests__/jito.spec.ts index f1cc449181..9f231303dd 100644 --- a/app/features/receipt/model/__tests__/jito.spec.ts +++ b/app/features/receipt/model/__tests__/jito.spec.ts @@ -1,8 +1,10 @@ -import { PublicKey, SystemProgram } from '@solana/web3.js'; +import { + mockSingleTransferTransaction, + mockUsdcJitoTransferTransaction, +} from '@features/receipt/__fixtures__/transactions'; +import { type ParsedInstruction, PublicKey, SystemProgram } from '@solana/web3.js'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { mockSingleTransferTransaction } from '../../mocks/single-transfer'; -import { mockUsdcJitoTransferTransaction } from '../../mocks/usdc-jito-transfer'; import { isJitoTransfer } from '../jito'; const JITO_TIP_ACCOUNT_IN_MOCK = '96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5'; @@ -75,7 +77,7 @@ describe('isJitoTransfer', () => { const customAccount = 'CustomJitoTipAccount1111111111111111111111111'; vi.stubEnv('NEXT_PUBLIC_RECEIPT_JITO_ACCOUNTS', customAccount); const instructions = mockUsdcJitoTransferTransaction.transaction.message.instructions; - const jitoTipInstruction = instructions[1]; + const jitoTipInstruction = instructions[1] as ParsedInstruction; expect(isJitoTransfer(jitoTipInstruction)).toBe(false); const customInstruction = { ...jitoTipInstruction, diff --git a/app/features/receipt/model/__tests__/memo.spec.ts b/app/features/receipt/model/__tests__/memo.spec.ts index 2c65ec5a0b..41d3a646ab 100644 --- a/app/features/receipt/model/__tests__/memo.spec.ts +++ b/app/features/receipt/model/__tests__/memo.spec.ts @@ -1,7 +1,6 @@ +import { mockNoTransferTransaction, mockSingleTransferTransaction } from '@features/receipt/__fixtures__/transactions'; import { describe, expect, it } from 'vitest'; -import { mockNoTransferTransaction } from '../../mocks/no-transfers'; -import { mockSingleTransferTransaction } from '../../mocks/single-transfer'; import { extractMemoFromTransaction } from '../memo'; describe('extractMemoFromTransaction', () => { diff --git a/app/features/receipt/model/__tests__/sol-transfer.spec.ts b/app/features/receipt/model/__tests__/sol-transfer.spec.ts index 507875a790..3ea0f36828 100644 --- a/app/features/receipt/model/__tests__/sol-transfer.spec.ts +++ b/app/features/receipt/model/__tests__/sol-transfer.spec.ts @@ -1,11 +1,15 @@ +import { + mockJitoOnlyTransferTransaction, + mockMultipleTransfersTransaction, + mockNoTransferTransaction, + mockSingleTransferTransaction, + mockZeroTransferTransaction, + RECEIVER, + RECEIVER_2, + SENDER, +} from '@features/receipt/__fixtures__/transactions'; import { describe, expect, it } from 'vitest'; -import { RECEIVER, RECEIVER_2, SENDER } from '../../mocks/addresses'; -import { mockJitoOnlyTransferTransaction } from '../../mocks/jito-only-transfer'; -import { mockMultipleTransfersTransaction } from '../../mocks/multiple-transfers'; -import { mockNoTransferTransaction } from '../../mocks/no-transfers'; -import { mockSingleTransferTransaction } from '../../mocks/single-transfer'; -import { mockZeroTransferTransaction } from '../../mocks/zero-transfer'; import { createSolTransferReceipt } from '../sol-transfer'; describe('createSolTransferReceipt', () => { @@ -15,8 +19,8 @@ describe('createSolTransferReceipt', () => { expect(result).toMatchObject({ fee: 5000, - receiver: RECEIVER.publicKey.toBase58(), - sender: SENDER.publicKey.toBase58(), + receiver: RECEIVER.toBase58(), + sender: SENDER.toBase58(), total: 300000000, type: 'sol', }); @@ -54,18 +58,18 @@ describe('createSolTransferReceipt', () => { expect(result?.transfers).toEqual([ { - receiver: RECEIVER.publicKey.toBase58(), - sender: SENDER.publicKey.toBase58(), + receiver: RECEIVER.toBase58(), + sender: SENDER.toBase58(), total: 80000000, }, { - receiver: RECEIVER_2.publicKey.toBase58(), - sender: SENDER.publicKey.toBase58(), + receiver: RECEIVER_2.toBase58(), + sender: SENDER.toBase58(), total: 50000000, }, { - receiver: RECEIVER.publicKey.toBase58(), - sender: SENDER.publicKey.toBase58(), + receiver: RECEIVER.toBase58(), + sender: SENDER.toBase58(), total: 10000000, }, ]); @@ -74,8 +78,8 @@ describe('createSolTransferReceipt', () => { it('should use the first instruction sender and receiver on the receipt root', () => { const result = createSolTransferReceipt(mockMultipleTransfersTransaction); - expect(result?.sender).toBe(SENDER.publicKey.toBase58()); - expect(result?.receiver).toBe(RECEIVER.publicKey.toBase58()); + expect(result?.sender).toBe(SENDER.toBase58()); + expect(result?.receiver).toBe(RECEIVER.toBase58()); }); }); diff --git a/app/features/receipt/model/__tests__/use-receipt-result.spec.tsx b/app/features/receipt/model/__tests__/use-receipt-result.spec.tsx index 1e92f6cb4b..b27cd13883 100644 --- a/app/features/receipt/model/__tests__/use-receipt-result.spec.tsx +++ b/app/features/receipt/model/__tests__/use-receipt-result.spec.tsx @@ -2,6 +2,10 @@ import { gen } from '@__fixtures__/gen'; import { GENESIS_HASHES } from '@entities/chain-id/lib/const'; import { tokenInfo } from '@entities/token-info/__fixtures__/token-info'; import type { TransactionWithMeta } from '@entities/transaction-data'; +import { + buildParsedTransaction, + buildTokenTransferCheckedIx, +} from '@entities/transaction-data/__fixtures__/parsed-transactions'; import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; import { renderHook } from '@testing-library/react'; import { Cluster, ClusterStatus } from '@utils/cluster'; @@ -9,7 +13,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { type ClusterContext, clusterContext, swrWrapper, waitForHook } from '@/app/__tests__/swr-hook'; -import { buildParsedTransaction, buildTokenTransferCheckedIx } from '../__fixtures__/builders'; import { useReceiptResult } from '../use-receipt-result'; const mocks = vi.hoisted(() => ({ diff --git a/app/features/receipt/receipt-page.tsx b/app/features/receipt/receipt-page.tsx index 6b31b2c47a..f8e8cfe21b 100644 --- a/app/features/receipt/receipt-page.tsx +++ b/app/features/receipt/receipt-page.tsx @@ -112,7 +112,7 @@ export function Receipt({ signature, autoRefresh }: ReceiptProps & WithAutoRefre return ; } -function messageForReason(reason: ReceiptUnavailabilityReason | undefined): string | undefined { +export function messageForReason(reason: ReceiptUnavailabilityReason | undefined): string | undefined { switch (reason) { case 'mixed-mint': return 'Receipts are only available when all token transfers in a transaction use the same mint. This transaction transfers multiple different tokens.'; diff --git a/app/features/receipt/ui/__stories__/BaseReceipt.responsive.stories.tsx b/app/features/receipt/ui/__stories__/BaseReceipt.responsive.stories.tsx index e47427f069..81b9ea4d7f 100644 --- a/app/features/receipt/ui/__stories__/BaseReceipt.responsive.stories.tsx +++ b/app/features/receipt/ui/__stories__/BaseReceipt.responsive.stories.tsx @@ -1,15 +1,12 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { defaultReceipt, forBaseReceipt } from '@features/receipt/__fixtures__/receipts'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BaseReceipt } from '../BaseReceipt'; -import { defaultReceipt, forBaseReceipt } from './receipt-fixtures'; const meta: Meta = { component: BaseReceipt, decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Features/Receipt/BaseReceipt@Media', }; diff --git a/app/features/receipt/ui/__stories__/BaseReceipt.stories.tsx b/app/features/receipt/ui/__stories__/BaseReceipt.stories.tsx index 7fb279e6d5..7a221a5b5b 100644 --- a/app/features/receipt/ui/__stories__/BaseReceipt.stories.tsx +++ b/app/features/receipt/ui/__stories__/BaseReceipt.stories.tsx @@ -1,8 +1,3 @@ -import type { Meta, StoryObj } from '@storybook-config/types'; -import { expect, within } from 'storybook/test'; - -import type { TransferRow } from '../../types'; -import { BaseReceipt, NoReceipt as NoReceiptComponent } from '../BaseReceipt'; import { defaultReceipt, forBaseReceipt, @@ -13,7 +8,12 @@ import { receiptTokenTransfer, receiptWithDomains, receiptWithMemo, -} from './receipt-fixtures'; +} from '@features/receipt/__fixtures__/receipts'; +import type { Meta, StoryObj } from '@storybook-config/types'; +import { expect, within } from 'storybook/test'; + +import type { TransferRow } from '../../types'; +import { BaseReceipt, NoReceipt as NoReceiptComponent } from '../BaseReceipt'; const meta: Meta = { argTypes: { diff --git a/app/features/receipt/ui/__stories__/BaseReceiptImage.stories.tsx b/app/features/receipt/ui/__stories__/BaseReceiptImage.stories.tsx index 1d68141ae4..3a2d6eb0de 100644 --- a/app/features/receipt/ui/__stories__/BaseReceiptImage.stories.tsx +++ b/app/features/receipt/ui/__stories__/BaseReceiptImage.stories.tsx @@ -1,8 +1,3 @@ -import { IMAGE_SIZE } from '@shared/lib/og/image-size'; -import type { Meta, StoryObj } from '@storybook-config/types'; -import { expect, within } from 'storybook/test'; - -import { BaseReceiptImage } from '../BaseReceiptImage'; import { defaultReceipt, receiptLargeAmountWithMemo, @@ -13,7 +8,12 @@ import { receiptMultiTransfer9, receiptTokenTransferSimple, receiptWithMemo, -} from './receipt-fixtures'; +} from '@features/receipt/__fixtures__/receipts'; +import { withOgImageFrame } from '@storybook-config/decorators'; +import type { Meta, StoryObj } from '@storybook-config/types'; +import { expect, within } from 'storybook/test'; + +import { BaseReceiptImage } from '../BaseReceiptImage'; const meta: Meta = { argTypes: { @@ -27,13 +27,7 @@ const meta: Meta = { }, }, component: BaseReceiptImage, - decorators: [ - Story => ( -
- -
- ), - ], + decorators: [withOgImageFrame], tags: ['autodocs', 'test'], title: 'Features/Receipt/BaseReceiptImage', }; diff --git a/app/features/receipt/ui/__stories__/ReceiptView.responsive.stories.tsx b/app/features/receipt/ui/__stories__/ReceiptView.responsive.stories.tsx index 15e1dad5ea..4ccf6a806e 100644 --- a/app/features/receipt/ui/__stories__/ReceiptView.responsive.stories.tsx +++ b/app/features/receipt/ui/__stories__/ReceiptView.responsive.stories.tsx @@ -1,22 +1,13 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import { fn } from 'storybook/test'; import { ReceiptView } from '../ReceiptView'; -import { defaultReceipt, forBaseReceipt } from './receipt-fixtures'; +import * as Base from './ReceiptView.stories'; const meta: Meta = { - args: { - downloadCsv: fn().mockResolvedValue(undefined), - downloadPdf: fn().mockResolvedValue(undefined), - signature: 'ExampleTransactionSignature', - transactionPath: 'https://example.com/tx/ExampleTransactionSignature', - }, + args: Base.default.args, component: ReceiptView, decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Features/Receipt/ReceiptView@Media', }; @@ -24,7 +15,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { data: forBaseReceipt(defaultReceipt) }; +const args = Base.Default.args; export const Mobile: Story = { args, diff --git a/app/features/receipt/ui/__stories__/ReceiptView.stories.tsx b/app/features/receipt/ui/__stories__/ReceiptView.stories.tsx index 2007d7dea5..b2b0b0f9e1 100644 --- a/app/features/receipt/ui/__stories__/ReceiptView.stories.tsx +++ b/app/features/receipt/ui/__stories__/ReceiptView.stories.tsx @@ -1,7 +1,3 @@ -import type { Meta, StoryObj } from '@storybook-config/types'; -import { expect, fn, userEvent, within } from 'storybook/test'; - -import { ReceiptView } from '../ReceiptView'; import { defaultReceipt, forBaseReceipt, @@ -11,7 +7,11 @@ import { receiptTokenTransfer, receiptWithDomains, receiptWithMemo, -} from './receipt-fixtures'; +} from '@features/receipt/__fixtures__/receipts'; +import type { Meta, StoryObj } from '@storybook-config/types'; +import { expect, fn, userEvent, within } from 'storybook/test'; + +import { ReceiptView } from '../ReceiptView'; const meta: Meta = { args: { diff --git a/app/features/security-txt/ui/__stories__/BaseSecurityNotification.stories.tsx b/app/features/security-txt/ui/__stories__/BaseSecurityNotification.stories.tsx index 5c0b647e4a..9a8849e51f 100644 --- a/app/features/security-txt/ui/__stories__/BaseSecurityNotification.stories.tsx +++ b/app/features/security-txt/ui/__stories__/BaseSecurityNotification.stories.tsx @@ -13,9 +13,6 @@ const meta = { story: 'Notification component displaying security.txt messages', }, }, - nextjs: { - appDirectory: true, - }, }, tags: ['autodocs', 'test'], title: 'Features/SecurityTxt/BaseSecurityNotification', diff --git a/app/features/security-txt/ui/__stories__/EmptySecurityTxtCard.responsive.stories.tsx b/app/features/security-txt/ui/__stories__/EmptySecurityTxtCard.responsive.stories.tsx index 444b666f7c..c370cf0d69 100644 --- a/app/features/security-txt/ui/__stories__/EmptySecurityTxtCard.responsive.stories.tsx +++ b/app/features/security-txt/ui/__stories__/EmptySecurityTxtCard.responsive.stories.tsx @@ -1,5 +1,5 @@ import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { EmptySecurityTxtCard } from '../EmptySecurityTxtCard'; @@ -8,9 +8,6 @@ import { EmptySecurityTxtCard } from '../EmptySecurityTxtCard'; const meta: Meta = { component: EmptySecurityTxtCard, decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Features/SecurityTxt/EmptySecurityTxtCard@Media', }; diff --git a/app/features/security-txt/ui/__stories__/PmpSecurityTxtTable.responsive.stories.tsx b/app/features/security-txt/ui/__stories__/PmpSecurityTxtTable.responsive.stories.tsx index c925054290..5cf267de21 100644 --- a/app/features/security-txt/ui/__stories__/PmpSecurityTxtTable.responsive.stories.tsx +++ b/app/features/security-txt/ui/__stories__/PmpSecurityTxtTable.responsive.stories.tsx @@ -1,18 +1,14 @@ import type { Meta, StoryObj } from '@storybook-config/types'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '../../../../../.storybook/responsive-decorators'; +import { withViewportFromGlobal } from '../../../../../.storybook/responsive-decorators'; import { PmpSecurityTxtTable } from '../PmpSecurityTxtTable'; -import defaultSecurityTxtMock from './mocks/defaultSecurityTxt.json'; +import * as Base from './PmpSecurityTxtTable.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta = { component: PmpSecurityTxtTable, decorators: [withViewportFromGlobal], - parameters: { - backgrounds: { default: 'Card' }, - nextjs: { appDirectory: true }, - viewport: { options: INITIAL_VIEWPORTS }, - }, + parameters: Base.default.parameters, tags: ['autodocs', 'test'], title: 'Components/Account/security/PmpSecurityTxtTable@Media', } satisfies Meta; @@ -20,7 +16,7 @@ const meta = { export default meta; type Story = StoryObj; -const args = { data: defaultSecurityTxtMock as any }; +const args = Base.Primary.args; export const Mobile: Story = { args, diff --git a/app/features/security-txt/ui/__stories__/PmpSecurityTxtTable.stories.tsx b/app/features/security-txt/ui/__stories__/PmpSecurityTxtTable.stories.tsx index 13091b2910..e863defa64 100644 --- a/app/features/security-txt/ui/__stories__/PmpSecurityTxtTable.stories.tsx +++ b/app/features/security-txt/ui/__stories__/PmpSecurityTxtTable.stories.tsx @@ -5,13 +5,6 @@ import defaultSecurityTxtMock from './mocks/defaultSecurityTxt.json'; const meta = { component: PmpSecurityTxtTable, - decorators: [ - Story => ( -
- -
- ), - ], parameters: { backgrounds: { default: 'Card', @@ -21,9 +14,6 @@ const meta = { story: 'Render security.txt from Program Metadata', }, }, - nextjs: { - appDirectory: true, - }, }, tags: ['autodocs', 'test'], title: 'Components/Account/security/PmpSecurityTxtTable', diff --git a/app/features/security-txt/ui/__stories__/ProgramSecurityTxtCard.stories.tsx b/app/features/security-txt/ui/__stories__/ProgramSecurityTxtCard.stories.tsx index 532e4ae7ca..7f402c9761 100644 --- a/app/features/security-txt/ui/__stories__/ProgramSecurityTxtCard.stories.tsx +++ b/app/features/security-txt/ui/__stories__/ProgramSecurityTxtCard.stories.tsx @@ -6,13 +6,6 @@ import defaultSecurityTxtMock from './mocks/defaultSecurityTxt.json'; const meta = { component: ProgramSecurityTxtCard, - decorators: [ - Story => ( -
- -
- ), - ], parameters: { backgrounds: { default: 'Card', @@ -22,9 +15,6 @@ const meta = { story: 'Render security.txt Card', }, }, - nextjs: { - appDirectory: true, - }, }, tags: ['autodocs', 'test'], title: 'Components/Account/security/ProgramSecurityTxtCard', diff --git a/app/features/security-txt/ui/__stories__/SecurityCard.responsive.stories.tsx b/app/features/security-txt/ui/__stories__/SecurityCard.responsive.stories.tsx index eb08a4765f..c155060923 100644 --- a/app/features/security-txt/ui/__stories__/SecurityCard.responsive.stories.tsx +++ b/app/features/security-txt/ui/__stories__/SecurityCard.responsive.stories.tsx @@ -1,46 +1,13 @@ -import { DEFAULT_SLOT } from '@__fixtures__/gen'; -import { PublicKey } from '@solana/web3.js'; -import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; -import { nextjsParameters, withClusterAndAccounts } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import { toBase64 } from '@/app/shared/lib/bytes'; - import { SecurityCard } from '../SecurityCard'; +import * as Base from './SecurityCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. -const PUBKEY = new PublicKey(TOKEN_PROGRAM_ADDRESS); -const AUTHORITY = PublicKey.default; - -const NEODYME_HEADER = '=======BEGIN SECURITY.TXT V1=======\0'; -const NEODYME_FOOTER = '=======END SECURITY.TXT V1=======\0'; - -function encodeNeodymeSecurityTxt(fields: Record): string { - const enc = new TextEncoder(); - const body = `${Object.entries(fields) - .flatMap(([k, v]) => [k, v]) - .join('\0')}\0`; - const bytes = enc.encode(`${NEODYME_HEADER}${body}${NEODYME_FOOTER}`); - return toBase64(bytes); -} - -const validSecurityTxt = encodeNeodymeSecurityTxt({ - auditors: 'Sample Auditor', - contacts: 'email:security@example.test,link:https://example.test/security', - name: 'Sample Program', - policy: 'https://example.test/SECURITY.md', - project_url: 'https://example.test', - source_code: 'https://github.com/example/sample', -}); - const meta = { component: SecurityCard, - decorators: [withViewportFromGlobal, withClusterAndAccounts], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withViewportFromGlobal, ...Base.default.decorators], tags: ['autodocs', 'test'], title: 'Features/SecurityTxt/SecurityCard@Media', } satisfies Meta; @@ -48,12 +15,7 @@ const meta = { export default meta; type Story = StoryObj; -const args = { - data: { - programData: { authority: AUTHORITY, data: [validSecurityTxt, 'base64'], slot: DEFAULT_SLOT }, - } as any, - pubkey: PUBKEY, -}; +const args = Base.WithEmbeddedSecurityTxt.args; export const Mobile: Story = { args, diff --git a/app/features/security-txt/ui/__stories__/SecurityCard.stories.tsx b/app/features/security-txt/ui/__stories__/SecurityCard.stories.tsx index 08ab737ab8..fdac8324f7 100644 --- a/app/features/security-txt/ui/__stories__/SecurityCard.stories.tsx +++ b/app/features/security-txt/ui/__stories__/SecurityCard.stories.tsx @@ -1,5 +1,5 @@ import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withClusterAndAccounts } from '@storybook-config/decorators'; +import { withClusterAndAccounts } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { toBase64 } from '@/app/shared/lib/bytes'; @@ -36,7 +36,6 @@ const validSecurityTxt = encodeNeodymeSecurityTxt({ const meta = { component: SecurityCard, decorators: [withClusterAndAccounts], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/SecurityTxt/SecurityCard', } satisfies Meta; diff --git a/app/features/security-txt/ui/__stories__/SecurityTXTBadge.stories.tsx b/app/features/security-txt/ui/__stories__/SecurityTXTBadge.stories.tsx index 1ecd826e59..3d57815d4e 100644 --- a/app/features/security-txt/ui/__stories__/SecurityTXTBadge.stories.tsx +++ b/app/features/security-txt/ui/__stories__/SecurityTXTBadge.stories.tsx @@ -1,11 +1,9 @@ -import { nextjsParameters } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { SecurityTXTBadge } from '../SecurityTXTBadge'; const meta: Meta = { component: SecurityTXTBadge, - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/SecurityTxt/SecurityTXTBadge', }; diff --git a/app/features/security-txt/ui/__tests__/helpers.ts b/app/features/security-txt/ui/__tests__/helpers.ts index 53363cfba7..c44c26d987 100644 --- a/app/features/security-txt/ui/__tests__/helpers.ts +++ b/app/features/security-txt/ui/__tests__/helpers.ts @@ -1,15 +1,11 @@ +import { makeProgramDataInfo } from '@entities/account/__fixtures__/account'; import type { NeodymeSecurityTxtFields, SecurityTxtFields } from '@solana/security-txt'; -import { PublicKey } from '@solana/web3.js'; import type { ResolvedSecurityTxt } from '../../model/useSecurityTxt'; // Minimal programData fixture for `SecurityCard`'s `data.programData` guard — its bytes are no longer // parsed (security.txt now resolves via `@solana/security-txt`), so the content is arbitrary. -export const programDataFixture = { - authority: PublicKey.default, - data: ['deadbeef', 'base64'] as [string, 'base64'], - slot: 123, -}; +export const programDataFixture = makeProgramDataInfo(); // TODO: rebuild these on `gen.securityTxt` (@__fixtures__/gen) so there's one security.txt fixture source. export function createPmpSecurityTxt(fields: Partial = {}): ResolvedSecurityTxt { @@ -50,23 +46,3 @@ export function createNeodymeSecurityTxt(fields: Partial = {}, -): ResolvedSecurityTxt { - return { - fields: { - ...createNeodymeSecurityTxt().fields, - acknowledgements: 'Test Acknowledgements', - auditors: 'Test Auditors', - encryption: 'pgp', - expiry: '2025-12-31', - preferred_languages: 'en', - source_code: 'https://github.com/example/test', - source_release: 'v1.0.0', - source_revision: 'abc123', - ...fields, - }, - type: 'elf', - }; -} diff --git a/app/features/stake/ui/__stories__/DelegationCard.stories.tsx b/app/features/stake/ui/__stories__/DelegationCard.stories.tsx index dacf94c18d..5a90c585f6 100644 --- a/app/features/stake/ui/__stories__/DelegationCard.stories.tsx +++ b/app/features/stake/ui/__stories__/DelegationCard.stories.tsx @@ -4,7 +4,7 @@ import { SYSTEM_PROGRAM_ADDRESS } from '@solana-program/system'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '../../../../../.storybook/decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '../../../../../.storybook/decorators'; import { EPOCH_NEVER_SET } from '../../lib/constants'; import type { StakeAccountInfo } from '../../lib/validators'; import { TotalRewardStatus } from '../../model/use-total-reward'; @@ -43,7 +43,6 @@ const meta = { component: DelegationCard, // The card renders vote/authority addresses, which resolve through both providers. decorators: [withClusterAndAccounts, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/Stake/DelegationCard', } satisfies Meta; diff --git a/app/features/stake/ui/__stories__/StakeAccountSection.responsive.stories.tsx b/app/features/stake/ui/__stories__/StakeAccountSection.responsive.stories.tsx index 86f43dd59c..7029076a4e 100644 --- a/app/features/stake/ui/__stories__/StakeAccountSection.responsive.stories.tsx +++ b/app/features/stake/ui/__stories__/StakeAccountSection.responsive.stories.tsx @@ -1,71 +1,15 @@ -import type { Account } from '@providers/accounts'; -import { address } from '@solana/kit'; -import { STAKE_PROGRAM_ADDRESS } from '@solana-program/stake'; -import { SYSTEM_PROGRAM_ADDRESS } from '@solana-program/system'; import type { Meta, StoryObj } from '@storybook-config/types'; -import { toLegacyPublicKey } from '@/app/shared/lib/web3js-compat'; - -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '../../../../../.storybook/decorators'; -import { - INITIAL_VIEWPORTS, - withMockRpc, - withViewportFromGlobal, -} from '../../../../../.storybook/responsive-decorators'; -import { EPOCH_NEVER_SET } from '../../lib/constants'; -import type { StakeAccountInfo } from '../../lib/validators'; +import { withViewportFromGlobal } from '../../../../../.storybook/responsive-decorators'; import { StakeAccountSection } from '../StakeAccountSection'; +import * as Base from './StakeAccountSection.stories'; -const STAKE_ACCOUNT_ADDRESS = toLegacyPublicKey(address('5ASxtmcPKDeD8NoE5QpskizPokqDdX1qHFiqZb1spLdo')); -const STAKE_PROGRAM = toLegacyPublicKey(STAKE_PROGRAM_ADDRESS); -const STAKER = address('2xNweLHLKifGNBhLp2giBonGDJ3dPAHpSTaMJmfcMon8'); -const WITHDRAWER = address('4TPTXRKCbL39nMkWAtRDMRB4gQkUfrfCMvwKS4AYoH7e'); -const VOTER = address('3MRBUAxwx7gWoGvAtzxLtzmhzwPDGAEqStKWb8cJnYQX'); -const RENT_RESERVE = 2_282_880n; -const DELEGATED_STAKE = 1_000_000_000n; - -const account: Account = { - data: {}, - executable: false, - lamports: Number(DELEGATED_STAKE + RENT_RESERVE), - owner: STAKE_PROGRAM, - pubkey: STAKE_ACCOUNT_ADDRESS, - space: 200, -}; - -const stakeAccount: StakeAccountInfo = { - meta: { - authorized: { staker: STAKER, withdrawer: WITHDRAWER }, - lockup: { custodian: SYSTEM_PROGRAM_ADDRESS, epoch: 0, unixTimestamp: 0 }, - rentExemptReserve: RENT_RESERVE, - }, - stake: { - creditsObserved: 12_345, - delegation: { - activationEpoch: 100n, - deactivationEpoch: EPOCH_NEVER_SET, - stake: DELEGATED_STAKE, - voter: VOTER, - warmupCooldownRate: 0.09, - }, - }, -}; - -const args = { - account, - activation: { active: Number(DELEGATED_STAKE), inactive: 0, state: 'active' as const }, - stakeAccount, - stakeAccountType: 'delegated' as const, -}; +const args = Base.Active.args; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta = { component: StakeAccountSection, - decorators: [withMockRpc, withViewportFromGlobal, withClusterAndAccounts, withTokenInfoBatch], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withViewportFromGlobal, ...Base.default.decorators], tags: ['autodocs', 'test'], title: 'Features/Stake/StakeAccountSection@Media', } satisfies Meta; diff --git a/app/features/stake/ui/__stories__/StakeAccountSection.stories.tsx b/app/features/stake/ui/__stories__/StakeAccountSection.stories.tsx index cd523b1846..76fa8d44d5 100644 --- a/app/features/stake/ui/__stories__/StakeAccountSection.stories.tsx +++ b/app/features/stake/ui/__stories__/StakeAccountSection.stories.tsx @@ -7,7 +7,7 @@ import { expect, within } from 'storybook/test'; import { toLegacyPublicKey } from '@/app/shared/lib/web3js-compat'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '../../../../../.storybook/decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '../../../../../.storybook/decorators'; import { withMockRpc } from '../../../../../.storybook/responsive-decorators'; import { EPOCH_NEVER_SET } from '../../lib/constants'; import type { StakeAccountInfo, StakeAccountType } from '../../lib/validators'; @@ -76,7 +76,6 @@ function initializedStakeInfo(): StakeAccountInfo { const meta = { component: StakeAccountSection, decorators: [withMockRpc, withClusterAndAccounts, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/Stake/StakeAccountSection', } satisfies Meta; diff --git a/app/features/stake/ui/__stories__/StakeHistoryCard.responsive.stories.tsx b/app/features/stake/ui/__stories__/StakeHistoryCard.responsive.stories.tsx index b97d9540e8..7f8607bf86 100644 --- a/app/features/stake/ui/__stories__/StakeHistoryCard.responsive.stories.tsx +++ b/app/features/stake/ui/__stories__/StakeHistoryCard.responsive.stories.tsx @@ -1,22 +1,13 @@ -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import type { SysvarStakeHistoryAccount } from '@validators/accounts/sysvar'; import { StakeHistoryCard } from '../StakeHistoryCard'; +import * as Base from './StakeHistoryCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. -function sysvar(entries: SysvarStakeHistoryAccount['info']): SysvarStakeHistoryAccount { - return { info: entries, type: 'stakeHistory' }; -} - const meta = { component: StakeHistoryCard, - decorators: [withViewportFromGlobal, withClusterAndAccounts, withTokenInfoBatch], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withViewportFromGlobal, ...Base.default.decorators], tags: ['autodocs', 'test'], title: 'Features/Stake/StakeHistoryCard@Media', } satisfies Meta; @@ -24,22 +15,7 @@ const meta = { export default meta; type Story = StoryObj; -const args = { - sysvarAccount: sysvar([ - { - epoch: 700, - stakeHistory: { activating: 12_500_000_000, deactivating: 8_300_000_000, effective: 384_120_000_000_000 }, - }, - { - epoch: 699, - stakeHistory: { activating: 9_700_000_000, deactivating: 11_200_000_000, effective: 383_400_000_000_000 }, - }, - { - epoch: 698, - stakeHistory: { activating: 14_100_000_000, deactivating: 6_900_000_000, effective: 382_960_000_000_000 }, - }, - ]), -}; +const args = Base.WithEntries.args; export const Mobile: Story = { args, diff --git a/app/features/stake/ui/__stories__/StakeHistoryCard.stories.tsx b/app/features/stake/ui/__stories__/StakeHistoryCard.stories.tsx index 98bd9bf75e..989543243e 100644 --- a/app/features/stake/ui/__stories__/StakeHistoryCard.stories.tsx +++ b/app/features/stake/ui/__stories__/StakeHistoryCard.stories.tsx @@ -2,7 +2,7 @@ import type { Meta, StoryObj } from '@storybook-config/types'; import type { SysvarStakeHistoryAccount } from '@validators/accounts/sysvar'; import { expect, within } from 'storybook/test'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '../../../../../.storybook/decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '../../../../../.storybook/decorators'; import { StakeHistoryCard } from '../StakeHistoryCard'; function sysvar(entries: SysvarStakeHistoryAccount['info']): SysvarStakeHistoryAccount { @@ -12,7 +12,6 @@ function sysvar(entries: SysvarStakeHistoryAccount['info']): SysvarStakeHistoryA const meta = { component: StakeHistoryCard, decorators: [withClusterAndAccounts, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/Stake/StakeHistoryCard', } satisfies Meta; diff --git a/app/features/subscriptions/__fixtures__/subscriptions-accounts.ts b/app/features/subscriptions/__fixtures__/subscriptions-accounts.ts new file mode 100644 index 0000000000..93caed3d9d --- /dev/null +++ b/app/features/subscriptions/__fixtures__/subscriptions-accounts.ts @@ -0,0 +1,97 @@ +import { gen } from '@__fixtures__/gen'; +import type { Account } from '@providers/accounts'; +import { address } from '@solana/kit'; +import { + AccountDiscriminator, + type FixedDelegation, + getFixedDelegationEncoder, + getPlanEncoder, + getRecurringDelegationEncoder, + getSubscriptionAuthorityEncoder, + getSubscriptionDelegationEncoder, + type Plan, + PlanStatus, + type RecurringDelegation, + type SubscriptionDelegation, + SUBSCRIPTIONS_PROGRAM_ADDRESS, +} from '@solana/subscriptions'; + +import { toLegacyPublicKey } from '@/app/shared/lib/web3js-compat'; + +const ZERO = address('11111111111111111111111111111111'); +export const USER = address(gen.address(1)); +const MINT = address(gen.address(2)); +const DELEGATEE = address(gen.address(3)); + +const HEADER = { delegatee: DELEGATEE, delegator: USER, payer: ZERO, version: 1 }; + +export const PLAN: Plan = { + bump: 255, + data: { + destinations: [ZERO, ZERO, ZERO, ZERO], + endTs: 0n, + metadataUri: 'https://example.com/plan.json', + mint: MINT, + planId: 42n, + pullers: [ZERO, ZERO, ZERO, ZERO], + terms: { amount: 1_000_000n, createdAt: 0n, periodHours: 24n }, + }, + discriminator: AccountDiscriminator.Plan, + owner: USER, + status: PlanStatus.Active, +}; + +export const FIXED_DELEGATION: FixedDelegation = { + amount: 500_000n, + expiryTs: 1_999_999_999n, + header: { ...HEADER, bump: 253, discriminator: AccountDiscriminator.FixedDelegation, initId: 1n }, + mint: MINT, + subscriptionAuthority: ZERO, +}; + +export const RECURRING_DELEGATION: RecurringDelegation = { + amountPerPeriod: 100_000n, + amountPulledInPeriod: 25_000n, + currentPeriodStartTs: 1_700_000_000n, + expiryTs: 1_999_999_999n, + header: { ...HEADER, bump: 252, discriminator: AccountDiscriminator.RecurringDelegation, initId: 2n }, + mint: MINT, + periodLengthS: 86_400n, + subscriptionAuthority: ZERO, +}; + +export const SUBSCRIPTION_DELEGATION: SubscriptionDelegation = { + amountPulledInPeriod: 50_000n, + currentPeriodStartTs: 1_700_000_000n, + expiresAtTs: 1_999_999_999n, + header: { ...HEADER, bump: 251, discriminator: AccountDiscriminator.SubscriptionDelegation, initId: 3n }, + terms: { amount: 200_000n, createdAt: 0n, periodHours: 48n }, +}; + +export const PLAN_BYTES = new Uint8Array(getPlanEncoder().encode(PLAN)); +export const FIXED_DELEGATION_BYTES = new Uint8Array(getFixedDelegationEncoder().encode(FIXED_DELEGATION)); +export const RECURRING_DELEGATION_BYTES = new Uint8Array(getRecurringDelegationEncoder().encode(RECURRING_DELEGATION)); +export const SUBSCRIPTION_DELEGATION_BYTES = new Uint8Array( + getSubscriptionDelegationEncoder().encode(SUBSCRIPTION_DELEGATION), +); +export const SUBSCRIPTION_AUTHORITY_BYTES = new Uint8Array( + getSubscriptionAuthorityEncoder().encode({ + bump: 254, + discriminator: AccountDiscriminator.SubscriptionAuthority, + initId: 7n, + payer: ZERO, + tokenMint: MINT, + user: USER, + }), +); + +export function subscriptionsAccount(raw: Uint8Array): Account { + return { + data: { raw }, + executable: false, + lamports: 1_000_000, + owner: toLegacyPublicKey(address(SUBSCRIPTIONS_PROGRAM_ADDRESS)), + pubkey: gen.publicKey(0), + space: raw.length, + }; +} diff --git a/app/features/subscriptions/lib/__tests__/decode-subscriptions-account.spec.ts b/app/features/subscriptions/lib/__tests__/decode-subscriptions-account.spec.ts index 0f3bb29e42..49c08b57c7 100644 --- a/app/features/subscriptions/lib/__tests__/decode-subscriptions-account.spec.ts +++ b/app/features/subscriptions/lib/__tests__/decode-subscriptions-account.spec.ts @@ -1,122 +1,32 @@ -import { gen } from '@__fixtures__/gen'; -import { address } from '@solana/kit'; import { - AccountDiscriminator, - getFixedDelegationEncoder, - getPlanEncoder, - getRecurringDelegationEncoder, - getSubscriptionAuthorityEncoder, - getSubscriptionDelegationEncoder, - PlanStatus, -} from '@solana/subscriptions'; + FIXED_DELEGATION_BYTES, + PLAN_BYTES, + RECURRING_DELEGATION_BYTES, + SUBSCRIPTION_AUTHORITY_BYTES, + SUBSCRIPTION_DELEGATION_BYTES, + USER, +} from '@features/subscriptions/__fixtures__/subscriptions-accounts'; +import { AccountDiscriminator } from '@solana/subscriptions'; import { describe, expect, it } from 'vitest'; import { decodeSubscriptionsAccount } from '../decode-subscriptions-account'; -// A valid Solana address used as placeholder for all address fields in fixtures. -const ZERO = address(gen.address(0)); - -// ─── Fixtures built with the SDK's own encoders ──────────────────────────────── -// Using the same codecs for encoding and decoding is the canonical way to -// produce valid byte sequences without hand-crafting binary layouts. -// The SDK's FixedSizeEncoder.encode() returns ReadonlyUint8Array at the type -// level but a regular Uint8Array at runtime; the cast makes the types line up. -function encode(encoder: { encode: (v: T) => unknown }, value: T): Uint8Array { - return encoder.encode(value) as unknown as Uint8Array; -} - -const PLAN_BYTES = encode(getPlanEncoder(), { - bump: 255, - data: { - destinations: [ZERO, ZERO, ZERO, ZERO], - endTs: 0n, - metadataUri: '', - mint: ZERO, - planId: 42n, - pullers: [ZERO, ZERO, ZERO, ZERO], - terms: { amount: 1_000n, createdAt: 0n, periodHours: 24n }, - }, - discriminator: AccountDiscriminator.Plan, - owner: ZERO, - status: PlanStatus.Active, -}); - -const FIXED_DELEGATION_BYTES = encode(getFixedDelegationEncoder(), { - amount: 500n, - expiryTs: 1_999_999_999n, - header: { - bump: 253, - delegatee: ZERO, - delegator: ZERO, - discriminator: AccountDiscriminator.FixedDelegation, - initId: 1n, - payer: ZERO, - version: 1, - }, - mint: ZERO, - subscriptionAuthority: ZERO, -}); - -const RECURRING_DELEGATION_BYTES = encode(getRecurringDelegationEncoder(), { - amountPerPeriod: 100n, - amountPulledInPeriod: 0n, - currentPeriodStartTs: 0n, - expiryTs: 1_999_999_999n, - header: { - bump: 252, - delegatee: ZERO, - delegator: ZERO, - discriminator: AccountDiscriminator.RecurringDelegation, - initId: 2n, - payer: ZERO, - version: 1, - }, - mint: ZERO, - periodLengthS: 86_400n, - subscriptionAuthority: ZERO, -}); - -const SUBSCRIPTION_DELEGATION_BYTES = encode(getSubscriptionDelegationEncoder(), { - amountPulledInPeriod: 0n, - currentPeriodStartTs: 0n, - expiresAtTs: 1_999_999_999n, - header: { - bump: 251, - delegatee: ZERO, - delegator: ZERO, - discriminator: AccountDiscriminator.SubscriptionDelegation, - initId: 3n, - payer: ZERO, - version: 1, - }, - terms: { amount: 200n, createdAt: 0n, periodHours: 48n }, -}); - -const SUBSCRIPTION_AUTHORITY_BYTES = encode(getSubscriptionAuthorityEncoder(), { - bump: 254, - discriminator: AccountDiscriminator.SubscriptionAuthority, - initId: 1n, - payer: ZERO, - tokenMint: ZERO, - user: ZERO, -}); - describe('decodeSubscriptionsAccount', () => { it('should decode a Plan account and expose its fields', () => { const result = decodeSubscriptionsAccount('addr', PLAN_BYTES); expect(result?.program).toBe('Plan'); if (result?.program !== 'Plan') return; expect(result.parsed.data.planId).toBe(42n); - expect(result.parsed.data.terms.amount).toBe(1_000n); + expect(result.parsed.data.terms.amount).toBe(1_000_000n); expect(result.parsed.data.terms.periodHours).toBe(24n); - expect(result.parsed.owner).toBe(ZERO); + expect(result.parsed.owner).toBe(USER); }); it('should decode a FixedDelegation account and expose its fields', () => { const result = decodeSubscriptionsAccount('addr', FIXED_DELEGATION_BYTES); expect(result?.program).toBe('FixedDelegation'); if (result?.program !== 'FixedDelegation') return; - expect(result.parsed.amount).toBe(500n); + expect(result.parsed.amount).toBe(500_000n); expect(result.parsed.expiryTs).toBe(1_999_999_999n); expect(result.parsed.header.discriminator).toBe(AccountDiscriminator.FixedDelegation); }); @@ -125,7 +35,7 @@ describe('decodeSubscriptionsAccount', () => { const result = decodeSubscriptionsAccount('addr', RECURRING_DELEGATION_BYTES); expect(result?.program).toBe('RecurringDelegation'); if (result?.program !== 'RecurringDelegation') return; - expect(result.parsed.amountPerPeriod).toBe(100n); + expect(result.parsed.amountPerPeriod).toBe(100_000n); expect(result.parsed.periodLengthS).toBe(86_400n); expect(result.parsed.header.discriminator).toBe(AccountDiscriminator.RecurringDelegation); }); @@ -134,7 +44,7 @@ describe('decodeSubscriptionsAccount', () => { const result = decodeSubscriptionsAccount('addr', SUBSCRIPTION_DELEGATION_BYTES); expect(result?.program).toBe('SubscriptionDelegation'); if (result?.program !== 'SubscriptionDelegation') return; - expect(result.parsed.terms.amount).toBe(200n); + expect(result.parsed.terms.amount).toBe(200_000n); expect(result.parsed.terms.periodHours).toBe(48n); expect(result.parsed.header.discriminator).toBe(AccountDiscriminator.SubscriptionDelegation); }); @@ -143,7 +53,7 @@ describe('decodeSubscriptionsAccount', () => { const result = decodeSubscriptionsAccount('addr', SUBSCRIPTION_AUTHORITY_BYTES); expect(result?.program).toBe('SubscriptionAuthority'); if (result?.program !== 'SubscriptionAuthority') return; - expect(result.parsed.user).toBe(ZERO); + expect(result.parsed.user).toBe(USER); expect(result.parsed.bump).toBe(254); }); diff --git a/app/features/subscriptions/ui/__stories__/EventAuthorityCard.stories.tsx b/app/features/subscriptions/ui/__stories__/EventAuthorityCard.stories.tsx index 0c69604762..8663d37226 100644 --- a/app/features/subscriptions/ui/__stories__/EventAuthorityCard.stories.tsx +++ b/app/features/subscriptions/ui/__stories__/EventAuthorityCard.stories.tsx @@ -1,7 +1,7 @@ import { gen } from '@__fixtures__/gen'; import type { Account } from '@providers/accounts'; import { address } from '@solana/kit'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import { withMockRpc } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; @@ -24,7 +24,6 @@ const account: Account = { const meta = { component: SubscriptionsEventAuthorityCard, decorators: [withMockRpc, withClusterAndAccounts, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/Subscriptions/EventAuthorityCard', } satisfies Meta; diff --git a/app/features/subscriptions/ui/__stories__/SubscriptionsAccountCard.responsive.stories.tsx b/app/features/subscriptions/ui/__stories__/SubscriptionsAccountCard.responsive.stories.tsx index 6747cc3e6a..28c4e99a63 100644 --- a/app/features/subscriptions/ui/__stories__/SubscriptionsAccountCard.responsive.stories.tsx +++ b/app/features/subscriptions/ui/__stories__/SubscriptionsAccountCard.responsive.stories.tsx @@ -1,64 +1,15 @@ -import { gen } from '@__fixtures__/gen'; -import type { Account } from '@providers/accounts'; -import { address } from '@solana/kit'; -import { AccountDiscriminator, getPlanEncoder, PlanStatus, SUBSCRIPTIONS_PROGRAM_ADDRESS } from '@solana/subscriptions'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withMockRpc, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import { toLegacyPublicKey } from '@/app/shared/lib/web3js-compat'; - import { SubscriptionsAccountCard } from '../SubscriptionsAccountCard'; +import * as Base from './SubscriptionsAccountCard.stories'; -const ZERO = address('11111111111111111111111111111111'); -const PROGRAM_OWNER = toLegacyPublicKey(address(SUBSCRIPTIONS_PROGRAM_ADDRESS)); -const ACCOUNT_ADDRESS = gen.publicKey(0); -const USER = address(gen.address(1)); -const MINT = address(gen.address(2)); - -function encode(encoder: { encode: (v: T) => unknown }, value: T): Uint8Array { - return encoder.encode(value) as unknown as Uint8Array; -} - -const PLAN_BYTES = encode(getPlanEncoder(), { - bump: 255, - data: { - destinations: [ZERO, ZERO, ZERO, ZERO], - endTs: 0n, - metadataUri: 'https://example.com/plan.json', - mint: MINT, - planId: 42n, - pullers: [ZERO, ZERO, ZERO, ZERO], - terms: { amount: 1_000_000n, createdAt: 0n, periodHours: 24n }, - }, - discriminator: AccountDiscriminator.Plan, - owner: USER, - status: PlanStatus.Active, -}); - -const account: Account = { - data: { raw: PLAN_BYTES }, - executable: false, - lamports: 1_000_000, - owner: PROGRAM_OWNER, - pubkey: ACCOUNT_ADDRESS, - space: PLAN_BYTES.length, -}; - -const onNotFound = () => { - throw new Error('onNotFound called unexpectedly'); -}; - -const args = { account, onNotFound }; +const args = Base.Plan.args; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta = { component: SubscriptionsAccountCard, - decorators: [withMockRpc, withViewportFromGlobal, withClusterAndAccounts, withTokenInfoBatch], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withViewportFromGlobal, ...Base.default.decorators], tags: ['autodocs', 'test'], title: 'Features/Subscriptions/SubscriptionsAccountCard@Media', } satisfies Meta; diff --git a/app/features/subscriptions/ui/__stories__/SubscriptionsAccountCard.stories.tsx b/app/features/subscriptions/ui/__stories__/SubscriptionsAccountCard.stories.tsx index 7087aa0f5d..d19f3d1abc 100644 --- a/app/features/subscriptions/ui/__stories__/SubscriptionsAccountCard.stories.tsx +++ b/app/features/subscriptions/ui/__stories__/SubscriptionsAccountCard.stories.tsx @@ -1,127 +1,21 @@ -import { gen } from '@__fixtures__/gen'; -import type { Account } from '@providers/accounts'; -import { address } from '@solana/kit'; import { - AccountDiscriminator, - getFixedDelegationEncoder, - getPlanEncoder, - getRecurringDelegationEncoder, - getSubscriptionAuthorityEncoder, - getSubscriptionDelegationEncoder, - PlanStatus, - SUBSCRIPTIONS_PROGRAM_ADDRESS, -} from '@solana/subscriptions'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; + FIXED_DELEGATION_BYTES, + PLAN_BYTES, + RECURRING_DELEGATION_BYTES, + SUBSCRIPTION_AUTHORITY_BYTES, + SUBSCRIPTION_DELEGATION_BYTES, + subscriptionsAccount, +} from '@features/subscriptions/__fixtures__/subscriptions-accounts'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import { withMockRpc } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; -import { toLegacyPublicKey } from '@/app/shared/lib/web3js-compat'; - import { SubscriptionsAccountCard } from '../SubscriptionsAccountCard'; -const ZERO = address('11111111111111111111111111111111'); -const PROGRAM_OWNER = toLegacyPublicKey(address(SUBSCRIPTIONS_PROGRAM_ADDRESS)); -const ACCOUNT_ADDRESS = gen.publicKey(0); -const USER = address(gen.address(1)); -const MINT = address(gen.address(2)); -const DELEGATEE = address(gen.address(3)); - -function encode(encoder: { encode: (v: T) => unknown }, value: T): Uint8Array { - return encoder.encode(value) as unknown as Uint8Array; -} - -const PLAN_BYTES = encode(getPlanEncoder(), { - bump: 255, - data: { - destinations: [ZERO, ZERO, ZERO, ZERO], - endTs: 0n, - metadataUri: 'https://example.com/plan.json', - mint: MINT, - planId: 42n, - pullers: [ZERO, ZERO, ZERO, ZERO], - terms: { amount: 1_000_000n, createdAt: 0n, periodHours: 24n }, - }, - discriminator: AccountDiscriminator.Plan, - owner: USER, - status: PlanStatus.Active, -}); - -const SUBSCRIPTION_AUTHORITY_BYTES = encode(getSubscriptionAuthorityEncoder(), { - bump: 254, - discriminator: AccountDiscriminator.SubscriptionAuthority, - initId: 7n, - payer: ZERO, - tokenMint: MINT, - user: USER, -}); - -const FIXED_DELEGATION_BYTES = encode(getFixedDelegationEncoder(), { - amount: 500_000n, - expiryTs: 1_999_999_999n, - header: { - bump: 253, - delegatee: DELEGATEE, - delegator: USER, - discriminator: AccountDiscriminator.FixedDelegation, - initId: 1n, - payer: ZERO, - version: 1, - }, - mint: MINT, - subscriptionAuthority: ZERO, -}); - -const RECURRING_DELEGATION_BYTES = encode(getRecurringDelegationEncoder(), { - amountPerPeriod: 100_000n, - amountPulledInPeriod: 25_000n, - currentPeriodStartTs: 1_700_000_000n, - expiryTs: 1_999_999_999n, - header: { - bump: 252, - delegatee: DELEGATEE, - delegator: USER, - discriminator: AccountDiscriminator.RecurringDelegation, - initId: 2n, - payer: ZERO, - version: 1, - }, - mint: MINT, - periodLengthS: 86_400n, - subscriptionAuthority: ZERO, -}); - -const SUBSCRIPTION_DELEGATION_BYTES = encode(getSubscriptionDelegationEncoder(), { - amountPulledInPeriod: 50_000n, - currentPeriodStartTs: 1_700_000_000n, - expiresAtTs: 1_999_999_999n, - header: { - bump: 251, - delegatee: DELEGATEE, - delegator: USER, - discriminator: AccountDiscriminator.SubscriptionDelegation, - initId: 3n, - payer: ZERO, - version: 1, - }, - terms: { amount: 200_000n, createdAt: 0n, periodHours: 48n }, -}); - -function makeAccount(raw: Uint8Array): Account { - return { - data: { raw }, - executable: false, - lamports: 1_000_000, - owner: PROGRAM_OWNER, - pubkey: ACCOUNT_ADDRESS, - space: raw.length, - }; -} - const meta = { component: SubscriptionsAccountCard, decorators: [withMockRpc, withClusterAndAccounts, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/Subscriptions/SubscriptionsAccountCard', } satisfies Meta; @@ -135,7 +29,7 @@ const onNotFound = () => { export const Plan: Story = { args: { - account: makeAccount(PLAN_BYTES), + account: subscriptionsAccount(PLAN_BYTES), onNotFound, }, play: async ({ canvasElement }) => { @@ -150,7 +44,7 @@ export const Plan: Story = { export const SubscriptionAuthority: Story = { args: { - account: makeAccount(SUBSCRIPTION_AUTHORITY_BYTES), + account: subscriptionsAccount(SUBSCRIPTION_AUTHORITY_BYTES), onNotFound, }, play: async ({ canvasElement }) => { @@ -162,7 +56,7 @@ export const SubscriptionAuthority: Story = { export const FixedDelegation: Story = { args: { - account: makeAccount(FIXED_DELEGATION_BYTES), + account: subscriptionsAccount(FIXED_DELEGATION_BYTES), onNotFound, }, play: async ({ canvasElement }) => { @@ -174,7 +68,7 @@ export const FixedDelegation: Story = { export const RecurringDelegation: Story = { args: { - account: makeAccount(RECURRING_DELEGATION_BYTES), + account: subscriptionsAccount(RECURRING_DELEGATION_BYTES), onNotFound, }, play: async ({ canvasElement }) => { @@ -188,7 +82,7 @@ export const RecurringDelegation: Story = { export const SubscriptionDelegation: Story = { args: { - account: makeAccount(SUBSCRIPTION_DELEGATION_BYTES), + account: subscriptionsAccount(SUBSCRIPTION_DELEGATION_BYTES), onNotFound, }, play: async ({ canvasElement }) => { diff --git a/app/features/subscriptions/ui/__stories__/WalletSubscriptionsCard.responsive.stories.tsx b/app/features/subscriptions/ui/__stories__/WalletSubscriptionsCard.responsive.stories.tsx index f068ff123a..1411bf9d48 100644 --- a/app/features/subscriptions/ui/__stories__/WalletSubscriptionsCard.responsive.stories.tsx +++ b/app/features/subscriptions/ui/__stories__/WalletSubscriptionsCard.responsive.stories.tsx @@ -1,96 +1,15 @@ -import { gen } from '@__fixtures__/gen'; -import { address } from '@solana/kit'; -import { - AccountDiscriminator, - type FixedDelegation, - type Plan, - PlanStatus, - type RecurringDelegation, - type SubscriptionDelegation, -} from '@solana/subscriptions'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withMockRpc, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { WalletSubscriptionsView } from '../WalletSubscriptionsCard'; +import * as Base from './WalletSubscriptionsCard.stories'; -const ZERO = address('11111111111111111111111111111111'); -const PLAN_ACCOUNT = address(gen.address(0)); -const SUB_ACCOUNT = address(gen.address(1)); -const FIXED_ACCOUNT = address(gen.address(2)); -const RECURRING_ACCOUNT = address(gen.address(3)); -const USER = address(gen.address(4)); -const MINT = address(gen.address(5)); -const DELEGATEE = address(gen.address(6)); - -const HEADER_BASE = { - delegatee: DELEGATEE, - delegator: USER, - payer: ZERO, - version: 1, -}; - -const PLAN: Plan = { - bump: 255, - data: { - destinations: [ZERO, ZERO, ZERO, ZERO], - endTs: 0n, - metadataUri: '', - mint: MINT, - planId: 42n, - pullers: [ZERO, ZERO, ZERO, ZERO], - terms: { amount: 1_000_000n, createdAt: 0n, periodHours: 24n }, - }, - discriminator: AccountDiscriminator.Plan, - owner: USER, - status: PlanStatus.Active, -}; - -const SUB_DELEGATION: SubscriptionDelegation = { - amountPulledInPeriod: 50_000n, - currentPeriodStartTs: 1_700_000_000n, - expiresAtTs: 1_999_999_999n, - header: { ...HEADER_BASE, bump: 251, discriminator: AccountDiscriminator.SubscriptionDelegation, initId: 3n }, - terms: { amount: 200_000n, createdAt: 0n, periodHours: 48n }, -}; - -const FIXED_DELEGATION: FixedDelegation = { - amount: 500_000n, - expiryTs: 1_999_999_999n, - header: { ...HEADER_BASE, bump: 253, discriminator: AccountDiscriminator.FixedDelegation, initId: 1n }, - mint: MINT, - subscriptionAuthority: ZERO, -}; - -const RECURRING_DELEGATION: RecurringDelegation = { - amountPerPeriod: 100_000n, - amountPulledInPeriod: 25_000n, - currentPeriodStartTs: 1_700_000_000n, - expiryTs: 1_999_999_999n, - header: { ...HEADER_BASE, bump: 252, discriminator: AccountDiscriminator.RecurringDelegation, initId: 2n }, - mint: MINT, - periodLengthS: 86_400n, - subscriptionAuthority: ZERO, -}; - -const args = { - delegations: [ - { address: SUB_ACCOUNT, data: SUB_DELEGATION, kind: 'subscription' as const }, - { address: FIXED_ACCOUNT, data: FIXED_DELEGATION, kind: 'fixed' as const }, - { address: RECURRING_ACCOUNT, data: RECURRING_DELEGATION, kind: 'recurring' as const }, - ], - delegationsReceived: [], - plans: [{ address: PLAN_ACCOUNT, data: PLAN }], -}; +const args = Base.AllSections.args; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta = { component: WalletSubscriptionsView, - decorators: [withMockRpc, withViewportFromGlobal, withClusterAndAccounts, withTokenInfoBatch], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withViewportFromGlobal, ...Base.default.decorators], tags: ['autodocs', 'test'], title: 'Features/Subscriptions/WalletSubscriptionsCard@Media', } satisfies Meta; diff --git a/app/features/subscriptions/ui/__stories__/WalletSubscriptionsCard.stories.tsx b/app/features/subscriptions/ui/__stories__/WalletSubscriptionsCard.stories.tsx index c24c8992e2..32ad35958a 100644 --- a/app/features/subscriptions/ui/__stories__/WalletSubscriptionsCard.stories.tsx +++ b/app/features/subscriptions/ui/__stories__/WalletSubscriptionsCard.stories.tsx @@ -1,89 +1,33 @@ import { gen } from '@__fixtures__/gen'; -import { address } from '@solana/kit'; import { - AccountDiscriminator, - type FixedDelegation, - type Plan, - PlanStatus, - type RecurringDelegation, - type SubscriptionDelegation, -} from '@solana/subscriptions'; -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; + FIXED_DELEGATION, + PLAN, + RECURRING_DELEGATION, + SUBSCRIPTION_DELEGATION, +} from '@features/subscriptions/__fixtures__/subscriptions-accounts'; +import { address } from '@solana/kit'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import { withMockRpc } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; import { WalletSubscriptionsView } from '../WalletSubscriptionsCard'; -const ZERO = address('11111111111111111111111111111111'); const PLAN_ACCOUNT = address(gen.address(0)); -const SUB_ACCOUNT = address(gen.address(1)); -const FIXED_ACCOUNT = address(gen.address(2)); -const RECURRING_ACCOUNT = address(gen.address(3)); -const USER = address(gen.address(4)); -const MINT = address(gen.address(5)); -const DELEGATEE = address(gen.address(6)); +const SUB_ACCOUNT = address(gen.address(4)); +const FIXED_ACCOUNT = address(gen.address(5)); +const RECURRING_ACCOUNT = address(gen.address(6)); const RECV_SUB_ACCOUNT = address(gen.address(7)); const RECV_FIXED_ACCOUNT = address(gen.address(8)); -const HEADER_BASE = { - delegatee: DELEGATEE, - delegator: USER, - payer: ZERO, - version: 1, -}; - -const PLAN: Plan = { - bump: 255, - data: { - destinations: [ZERO, ZERO, ZERO, ZERO], - endTs: 0n, - metadataUri: '', - mint: MINT, - planId: 42n, - pullers: [ZERO, ZERO, ZERO, ZERO], - terms: { amount: 1_000_000n, createdAt: 0n, periodHours: 24n }, - }, - discriminator: AccountDiscriminator.Plan, - owner: USER, - status: PlanStatus.Active, -}; - -const SUB_DELEGATION: SubscriptionDelegation = { - amountPulledInPeriod: 50_000n, - currentPeriodStartTs: 1_700_000_000n, - expiresAtTs: 1_999_999_999n, - header: { ...HEADER_BASE, bump: 251, discriminator: AccountDiscriminator.SubscriptionDelegation, initId: 3n }, - terms: { amount: 200_000n, createdAt: 0n, periodHours: 48n }, -}; - -const FIXED_DELEGATION: FixedDelegation = { - amount: 500_000n, - expiryTs: 1_999_999_999n, - header: { ...HEADER_BASE, bump: 253, discriminator: AccountDiscriminator.FixedDelegation, initId: 1n }, - mint: MINT, - subscriptionAuthority: ZERO, -}; - -const RECURRING_DELEGATION: RecurringDelegation = { - amountPerPeriod: 100_000n, - amountPulledInPeriod: 25_000n, - currentPeriodStartTs: 1_700_000_000n, - expiryTs: 1_999_999_999n, - header: { ...HEADER_BASE, bump: 252, discriminator: AccountDiscriminator.RecurringDelegation, initId: 2n }, - mint: MINT, - periodLengthS: 86_400n, - subscriptionAuthority: ZERO, -}; - const ALL_DATA = { delegations: [ - { address: SUB_ACCOUNT, data: SUB_DELEGATION, kind: 'subscription' as const }, + { address: SUB_ACCOUNT, data: SUBSCRIPTION_DELEGATION, kind: 'subscription' as const }, { address: FIXED_ACCOUNT, data: FIXED_DELEGATION, kind: 'fixed' as const }, { address: RECURRING_ACCOUNT, data: RECURRING_DELEGATION, kind: 'recurring' as const }, ], delegationsReceived: [ - { address: RECV_SUB_ACCOUNT, data: SUB_DELEGATION, kind: 'subscription' as const }, + { address: RECV_SUB_ACCOUNT, data: SUBSCRIPTION_DELEGATION, kind: 'subscription' as const }, { address: RECV_FIXED_ACCOUNT, data: FIXED_DELEGATION, kind: 'fixed' as const }, ], plans: [{ address: PLAN_ACCOUNT, data: PLAN }], @@ -92,7 +36,6 @@ const ALL_DATA = { const meta = { component: WalletSubscriptionsView, decorators: [withMockRpc, withClusterAndAccounts, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/Subscriptions/WalletSubscriptionsCard', } satisfies Meta; @@ -120,7 +63,9 @@ export const AllSections: Story = { export const ReceivedSubscriptionsOnly: Story = { args: { delegations: [], - delegationsReceived: [{ address: RECV_SUB_ACCOUNT, data: SUB_DELEGATION, kind: 'subscription' as const }], + delegationsReceived: [ + { address: RECV_SUB_ACCOUNT, data: SUBSCRIPTION_DELEGATION, kind: 'subscription' as const }, + ], plans: [], }, play: async ({ canvasElement }) => { @@ -144,7 +89,7 @@ export const PlansOnly: Story = { export const SubscriptionsOnly: Story = { args: { - delegations: [{ address: SUB_ACCOUNT, data: SUB_DELEGATION, kind: 'subscription' as const }], + delegations: [{ address: SUB_ACCOUNT, data: SUBSCRIPTION_DELEGATION, kind: 'subscription' as const }], delegationsReceived: [], plans: [], }, diff --git a/app/features/subscriptions/ui/__tests__/SubscriptionsAccountCard.spec.tsx b/app/features/subscriptions/ui/__tests__/SubscriptionsAccountCard.spec.tsx index 1eae2d0297..9895e846cb 100644 --- a/app/features/subscriptions/ui/__tests__/SubscriptionsAccountCard.spec.tsx +++ b/app/features/subscriptions/ui/__tests__/SubscriptionsAccountCard.spec.tsx @@ -1,17 +1,12 @@ -import { gen } from '@__fixtures__/gen'; +import { + SUBSCRIPTION_AUTHORITY_BYTES, + subscriptionsAccount, +} from '@features/subscriptions/__fixtures__/subscriptions-accounts'; import type { Account } from '@providers/accounts'; import { type CacheEntry, FetchStatus } from '@providers/cache'; -import { address } from '@solana/kit'; -import { - AccountDiscriminator, - getSubscriptionAuthorityEncoder, - SUBSCRIPTIONS_PROGRAM_ADDRESS, -} from '@solana/subscriptions'; import { render, screen } from '@testing-library/react'; import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { toLegacyPublicKey } from '@/app/shared/lib/web3js-compat'; - import { SubscriptionsAccountCard } from '../SubscriptionsAccountCard'; const mock = vi.hoisted(() => ({ entry: undefined as CacheEntry | undefined })); @@ -47,25 +42,7 @@ describe('SubscriptionsAccountCard', () => { }); }); -const RAW = new Uint8Array( - getSubscriptionAuthorityEncoder().encode({ - bump: 254, - discriminator: AccountDiscriminator.SubscriptionAuthority, - initId: 7n, - payer: address(gen.address(1)), - tokenMint: address(gen.address(2)), - user: address(gen.address(3)), - }), -); - -const ACCOUNT: Account = { - data: { raw: RAW }, - executable: false, - lamports: 1, - owner: toLegacyPublicKey(address(SUBSCRIPTIONS_PROGRAM_ADDRESS)), - pubkey: gen.publicKey(0), - space: RAW.length, -}; +const ACCOUNT = subscriptionsAccount(SUBSCRIPTION_AUTHORITY_BYTES); function renderCard() { render( diff --git a/app/features/supply/model/__tests__/use-supply.spec.tsx b/app/features/supply/model/__tests__/use-supply.spec.tsx index 2c9f916880..9dcfd94702 100644 --- a/app/features/supply/model/__tests__/use-supply.spec.tsx +++ b/app/features/supply/model/__tests__/use-supply.spec.tsx @@ -3,6 +3,7 @@ import { Cluster, ClusterStatus } from '@utils/cluster'; import { type SWRConfiguration } from 'swr'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { reported } from '@/app/__tests__/rpc-errors'; import { type ClusterContext, clusterContext, @@ -277,10 +278,7 @@ describe('useSupply', () => { expect(fetchMock).toHaveBeenCalledTimes(1); expect(Logger.warn).toHaveBeenCalledWith( expect.any(String), - expect.objectContaining({ - sentry: true, - sentryExtras: expect.objectContaining({ cluster: Cluster.Mainnet, status: 400 }), - }), + reported({ cluster: Cluster.Mainnet, status: 400 }), ); }); @@ -332,13 +330,7 @@ describe('useSupply', () => { expect(fetchMock).toHaveBeenCalledTimes(1); expect(Logger.error).toHaveBeenCalledTimes(1); - expect(Logger.error).toHaveBeenCalledWith( - expect.any(Error), - expect.objectContaining({ - sentry: true, - sentryExtras: expect.objectContaining({ cluster: Cluster.Mainnet }), - }), - ); + expect(Logger.error).toHaveBeenCalledWith(expect.any(Error), reported({ cluster: Cluster.Mainnet })); }); it("should not retry at the visitor's own node, where each attempt is another scan", async () => { @@ -368,13 +360,7 @@ describe('useSupply', () => { const { result } = renderSupply(); await waitForHook(() => expect(result.current.kind).toBe('failed')); - expect(Logger.error).toHaveBeenCalledWith( - expect.any(Error), - expect.objectContaining({ - sentry: true, - sentryExtras: expect.objectContaining({ cluster: Cluster.Devnet }), - }), - ); + expect(Logger.error).toHaveBeenCalledWith(expect.any(Error), reported({ cluster: Cluster.Devnet })); }); it('should keep supply already in hand when a revalidation fails', async () => { diff --git a/app/features/token-batch/lib/__tests__/test-utils.ts b/app/features/token-batch/lib/__tests__/test-utils.ts index 5d5ffddde3..08df83e129 100644 --- a/app/features/token-batch/lib/__tests__/test-utils.ts +++ b/app/features/token-batch/lib/__tests__/test-utils.ts @@ -24,16 +24,6 @@ export function makeAccount(writable = true, signer = false) { }; } -export function buildBatchData(subInstructions: { numAccounts: number; data: Uint8Array }[]): Uint8Array { - const parts: Uint8Array[] = [new Uint8Array([BATCH_DISCRIMINATOR])]; - for (const sub of subInstructions) { - if (sub.data.length > 255) throw new Error(`Sub-instruction data exceeds u8 max (${sub.data.length} bytes)`); - parts.push(new Uint8Array([sub.numAccounts, sub.data.length])); - parts.push(sub.data); - } - return concatBytes(...parts); -} - export function makeTransferData(amount: bigint): Uint8Array { return concatBytes(new Uint8Array([3]), writeU64LE(amount)); } diff --git a/app/features/token-batch/ui/__stories__/TokenBatchCard.stories.tsx b/app/features/token-batch/ui/__stories__/TokenBatchCard.stories.tsx index dd6b6e6939..35f23d4f75 100644 --- a/app/features/token-batch/ui/__stories__/TokenBatchCard.stories.tsx +++ b/app/features/token-batch/ui/__stories__/TokenBatchCard.stories.tsx @@ -1,12 +1,7 @@ import { toRawInstructionNode } from '@entities/instruction-card'; import { TOKEN_2022_PROGRAM_ID } from '@providers/accounts/tokens'; import { PublicKey, TransactionInstruction } from '@solana/web3.js'; -import { - nextjsParameters, - withTokenInfoBatch, - withTransactions, - withTxInstructionSurface, -} from '@storybook-config/decorators'; +import { instructionCardDecorators } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; @@ -18,10 +13,7 @@ import { TokenBatchCard } from '../TokenBatchCard'; const meta = { component: TokenBatchCard, - decorators: [withTxInstructionSurface, withTransactions, withTokenInfoBatch], - parameters: { - ...nextjsParameters, - }, + decorators: instructionCardDecorators, tags: ['autodocs', 'test'], title: 'Features/TokenBatch/TokenBatchCard', } satisfies Meta; diff --git a/app/features/token-market-data/model/__tests__/use-token-market-data.spec.ts b/app/features/token-market-data/model/__tests__/use-token-market-data.spec.ts index 85b793e528..be5107b2f4 100644 --- a/app/features/token-market-data/model/__tests__/use-token-market-data.spec.ts +++ b/app/features/token-market-data/model/__tests__/use-token-market-data.spec.ts @@ -1,8 +1,9 @@ // @vitest-environment jsdom import { renderHook } from '@testing-library/react'; -import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { stubFetch } from '@/app/__tests__/rpc-fetch'; import { swrWrapper, waitForHook } from '@/app/__tests__/swr-hook'; import { Logger } from '@/app/shared/lib/logger'; import { Cluster } from '@/app/utils/cluster'; @@ -17,27 +18,22 @@ vi.mock('@/app/utils/use-tab-visibility', () => ({ default: vi.fn() })); import { useCluster } from '@/app/providers/cluster'; import useTabVisibility from '@/app/utils/use-tab-visibility'; -let fetchSpy: MockInstance; -function mockResponse(status: number, body: unknown = {}) { - fetchSpy.mockResolvedValueOnce({ json: async () => body, ok: status >= 200 && status < 300, status } as Response); -} +const { fetchMock, respondWith } = stubFetch(); describe('fetchTokenMarketData', () => { beforeEach(() => { vi.clearAllMocks(); - fetchSpy = vi.spyOn(globalThis, 'fetch'); }); - afterEach(() => vi.restoreAllMocks()); it('should return Success with parsed stats', async () => { - mockResponse(200, createTokenMarketData()); + respondWith(200, createTokenMarketData()); const r = await fetchTokenMarketData(['token-market-data', 'addr']); expect(r.status).toBe(TokenMarketDataStatus.Success); expect(r.stats).toEqual(createTokenMarketStats()); }); it('should parse stats when only price is present', async () => { - mockResponse(200, { lastUpdated: null, marketCapRank: null, price: 1.23 }); + respondWith(200, { lastUpdated: null, marketCapRank: null, price: 1.23 }); const r = await fetchTokenMarketData(['token-market-data', 'addr']); expect(r.status).toBe(TokenMarketDataStatus.Success); expect(r.stats).toEqual({ @@ -51,40 +47,40 @@ describe('fetchTokenMarketData', () => { }); it('should coerce null marketCapRank to undefined', async () => { - mockResponse(200, createTokenMarketData({ marketCapRank: null })); + respondWith(200, createTokenMarketData({ marketCapRank: null })); expect((await fetchTokenMarketData(['token-market-data', 'addr'])).stats?.marketCapRank).toBeUndefined(); }); it('should return RateLimited for 429', async () => { - mockResponse(429); + respondWith(429, {}); expect((await fetchTokenMarketData(['token-market-data', 'addr'])).status).toBe( TokenMarketDataStatus.RateLimited, ); }); it.each([404, 500, 502])('should return FetchFailed for %i', async status => { - mockResponse(status); + respondWith(status, {}); expect((await fetchTokenMarketData(['token-market-data', 'addr'])).status).toBe( TokenMarketDataStatus.FetchFailed, ); }); it('should return FetchFailed on schema mismatch', async () => { - mockResponse(200, { unexpected: 'shape' }); + respondWith(200, { unexpected: 'shape' }); expect((await fetchTokenMarketData(['token-market-data', 'addr'])).status).toBe( TokenMarketDataStatus.FetchFailed, ); }); it('should return FetchFailed when the network request throws', async () => { - fetchSpy.mockRejectedValueOnce(new TypeError('Failed to fetch')); + fetchMock.mockRejectedValueOnce(new TypeError('Failed to fetch')); expect((await fetchTokenMarketData(['token-market-data', 'addr'])).status).toBe( TokenMarketDataStatus.FetchFailed, ); }); it('should report a schema mismatch to Sentry', async () => { - mockResponse(200, { unexpected: 'shape' }); + respondWith(200, { unexpected: 'shape' }); await fetchTokenMarketData(['token-market-data', 'addr']); expect(Logger.error).toHaveBeenCalledTimes(1); }); @@ -92,26 +88,24 @@ describe('fetchTokenMarketData', () => { describe('useTokenMarketData', () => { beforeEach(() => { - fetchSpy = vi.spyOn(globalThis, 'fetch'); vi.mocked(useCluster).mockReturnValue({ cluster: Cluster.Mainnet } as ReturnType); vi.mocked(useTabVisibility).mockReturnValue({ visible: true }); }); - afterEach(() => vi.restoreAllMocks()); const wrapper = swrWrapper({ dedupingInterval: 0, errorRetryCount: 2, errorRetryInterval: 50 }); it('should be Success when fetch succeeds', async () => { - mockResponse(200, createTokenMarketData()); + respondWith(200, createTokenMarketData()); const { result } = renderHook(() => useTokenMarketData('addr', true), { wrapper }); await waitForHook(() => expect(result.current?.status).toBe(TokenMarketDataStatus.Success)); expect(result.current?.stats?.price).toBe(1.23); }); it('should be FetchFailed for 404 without retry', async () => { - mockResponse(404); + respondWith(404, {}); const { result } = renderHook(() => useTokenMarketData('addr', true), { wrapper }); await waitForHook(() => expect(result.current?.status).toBe(TokenMarketDataStatus.FetchFailed)); - expect(fetchSpy).toHaveBeenCalledTimes(1); + expect(fetchMock).toHaveBeenCalledTimes(1); }); it.each([ @@ -122,6 +116,6 @@ describe('useTokenMarketData', () => { vi.mocked(useCluster).mockReturnValue({ cluster } as ReturnType); vi.mocked(useTabVisibility).mockReturnValue({ visible }); renderHook(() => useTokenMarketData('addr', isTokenMint), { wrapper }); - expect(fetchSpy).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); }); }); diff --git a/app/features/token-market-data/ui/__stories__/MarketData.stories.tsx b/app/features/token-market-data/ui/__stories__/MarketData.stories.tsx index 03b051819c..ac7b7fead4 100644 --- a/app/features/token-market-data/ui/__stories__/MarketData.stories.tsx +++ b/app/features/token-market-data/ui/__stories__/MarketData.stories.tsx @@ -14,10 +14,10 @@ export default meta; type Story = StoryObj; // More on writing stories with args: https://storybook.js.org/docs/writing-stories/args -export const MarketCap: Story = { +export const MarketCap = { args: { label: 'Market Cap', - lastUpdatedAt: new Date(), + lastUpdatedAt: new Date('2026-01-01T00:00:00Z'), value: { volume: 58_800_000_000, }, @@ -29,9 +29,9 @@ export const MarketCap: Story = { const marketCapValueEl = canvas.getByText('$58.8B'); expect(marketCapValueEl).toBeInTheDocument(); }, -}; +} satisfies Story; -export const Volume: Story = { +export const Volume = { args: { label: '24 Hour Volume', value: { volume: 3_600_000_000 }, @@ -43,69 +43,20 @@ export const Volume: Story = { const volumeValueEl = canvas.getByText('$3.6B'); expect(volumeValueEl).toBeInTheDocument(); }, -}; +} satisfies Story; -export const PriceUpTrend: Story = { - args: { - label: 'Price', - rank: 1, - value: { - precision: 6, - price: 0.999887, - trend: 0.1, - }, - }, - async play({ canvasElement }) { - const canvas = within(canvasElement); - const priceEl = canvas.getByText('Price'); - expect(priceEl).toBeInTheDocument(); - const priceValueEl = canvas.getByText('$0.999887'); - expect(priceValueEl).toBeInTheDocument(); - const rankEl = canvas.getByText('Rank #1'); - expect(rankEl).toBeInTheDocument(); - }, -}; +export const PriceUpTrend = priceStory(1, 0.1); +export const PriceDownTrend = priceStory(2, -0.1); +export const PriceNeutralTrend = priceStory(2, 0, '0%'); -export const PriceDownTrend: Story = { - args: { - label: 'Price', - rank: 2, - value: { - precision: 6, - price: 0.999887, - trend: -0.1, +function priceStory(rank: number, trend: number, ...texts: string[]) { + return { + args: { label: 'Price', rank, value: { precision: 6, price: 0.999887, trend } }, + async play({ canvasElement }) { + const canvas = within(canvasElement); + for (const text of ['Price', '$0.999887', `Rank #${rank}`, ...texts]) { + expect(canvas.getByText(text)).toBeInTheDocument(); + } }, - }, - async play({ canvasElement }) { - const canvas = within(canvasElement); - const priceEl = canvas.getByText('Price'); - expect(priceEl).toBeInTheDocument(); - const priceValueEl = canvas.getByText('$0.999887'); - expect(priceValueEl).toBeInTheDocument(); - const rankEl = canvas.getByText('Rank #2'); - expect(rankEl).toBeInTheDocument(); - }, -}; - -export const PriceNeutralTrend: Story = { - args: { - label: 'Price', - rank: 2, - value: { - precision: 6, - price: 0.999887, - trend: 0, - }, - }, - async play({ canvasElement }) { - const canvas = within(canvasElement); - const priceEl = canvas.getByText('Price'); - expect(priceEl).toBeInTheDocument(); - const priceValueEl = canvas.getByText('$0.999887'); - expect(priceValueEl).toBeInTheDocument(); - const rankEl = canvas.getByText('Rank #2'); - expect(rankEl).toBeInTheDocument(); - const trendEl = canvas.getByText('0%'); - expect(trendEl).toBeInTheDocument(); - }, -}; + } satisfies Story; +} diff --git a/app/features/token-market-data/ui/__stories__/MarketDataSeries.stories.tsx b/app/features/token-market-data/ui/__stories__/MarketDataSeries.stories.tsx index db39bf7e27..499dbec57e 100644 --- a/app/features/token-market-data/ui/__stories__/MarketDataSeries.stories.tsx +++ b/app/features/token-market-data/ui/__stories__/MarketDataSeries.stories.tsx @@ -2,6 +2,7 @@ import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; import { MarketData } from '../MarketData'; +import * as Base from './MarketData.stories'; // More on how to set up stories at: https://storybook.js.org/docs/writing-stories#default-export const meta = { @@ -16,28 +17,7 @@ type Story = StoryObj; // More on writing stories with args: https://storybook.js.org/docs/writing-stories/args export const Primary: Story = { args: { - data: [ - { - label: 'Market Cap', - lastUpdatedAt: new Date(), - value: { - volume: 58_800_000_000, - }, - }, - { - label: '24 Hour Volume', - value: { volume: 3_600_000_000 }, - }, - { - label: 'Price', - rank: 1, - value: { - precision: 6, - price: 0.999887, - trend: 0.1, - }, - }, - ], + data: [Base.MarketCap.args, Base.Volume.args, Base.PriceUpTrend.args], }, async play({ canvasElement }) { const canvas = within(canvasElement); diff --git a/app/features/token-verification-badge/model/__tests__/use-coingecko.spec.ts b/app/features/token-verification-badge/model/__tests__/use-coingecko.spec.ts index da6725c8a0..5b7ab29f09 100644 --- a/app/features/token-verification-badge/model/__tests__/use-coingecko.spec.ts +++ b/app/features/token-verification-badge/model/__tests__/use-coingecko.spec.ts @@ -1,8 +1,9 @@ // @vitest-environment jsdom import { renderHook } from '@testing-library/react'; -import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { stubFetch } from '@/app/__tests__/rpc-fetch'; import { swrWrapper, waitForHook } from '@/app/__tests__/swr-hook'; import { Logger } from '@/app/shared/lib/logger'; import { Cluster } from '@/app/utils/cluster'; @@ -15,70 +16,57 @@ vi.mock('@/app/utils/use-tab-visibility', () => ({ default: vi.fn() })); import { useCluster } from '@/app/providers/cluster'; import useTabVisibility from '@/app/utils/use-tab-visibility'; -let fetchSpy: MockInstance; - -function mockResponse(status: number, body: unknown = {}) { - fetchSpy.mockResolvedValueOnce({ - json: async () => body, - ok: status >= 200 && status < 300, - status, - } as Response); -} +const { fetchMock, respondWith } = stubFetch(); describe('fetchCoinGeckoVerification', () => { beforeEach(() => { vi.clearAllMocks(); - fetchSpy = vi.spyOn(globalThis, 'fetch'); - }); - - afterEach(() => { - vi.restoreAllMocks(); }); it('should return Success with verified true', async () => { - mockResponse(200, { verified: true }); + respondWith(200, { verified: true }); const result = await fetchCoinGeckoVerification(['coingecko', 'address']); expect(result).toEqual({ status: CoingeckoStatus.Success, verified: true }); }); it('should return Success with verified false', async () => { - mockResponse(200, { verified: false }); + respondWith(200, { verified: false }); const result = await fetchCoinGeckoVerification(['coingecko', 'address']); expect(result).toEqual({ status: CoingeckoStatus.Success, verified: false }); }); it('should return the coinGeckoId when present', async () => { - mockResponse(200, { coinGeckoId: 'usd-coin', verified: true }); + respondWith(200, { coinGeckoId: 'usd-coin', verified: true }); const result = await fetchCoinGeckoVerification(['coingecko', 'address']); expect(result).toEqual({ coinGeckoId: 'usd-coin', status: CoingeckoStatus.Success, verified: true }); }); it('should return RateLimited for 429', async () => { - mockResponse(429); + respondWith(429, {}); const result = await fetchCoinGeckoVerification(['coingecko', 'address']); expect(result).toEqual({ status: CoingeckoStatus.RateLimited, verified: false }); }); it.each([404, 500, 502])('should return FetchFailed for %i', async status => { - mockResponse(status); + respondWith(status, {}); const result = await fetchCoinGeckoVerification(['coingecko', 'address']); expect(result).toEqual({ status: CoingeckoStatus.FetchFailed, verified: false }); }); it('should return FetchFailed when response does not match schema', async () => { - mockResponse(200, { unexpected: 'shape' }); + respondWith(200, { unexpected: 'shape' }); const result = await fetchCoinGeckoVerification(['coingecko', 'address']); expect(result).toEqual({ status: CoingeckoStatus.FetchFailed, verified: false }); }); it('should return FetchFailed when the network request throws', async () => { - fetchSpy.mockRejectedValueOnce(new TypeError('Failed to fetch')); + fetchMock.mockRejectedValueOnce(new TypeError('Failed to fetch')); const result = await fetchCoinGeckoVerification(['coingecko', 'address']); expect(result).toEqual({ status: CoingeckoStatus.FetchFailed, verified: false }); }); it('should report a schema mismatch to Sentry', async () => { - mockResponse(200, { unexpected: 'shape' }); + respondWith(200, { unexpected: 'shape' }); await fetchCoinGeckoVerification(['coingecko', 'address']); expect(Logger.error).toHaveBeenCalledTimes(1); }); @@ -86,19 +74,14 @@ describe('fetchCoinGeckoVerification', () => { describe('useCoinGeckoVerification', () => { beforeEach(() => { - fetchSpy = vi.spyOn(globalThis, 'fetch'); vi.mocked(useCluster).mockReturnValue({ cluster: Cluster.Mainnet } as ReturnType); vi.mocked(useTabVisibility).mockReturnValue({ visible: true }); }); - afterEach(() => { - vi.restoreAllMocks(); - }); - const wrapper = swrWrapper({ dedupingInterval: 0, errorRetryCount: 2, errorRetryInterval: 50 }); it('should return Success when fetch succeeds', async () => { - mockResponse(200, { verified: true }); + respondWith(200, { verified: true }); const { result } = renderHook(() => useCoinGeckoVerification('address'), { wrapper }); await waitForHook(() => expect(result.current?.status).toBe(CoingeckoStatus.Success)); expect(result.current?.verified).toBe(true); @@ -110,11 +93,11 @@ describe('useCoinGeckoVerification', () => { [500, CoingeckoStatus.FetchFailed], [502, CoingeckoStatus.FetchFailed], ])('should map %i to %s without retrying', async (status, expectedStatus) => { - mockResponse(status); + respondWith(status, {}); const { result } = renderHook(() => useCoinGeckoVerification('address'), { wrapper }); await waitForHook(() => expect(result.current?.status).toBe(expectedStatus)); - expect(fetchSpy).toHaveBeenCalledTimes(1); + expect(fetchMock).toHaveBeenCalledTimes(1); }); it.each([ @@ -125,6 +108,6 @@ describe('useCoinGeckoVerification', () => { vi.mocked(useCluster).mockReturnValue({ cluster } as ReturnType); vi.mocked(useTabVisibility).mockReturnValue({ visible }); renderHook(() => useCoinGeckoVerification('address', enabled), { wrapper }); - expect(fetchSpy).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); }); }); diff --git a/app/features/token-verification-badge/model/use-verification-sources.ts b/app/features/token-verification-badge/model/use-verification-sources.ts index 2a34c95461..ee10135588 100644 --- a/app/features/token-verification-badge/model/use-verification-sources.ts +++ b/app/features/token-verification-badge/model/use-verification-sources.ts @@ -60,6 +60,10 @@ export function useTokenVerification({ address, isTokenMint }: VerificationTarge }, ]; + return groupVerificationSources(sources); +} + +export function groupVerificationSources(sources: VerificationSource[]): TokenVerificationResult { const rateLimitedSources = sources.filter(s => s.isRateLimited); const sourcesToApply = sources.filter(s => !s.verified && !s.isVerificationFound && !s.isRateLimited); const verificationFoundSources = sources.filter(s => s.isVerificationFound); diff --git a/app/features/token-verification-badge/ui/__stories__/TokenVerificationBadge.stories.tsx b/app/features/token-verification-badge/ui/__stories__/TokenVerificationBadge.stories.tsx index 731d11b36d..e0b9e53833 100644 --- a/app/features/token-verification-badge/ui/__stories__/TokenVerificationBadge.stories.tsx +++ b/app/features/token-verification-badge/ui/__stories__/TokenVerificationBadge.stories.tsx @@ -1,8 +1,8 @@ import type { Meta, StoryObj } from '@storybook-config/types'; +import { groupVerificationSources } from '../../model/use-verification-sources'; import { BaseTokenVerificationBadge } from '../BaseTokenVerificationBadge'; import { - createMockVerificationResult, mockAllVerifiedSources, mockDangerousTokenSources, mockNotVerifiedSources, @@ -22,41 +22,36 @@ type Story = StoryObj; export const Loading: Story = { args: { isLoading: true, - verificationResult: { - rateLimitedSources: [], - sources: [], - sourcesToApply: [], - verificationFoundSources: [], - }, + verificationResult: groupVerificationSources([]), }, }; export const FullyVerified: Story = { args: { - verificationResult: createMockVerificationResult(mockAllVerifiedSources()), + verificationResult: groupVerificationSources(mockAllVerifiedSources()), }, }; export const PartiallyVerified: Story = { args: { - verificationResult: createMockVerificationResult(mockPartiallyVerifiedSources()), + verificationResult: groupVerificationSources(mockPartiallyVerifiedSources()), }, }; export const NotVerified: Story = { args: { - verificationResult: createMockVerificationResult(mockNotVerifiedSources()), + verificationResult: groupVerificationSources(mockNotVerifiedSources()), }, }; export const RateLimited: Story = { args: { - verificationResult: createMockVerificationResult(mockRateLimitedSources()), + verificationResult: groupVerificationSources(mockRateLimitedSources()), }, }; export const DangerousToken: Story = { args: { - verificationResult: createMockVerificationResult(mockDangerousTokenSources()), + verificationResult: groupVerificationSources(mockDangerousTokenSources()), }, }; diff --git a/app/features/token-verification-badge/ui/__stories__/TokenVerificationButton.stories.tsx b/app/features/token-verification-badge/ui/__stories__/TokenVerificationButton.stories.tsx index 7781fc22f1..6a1dc17ba4 100644 --- a/app/features/token-verification-badge/ui/__stories__/TokenVerificationButton.stories.tsx +++ b/app/features/token-verification-badge/ui/__stories__/TokenVerificationButton.stories.tsx @@ -1,31 +1,13 @@ import type { Meta, StoryObj } from '@storybook-config/types'; import { fn } from 'storybook/test'; -import { EVerificationSource, type VerificationSource } from '../../lib/types'; import { ERiskLevel } from '../../model/use-rugcheck'; import { TokenVerificationButton } from '../TokenVerificationButton'; +import { mockJupiterSource, mockRugCheckSource } from './mock-verification-data'; -const jupiterVerified: VerificationSource = { - name: EVerificationSource.Jupiter, - url: 'https://jup.ag', - verified: true, -}; - -const rugcheckGood: VerificationSource = { - level: ERiskLevel.Good, - name: EVerificationSource.RugCheck, - score: 90, - url: 'https://rugcheck.xyz', - verified: true, -}; - -const rugcheckWarning: VerificationSource = { - level: ERiskLevel.Warning, - name: EVerificationSource.RugCheck, - score: 55, - url: 'https://rugcheck.xyz', - verified: true, -}; +const jupiterVerified = mockJupiterSource(); +const rugcheckGood = mockRugCheckSource({ level: ERiskLevel.Good, score: 90 }); +const rugcheckWarning = mockRugCheckSource({ level: ERiskLevel.Warning, score: 55 }); const meta: Meta = { args: { isOpen: false, onClick: fn() }, diff --git a/app/features/token-verification-badge/ui/__stories__/TokenVerificationContent.stories.tsx b/app/features/token-verification-badge/ui/__stories__/TokenVerificationContent.stories.tsx index 9fd2e9129d..5545b64de0 100644 --- a/app/features/token-verification-badge/ui/__stories__/TokenVerificationContent.stories.tsx +++ b/app/features/token-verification-badge/ui/__stories__/TokenVerificationContent.stories.tsx @@ -1,35 +1,19 @@ import type { Meta, StoryObj } from '@storybook-config/types'; -import { EVerificationSource, type VerificationSource } from '../../lib/types'; import { ERiskLevel } from '../../model/use-rugcheck'; import { TokenVerificationContent } from '../TokenVerificationContent'; +import { mockCoinGeckoSource, mockJupiterSource, mockRugCheckSource } from './mock-verification-data'; -const jupiterVerified: VerificationSource = { - name: EVerificationSource.Jupiter, - url: 'https://jup.ag', - verified: true, -}; - -const rugcheckGood: VerificationSource = { - level: ERiskLevel.Good, - name: EVerificationSource.RugCheck, - score: 88, - url: 'https://rugcheck.xyz', - verified: true, -}; - -const rugcheckRateLimited: VerificationSource = { +const jupiterVerified = mockJupiterSource(); +const rugcheckGood = mockRugCheckSource({ level: ERiskLevel.Good, score: 88 }); +const rugcheckRateLimited = mockRugCheckSource({ isRateLimited: true, - name: EVerificationSource.RugCheck, - url: 'https://rugcheck.xyz', + isVerificationFound: false, + level: undefined, + score: undefined, verified: false, -}; - -const coingeckoApply: VerificationSource = { - applyUrl: 'https://www.coingecko.com', - name: EVerificationSource.CoinGecko, - verified: false, -}; +}); +const coingeckoApply = mockCoinGeckoSource({ isVerificationFound: false, verified: false }); const meta: Meta = { component: TokenVerificationContent, diff --git a/app/features/token-verification-badge/ui/__stories__/mock-verification-data.tsx b/app/features/token-verification-badge/ui/__stories__/mock-verification-data.tsx index c9137f24c6..478b7e6f65 100644 --- a/app/features/token-verification-badge/ui/__stories__/mock-verification-data.tsx +++ b/app/features/token-verification-badge/ui/__stories__/mock-verification-data.tsx @@ -1,6 +1,5 @@ import { EVerificationSource, VerificationSource } from '../../lib/types'; import { ERiskLevel } from '../../model/use-rugcheck'; -import { TokenVerificationResult } from '../../model/use-verification-sources'; const MOCK_ADDRESS = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; @@ -69,17 +68,3 @@ export const mockDangerousTokenSources = (): VerificationSource[] => [ mockJupiterSource({ isVerificationFound: false, verified: false }), mockRugCheckSource({ level: ERiskLevel.Danger, score: 85, verified: false }), ]; - -// Helper to create TokenVerificationResult -export const createMockVerificationResult = (sources: VerificationSource[]): TokenVerificationResult => { - const rateLimitedSources = sources.filter(s => s.isRateLimited); - const sourcesToApply = sources.filter(s => !s.verified && !s.isVerificationFound && !s.isRateLimited); - const verificationFoundSources = sources.filter(s => s.isVerificationFound); - - return { - rateLimitedSources, - sources, - sourcesToApply, - verificationFoundSources, - }; -}; diff --git a/app/features/transaction-history/model/__tests__/use-fetch-account-history.spec.tsx b/app/features/transaction-history/model/__tests__/use-fetch-account-history.spec.tsx index b09a10fea6..725bb75eb6 100644 --- a/app/features/transaction-history/model/__tests__/use-fetch-account-history.spec.tsx +++ b/app/features/transaction-history/model/__tests__/use-fetch-account-history.spec.tsx @@ -3,6 +3,7 @@ import { act, renderHook } from '@testing-library/react'; import React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { rpcStub } from '@/app/__tests__/mock-rpc'; import { waitForHook } from '@/app/__tests__/swr-hook'; vi.mock('@providers/cluster', () => ({ @@ -12,21 +13,9 @@ vi.mock('@providers/cluster', () => ({ })), })); -// The kit rpc pattern is rpc.getSignaturesForAddress(address, config).send(); the mock unwraps -// the pending-request layer so tests can queue results with plain mockResolvedValue*. const rpcMocks = vi.hoisted(() => ({ getSignaturesForAddress: vi.fn() })); -vi.mock('@entities/cluster', async () => { - const actual = await vi.importActual('@entities/cluster'); - return { - ...actual, - getRpc: () => ({ - getSignaturesForAddress: (...args: unknown[]) => ({ - send: () => rpcMocks.getSignaturesForAddress(...args), - }), - }), - }; -}); +vi.mock('@/app/entities/cluster/api/get-rpc', () => ({ getRpc: () => rpcStub(rpcMocks) })); // Must import after mocks import { FetchStatus } from '@providers/cache'; diff --git a/app/features/transaction-history/ui/__stories__/TransactionDetailsDrawer.stories.tsx b/app/features/transaction-history/ui/__stories__/TransactionDetailsDrawer.stories.tsx index 054813861d..2b5c995517 100644 --- a/app/features/transaction-history/ui/__stories__/TransactionDetailsDrawer.stories.tsx +++ b/app/features/transaction-history/ui/__stories__/TransactionDetailsDrawer.stories.tsx @@ -1,5 +1,4 @@ import { MockClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; -import { nextjsParameters } from '@storybook-config/decorators'; import type { Decorator, Meta, StoryObj } from '@storybook-config/types'; import { expect, fn, userEvent, within } from 'storybook/test'; @@ -40,7 +39,6 @@ const meta = { component: TransactionDetailsDrawer, decorators: [withCluster], parameters: { - ...nextjsParameters, viewport: { defaultViewport: 'mobile1' }, }, tags: ['autodocs', 'test'], diff --git a/app/features/transaction-share/ui/__stories__/BaseTxImage.stories.tsx b/app/features/transaction-share/ui/__stories__/BaseTxImage.stories.tsx index 964760f64e..e235a49a73 100644 --- a/app/features/transaction-share/ui/__stories__/BaseTxImage.stories.tsx +++ b/app/features/transaction-share/ui/__stories__/BaseTxImage.stories.tsx @@ -1,7 +1,7 @@ import { gen } from '@__fixtures__/gen'; import { truncateAddress } from '@entities/address'; import { type InstructionSummary, UNKNOWN_PROGRAM_NAME } from '@entities/transaction-data'; -import { IMAGE_SIZE } from '@shared/lib/og/image-size'; +import { withOgImageFrame } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; @@ -57,13 +57,7 @@ const meta: Meta = { }, args: { glows: GLOWS, signature: SIGNATURE }, component: BaseTxImage, - decorators: [ - Story => ( -
- -
- ), - ], + decorators: [withOgImageFrame], tags: ['autodocs', 'test'], title: 'Features/TransactionShare/BaseTxImage', }; diff --git a/app/features/transaction/model/__tests__/use-cluster-transaction-search.spec.ts b/app/features/transaction/model/__tests__/use-cluster-transaction-search.spec.ts index 44a33fa0b7..f1222da6ae 100644 --- a/app/features/transaction/model/__tests__/use-cluster-transaction-search.spec.ts +++ b/app/features/transaction/model/__tests__/use-cluster-transaction-search.spec.ts @@ -1,5 +1,6 @@ // @vitest-environment jsdom +import { createSolanaRpc } from '@solana/kit'; import { act, renderHook } from '@testing-library/react'; import { useSearchParams } from 'next/navigation'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -11,17 +12,9 @@ import { Cluster } from '@/app/utils/cluster'; const mockSend = vi.fn(); -vi.mock('next/navigation', () => ({ - useSearchParams: vi.fn(() => new URLSearchParams()), -})); +vi.mock('next/navigation', () => import('@/app/__tests__/next-navigation')); -vi.mock('@solana/kit', async () => { - const actual = await vi.importActual('@solana/kit'); - return { - ...actual, - createSolanaRpc: vi.fn(() => rpcStub({ getSignatureStatuses: mockSend })), - }; -}); +vi.mocked(createSolanaRpc).mockImplementation(() => rpcStub({ getSignatureStatuses: mockSend }) as never); const NOT_FOUND = { value: [null] }; const FOUND = { value: [{ confirmationStatus: 'finalized', confirmations: null, err: null, slot: 100 }] }; @@ -75,7 +68,6 @@ describe('useClusterTransactionSearch', () => { }); it('should exclude the current cluster from the probe list', async () => { - const { createSolanaRpc } = await import('@solana/kit'); const { useClusterTransactionSearch } = await import('../use-cluster-transaction-search'); renderHook(() => useClusterTransactionSearch(DEFAULT_SIGNATURE, Cluster.Mainnet)); @@ -97,7 +89,6 @@ describe('useClusterTransactionSearch', () => { typeof useSearchParams >, ); - const { createSolanaRpc } = await import('@solana/kit'); const { useClusterTransactionSearch } = await import('../use-cluster-transaction-search'); renderHook(() => useClusterTransactionSearch(DEFAULT_SIGNATURE, Cluster.Custom)); diff --git a/app/features/transaction/ui/__fixtures__/transaction.ts b/app/features/transaction/ui/__fixtures__/transaction.ts index b86d92d513..75dbcd3c16 100644 --- a/app/features/transaction/ui/__fixtures__/transaction.ts +++ b/app/features/transaction/ui/__fixtures__/transaction.ts @@ -4,13 +4,13 @@ import { createWeb3TransactionBytes } from '@entities/transaction-data/__fixture import { getBase58Decoder } from '@solana/kit'; import type { ParsedTransactionWithMeta } from '@solana/web3.js'; import { ComputeBudgetProgram, PublicKey, SystemProgram, TransactionMessage, VersionedMessage } from '@solana/web3.js'; +import { getSetComputeUnitLimitInstructionDataEncoder } from '@solana-program/compute-budget'; import { mockParsedTransactionDetails, mockRawTransactionDetails, mockTransactionStatus, } from '@storybook-config/__fixtures__/transactions'; -import { alloc, writeUint32LE } from '@/app/shared/lib/bytes'; import { parseTransactionBytes } from '@/app/shared/lib/parse-transaction-bytes'; export { DEFAULT_SIGNATURE }; @@ -120,9 +120,7 @@ export const MOCK_PARSED_TX_NO_BLOCK_TIME = mockParsedTransactionDetails({ * decoded instruction whose data is base58, which is what the requested-CU estimator reads. */ function withComputeUnitLimit(units: number) { - const data = alloc(5); - data[0] = 2; // SetComputeUnitLimit - writeUint32LE(data, units, 1); + const data = getSetComputeUnitLimitInstructionDataEncoder().encode({ units }); return { ...BASE_TX, diff --git a/app/features/transaction/ui/__fixtures__/withTransactionProviders.tsx b/app/features/transaction/ui/__fixtures__/withTransactionProviders.tsx index e51c57398f..3971d43dfc 100644 --- a/app/features/transaction/ui/__fixtures__/withTransactionProviders.tsx +++ b/app/features/transaction/ui/__fixtures__/withTransactionProviders.tsx @@ -8,10 +8,37 @@ import { import { MockAccountsProvider } from '@storybook-config/__mocks__/MockAccountsProvider'; import { MockTokenInfoBatchProvider } from '@storybook-config/__mocks__/MockTokenInfoBatchProvider'; import { MockTransactionsProvider } from '@storybook-config/__mocks__/MockTransactionsProvider'; +import type { Decorator } from '@storybook-config/types'; import React from 'react'; import { instructionParserDispatcher } from '@/app/tx/instruction-parser-dispatcher'; +import { AccountsCard } from '../AccountsCard'; +import { DEFAULT_SIGNATURE, MOCK_PARSED_TX, MOCK_STATUS } from './transaction'; + +export function accountsCardWithProviders() { + const Wrapper = withTransactionProviders( + { [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, + { [DEFAULT_SIGNATURE]: MOCK_STATUS }, + ); + return ( + + + + ); +} + +export function withTransaction(...data: Parameters): Decorator { + const Wrapper = withTransactionProviders(...data); + return function WithTransaction(Story) { + return ( + + + + ); + }; +} + export function withTransactionProviders( parsed: Record>, status: Record>, diff --git a/app/features/transaction/ui/__stories__/AccountDetailDrawer.stories.tsx b/app/features/transaction/ui/__stories__/AccountDetailDrawer.stories.tsx index 80fe44a4c0..e4881bb605 100644 --- a/app/features/transaction/ui/__stories__/AccountDetailDrawer.stories.tsx +++ b/app/features/transaction/ui/__stories__/AccountDetailDrawer.stories.tsx @@ -1,7 +1,7 @@ import { gen } from '@__fixtures__/gen'; import { ParsedMessage, ParsedMessageAccount, PublicKey, SystemProgram } from '@solana/web3.js'; import type { Meta, StoryObj } from '@storybook/nextjs-vite'; -import { nextjsParameters, withClusterAccountsAndTokenInfo } from '@storybook-config/decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import { expect, fn, within } from 'storybook/test'; import { AccountDetailDrawer } from '../AccountDetailDrawer'; @@ -31,9 +31,8 @@ const meta: Meta = { open: true, }, component: AccountDetailDrawer, - decorators: [withClusterAccountsAndTokenInfo], + decorators: [withClusterAndAccounts, withTokenInfoBatch], parameters: { - ...nextjsParameters, // Render at mobile viewport to match intended use case viewport: { defaultViewport: 'mobile1' }, }, diff --git a/app/features/transaction/ui/__stories__/AccountExpandedContent.stories.tsx b/app/features/transaction/ui/__stories__/AccountExpandedContent.stories.tsx index fb049f798a..f10ec76fe3 100644 --- a/app/features/transaction/ui/__stories__/AccountExpandedContent.stories.tsx +++ b/app/features/transaction/ui/__stories__/AccountExpandedContent.stories.tsx @@ -1,14 +1,13 @@ /* eslint-disable no-restricted-syntax -- storybook play functions use RegExp for pattern matching */ import { gen } from '@__fixtures__/gen'; +import { makeAccount } from '@entities/account/__fixtures__/account'; import { PublicKey, SystemProgram } from '@solana/web3.js'; import type { Meta, StoryObj } from '@storybook/nextjs-vite'; -import { MockAccountsProvider } from '@storybook-config/__mocks__/MockAccountsProvider'; -import { nextjsParameters, withClusterAccountsAndTokenInfo } from '@storybook-config/decorators'; -import React from 'react'; +import { withAccountsState, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import { expect, within } from 'storybook/test'; import { FetchStatus } from '@/app/providers/cache'; -import { ClusterProvider } from '@/app/providers/cluster'; +import { MAINNET_BETA_URL } from '@/app/utils/cluster'; import { AccountExpandedContent } from '../AccountExpandedContent'; @@ -22,10 +21,7 @@ const meta: Meta = { enabled: true, }, component: AccountExpandedContent, - decorators: [withClusterAccountsAndTokenInfo], - parameters: { - ...nextjsParameters, - }, + decorators: [withClusterAndAccounts, withTokenInfoBatch], tags: ['autodocs', 'test'], title: 'Features/Transaction/AccountExpandedContent', }; @@ -90,27 +86,15 @@ export const WithAccountSize: Story = { enabled: true, }, decorators: [ - Story => ( - - - - - - ), + withAccountsState({ + entries: { + [SIZED_ADDRESS]: { + data: makeAccount({ pubkey: new PublicKey(SIZED_ADDRESS), space: 1024 }), + status: FetchStatus.Fetched, + }, + }, + url: MAINNET_BETA_URL, + }), ], play: async ({ canvasElement }) => { const canvas = within(canvasElement); @@ -125,27 +109,15 @@ export const EmptyAccount: Story = { enabled: true, }, decorators: [ - Story => ( - - - - - - ), + withAccountsState({ + entries: { + [SIZED_ADDRESS]: { + data: makeAccount({ pubkey: new PublicKey(SIZED_ADDRESS), space: 0 }), + status: FetchStatus.Fetched, + }, + }, + url: MAINNET_BETA_URL, + }), ], play: async ({ canvasElement }) => { const canvas = within(canvasElement); diff --git a/app/features/transaction/ui/__stories__/AccountsCard.stories.tsx b/app/features/transaction/ui/__stories__/AccountsCard.stories.tsx index 1535d931ef..5877a6a048 100644 --- a/app/features/transaction/ui/__stories__/AccountsCard.stories.tsx +++ b/app/features/transaction/ui/__stories__/AccountsCard.stories.tsx @@ -1,4 +1,3 @@ -import { nextjsParameters } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { @@ -8,7 +7,7 @@ import { MOCK_PARSED_TX, MOCK_STATUS, } from '../__fixtures__/transaction'; -import { withTransactionProviders } from '../__fixtures__/withTransactionProviders'; +import { withTransaction } from '../__fixtures__/withTransactionProviders'; import { AccountsCard } from '../AccountsCard'; const meta: Meta = { @@ -16,9 +15,6 @@ const meta: Meta = { signature: DEFAULT_SIGNATURE, }, component: AccountsCard, - parameters: { - ...nextjsParameters, - }, tags: ['autodocs', 'test'], title: 'Features/Transaction/AccountsCard', }; @@ -27,46 +23,13 @@ export default meta; type Story = StoryObj; export const WithAccounts: Story = { - decorators: [ - Story => { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, - { [DEFAULT_SIGNATURE]: MOCK_STATUS }, - ); - return ( - - - - ); - }, - ], + decorators: [withTransaction({ [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, { [DEFAULT_SIGNATURE]: MOCK_STATUS })], }; export const FailedTransaction: Story = { - decorators: [ - Story => { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_FAILED_TX }, - { [DEFAULT_SIGNATURE]: MOCK_FAILED_STATUS }, - ); - return ( - - - - ); - }, - ], + decorators: [withTransaction({ [DEFAULT_SIGNATURE]: MOCK_FAILED_TX }, { [DEFAULT_SIGNATURE]: MOCK_FAILED_STATUS })], }; export const NoTransaction: Story = { - decorators: [ - Story => { - const Wrapper = withTransactionProviders({}, {}); - return ( - - - - ); - }, - ], + decorators: [withTransaction({}, {})], }; diff --git a/app/features/transaction/ui/__stories__/InstructionsSection.stories.tsx b/app/features/transaction/ui/__stories__/InstructionsSection.stories.tsx index 6ada2699bf..0694c3b322 100644 --- a/app/features/transaction/ui/__stories__/InstructionsSection.stories.tsx +++ b/app/features/transaction/ui/__stories__/InstructionsSection.stories.tsx @@ -1,4 +1,3 @@ -import { nextjsParameters } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { @@ -8,7 +7,7 @@ import { MOCK_PARSED_TX, MOCK_STATUS, } from '../__fixtures__/transaction'; -import { withTransactionProviders } from '../__fixtures__/withTransactionProviders'; +import { withTransaction } from '../__fixtures__/withTransactionProviders'; import { InstructionsSection } from '../InstructionsSection'; const meta: Meta = { @@ -16,9 +15,6 @@ const meta: Meta = { signature: DEFAULT_SIGNATURE, }, component: InstructionsSection, - parameters: { - ...nextjsParameters, - }, tags: ['autodocs', 'test'], title: 'Features/Transaction/InstructionsSection', }; @@ -27,46 +23,13 @@ export default meta; type Story = StoryObj; export const SystemTransfer: Story = { - decorators: [ - Story => { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, - { [DEFAULT_SIGNATURE]: MOCK_STATUS }, - ); - return ( - - - - ); - }, - ], + decorators: [withTransaction({ [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, { [DEFAULT_SIGNATURE]: MOCK_STATUS })], }; export const FailedTransaction: Story = { - decorators: [ - Story => { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_FAILED_TX }, - { [DEFAULT_SIGNATURE]: MOCK_FAILED_STATUS }, - ); - return ( - - - - ); - }, - ], + decorators: [withTransaction({ [DEFAULT_SIGNATURE]: MOCK_FAILED_TX }, { [DEFAULT_SIGNATURE]: MOCK_FAILED_STATUS })], }; export const NoDetails: Story = { - decorators: [ - Story => { - const Wrapper = withTransactionProviders({}, { [DEFAULT_SIGNATURE]: MOCK_STATUS }); - return ( - - - - ); - }, - ], + decorators: [withTransaction({}, { [DEFAULT_SIGNATURE]: MOCK_STATUS })], }; diff --git a/app/features/transaction/ui/__stories__/ProgramLogSection.stories.tsx b/app/features/transaction/ui/__stories__/ProgramLogSection.stories.tsx index a0df3511ed..68c7d5a97e 100644 --- a/app/features/transaction/ui/__stories__/ProgramLogSection.stories.tsx +++ b/app/features/transaction/ui/__stories__/ProgramLogSection.stories.tsx @@ -1,4 +1,3 @@ -import { nextjsParameters } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { @@ -9,7 +8,7 @@ import { MOCK_PARSED_TX, MOCK_STATUS, } from '../__fixtures__/transaction'; -import { withTransactionProviders } from '../__fixtures__/withTransactionProviders'; +import { withTransaction } from '../__fixtures__/withTransactionProviders'; import { ProgramLogSection } from '../ProgramLogSection'; const meta: Meta = { @@ -17,9 +16,6 @@ const meta: Meta = { signature: DEFAULT_SIGNATURE, }, component: ProgramLogSection, - parameters: { - ...nextjsParameters, - }, tags: ['autodocs', 'test'], title: 'Features/Transaction/ProgramLogSection', }; @@ -28,49 +24,13 @@ export default meta; type Story = StoryObj; export const SuccessfulLogs: Story = { - decorators: [ - Story => { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, - { [DEFAULT_SIGNATURE]: MOCK_STATUS }, - ); - return ( - - - - ); - }, - ], + decorators: [withTransaction({ [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, { [DEFAULT_SIGNATURE]: MOCK_STATUS })], }; export const FailedLogs: Story = { - decorators: [ - Story => { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_FAILED_TX }, - { [DEFAULT_SIGNATURE]: MOCK_FAILED_STATUS }, - ); - return ( - - - - ); - }, - ], + decorators: [withTransaction({ [DEFAULT_SIGNATURE]: MOCK_FAILED_TX }, { [DEFAULT_SIGNATURE]: MOCK_FAILED_STATUS })], }; export const NoLogs: Story = { - decorators: [ - Story => { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_NO_LOGS_TX }, - { [DEFAULT_SIGNATURE]: MOCK_STATUS }, - ); - return ( - - - - ); - }, - ], + decorators: [withTransaction({ [DEFAULT_SIGNATURE]: MOCK_NO_LOGS_TX }, { [DEFAULT_SIGNATURE]: MOCK_STATUS })], }; diff --git a/app/features/transaction/ui/__stories__/SummaryCard.stories.tsx b/app/features/transaction/ui/__stories__/SummaryCard.stories.tsx index 0b6fab6622..b5abf7aa2d 100644 --- a/app/features/transaction/ui/__stories__/SummaryCard.stories.tsx +++ b/app/features/transaction/ui/__stories__/SummaryCard.stories.tsx @@ -1,5 +1,4 @@ import { mockTransactionStatus } from '@storybook-config/__fixtures__/transactions'; -import { nextjsParameters } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { AutoRefresh } from '@/app/shared/lib/use-auto-refresh'; @@ -15,7 +14,7 @@ import { MOCK_RAW_TX_NO_BLOCK_TIME, MOCK_STATUS, } from '../__fixtures__/transaction'; -import { withTransactionProviders } from '../__fixtures__/withTransactionProviders'; +import { withTransaction } from '../__fixtures__/withTransactionProviders'; import { SummaryCard } from '../SummaryCard'; const meta: Meta = { @@ -24,9 +23,6 @@ const meta: Meta = { signature: DEFAULT_SIGNATURE, }, component: SummaryCard, - parameters: { - ...nextjsParameters, - }, tags: ['autodocs', 'test'], title: 'Features/Transaction/SummaryCard', }; @@ -36,18 +32,11 @@ type Story = StoryObj; export const Finalized: Story = { decorators: [ - Story => { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, - { [DEFAULT_SIGNATURE]: MOCK_STATUS }, - { [DEFAULT_SIGNATURE]: MOCK_RAW_TX }, - ); - return ( - - - - ); - }, + withTransaction( + { [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, + { [DEFAULT_SIGNATURE]: MOCK_STATUS }, + { [DEFAULT_SIGNATURE]: MOCK_RAW_TX }, + ), ], }; @@ -56,55 +45,24 @@ export const Confirming: Story = { autoRefresh: AutoRefresh.Active, }, decorators: [ - Story => { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, - { - [DEFAULT_SIGNATURE]: mockTransactionStatus({ - confirmationStatus: 'confirmed', - confirmations: 10, - }), - }, - ); - return ( - - - - ); - }, + withTransaction( + { [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, + { [DEFAULT_SIGNATURE]: mockTransactionStatus({ confirmationStatus: 'confirmed', confirmations: 10 }) }, + ), ], }; export const Failed: Story = { - decorators: [ - Story => { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_FAILED_TX }, - { [DEFAULT_SIGNATURE]: MOCK_FAILED_STATUS }, - ); - return ( - - - - ); - }, - ], + decorators: [withTransaction({ [DEFAULT_SIGNATURE]: MOCK_FAILED_TX }, { [DEFAULT_SIGNATURE]: MOCK_FAILED_STATUS })], }; export const NoTimestamp: Story = { decorators: [ - Story => { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_PARSED_TX_NO_BLOCK_TIME }, - { [DEFAULT_SIGNATURE]: mockTransactionStatus() }, - { [DEFAULT_SIGNATURE]: MOCK_RAW_TX_NO_BLOCK_TIME }, - ); - return ( - - - - ); - }, + withTransaction( + { [DEFAULT_SIGNATURE]: MOCK_PARSED_TX_NO_BLOCK_TIME }, + { [DEFAULT_SIGNATURE]: mockTransactionStatus() }, + { [DEFAULT_SIGNATURE]: MOCK_RAW_TX_NO_BLOCK_TIME }, + ), ], }; @@ -117,17 +75,10 @@ export const NoTimestamp: Story = { */ export const LooseComputeBudget: Story = { decorators: [ - Story => { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_LOOSE_BUDGET_TX }, - { [DEFAULT_SIGNATURE]: MOCK_STATUS }, - { [DEFAULT_SIGNATURE]: MOCK_RAW_TX }, - ); - return ( - - - - ); - }, + withTransaction( + { [DEFAULT_SIGNATURE]: MOCK_LOOSE_BUDGET_TX }, + { [DEFAULT_SIGNATURE]: MOCK_STATUS }, + { [DEFAULT_SIGNATURE]: MOCK_RAW_TX }, + ), ], }; diff --git a/app/features/transaction/ui/__stories__/TokenBalancesCard.responsive.stories.tsx b/app/features/transaction/ui/__stories__/TokenBalancesCard.responsive.stories.tsx index 07c595d388..23bc4aa2ea 100644 --- a/app/features/transaction/ui/__stories__/TokenBalancesCard.responsive.stories.tsx +++ b/app/features/transaction/ui/__stories__/TokenBalancesCard.responsive.stories.tsx @@ -1,35 +1,12 @@ -import { PublicKey } from '@solana/web3.js'; -import { nextjsParameters, withMockTransactions, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; -import BigNumber from 'bignumber.js'; -import { TokenBalancesCardInner, type TokenBalancesCardInnerProps } from '../TokenBalancesCard'; - -const sampleRows: TokenBalancesCardInnerProps['rows'] = [ - { - account: new PublicKey('11111111111111111111111111111111'), - accountIndex: 0, - balance: '1.234', - delta: new BigNumber('1.234'), - mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', - }, - { - account: new PublicKey('SysvarRent111111111111111111111111111111111'), - accountIndex: 1, - balance: '42.0', - delta: new BigNumber('-0.5'), - mint: 'So11111111111111111111111111111111111111112', - }, -]; +import { TokenBalancesCardInner } from '../TokenBalancesCard'; +import * as Base from './TokenBalancesCard.stories'; const meta: Meta = { component: TokenBalancesCardInner, - decorators: [withTokenInfoBatch, withMockTransactions, withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withViewportFromGlobal], tags: ['autodocs', 'test'], title: 'Components/Transaction/TokenBalancesCard@Media', }; @@ -37,8 +14,8 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { rows: sampleRows }; +const { args, decorators } = Base.Inner_MultipleRows; -export const Mobile: Story = { args, globals: { viewport: { value: 'iphonex' } } }; -export const TabletPortrait: Story = { args, globals: { viewport: { value: 'ipad' } } }; -export const TabletLandscape: Story = { args, globals: { viewport: { isRotated: true, value: 'ipad' } } }; +export const Mobile: Story = { args, decorators, globals: { viewport: { value: 'iphonex' } } }; +export const TabletPortrait: Story = { args, decorators, globals: { viewport: { value: 'ipad' } } }; +export const TabletLandscape: Story = { args, decorators, globals: { viewport: { isRotated: true, value: 'ipad' } } }; diff --git a/app/features/transaction/ui/__stories__/TokenBalancesCard.stories.tsx b/app/features/transaction/ui/__stories__/TokenBalancesCard.stories.tsx index 15145fc95d..ace6604493 100644 --- a/app/features/transaction/ui/__stories__/TokenBalancesCard.stories.tsx +++ b/app/features/transaction/ui/__stories__/TokenBalancesCard.stories.tsx @@ -1,14 +1,10 @@ -import { ClusterProvider } from '@providers/cluster'; import { PublicKey } from '@solana/web3.js'; -import { MockAccountsProvider } from '@storybook-config/__mocks__/MockAccountsProvider'; -import { MockTokenInfoBatchProvider } from '@storybook-config/__mocks__/MockTokenInfoBatchProvider'; -import { nextjsParameters } from '@storybook-config/decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { BigNumber } from 'bignumber.js'; -import React from 'react'; import { DEFAULT_SIGNATURE, MOCK_PARSED_TX, MOCK_STATUS, RECIPIENT, TOKEN_MINT } from '../__fixtures__/transaction'; -import { withTransactionProviders } from '../__fixtures__/withTransactionProviders'; +import { withTransaction } from '../__fixtures__/withTransactionProviders'; import { TokenBalancesCard, TokenBalancesCardInner } from '../TokenBalancesCard'; const metaConnected: Meta = { @@ -16,9 +12,6 @@ const metaConnected: Meta = { signature: DEFAULT_SIGNATURE, }, component: TokenBalancesCard, - parameters: { - ...nextjsParameters, - }, tags: ['autodocs', 'test'], title: 'Features/Transaction/TokenBalancesCard', }; @@ -27,32 +20,11 @@ export default metaConnected; type Story = StoryObj; export const WithTokenBalances: Story = { - decorators: [ - Story => { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, - { [DEFAULT_SIGNATURE]: MOCK_STATUS }, - ); - return ( - - - - ); - }, - ], + decorators: [withTransaction({ [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, { [DEFAULT_SIGNATURE]: MOCK_STATUS })], }; export const NoBalanceChanges: Story = { - decorators: [ - Story => { - const Wrapper = withTransactionProviders({}, {}); - return ( - - - - ); - }, - ], + decorators: [withTransaction({}, {})], }; const SAMPLE_ROWS = [ @@ -78,43 +50,22 @@ export const Inner_MultipleRows: StoryObj = { args: { rows: SAMPLE_ROWS, }, - render: args => ( - - - - - - - - ), + decorators: [withClusterAndAccounts, withTokenInfoBatch], + render: args => , }; export const Inner_PositiveDelta: StoryObj = { args: { rows: [SAMPLE_ROWS[0]], }, - render: args => ( - - - - - - - - ), + decorators: [withClusterAndAccounts, withTokenInfoBatch], + render: args => , }; export const Inner_NegativeDelta: StoryObj = { args: { rows: [SAMPLE_ROWS[1]], }, - render: args => ( - - - - - - - - ), + decorators: [withClusterAndAccounts, withTokenInfoBatch], + render: args => , }; diff --git a/app/features/transaction/ui/__tests__/AccountExpandedContent-raw-data.spec.tsx b/app/features/transaction/ui/__tests__/AccountExpandedContent-raw-data.spec.tsx index 3148c0b604..a086797d28 100644 --- a/app/features/transaction/ui/__tests__/AccountExpandedContent-raw-data.spec.tsx +++ b/app/features/transaction/ui/__tests__/AccountExpandedContent-raw-data.spec.tsx @@ -1,5 +1,5 @@ import { gen } from '@__fixtures__/gen'; -import { PublicKey } from '@solana/web3.js'; +import { makeAccount } from '@entities/account/__fixtures__/account'; import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { SWRConfig } from 'swr'; @@ -9,18 +9,11 @@ vi.mock('next/navigation'); const mockGetAccountInfo = vi.fn(); -vi.mock('@entities/cluster/@x/account', async () => { - const actual = await vi.importActual('@entities/cluster/@x/account'); - return { - ...actual, - getRpc: vi.fn(() => ({ - getAccountInfo: (...args: unknown[]) => ({ - send: async () => ({ value: await mockGetAccountInfo(...args) }), - }), - })), - }; -}); +vi.mock('@/app/entities/cluster/api/get-rpc', () => ({ + getRpc: () => rpcValueStub({ getAccountInfo: mockGetAccountInfo }), +})); +import { rpcValueStub } from '@/app/__tests__/mock-rpc'; import type { Account } from '@/app/providers/accounts'; import { ClusterProvider } from '@/app/providers/cluster'; import { toBase64 } from '@/app/shared/lib/bytes'; @@ -32,14 +25,7 @@ const ADDRESS = PUBKEY.toBase58(); const ACCOUNT_BYTES = new Uint8Array([0xde, 0xad, 0xbe, 0xef]); const ACCOUNT_HEX = 'de ad be ef'; -const account: Account = { - data: {}, - executable: false, - lamports: 1_000_000_000, - owner: PublicKey.default, - pubkey: PUBKEY, - space: 4, -} as Account; +const account = makeAccount({ pubkey: PUBKEY, space: 4 }); describe('transaction::AccountExpandedContent raw data', () => { beforeEach(() => { diff --git a/app/features/transaction/ui/__tests__/AccountsCard-drawer.spec.tsx b/app/features/transaction/ui/__tests__/AccountsCard-drawer.spec.tsx index 5628b588a2..fc301dacb5 100644 --- a/app/features/transaction/ui/__tests__/AccountsCard-drawer.spec.tsx +++ b/app/features/transaction/ui/__tests__/AccountsCard-drawer.spec.tsx @@ -4,9 +4,8 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; vi.mock('next/navigation'); -import { DEFAULT_SIGNATURE, FEE_PAYER, MOCK_PARSED_TX, MOCK_STATUS } from '../__fixtures__/transaction'; -import { withTransactionProviders } from '../__fixtures__/withTransactionProviders'; -import { AccountsCard } from '../AccountsCard'; +import { FEE_PAYER } from '../__fixtures__/transaction'; +import { accountsCardWithProviders } from '../__fixtures__/withTransactionProviders'; const LG_WIDTH = 992; const MOBILE_WIDTH = 375; @@ -20,7 +19,7 @@ describe('transaction::AccountsCard drawer', () => { afterEach(() => vi.restoreAllMocks()); test('should open the tapped account', async () => { - renderCard(); + render(accountsCardWithProviders()); await tapFeePayer(); @@ -30,7 +29,7 @@ describe('transaction::AccountsCard drawer', () => { }); test('should close on Close', async () => { - renderCard(); + render(accountsCardWithProviders()); await tapFeePayer(); await screen.findByRole('dialog'); @@ -40,7 +39,7 @@ describe('transaction::AccountsCard drawer', () => { }); test('should open again after a close', async () => { - renderCard(); + render(accountsCardWithProviders()); await tapFeePayer(); await userEvent.click(await screen.findByRole('button', { name: 'Close' })); await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); @@ -51,7 +50,7 @@ describe('transaction::AccountsCard drawer', () => { }); test('should stay closed after the viewport widens and narrows again', async () => { - renderCard(); + render(accountsCardWithProviders()); await tapFeePayer(); await screen.findByRole('dialog'); @@ -64,18 +63,6 @@ describe('transaction::AccountsCard drawer', () => { }); }); -function renderCard() { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, - { [DEFAULT_SIGNATURE]: MOCK_STATUS }, - ); - return render( - - - , - ); -} - async function tapFeePayer() { await userEvent.click(screen.getAllByText(FEE_PAYER.toBase58())[0]); } diff --git a/app/features/transaction/ui/__tests__/AccountsCard-expanded.spec.tsx b/app/features/transaction/ui/__tests__/AccountsCard-expanded.spec.tsx index 06d6ba35a0..ea82b6f0b5 100644 --- a/app/features/transaction/ui/__tests__/AccountsCard-expanded.spec.tsx +++ b/app/features/transaction/ui/__tests__/AccountsCard-expanded.spec.tsx @@ -4,15 +4,13 @@ import { describe, expect, test, vi } from 'vitest'; vi.mock('next/navigation'); -import { DEFAULT_SIGNATURE, MOCK_PARSED_TX, MOCK_STATUS } from '../__fixtures__/transaction'; -import { withTransactionProviders } from '../__fixtures__/withTransactionProviders'; -import { AccountsCard } from '../AccountsCard'; +import { accountsCardWithProviders } from '../__fixtures__/withTransactionProviders'; const TOKEN_ACCOUNT_ROW = 2; describe('transaction::AccountsCard expanded content', () => { test('should show the account details when a row expands', async () => { - renderCard(); + render(accountsCardWithProviders()); await expandRow(TOKEN_ACCOUNT_ROW); @@ -21,7 +19,7 @@ describe('transaction::AccountsCard expanded content', () => { }); test('should show no details for a row that stays collapsed', async () => { - renderCard(); + render(accountsCardWithProviders()); await expandRow(TOKEN_ACCOUNT_ROW); await screen.findByText('Allocated Data Size'); @@ -30,7 +28,7 @@ describe('transaction::AccountsCard expanded content', () => { }); test('should show the details again after a collapse', async () => { - renderCard(); + render(accountsCardWithProviders()); await expandRow(TOKEN_ACCOUNT_ROW); await screen.findByText('Allocated Data Size'); @@ -43,18 +41,6 @@ describe('transaction::AccountsCard expanded content', () => { }); }); -function renderCard() { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, - { [DEFAULT_SIGNATURE]: MOCK_STATUS }, - ); - return render( - - - , - ); -} - async function expandRow(index: number) { await userEvent.click(screen.getAllByRole('button', { name: 'Expand account details' })[index]); } diff --git a/app/features/transaction/ui/__tests__/AccountsCard-total.spec.tsx b/app/features/transaction/ui/__tests__/AccountsCard-total.spec.tsx index 7aa5b9d2fd..5d065365ac 100644 --- a/app/features/transaction/ui/__tests__/AccountsCard-total.spec.tsx +++ b/app/features/transaction/ui/__tests__/AccountsCard-total.spec.tsx @@ -1,26 +1,19 @@ import { act, render, screen } from '@testing-library/react'; -import { SWRConfig } from 'swr'; import { beforeEach, describe, expect, test, vi } from 'vitest'; +import { rpcValueStub } from '@/app/__tests__/mock-rpc'; +import { swrWrapper } from '@/app/__tests__/swr-hook'; + vi.mock('next/navigation'); const mockGetMultipleAccounts = vi.fn(); -vi.mock('@entities/cluster/@x/account', async () => { - const actual = await vi.importActual('@entities/cluster/@x/account'); - return { - ...actual, - getRpc: vi.fn(() => ({ - getMultipleAccounts: (...args: unknown[]) => ({ - send: async () => ({ value: await mockGetMultipleAccounts(...args) }), - }), - })), - }; -}); +vi.mock('@/app/entities/cluster/api/get-rpc', () => ({ + getRpc: () => rpcValueStub({ getMultipleAccounts: mockGetMultipleAccounts }), +})); -import { DEFAULT_SIGNATURE, FEE_PAYER, MOCK_PARSED_TX, MOCK_STATUS } from '../__fixtures__/transaction'; -import { withTransactionProviders } from '../__fixtures__/withTransactionProviders'; -import { AccountsCard } from '../AccountsCard'; +import { FEE_PAYER } from '../__fixtures__/transaction'; +import { accountsCardWithProviders } from '../__fixtures__/withTransactionProviders'; describe('transaction::AccountsCard total size', () => { beforeEach(() => { @@ -70,17 +63,7 @@ describe('transaction::AccountsCard total size', () => { }); function renderCard() { - const Wrapper = withTransactionProviders( - { [DEFAULT_SIGNATURE]: MOCK_PARSED_TX }, - { [DEFAULT_SIGNATURE]: MOCK_STATUS }, - ); - return render( - new Map() }}> - - - - , - ); + return render(accountsCardWithProviders(), { wrapper: swrWrapper() }); } async function sizesAnswered() { diff --git a/app/features/transaction/ui/__tests__/InstructionsSection-CardFallback.spec.tsx b/app/features/transaction/ui/__tests__/InstructionsSection-CardFallback.spec.tsx index bf8483e36f..444d9b9910 100644 --- a/app/features/transaction/ui/__tests__/InstructionsSection-CardFallback.spec.tsx +++ b/app/features/transaction/ui/__tests__/InstructionsSection-CardFallback.spec.tsx @@ -1,5 +1,6 @@ import { DEFAULT_SIGNATURE, gen } from '@__fixtures__/gen'; import { type InstructionNode, useInstructionSurface } from '@entities/instruction-card'; +import { buildParsedTransaction } from '@entities/transaction-data/__fixtures__/parsed-transactions'; import { WORMHOLE_PROGRAM_IDS } from '@explorer/decoder-wormhole/detection'; import { LIGHTHOUSE_ADDRESS } from '@features/decode-instruction-lighthouse'; import { MPL_TOKEN_METADATA_PROGRAM_ID } from '@metaplex-foundation/mpl-token-metadata'; @@ -8,7 +9,7 @@ import { getBase58Decoder } from '@solana/kit'; import { ComputeBudgetProgram, type ParsedInstruction, - type ParsedTransaction, + type ParsedTransactionWithMeta, type PartiallyDecodedInstruction, PublicKey, SystemProgram, @@ -61,7 +62,7 @@ const PARSED_TRANSFER_IX: ParsedInstruction = { programId: SystemProgram.programId, }; -let transactionWithMeta: { meta: unknown; slot: number; transaction: ParsedTransaction }; +let transactionWithMeta: ParsedTransactionWithMeta; vi.mock('@features/decode-instruction-lighthouse', async importOriginal => ({ ...(await importOriginal()), @@ -97,22 +98,9 @@ vi.mock('@components/instruction/system/SystemDetailsCard', () => ({ }, })); -vi.mock('swr', () => ({ - __esModule: true, - default: vi.fn(() => ({ - data: undefined, - error: undefined, - isLoading: false, - isValidating: false, - mutate: vi.fn(), - })), -})); +vi.mock('swr', async () => (await import('@/app/__tests__/swr-idle')).idleSwrModule); -vi.mock('next/navigation', () => ({ - usePathname: vi.fn(() => '/'), - useRouter: vi.fn(() => ({ push: vi.fn(), replace: vi.fn() })), - useSearchParams: vi.fn(() => new URLSearchParams()), -})); +vi.mock('next/navigation', () => import('@/app/__tests__/next-navigation')); vi.mock('next/link', () => ({ __esModule: true, @@ -212,19 +200,12 @@ function renderSection( instructions: (ParsedInstruction | PartiallyDecodedInstruction)[], inner: (ParsedInstruction | PartiallyDecodedInstruction)[] = [], ) { - transactionWithMeta = { - meta: { innerInstructions: [{ index: 0, instructions: inner }] }, + transactionWithMeta = buildParsedTransaction({ + accountKeys: [PAYER], + innerInstructions: [{ index: 0, instructions: inner }], + instructions, slot: INNER_INSTRUCTIONS_START_SLOT, - transaction: { - message: { - accountKeys: [{ pubkey: PAYER, signer: true, source: 'transaction', writable: true }], - addressTableLookups: null, - instructions, - recentBlockhash: PublicKey.default.toBase58(), - }, - signatures: [DEFAULT_SIGNATURE], - } as unknown as ParsedTransaction, - }; + }); return render( diff --git a/app/features/transaction/ui/__tests__/InstructionsSection-Pmp.spec.tsx b/app/features/transaction/ui/__tests__/InstructionsSection-Pmp.spec.tsx index 887da8a837..ccac731fe6 100644 --- a/app/features/transaction/ui/__tests__/InstructionsSection-Pmp.spec.tsx +++ b/app/features/transaction/ui/__tests__/InstructionsSection-Pmp.spec.tsx @@ -3,8 +3,9 @@ import { DEFAULT_SIGNATURE, gen } from '@__fixtures__/gen'; // From the literal's own library-free module: the feature no longer re-exports it, and this spec only needs the // program id to build a fixture instruction - not the decoders that `@entities/pmp-account` would pull in. import { PMP_ADDRESS } from '@entities/pmp-account/lib/program-address'; +import { buildParsedTransaction } from '@entities/transaction-data/__fixtures__/parsed-transactions'; import { getBase58Decoder } from '@solana/kit'; -import { type ParsedTransaction, PublicKey } from '@solana/web3.js'; +import { PublicKey } from '@solana/web3.js'; import { Compression, DataSource, @@ -34,40 +35,28 @@ const SET_DATA = getSetDataInstructionDataEncoder().encode({ format: Format.Json, }) as Uint8Array; -// A minimal ParsedTransaction with one PMP instruction. `intoTransactionInstruction` looks each ix account up in +// A transaction with one PMP instruction. `intoTransactionInstruction` looks each ix account up in // `message.accountKeys` and base58-decodes `data`, so both have to line up for the raw path to produce an ix. // Built once at module scope for a stable identity across renders. Safe to reference from the vi.mock factory // below even though vi.mock is hoisted, because it is only ever READ inside the returned arrow, which runs at -// render time. `as unknown as` because the fixture carries only the fields the section actually reads. -const PARSED_TX = { - message: { - accountKeys: [ - { pubkey: METADATA, signer: false, source: 'transaction', writable: true }, - { pubkey: AUTHORITY, signer: true, source: 'transaction', writable: false }, - ], - addressTableLookups: null, - instructions: [ - { - accounts: [METADATA, AUTHORITY], - data: BASE58_DECODER.decode(SET_DATA), - programId: new PublicKey(PMP_ADDRESS), - }, - ], - recentBlockhash: PublicKey.default.toBase58(), - }, - signatures: [SIGNATURE], -} as unknown as ParsedTransaction; +// render time. +const PARSED_TX = buildParsedTransaction({ + accountKeys: [ + { pubkey: METADATA, signer: false }, + { pubkey: AUTHORITY, signer: true, writable: false }, + ], + instructions: [ + { + accounts: [METADATA, AUTHORITY], + data: BASE58_DECODER.decode(SET_DATA), + programId: new PublicKey(PMP_ADDRESS), + }, + ], + meta: null, + slot: 1, +}); -vi.mock('swr', () => ({ - __esModule: true, - default: vi.fn(() => ({ - data: undefined, - error: undefined, - isLoading: false, - isValidating: false, - mutate: vi.fn(), - })), -})); +vi.mock('swr', async () => (await import('@/app/__tests__/swr-idle')).idleSwrModule); vi.mock('next/navigation', () => import('@/app/__tests__/next-navigation')); @@ -76,7 +65,7 @@ vi.mock('next/navigation', () => import('@/app/__tests__/next-navigation')); vi.mock('@providers/transactions', async importOriginal => ({ ...(await importOriginal()), useTransactionDetails: vi.fn(() => ({ - data: { transactionWithMeta: { meta: null, slot: 1, transaction: PARSED_TX } }, + data: { transactionWithMeta: PARSED_TX }, })), useTransactionStatus: vi.fn(() => ({ data: { info: { result: { err: null } } } })), })); diff --git a/app/features/transaction/ui/__tests__/TransactionNotFoundCard.spec.tsx b/app/features/transaction/ui/__tests__/TransactionNotFoundCard.spec.tsx index 2afd927935..1c2dc48208 100644 --- a/app/features/transaction/ui/__tests__/TransactionNotFoundCard.spec.tsx +++ b/app/features/transaction/ui/__tests__/TransactionNotFoundCard.spec.tsx @@ -1,3 +1,4 @@ +import { createSolanaRpc } from '@solana/kit'; import { act, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -19,20 +20,11 @@ vi.mock('@/app/utils/url', () => ({ useClusterPath: vi.fn(({ pathname }: { pathname: string }) => pathname), })); -// Mock next/navigation -vi.mock('next/navigation', () => ({ - useSearchParams: vi.fn(() => new URLSearchParams()), -})); +vi.mock('next/navigation', () => import('@/app/__tests__/next-navigation')); // Mock createSolanaRpc: by default all clusters return null (not found) const mockSend = vi.fn().mockResolvedValue({ value: [null] }); -vi.mock('@solana/kit', async () => { - const actual = await vi.importActual('@solana/kit'); - return { - ...actual, - createSolanaRpc: vi.fn(() => rpcStub({ getSignatureStatuses: mockSend })), - }; -}); +vi.mocked(createSolanaRpc).mockImplementation(() => rpcStub({ getSignatureStatuses: mockSend }) as never); describe('TransactionNotFoundCard', () => { beforeEach(() => { diff --git a/app/features/vote/model/__tests__/vote-accounts.spec.tsx b/app/features/vote/model/__tests__/vote-accounts.spec.tsx index 28b1ca2c83..a11f0a5cc0 100644 --- a/app/features/vote/model/__tests__/vote-accounts.spec.tsx +++ b/app/features/vote/model/__tests__/vote-accounts.spec.tsx @@ -3,9 +3,11 @@ import { Cluster, ClusterStatus } from '@utils/cluster'; import { type SWRConfiguration } from 'swr'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { reported } from '@/app/__tests__/rpc-errors'; import { type ClusterContext, clusterContext, + connectedTo, FAST_RETRY, refocusTab, renderHookWithRevalidate, @@ -28,11 +30,6 @@ const mocks = vi.hoisted(() => ({ getVoteAccounts: vi.fn(), })); -/** A connected endpoint the visitor has settled on. */ -function connectedTo(cluster: Cluster, url: string) { - return clusterContext({ cluster, connectableUrl: url, status: ClusterStatus.Connected, url }); -} - vi.mock('@entities/cluster', () => ({ getRpc: mocks.getRpc, useCluster: () => mocks.cluster })); const RESPONSE = { @@ -82,10 +79,7 @@ describe('useVoteAccounts', () => { // and context outside `sentryExtras` never reaches Sentry, so a plain field goes nowhere at all. expect(Logger.warn).toHaveBeenCalledWith( expect.any(String), - expect.objectContaining({ - sentry: true, - sentryExtras: expect.objectContaining({ cluster: Cluster.Mainnet, rpcError: 'rpc down' }), - }), + reported({ cluster: Cluster.Mainnet, rpcError: 'rpc down' }), ); // One slow cluster must not be able to set the *error* rate: this fires from the browser, once per // visitor, with no CDN in front of it and no rate limit behind it. diff --git a/app/features/vote/ui/__stories__/VoteAccountSection.responsive.stories.tsx b/app/features/vote/ui/__stories__/VoteAccountSection.responsive.stories.tsx index e698af0232..8d827351d3 100644 --- a/app/features/vote/ui/__stories__/VoteAccountSection.responsive.stories.tsx +++ b/app/features/vote/ui/__stories__/VoteAccountSection.responsive.stories.tsx @@ -1,18 +1,13 @@ -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withMockRpc, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { VoteAccountSection } from '../VoteAccountSection'; -import { accountFixture, BASE_SLOT, voteAccountV4Fixture } from './fixtures'; +import * as Base from './VoteAccountSection.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta = { component: VoteAccountSection, - decorators: [withMockRpc, withViewportFromGlobal, withClusterAndAccounts, withTokenInfoBatch], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withViewportFromGlobal, ...Base.default.decorators], tags: ['autodocs', 'test'], title: 'Features/Vote/VoteAccountSection@Media', } satisfies Meta; @@ -20,10 +15,7 @@ const meta = { export default meta; type Story = StoryObj; -const args = { - account: accountFixture(), - voteAccount: voteAccountV4Fixture([{ confirmationCount: 31, slot: BASE_SLOT }]), -}; +const args = Base.V4.args; export const Mobile: Story = { args, diff --git a/app/features/vote/ui/__stories__/VoteAccountSection.stories.tsx b/app/features/vote/ui/__stories__/VoteAccountSection.stories.tsx index 1cb04066e5..64f97661fe 100644 --- a/app/features/vote/ui/__stories__/VoteAccountSection.stories.tsx +++ b/app/features/vote/ui/__stories__/VoteAccountSection.stories.tsx @@ -1,4 +1,4 @@ -import { nextjsParameters, withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; +import { withClusterAndAccounts, withTokenInfoBatch } from '@storybook-config/decorators'; import { withMockRpc } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; @@ -9,7 +9,6 @@ import { accountFixture, BASE_SLOT, voteAccountFixture, voteAccountV4Fixture } f const meta = { component: VoteAccountSection, decorators: [withMockRpc, withClusterAndAccounts, withTokenInfoBatch], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/Vote/VoteAccountSection', } satisfies Meta; diff --git a/app/features/vote/ui/__stories__/VoteDetailsCard.responsive.stories.tsx b/app/features/vote/ui/__stories__/VoteDetailsCard.responsive.stories.tsx index c968eb8e1c..982e3acaa6 100644 --- a/app/features/vote/ui/__stories__/VoteDetailsCard.responsive.stories.tsx +++ b/app/features/vote/ui/__stories__/VoteDetailsCard.responsive.stories.tsx @@ -1,39 +1,13 @@ -import { toInstructionNode } from '@entities/instruction-card'; -import { - nextjsParameters, - withMockTransactions, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { VoteDetailsCard } from '../instructions/VoteDetailsCard'; -import { - BASE_SLOT, - CLOCK_SYSVAR_ADDRESS, - HASH, - TIMESTAMP, - VOTE_ACCOUNT_ADDRESS, - VOTE_AUTHORITY_ADDRESS, - voteParsedInstruction, -} from './fixtures'; +import * as Base from './VoteDetailsCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta = { component: VoteDetailsCard, - decorators: [ - withViewportFromGlobal, - withTxInstructionSurface, - withMockTransactions, - withScrollAnchor, - withTokenInfoBatch, - ], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withViewportFromGlobal, ...Base.default.decorators], tags: ['autodocs', 'test'], title: 'Features/Vote/VoteDetailsCard@Media', } satisfies Meta; @@ -41,44 +15,10 @@ const meta = { export default meta; type Story = StoryObj; -const towerSyncIx = voteParsedInstruction({ - info: { - towerSync: { - blockId: HASH, - hash: HASH, - lockouts: [ - { confirmation_count: 31, slot: BASE_SLOT }, - { confirmation_count: 30, slot: BASE_SLOT + 1 }, - ], - root: BASE_SLOT - 1, - timestamp: TIMESTAMP, - }, - voteAccount: VOTE_ACCOUNT_ADDRESS, - voteAuthority: VOTE_AUTHORITY_ADDRESS, - }, - type: 'towersync', -}); +const args = Base.TowerSync.args; // The BLS authority is the widest payload — exercises base64-row wrapping at narrow widths. -const blsAuthorityIx = voteParsedInstruction({ - info: { - authority: VOTE_AUTHORITY_ADDRESS, - authorityType: { - VoterWithBLS: { - bls_proof_of_possession: new Array(96).fill(7), - bls_pubkey: new Array(48).fill(3), - }, - }, - clockSysvar: CLOCK_SYSVAR_ADDRESS, - newAuthority: VOTE_AUTHORITY_ADDRESS, - voteAccount: VOTE_ACCOUNT_ADDRESS, - }, - type: 'authorizeChecked', -}); - -const args = { node: toInstructionNode({ index: 0, ix: towerSyncIx }), parsed: towerSyncIx.parsed }; - -const blsArgs = { node: toInstructionNode({ index: 0, ix: blsAuthorityIx }), parsed: blsAuthorityIx.parsed }; +const blsArgs = Base.AuthorizeCheckedWithBls.args; export const Mobile: Story = { args, diff --git a/app/features/vote/ui/__stories__/VoteDetailsCard.stories.tsx b/app/features/vote/ui/__stories__/VoteDetailsCard.stories.tsx index 67390119e3..9ba7c66106 100644 --- a/app/features/vote/ui/__stories__/VoteDetailsCard.stories.tsx +++ b/app/features/vote/ui/__stories__/VoteDetailsCard.stories.tsx @@ -1,11 +1,5 @@ import { toInstructionNode } from '@entities/instruction-card'; -import { - nextjsParameters, - withMockTransactions, - withScrollAnchor, - withTokenInfoBatch, - withTxInstructionSurface, -} from '@storybook-config/decorators'; +import { instructionCardDecorators } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { expect, within } from 'storybook/test'; @@ -24,8 +18,7 @@ import { const meta = { component: VoteDetailsCard, - decorators: [withTxInstructionSurface, withMockTransactions, withScrollAnchor, withTokenInfoBatch], - parameters: nextjsParameters, + decorators: instructionCardDecorators, tags: ['autodocs', 'test'], title: 'Features/Vote/VoteDetailsCard', } satisfies Meta; diff --git a/app/features/vote/ui/__stories__/VotesCard.responsive.stories.tsx b/app/features/vote/ui/__stories__/VotesCard.responsive.stories.tsx index d5d550dfad..fd05c35194 100644 --- a/app/features/vote/ui/__stories__/VotesCard.responsive.stories.tsx +++ b/app/features/vote/ui/__stories__/VotesCard.responsive.stories.tsx @@ -1,18 +1,13 @@ -import { nextjsParameters, withCluster } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { VotesCard } from '../VotesCard'; -import { BASE_SLOT, voteAccountFixture } from './fixtures'; +import * as Base from './VotesCard.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta: Meta = { component: VotesCard, - decorators: [withViewportFromGlobal, withCluster], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, + decorators: [withViewportFromGlobal, ...Base.default.decorators], tags: ['autodocs', 'test'], title: 'Features/Vote/VotesCard@Media', }; @@ -20,14 +15,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const votes = Array.from({ length: 6 }, (_, i) => ({ - confirmationCount: 31 - i, - slot: BASE_SLOT + i, -})); - -const args = { - voteAccount: voteAccountFixture(votes), -}; +const args = Base.WithVotes.args; export const Mobile: Story = { args, diff --git a/app/features/vote/ui/__stories__/VotesCard.stories.tsx b/app/features/vote/ui/__stories__/VotesCard.stories.tsx index 036179bbbe..da82981b22 100644 --- a/app/features/vote/ui/__stories__/VotesCard.stories.tsx +++ b/app/features/vote/ui/__stories__/VotesCard.stories.tsx @@ -1,16 +1,15 @@ -import { nextjsParameters, withCluster } from '@storybook-config/decorators'; +import { withCluster } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { VotesCard } from '../VotesCard'; import { BASE_SLOT, voteAccountFixture } from './fixtures'; -const meta: Meta = { +const meta = { component: VotesCard, decorators: [withCluster], - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Features/Vote/VotesCard', -}; +} satisfies Meta; export default meta; type Story = StoryObj; diff --git a/app/og/account/[address]/__tests__/route.spec.ts b/app/og/account/[address]/__tests__/route.spec.ts index d9b43d8ad2..dcf909026e 100644 --- a/app/og/account/[address]/__tests__/route.spec.ts +++ b/app/og/account/[address]/__tests__/route.spec.ts @@ -17,7 +17,6 @@ vi.mock('@features/account-share/server', () => ({ loadOgGlows: mocks.loadOgGlows, })); vi.mock('@/app/shared/lib/og/fonts', () => ({ loadOgFonts: mocks.loadOgFonts })); -vi.mock('@/app/shared/lib/logger', () => ({ Logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } })); import { GET } from '../route'; diff --git a/app/og/receipt/[signature]/__tests__/route.spec.ts b/app/og/receipt/[signature]/__tests__/route.spec.ts index 60cdc809eb..666f4899c3 100644 --- a/app/og/receipt/[signature]/__tests__/route.spec.ts +++ b/app/og/receipt/[signature]/__tests__/route.spec.ts @@ -1,3 +1,4 @@ +import { DEFAULT_SIGNATURE as validSignature } from '@__fixtures__/gen'; import { createReceipt, ReceiptError } from '@features/receipt/server'; import { NextRequest } from 'next/server'; import { beforeEach, describe, expect, it, vi } from 'vitest'; @@ -31,8 +32,6 @@ vi.mock('@features/receipt/server', async () => { }; }); -const validSignature = '5yKzCuw1e9d58HcnzSL31cczfXUux2H4Ga5TAR2RcQLE5W8BiTAC9x9MvhLtc4h99sC9XxLEAjhrXyfKezdMkZFV'; - describe('GET /og/receipt/[signature]', () => { beforeEach(() => { vi.clearAllMocks(); diff --git a/app/providers/__tests__/block.test.tsx b/app/providers/__tests__/block.test.tsx index 26a76eb84e..1cbee485b4 100644 --- a/app/providers/__tests__/block.test.tsx +++ b/app/providers/__tests__/block.test.tsx @@ -14,8 +14,7 @@ const getBlocks = vi.fn(); const getSlotLeaders = vi.fn(); const getRpc = vi.fn((_url: string) => rpcStub({ getBlocks, getSlotLeaders })); -vi.mock('@entities/cluster', async importOriginal => ({ - ...((await importOriginal()) as Record), +vi.mock('@/app/entities/cluster/api/get-rpc', () => ({ getRpc: (...args: [string]) => getRpc(...args), })); diff --git a/app/providers/__tests__/cache-entry.spec.tsx b/app/providers/__tests__/cache-entry.spec.tsx index 7001e421ed..8f44e8cfa4 100644 --- a/app/providers/__tests__/cache-entry.spec.tsx +++ b/app/providers/__tests__/cache-entry.spec.tsx @@ -1,6 +1,6 @@ import { renderHook } from '@testing-library/react'; import { createElement, type ReactNode } from 'react'; -import { describe, expect, it, vi } from 'vitest'; +import { describe, expect, it } from 'vitest'; import { Cluster, clusterSelection, ClusterStatus, clusterUrl } from '@/app/entities/cluster/lib/cluster'; import { toConnectableUrl } from '@/app/entities/cluster/lib/connectable-url'; @@ -8,8 +8,6 @@ import { type ClusterState, StateContext } from '@/app/entities/cluster/model/cl import { type CacheEntry, FetchStatus } from '@/app/providers/cache'; import { useCacheEntries, useCacheEntry } from '@/app/providers/cache-entry'; -vi.mock('@solana/kit', () => ({ createSolanaRpc: vi.fn() })); - describe('useCacheEntry', () => { it('should report a missing entry as failed once the connection failed', () => { // Every provider gates its fetch on a connected cluster, so a missing entry here is not diff --git a/app/providers/__tests__/epoch.test.tsx b/app/providers/__tests__/epoch.test.tsx index ff3ef10710..044034e7e0 100644 --- a/app/providers/__tests__/epoch.test.tsx +++ b/app/providers/__tests__/epoch.test.tsx @@ -17,8 +17,7 @@ const getBlocks = vi.fn(); const getBlockTime = vi.fn(); const getRpc = vi.fn((_url: string) => rpcStub({ getBlockTime, getBlocks })); -vi.mock('@entities/cluster', async importOriginal => ({ - ...((await importOriginal()) as Record), +vi.mock('@/app/entities/cluster/api/get-rpc', () => ({ getRpc: (...args: [string]) => getRpc(...args), })); diff --git a/app/providers/accounts/__stories__/flagged-accounts.responsive.stories.tsx b/app/providers/accounts/__stories__/flagged-accounts.responsive.stories.tsx index 79517fe65a..8b2db84345 100644 --- a/app/providers/accounts/__stories__/flagged-accounts.responsive.stories.tsx +++ b/app/providers/accounts/__stories__/flagged-accounts.responsive.stories.tsx @@ -1,5 +1,4 @@ -import { nextjsParameters } from '@storybook-config/decorators'; -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import FLAGGED_ACCOUNTS_WARNING from '../flagged-accounts'; @@ -7,10 +6,6 @@ import FLAGGED_ACCOUNTS_WARNING from '../flagged-accounts'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta = { decorators: [withViewportFromGlobal], - parameters: { - ...nextjsParameters, - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Providers/Accounts/FlaggedAccountWarnings@Media', } satisfies Meta; diff --git a/app/providers/accounts/__stories__/flagged-accounts.stories.tsx b/app/providers/accounts/__stories__/flagged-accounts.stories.tsx index cabd70d956..5be350fae8 100644 --- a/app/providers/accounts/__stories__/flagged-accounts.stories.tsx +++ b/app/providers/accounts/__stories__/flagged-accounts.stories.tsx @@ -1,4 +1,3 @@ -import { nextjsParameters } from '@storybook-config/decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import FLAGGED_ACCOUNTS_WARNING from '../flagged-accounts'; @@ -6,7 +5,6 @@ import FLAGGED_ACCOUNTS_WARNING from '../flagged-accounts'; // Each story renders one of the three unique IncidentDescription JSX entries from FLAGGED_ACCOUNTS_WARNING. // The map keys (account addresses) are stable; addresses below were picked one per incident type. const meta = { - parameters: nextjsParameters, tags: ['autodocs', 'test'], title: 'Providers/Accounts/FlaggedAccountWarnings', } satisfies Meta; diff --git a/app/providers/accounts/__tests__/accounts-provider.spec.tsx b/app/providers/accounts/__tests__/accounts-provider.spec.tsx index 21b82ddcb1..c1dee7ddc1 100644 --- a/app/providers/accounts/__tests__/accounts-provider.spec.tsx +++ b/app/providers/accounts/__tests__/accounts-provider.spec.tsx @@ -25,10 +25,7 @@ vi.mock('../../cluster', async importOriginal => { return { ...actual, useCluster: useClusterMock }; }); -vi.mock('@entities/cluster', async importOriginal => { - const actual = await importOriginal(); - return { ...actual, getRpc }; -}); +vi.mock('@/app/entities/cluster/api/get-rpc', () => ({ getRpc })); vi.mock('@entities/nft', async importOriginal => { const actual = await importOriginal(); diff --git a/app/providers/accounts/__tests__/rewards.spec.tsx b/app/providers/accounts/__tests__/rewards.spec.tsx index 2f729a16c1..02d831fb8f 100644 --- a/app/providers/accounts/__tests__/rewards.spec.tsx +++ b/app/providers/accounts/__tests__/rewards.spec.tsx @@ -18,10 +18,9 @@ vi.mock('@providers/cluster', async importOriginal => { return { ...actual, useCluster: useClusterMock }; }); -vi.mock('@entities/cluster', async importOriginal => { - const actual = await importOriginal(); - return { ...actual, getRpc: () => rpcStub({ getEpochInfo, getInflationReward }) }; -}); +vi.mock('@/app/entities/cluster/api/get-rpc', () => ({ + getRpc: () => rpcStub({ getEpochInfo, getInflationReward }), +})); import { RewardsProvider, useFetchRewards, useRewards } from '../rewards'; diff --git a/app/providers/accounts/__tests__/tokens.spec.tsx b/app/providers/accounts/__tests__/tokens.spec.tsx index 0f2f155824..89c229f38f 100644 --- a/app/providers/accounts/__tests__/tokens.spec.tsx +++ b/app/providers/accounts/__tests__/tokens.spec.tsx @@ -18,10 +18,7 @@ vi.mock('@providers/cluster', async importOriginal => { return { ...actual, useCluster: useClusterMock }; }); -vi.mock('@entities/cluster', async importOriginal => { - const actual = await importOriginal(); - return { ...actual, getRpc: () => rpcStub({ getTokenAccountsByOwner }) }; -}); +vi.mock('@/app/entities/cluster/api/get-rpc', () => ({ getRpc: () => rpcStub({ getTokenAccountsByOwner }) })); import { MockAccountsProvider } from '@storybook-config/__mocks__/MockAccountsProvider'; import { MockClusterProvider } from '@storybook-config/__mocks__/MockClusterProvider'; diff --git a/app/providers/transactions/__tests__/index.test.tsx b/app/providers/transactions/__tests__/index.test.tsx index c818071c3c..09388971ec 100644 --- a/app/providers/transactions/__tests__/index.test.tsx +++ b/app/providers/transactions/__tests__/index.test.tsx @@ -11,8 +11,7 @@ const MOCK_URL = 'https://api.mainnet-beta.solana.com'; const getSignatureStatuses = vi.fn(); const getRpc = vi.fn((_url: string) => rpcStub({ getSignatureStatuses })); -vi.mock('@entities/cluster', async importOriginal => ({ - ...((await importOriginal()) as Record), +vi.mock('@/app/entities/cluster/api/get-rpc', () => ({ getRpc: (...args: [string]) => getRpc(...args), })); diff --git a/app/providers/wallet/__tests__/sign-web3js-transaction.spec.ts b/app/providers/wallet/__tests__/sign-web3js-transaction.spec.ts index 555e78591a..6ed9b43675 100644 --- a/app/providers/wallet/__tests__/sign-web3js-transaction.spec.ts +++ b/app/providers/wallet/__tests__/sign-web3js-transaction.spec.ts @@ -1,3 +1,4 @@ +import { compileV0Message } from '@entities/transaction-data/__fixtures__/wire-transactions'; import { generateKeyPairSigner, getTransactionCodec, @@ -9,13 +10,7 @@ import { verifySignature, } from '@solana/kit'; import type { WalletSigner } from '@solana/kit-plugin-wallet'; -import { - PublicKey, - Transaction, - TransactionInstruction, - TransactionMessage, - VersionedTransaction, -} from '@solana/web3.js'; +import { PublicKey, Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js'; import { describe, expect, it } from 'vitest'; import { signWeb3jsTransaction, signWeb3jsTransactions } from '../sign-web3js-transaction'; @@ -41,12 +36,7 @@ function makeLegacyTransaction(): Transaction { } function makeVersionedTransaction(): VersionedTransaction { - const message = new TransactionMessage({ - instructions: [makeInstruction()], - payerKey: signerPublicKey, - recentBlockhash: blockhash, - }).compileToV0Message(); - return new VersionedTransaction(message); + return new VersionedTransaction(compileV0Message(signerPublicKey, makeInstruction())); } function sign(messageBytes: ReadonlyUint8Array): Promise { diff --git a/app/shared/lib/__tests__/errors.spec.ts b/app/shared/lib/__tests__/errors.spec.ts index fd26a00d1c..55158c91da 100644 --- a/app/shared/lib/__tests__/errors.spec.ts +++ b/app/shared/lib/__tests__/errors.spec.ts @@ -4,11 +4,12 @@ import { SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND, SOLANA_ERROR__JSON_RPC__PARSE_ERROR, SOLANA_ERROR__RPC__INTEGER_OVERFLOW, - SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, SolanaError, } from '@solana/kit'; import { describe, expect, it } from 'vitest'; +import { connectionFailure, httpError } from '@/app/__tests__/rpc-errors'; + import { classifyTransientError, isRetryableError, @@ -42,10 +43,7 @@ describe('isRetryableFetchError', () => { it.each([['EAI_AGAIN'], ['EHOSTUNREACH'], ['ENETUNREACH'], ['ECONNABORTED']])( 'should match a %s connection failure', code => { - const error = Object.assign(new TypeError('fetch failed'), { - cause: Object.assign(new Error('connect'), { code }), - }); - expect(isRetryableFetchError(error)).toBe(true); + expect(isRetryableFetchError(connectionFailure(code))).toBe(true); }, ); @@ -55,10 +53,7 @@ describe('isRetryableFetchError', () => { ['a hostname that does not resolve', 'ENOTFOUND'], ['a TLS handshake the client will not complete', 'EPROTO'], ])('should not match %s', (_reason, code) => { - const error = Object.assign(new TypeError('fetch failed'), { - cause: Object.assign(new Error('connect'), { code }), - }); - expect(isRetryableFetchError(error)).toBe(false); + expect(isRetryableFetchError(connectionFailure(code))).toBe(false); }); it('should not match non-error values', () => { @@ -135,14 +130,6 @@ describe('isRpcMisconfigError', () => { expect(isRpcMisconfigError(httpError(429))).toBe(false); }); - function httpError(statusCode: number) { - return new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, { - headers: new Headers(), - message: `HTTP ${statusCode}`, - statusCode, - }); - } - it('should not match a failure that is not an RPC error at all', () => { expect(isRpcMisconfigError(new Error('boom'))).toBe(false); expect(isRpcMisconfigError(new SyntaxError('Unexpected token <'))).toBe(false); diff --git a/app/shared/ui/Alert/__stories__/Alert.responsive.stories.tsx b/app/shared/ui/Alert/__stories__/Alert.responsive.stories.tsx index 51e704d253..c68bad698c 100644 --- a/app/shared/ui/Alert/__stories__/Alert.responsive.stories.tsx +++ b/app/shared/ui/Alert/__stories__/Alert.responsive.stories.tsx @@ -1,4 +1,4 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { Alert } from '../Alert'; @@ -7,9 +7,6 @@ import { Alert } from '../Alert'; const meta: Meta = { component: Alert, decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Shared/Alert@Media', }; diff --git a/app/shared/ui/FormControl/__stories__/FormControl.responsive.stories.tsx b/app/shared/ui/FormControl/__stories__/FormControl.responsive.stories.tsx index 642b79d265..50f4878fb0 100644 --- a/app/shared/ui/FormControl/__stories__/FormControl.responsive.stories.tsx +++ b/app/shared/ui/FormControl/__stories__/FormControl.responsive.stories.tsx @@ -1,15 +1,13 @@ -import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators'; +import { withViewportFromGlobal } from '@storybook-config/responsive-decorators'; import type { Meta, StoryObj } from '@storybook-config/types'; import { FormControl } from '../FormControl'; +import * as Base from './FormControl.stories'; // Known: switching between Mobile/Tablet variants has a brief lag from viewport addon iframe resize + remount. const meta: Meta = { component: FormControl, decorators: [withViewportFromGlobal], - parameters: { - viewport: { options: INITIAL_VIEWPORTS }, - }, tags: ['autodocs', 'test'], title: 'Shared/FormControl@Media', }; @@ -17,10 +15,7 @@ const meta: Meta = { export default meta; type Story = StoryObj; -const args = { - children: