Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 6 additions & 12 deletions app/(main)/market/bsv21/[tokenId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { ArrowLeft } from "lucide-react";
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import ImageWithFallback from "@/components/image-with-fallback";
import { Bsv21DetailClient } from "@/components/market/bsv21-detail-client";
import { createStackServices, stackContentUrl } from "@/lib/stack";
import { isValidOutpoint } from "@/lib/validation";
import { TokenIcon } from "@/components/wallet/token-row";
import { bsv21IconSrc } from "@/lib/bsv21-icon";
import { createStackServices } from "@/lib/stack";
import {
formatBsv21Amount,
getBsv21Listings,
Expand All @@ -31,6 +31,8 @@ export default async function Bsv21DetailPage({
const decimals = Number.parseInt(details.token.dec ?? "0", 10);
const symbol = details.token.sym || tokenId.slice(0, 8);
const overlayFee = safeOverlayFee(details);
// Shown at 80px; ask the image API for 2x.
const iconSrc = bsv21IconSrc(tokenId, details.token.icon, 160);

return (
<div className="mx-auto w-full max-w-5xl space-y-8 p-4">
Expand All @@ -41,15 +43,7 @@ export default async function Bsv21DetailPage({
<ArrowLeft className="mr-2 size-4" /> Back to BSV21 tokens
</Link>
<header className="flex flex-col gap-5 sm:flex-row sm:items-start">
{details.token.icon && isValidOutpoint(details.token.icon) ? (
<ImageWithFallback
src={stackContentUrl(details.token.icon)}
alt=""
width={80}
height={80}
className="size-20 rounded-lg border object-cover"
/>
) : null}
<TokenIcon icon={iconSrc} size={80} />
<div className="min-w-0 space-y-2">
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-3xl font-bold">{symbol}</h1>
Expand Down
35 changes: 18 additions & 17 deletions app/api/image/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { lookup } from "node:dns/promises";
import { ImageProtocols } from "bitcoin-image";
import { type NextRequest, NextResponse } from "next/server";
import sharp from "sharp";
import { reportDiagnostic } from "@/lib/runtime-diagnostics";
import { reportFailure } from "@/lib/runtime-diagnostics";

/**
* SSRF protection: block requests to private/reserved IP ranges.
Expand Down Expand Up @@ -246,23 +246,24 @@ export async function GET(request: NextRequest) {
"X-Cache": "MISS",
},
});
} catch {
const diagnostic = reportDiagnostic({
category: "route",
code: "route.unexpected",
operation: "api.image",
recoverable: true,
context: { route: "/api/image", retryable: true },
});
// Fallback error image
return new NextResponse(
`<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"><rect width="100%" height="100%" fill="#eee"/><text x="50%" y="50%" fill="#999" text-anchor="middle" dy=".3em">Image Error</text></svg>`,
} catch (error) {
// A 502, not a placeholder image: the page's onError must see the
// failure so it can show its own fallback.
const diagnostic = reportFailure(
{
category: "route",
code: "route.unexpected",
operation: "api.image",
recoverable: true,
context: { route: "/api/image", retryable: true },
},
error,
);
return NextResponse.json(
{ error: "Could not process the image" },
{
status: 200,
headers: {
"Content-Type": "image/svg+xml",
"X-Correlation-ID": diagnostic.correlationId,
},
status: 502,
headers: { "X-Correlation-ID": diagnostic.correlationId },
},
);
}
Expand Down
2 changes: 1 addition & 1 deletion components/wallet/bsv21-detail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ export default function Bsv21Detail({ tokenId }: { tokenId: string }) {
) : null}
</>
}
icon={bsv21Icon(token, chain)}
icon={bsv21Icon(token, chain, 64)}
id={token.id}
idLabel="Token ID"
status={
Expand Down
13 changes: 8 additions & 5 deletions components/wallet/token-grid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ import {
SoundDialog,
} from "@/components/ui/sound-dialog";
import { useSound } from "@/hooks/use-sound";
import { bsv21IconSrc } from "@/lib/bsv21-icon";
import type { Chain } from "@/lib/chain-endpoints";
import { useBsv21Availability } from "@/lib/hooks/use-stack-features";
import { getOrdinalThumbnail } from "@/lib/image-utils";
import { reportDiagnostic } from "@/lib/runtime-diagnostics";
import {
type AssetSurfaceState,
Expand Down Expand Up @@ -75,9 +75,12 @@ export function Bsv21Unreadable({ state }: { state: AssetSurfaceState }) {
);
}

/** A BSV-21 token's icon, else its deploy inscription's thumbnail. */
export const bsv21Icon = (token: Bsv21Balance, chain: Chain) =>
token.icon || getOrdinalThumbnail(token.id, 100, chain);
/**
* A BSV-21 token's icon through OrdFS, sized for a TokenIcon tile of `size`
* CSS px. No icon shows the coin: the deploy inscription is BSV-20 JSON.
*/
export const bsv21Icon = (token: Bsv21Balance, chain: Chain, size: 40 | 64) =>
bsv21IconSrc(token.id, token.icon, size * 2, chain);

/** Says why BSV-21 sends, mints and creates are off, once the stack has answered. */
export function Bsv21UnavailableNotice() {
Expand Down Expand Up @@ -388,7 +391,7 @@ export default function TokenGrid() {
amount={formatBsv21Amount(bsv21Spendable(token), token.dec)}
caption={shortOutpoint(token.id)}
href={tokenDetailHref("bsv21", token.id)}
icon={bsv21Icon(token, chain)}
icon={bsv21Icon(token, chain, 40)}
key={token.id}
ticker={bsv21Ticker(token)}
/>
Expand Down
29 changes: 23 additions & 6 deletions components/wallet/token-row.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,41 +3,58 @@
import { ChevronRight, Coins } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import type { ReactNode } from "react";
import { type ReactNode, useState } from "react";
import { Skeleton } from "@/components/ui/skeleton";
import { useSound } from "@/hooks/use-sound";
import { cn } from "@/lib/utils";

/** A token's icon, else a coin, in a rounded tile: 40px in a row, 64 on its page. */
/**
* A token's icon, else a coin, in a rounded tile: 40px in a row, 64 on its
* wallet page, 80 on its market page. An icon that fails to load is logged
* and replaced by the coin.
*/
export function TokenIcon({
icon,
size,
}: {
icon: string | undefined;
size: 40 | 64;
size: 40 | 64 | 80;
}) {
const [failedSrc, setFailedSrc] = useState<string | null>(null);
const showImage = Boolean(icon) && failedSrc !== icon;
return (
<div
data-slot="token-icon"
data-icon-src={icon || undefined}
className={cn(
"relative flex shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted",
size === 64 ? "size-16 border" : "size-10",
size === 80
? "size-20 border"
: size === 64
? "size-16 border"
: "size-10",
)}
>
{icon ? (
{icon && showImage ? (
<Image
src={icon}
alt=""
fill
sizes={`${size}px`}
className="object-cover"
unoptimized
onError={() => {
console.error("[token-icon] image failed to load", { src: icon });
setFailedSrc(icon);
}}
/>
) : (
<Coins
aria-hidden="true"
data-testid={icon ? "token-icon-failed" : "token-icon-none"}
className={cn(
"text-muted-foreground",
size === 64 ? "size-8" : "size-5",
size === 40 ? "size-5" : "size-8",
)}
/>
)}
Expand Down
55 changes: 55 additions & 0 deletions e2e/tokens-section-wallet.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,54 @@ function readRows(browser: Browser) {
}, null);
}

/**
* Every BSV-21 icon tile under `scope` once its image has loaded or failed.
* A tile's src (kept on the tile, so a failed load that swapped in the coin
* is still checked) must be OrdFS content through /api/image, never a bare
* outpoint, and an image still shown must have pixels.
*/
async function checkBsv21Icons(
browser: Browser,
scope: string,
where: string,
problems: LayoutProblems,
) {
await browser.waitFor(
`${where}: token icons to load or fail`,
(selector: string) =>
Array.from(
document.querySelectorAll<HTMLImageElement>(
`${selector} [data-slot="token-icon"] img`,
),
).every((img) => img.complete),
scope,
CHAIN_TIMEOUT,
);
const tiles = await browser.evaluate(
(selector: string) =>
Array.from(
document.querySelectorAll(`${selector} [data-slot="token-icon"]`),
).map((tile) => ({
src: tile.getAttribute("data-icon-src"),
imageWidth: tile.querySelector("img")?.naturalWidth ?? null,
})),
scope,
);
for (const tile of tiles) {
if (tile.src === null) continue;
const source = tile.src.startsWith("/api/image?")
? new URLSearchParams(tile.src.slice("/api/image?".length)).get("url")
: null;
if (!source?.includes("/content/")) {
problems.add(
`${where}: a token icon's src is ${JSON.stringify(tile.src)}, expected OrdFS content through /api/image.`,
);
} else if (tile.imageWidth === 0) {
problems.add(`${where}: token icon ${tile.src} loaded with no pixels.`);
}
}
}

async function checkPhones(
browser: Browser,
pathname: string,
Expand Down Expand Up @@ -191,6 +239,12 @@ walletTest(
problems.add(`/wallet/tokens: a 1Color row links to ${href}.`);
}
}
await checkBsv21Icons(
browser,
'section[aria-labelledby="tokens-bsv21"]',
"/wallet/tokens",
problems,
);
problems.throwIfAny("Tokens on testnet");

// Each standard's page has its own headline and the back arrow to
Expand Down Expand Up @@ -255,6 +309,7 @@ walletTest(
null,
CHAIN_TIMEOUT,
);
await checkBsv21Icons(browser, "main", first, problems);
await checkPhones(browser, first, problems);
problems.throwIfAny("BSV-21 token page on testnet");
// The BSV-21 page was checked; only part was left out, so the test
Expand Down
76 changes: 76 additions & 0 deletions lib/bsv21-icon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import type { Chain } from "./chain-endpoints";
import { getCoverImageUrl } from "./image-utils";
import { clipForLog } from "./runtime-diagnostics";
import { stackContentUrl } from "./stack";

const OUTPOINT = /^[0-9a-fA-F]{64}[._](0|[1-9][0-9]*)$/;
const RELATIVE_OUTPOINT = /^_(0|[1-9][0-9]*)$/;

/**
* A BSV-21 `icon` field as a txid_vout outpoint. The field is an outpoint
* (txid_vout or txid.vout), or `_N` for output N of the deploy transaction.
*/
export function bsv21IconOutpoint(
tokenId: string,
icon: string,
): string | null {
const normalized = icon.trim();
if (RELATIVE_OUTPOINT.test(normalized)) {
return `${tokenId.slice(0, 64)}${normalized}`.toLowerCase();
}
if (!OUTPOINT.test(normalized)) return null;
return normalized.replace(".", "_").toLowerCase();
}

/** An icon given as a full URL, kept only on OrdFS hosts we trust. */
export function trustedBsv21IconUrl(icon: string): string | null {
try {
const url = new URL(icon);
if (url.protocol !== "https:" || url.port || url.username || url.password) {
return null;
}
if (
url.hostname === "api.1sat.app" &&
url.pathname.startsWith("/content/")
) {
return url.toString();
}
if (url.hostname === "ordfs.network") return url.toString();
if (url.hostname === "themetoken.dev" && url.pathname.startsWith("/og/")) {
return url.toString();
}
return null;
} catch {
return null;
}
}

const reportedBadIcons = new Set<string>();

/**
* The image src for a BSV-21 token icon: its OrdFS content, resized by the
* image API to `size` px square. `size` is the device-pixel size (twice the
* CSS size for sharp icons). Undefined when the token has no usable icon, so
* the caller shows its placeholder; an unusable value is logged once.
*/
export function bsv21IconSrc(
tokenId: string,
icon: string | undefined,
size: number,
chain: Chain = "main",
): string | undefined {
if (!icon) return undefined;
const outpoint = bsv21IconOutpoint(tokenId, icon);
const source = outpoint
? stackContentUrl(outpoint, chain)
: trustedBsv21IconUrl(icon);
if (source) return getCoverImageUrl(source, size);
if (!reportedBadIcons.has(icon)) {
reportedBadIcons.add(icon);
console.error("[bsv21-icon] unusable icon value", {
tokenId,
icon: clipForLog(icon, 160),
});
}
return undefined;
}
13 changes: 3 additions & 10 deletions lib/hooks/use-legacy-assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
} from "@1sat/actions";
import type { IndexedOutput } from "@1sat/types";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { bsv21IconSrc } from "@/lib/bsv21-icon";
import { createStackServices, stackContentUrl } from "@/lib/stack";
import {
type AddressScanStatus,
Expand Down Expand Up @@ -80,15 +81,6 @@ const enrichOrdinal = (out: IndexedOutput): EnrichedOrdinal => {
return { ...out, origin, contentType, name, contentUrl };
};

const resolveIconUrl = (tokenId: string, icon?: string): string => {
if (!icon) return "";
let outpoint = icon;
if (icon.startsWith("_")) {
outpoint = `${tokenId.split("_")[0]}${icon}`;
}
return stackContentUrl(outpoint);
};

/**
* Scan legacy addresses via the 1sat stack (@1sat/actions scanAddress for
* each address): forced indexer re-sync, event-tag categorization (funding vs
Expand Down Expand Up @@ -203,7 +195,8 @@ export function useAddressAssets(
bsv21Tokens: excludeUnsweepableTokens(result?.bsv21Tokens ?? EMPTY).map(
(t) => ({
...t,
icon: resolveIconUrl(t.tokenId, t.icon),
// Sweep rows show icons in 40px tiles.
icon: bsv21IconSrc(t.tokenId, t.icon, 80) ?? "",
}),
),
bsv20Tokens: result?.bsv20Tokens ?? EMPTY,
Expand Down
Loading
Loading