diff --git a/app/api/image/route.ts b/app/api/image/route.ts
index be7235e..a92e113 100644
--- a/app/api/image/route.ts
+++ b/app/api/image/route.ts
@@ -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.
@@ -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(
- `
`,
+ } 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 },
},
);
}
diff --git a/components/wallet/bsv21-detail.tsx b/components/wallet/bsv21-detail.tsx
index 9b4d4c0..605e25f 100644
--- a/components/wallet/bsv21-detail.tsx
+++ b/components/wallet/bsv21-detail.tsx
@@ -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={
diff --git a/components/wallet/token-grid.tsx b/components/wallet/token-grid.tsx
index 5c2c711..4a8d705 100644
--- a/components/wallet/token-grid.tsx
+++ b/components/wallet/token-grid.tsx
@@ -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,
@@ -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() {
@@ -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)}
/>
diff --git a/components/wallet/token-row.tsx b/components/wallet/token-row.tsx
index 9080073..e67bdd9 100644
--- a/components/wallet/token-row.tsx
+++ b/components/wallet/token-row.tsx
@@ -3,27 +3,39 @@
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
(null);
+ const showImage = Boolean(icon) && failedSrc !== icon;
return (
- {icon ? (
+ {icon && showImage ? (
{
+ console.error("[token-icon] image failed to load", { src: icon });
+ setFailedSrc(icon);
+ }}
/>
) : (
)}
diff --git a/e2e/tokens-section-wallet.e2e.ts b/e2e/tokens-section-wallet.e2e.ts
index 97ef4e6..828afd6 100644
--- a/e2e/tokens-section-wallet.e2e.ts
+++ b/e2e/tokens-section-wallet.e2e.ts
@@ -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(
+ `${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,
@@ -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
@@ -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
diff --git a/lib/bsv21-icon.ts b/lib/bsv21-icon.ts
new file mode 100644
index 0000000..048d178
--- /dev/null
+++ b/lib/bsv21-icon.ts
@@ -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();
+
+/**
+ * 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;
+}
diff --git a/lib/hooks/use-legacy-assets.ts b/lib/hooks/use-legacy-assets.ts
index b96c7f4..c168c9b 100644
--- a/lib/hooks/use-legacy-assets.ts
+++ b/lib/hooks/use-legacy-assets.ts
@@ -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,
@@ -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
@@ -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,
diff --git a/lib/p2p-bsv21-offer.ts b/lib/p2p-bsv21-offer.ts
index f380c86..ee13e10 100644
--- a/lib/p2p-bsv21-offer.ts
+++ b/lib/p2p-bsv21-offer.ts
@@ -1,11 +1,11 @@
import type { Bsv21Balance } from "@1sat/actions";
+import { bsv21IconOutpoint, trustedBsv21IconUrl } from "./bsv21-icon";
import { getOrdinalThumbnail } from "./image-utils";
import type { P2PBsv21TradeItem } from "./types/p2p";
import { formatBsv21Amount, parseBsv21Amount } from "./wallet/bsv21-actions";
const CANONICAL_TOKEN_ID = /^[0-9a-f]{64}_(0|[1-9][0-9]*)$/;
const CANONICAL_ATOMIC_BALANCE = /^(?:0|[1-9][0-9]*)$/;
-const OUTPOINT = /^[0-9a-fA-F]{64}[._](0|[1-9][0-9]*)$/;
export interface Bsv21OfferToken {
id: string;
@@ -27,45 +27,14 @@ function safeSymbol(symbol: string | undefined): string | null {
return normalized || null;
}
-function canonicalIconOutpoint(tokenId: string, icon: string): string | null {
- const normalized = icon.trim();
- if (/^_(0|[1-9][0-9]*)$/.test(normalized)) {
- return `${tokenId.slice(0, 64)}${normalized}`;
- }
- if (!OUTPOINT.test(normalized)) return null;
- return normalized.replace(".", "_").toLowerCase();
-}
-
-function trustedIconUrl(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;
- }
-}
-
export function getSafeBsv21OfferImage(
tokenId: string,
icon: string | undefined,
): string | undefined {
if (!icon) return undefined;
- const outpoint = canonicalIconOutpoint(tokenId, icon);
+ const outpoint = bsv21IconOutpoint(tokenId, icon);
if (outpoint) return getOrdinalThumbnail(outpoint, 200);
- return trustedIconUrl(icon) ?? undefined;
+ return trustedBsv21IconUrl(icon) ?? undefined;
}
export function toBsv21OfferToken(token: Bsv21Balance): Bsv21OfferToken | null {
diff --git a/lib/wallet/bsv21-actions.ts b/lib/wallet/bsv21-actions.ts
index a03958c..bc7eead 100644
--- a/lib/wallet/bsv21-actions.ts
+++ b/lib/wallet/bsv21-actions.ts
@@ -188,11 +188,13 @@ export async function getBsv21Listings(
limit: 100,
});
if (marketOutputs.length === 0) return [];
- const tokenOutputs = await ctx.services.bsv21.validateOutputs(
- tokenId,
- marketOutputs.map((output) => output.outpoint),
- { unspent: true, tags: "bsv21" },
- );
+ // The stack answers null, not [], when no listing holds this token.
+ const tokenOutputs =
+ (await ctx.services.bsv21.validateOutputs(
+ tokenId,
+ marketOutputs.map((output) => output.outpoint),
+ { unspent: true, tags: "bsv21" },
+ )) ?? [];
const marketByOutpoint = new Map(
marketOutputs.map((output) => [toStackOutpoint(output.outpoint), output]),
);
diff --git a/tests/bsv21-actions.test.ts b/tests/bsv21-actions.test.ts
index 2bc566c..f431b54 100644
--- a/tests/bsv21-actions.test.ts
+++ b/tests/bsv21-actions.test.ts
@@ -114,6 +114,16 @@ describe("BSV21 listing safety", () => {
);
});
+ it("reads the stack's null answer as no listings for the token", async () => {
+ const ctx = context();
+ (
+ ctx.services as unknown as {
+ bsv21: { validateOutputs: () => Promise };
+ }
+ ).bsv21.validateOutputs = async () => null;
+ assert.deepEqual(await getBsv21Listings(ctx, tokenId), []);
+ });
+
it("rejects spent, amount-changed, and price-changed reviews", async () => {
assert.deepEqual(
await getBsv21Listings(context({ spentToken: true }), tokenId),
diff --git a/tests/bsv21-icon.test.ts b/tests/bsv21-icon.test.ts
new file mode 100644
index 0000000..cbbed35
--- /dev/null
+++ b/tests/bsv21-icon.test.ts
@@ -0,0 +1,101 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { describe, it } from "node:test";
+import { bsv21IconOutpoint, bsv21IconSrc } from "../lib/bsv21-icon";
+import { STACK_URL, TEST_STACK_URL } from "../lib/stack";
+
+const TXID = "87f1d0785cf9b4951e75e8cf9353d63a49f98e9b6b255bcd6a986db929a00472";
+const TOKEN_ID = `${"ab".repeat(32)}_0`;
+
+/** The source and transforms of an /api/image src. */
+function parseImageSrc(src: string | undefined) {
+ assert.ok(src, "expected an image src");
+ assert.ok(src.startsWith("/api/image?"), src);
+ const params = new URLSearchParams(src.slice("/api/image?".length));
+ return {
+ url: params.get("url"),
+ w: params.get("w"),
+ h: params.get("h"),
+ fit: params.get("fit"),
+ q: params.get("q"),
+ };
+}
+
+describe("BSV-21 token icons", () => {
+ it("renders a bare outpoint icon through OrdFS with resize transforms", () => {
+ const src = bsv21IconSrc(TOKEN_ID, `${TXID}_0`, 80);
+ assert.notEqual(src, `${TXID}_0`);
+ assert.deepEqual(parseImageSrc(src), {
+ url: `${STACK_URL}/content/${TXID}_0`,
+ w: "80",
+ h: "80",
+ fit: null,
+ q: "80",
+ });
+ });
+
+ it("resolves _N to that output of the deploy transaction", () => {
+ assert.equal(bsv21IconOutpoint(TOKEN_ID, "_2"), `${"ab".repeat(32)}_2`);
+ assert.equal(
+ parseImageSrc(bsv21IconSrc(TOKEN_ID, "_2", 128)).url,
+ `${STACK_URL}/content/${"ab".repeat(32)}_2`,
+ );
+ });
+
+ it("accepts txid.vout and upper case, emitting txid_vout", () => {
+ assert.equal(
+ bsv21IconOutpoint(TOKEN_ID, `${TXID.toUpperCase()}.3`),
+ `${TXID}_3`,
+ );
+ });
+
+ it("uses the testnet OrdFS on testnet", () => {
+ assert.equal(
+ parseImageSrc(bsv21IconSrc(TOKEN_ID, `${TXID}_0`, 80, "test")).url,
+ `${TEST_STACK_URL}/content/${TXID}_0`,
+ );
+ });
+
+ it("transforms trusted OrdFS URLs and drops anything else", () => {
+ const ordfs = `https://ordfs.network/content/${TXID}_0`;
+ assert.equal(parseImageSrc(bsv21IconSrc(TOKEN_ID, ordfs, 80)).url, ordfs);
+ const originalError = console.error;
+ const logged: unknown[][] = [];
+ console.error = (...args: unknown[]) => logged.push(args);
+ try {
+ assert.equal(
+ bsv21IconSrc(TOKEN_ID, "https://example.com/x.png", 80),
+ undefined,
+ );
+ assert.equal(bsv21IconSrc(TOKEN_ID, "not-an-icon", 80), undefined);
+ assert.equal(bsv21IconSrc(TOKEN_ID, "not-an-icon", 80), undefined);
+ } finally {
+ console.error = originalError;
+ }
+ assert.equal(logged.length, 2, "each unusable icon is logged once");
+ assert.equal(bsv21IconSrc(TOKEN_ID, undefined, 80), undefined);
+ assert.equal(bsv21IconSrc(TOKEN_ID, "", 80), undefined);
+ });
+
+ it("never hands a raw icon field to an image src", () => {
+ const read = (path: string) =>
+ readFileSync(join(process.cwd(), path), "utf8");
+ const grid = read("components/wallet/token-grid.tsx");
+ assert.match(
+ grid,
+ /bsv21IconSrc\(token\.id, token\.icon, size \* 2, chain\)/,
+ );
+ assert.doesNotMatch(grid, /token\.icon \|\| getOrdinalThumbnail/);
+ assert.match(read("lib/hooks/use-legacy-assets.ts"), /bsv21IconSrc\(/);
+ assert.match(
+ read("app/(main)/market/bsv21/[tokenId]/page.tsx"),
+ /bsv21IconSrc\(tokenId, details\.token\.icon/,
+ );
+ assert.match(read("components/wallet/token-row.tsx"), /onError=/);
+ assert.match(
+ read("app/(main)/market/bsv21/[tokenId]/page.tsx"),
+ //,
+ );
+ });
+});