Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions app/api/token-image/[mintAddress]/__tests__/route.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { GET } from '../route';

vi.mock('@/app/entities/digital-asset/server', () => ({
getAssetBatch: vi.fn(),
}));

const VALID_MINT = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
const BASE_URL = `http://localhost:3000/api/token-image/${VALID_MINT}`;

function makeRequest(url = BASE_URL) {
return new Request(url);
}

function makeParams(mintAddress = VALID_MINT) {
return { params: Promise.resolve({ mintAddress }) };
}

describe('GET /api/token-image/[mintAddress]', () => {
let getAssetBatch: ReturnType<typeof vi.fn>;

beforeEach(async () => {
vi.clearAllMocks();
const mod = await import('@/app/entities/digital-asset/server');
getAssetBatch = vi.mocked(mod.getAssetBatch);
});

describe('validation', () => {
it('should return 400 for an invalid mint address', async () => {
const response = await GET(makeRequest(), makeParams('not-a-pubkey'));

expect(response.status).toBe(400);
const data = await response.json();
expect(data.error).toBe('Invalid mint address');
});

it('should return 400 for an invalid cluster slug', async () => {
const response = await GET(makeRequest(`${BASE_URL}?cluster=unknown-cluster`), makeParams());

expect(response.status).toBe(400);
const data = await response.json();
expect(data.error).toBe('Invalid cluster');
});

it('should not cache invalid mint address 400 errors', async () => {
const response = await GET(makeRequest(), makeParams('not-a-pubkey'));

expect(response.headers.get('Cache-Control')).toBe('no-store, max-age=0');
});

it('should not cache invalid cluster 400 errors', async () => {
const response = await GET(makeRequest(`${BASE_URL}?cluster=unknown-cluster`), makeParams());

expect(response.headers.get('Cache-Control')).toBe('no-store, max-age=0');
});
});

describe('successful requests', () => {
it('should return the image URL when the asset has one', async () => {
getAssetBatch.mockResolvedValueOnce([
{ content: { links: { image: 'https://example.com/image.png' } }, id: VALID_MINT },
]);

const response = await GET(makeRequest(), makeParams());

expect(response.status).toBe(200);
const data = await response.json();
expect(data.image).toBe('https://example.com/image.png');
});

it('should return undefined image when asset has no image link', async () => {
getAssetBatch.mockResolvedValueOnce([{ content: { links: {} }, id: VALID_MINT }]);

const response = await GET(makeRequest(), makeParams());

expect(response.status).toBe(200);
const data = await response.json();
expect(data.image).toBeUndefined();
});

it('should return no-store headers when no assets are returned', async () => {
getAssetBatch.mockResolvedValueOnce(null);

const response = await GET(makeRequest(), makeParams());

expect(response.status).toBe(200);
expect(response.headers.get('Cache-Control')).toBe('no-store, max-age=0');
});

it('should return cache headers on a successful image response', async () => {
getAssetBatch.mockResolvedValueOnce([
{ content: { links: { image: 'https://example.com/image.png' } }, id: VALID_MINT },
]);

const response = await GET(makeRequest(), makeParams());

expect(response.headers.get('Cache-Control')).toBe(
'public, max-age=3600, s-maxage=3600, stale-while-revalidate=3600',
);
});

it('should call getAssetBatch with the mint address', async () => {
getAssetBatch.mockResolvedValueOnce([{ content: { links: {} }, id: VALID_MINT }]);

await GET(makeRequest(), makeParams());

expect(getAssetBatch).toHaveBeenCalledWith([VALID_MINT], expect.any(String));
});
});
});
44 changes: 44 additions & 0 deletions app/api/token-image/[mintAddress]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { isAddress } from '@solana/kit';
import { NextResponse } from 'next/server';

import { getAssetBatch } from '@/app/entities/digital-asset/server';
import { NO_STORE_HEADERS } from '@/app/shared/lib/http-utils';
import { Cluster, clusterFromSlug, clusterSlug, serverClusterUrl } from '@/app/utils/cluster';

const IMAGE_CACHE_HEADERS = {
'Cache-Control': 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=3600',
};

type Params = {
params: Promise<{
mintAddress: string;
}>;
};

export async function GET(request: Request, props: Params) {
const { mintAddress } = await props.params;

if (!isAddress(mintAddress)) {
return NextResponse.json({ error: 'Invalid mint address' }, { headers: NO_STORE_HEADERS, status: 400 });
}

const { searchParams } = new URL(request.url);
const clusterParam = searchParams.get('cluster') ?? clusterSlug(Cluster.MainnetBeta);
const customUrl = searchParams.get('customUrl') ?? '';
Comment thread
askov marked this conversation as resolved.
Outdated

const cluster = clusterFromSlug(clusterParam);
if (cluster === null) {
return NextResponse.json({ error: 'Invalid cluster' }, { headers: NO_STORE_HEADERS, status: 400 });
}

const rpcUrl = serverClusterUrl(cluster, customUrl);
const assets = await getAssetBatch([mintAddress], rpcUrl);
Comment thread
C0mberry marked this conversation as resolved.
Outdated

if (!assets) {
return NextResponse.json({ image: undefined }, { headers: NO_STORE_HEADERS });
}

const asset = assets.find(a => a.id === mintAddress);
const image = asset?.content.links?.image;
return NextResponse.json({ image }, { headers: IMAGE_CACHE_HEADERS });
}
27 changes: 16 additions & 11 deletions app/components/account/AccountHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { CompressedNftAccountHeader } from '@components/account/CompressedNftCar
import { MetaplexNFTHeader } from '@components/account/MetaplexNFTHeader';
import { isNFTokenAccount } from '@components/account/nftoken/isNFTokenAccount';
import { NFTokenAccountHeader } from '@components/account/nftoken/NFTokenAccountHeader';
import { useDasImage } from '@entities/digital-asset';
import { isMetaplexNFT } from '@entities/nft';
import {
Account,
Expand Down Expand Up @@ -112,19 +113,26 @@ function TokenMintHeader({
const metadataPointerExtension = mintInfo?.extensions?.find(
({ extension }: { extension: string }) => extension === 'metadataPointer',
);

const defaultCard = useMemo(
() => <TokenMintHeaderCard token={tokenInfo ? tokenInfo : { logoURI: undefined, name: undefined }} />,
[tokenInfo],
// Skip DAS fetch when a definitive image is already available. Token-2022 is excluded:
// its image comes from an async metadata URI fetch, so DAS still serves as a useful fallback.
const dasImage = useDasImage(
tokenInfo?.logoURI || isRedactedTokenAddress(address) || parsedData?.nftData?.json?.image ? undefined : address,
);

const defaultCard = useMemo(() => {
const logoURI = tokenInfo?.logoURI ?? dasImage;
const token = tokenInfo ? { ...tokenInfo, logoURI } : { logoURI, name: undefined };
return <TokenMintHeaderCard token={token} />;
}, [dasImage, tokenInfo]);

if (metadataPointerExtension && metadataExtension) {
return (
<>
<ErrorBoundary fallback={defaultCard}>
<Suspense fallback={defaultCard}>
<Token22MintHeader
address={address}
fallbackLogoURI={dasImage}
metadataExtension={metadataExtension as any}
metadataPointerExtension={metadataPointerExtension as any}
/>
Expand All @@ -138,23 +146,23 @@ function TokenMintHeader({
return defaultCard;
} else if (parsedData?.nftData) {
const token = {
logoURI: parsedData?.nftData?.json?.image,
logoURI: parsedData?.nftData?.json?.image ?? dasImage,
name: parsedData?.nftData?.json?.name ?? parsedData?.nftData.metadata.name,
symbol: parsedData?.nftData?.metadata.symbol,
};
return <TokenMintHeaderCard token={token} />;
} else if (tokenInfo) {
return defaultCard;
}
return defaultCard;
}

function Token22MintHeader({
address,
fallbackLogoURI,
metadataExtension,
metadataPointerExtension,
}: {
address: string;
fallbackLogoURI?: string;
metadataExtension: { extension: 'tokenMetadata'; state?: any };
metadataPointerExtension: { extension: 'metadataPointer'; state?: any };
}) {
Expand All @@ -163,13 +171,10 @@ function Token22MintHeader({
const metadata = useMetadataJsonLink(getProxiedUri(tokenMetadata.uri));

const headerTokenMetadata = {
logoURI: '',
logoURI: metadata?.image ?? fallbackLogoURI ?? '',
name: tokenMetadata.name,
symbol: tokenMetadata.symbol,
};
if (metadata) {
headerTokenMetadata.logoURI = metadata.image;
}

// Handles the basic case where MetadataPointer is referencing the Token Metadata extension directly
// Does not handle the case where MetadataPointer is pointing at a separate account.
Expand Down
1 change: 1 addition & 0 deletions app/entities/digital-asset/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { useDasImage } from './model/use-das-image';
66 changes: 66 additions & 0 deletions app/entities/digital-asset/model/__tests__/use-das-image.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { Cluster, clusterSlug } from '@/app/utils/cluster';

vi.mock('@/app/providers/cluster', () => ({ useCluster: vi.fn() }));
vi.mock('swr', () => ({ default: vi.fn() }));

import useSWR from 'swr';

import { useCluster } from '@/app/providers/cluster';

import { useDasImage } from '../use-das-image';

describe('useDasImage', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(useCluster).mockReturnValue({ cluster: Cluster.MainnetBeta, customUrl: '' } as ReturnType<
typeof useCluster
>);
vi.mocked(useSWR).mockReturnValue({ data: undefined } as ReturnType<typeof useSWR>);
});

it('should return undefined when no mintAddress', () => {
const { result } = renderHook(() => useDasImage(undefined));
expect(result.current).toBeUndefined();
expect(useSWR).toHaveBeenCalledWith(undefined, expect.any(Function), expect.any(Object));
});

it('should return the image URL from SWR data', () => {
vi.mocked(useSWR).mockReturnValue({ data: 'https://example.com/image.png' } as ReturnType<typeof useSWR>);

const { result } = renderHook(() => useDasImage('SomeMintAddress'));
expect(result.current).toBe('https://example.com/image.png');
});

it('should return undefined when SWR has no data', () => {
const { result } = renderHook(() => useDasImage('SomeMintAddress'));
expect(result.current).toBeUndefined();
});

it('should pass correct SWR key including cluster slug and customUrl', () => {
vi.mocked(useCluster).mockReturnValue({
cluster: Cluster.Devnet,
customUrl: 'https://custom.rpc',
} as ReturnType<typeof useCluster>);

renderHook(() => useDasImage('SomeMintAddress'));

expect(useSWR).toHaveBeenCalledWith(
['das-image', 'SomeMintAddress', clusterSlug(Cluster.Devnet), 'https://custom.rpc'],
expect.any(Function),
expect.any(Object),
);
});

it('should pass correct SWR config', () => {
renderHook(() => useDasImage('SomeMintAddress'));

expect(useSWR).toHaveBeenCalledWith(expect.any(Array), expect.any(Function), {
dedupingInterval: 5 * 60 * 1000,
revalidateOnFocus: false,
revalidateOnReconnect: false,
});
});
});
36 changes: 36 additions & 0 deletions app/entities/digital-asset/model/use-das-image.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import useSWR from 'swr';

import { useCluster } from '@/app/providers/cluster';
import { Cluster, clusterSlug } from '@/app/utils/cluster';

type DasImageKey = ['das-image', string, string, string];

function getDasImageKey(cluster: Cluster, mintAddress: string, customUrl: string): DasImageKey {
return ['das-image', mintAddress, clusterSlug(cluster), customUrl];
}

async function fetchDasImage([, mintAddress, cluster, customUrl]: DasImageKey): Promise<string | undefined> {
try {
const params = new URLSearchParams({ cluster });
if (customUrl) params.set('customUrl', customUrl);
const response = await fetch(`/api/token-image/${mintAddress}?${params}`);
if (!response.ok) return undefined;
const data = await response.json();
return typeof data.image === 'string' ? data.image : undefined;
} catch {
return undefined;
}
}

const DAS_IMAGE_SWR_CONFIG = {
dedupingInterval: 5 * 60 * 1000,
revalidateOnFocus: false,
revalidateOnReconnect: false,
};

export function useDasImage(mintAddress?: string): string | undefined {
const { cluster, customUrl } = useCluster();
const swrKey = mintAddress ? getDasImageKey(cluster, mintAddress, customUrl) : undefined;
const { data } = useSWR(swrKey, fetchDasImage, DAS_IMAGE_SWR_CONFIG);
return data;
}
Loading