+
= T | undefined | null;
const registryStore = useRegistryStore();
diff --git a/src/components/address/AddressHeader.vue b/src/components/address/AddressHeader.vue
index 3b8a452..a156dc1 100644
--- a/src/components/address/AddressHeader.vue
+++ b/src/components/address/AddressHeader.vue
@@ -68,7 +68,7 @@ onBeforeUnmount(() => {
const qrAddress = computed(() =>
normalizeDisplayAddress(props.address, {
removePrefix: false,
- }),
+ }) || "",
);
const displayAddress = computed(() => normalizeDisplayAddress(props.address));
const addressType = computed(() => getAddressType(qrAddress.value));
diff --git a/src/components/address/AddressTransaction.vue b/src/components/address/AddressTransaction.vue
index 01c3c90..c0e28c2 100644
--- a/src/components/address/AddressTransaction.vue
+++ b/src/components/address/AddressTransaction.vue
@@ -25,29 +25,24 @@
diff --git a/src/components/Transaction/TransactionList.vue b/src/components/Transaction/TransactionList.vue
index 90a16c2..4b3335a 100644
--- a/src/components/Transaction/TransactionList.vue
+++ b/src/components/Transaction/TransactionList.vue
@@ -106,7 +106,7 @@ export type Transactions = Array<{
diff --git a/src/components/token/Address.vue b/src/components/token/Address.vue
index 303bcef..2a003e8 100644
--- a/src/components/token/Address.vue
+++ b/src/components/token/Address.vue
@@ -66,6 +66,7 @@ const addressList = computed(() => {
([lockingBytecode, amount]) => {
const address = formatLockingBytecodeAddress(
lockingBytecode.substring(2),
+ { tokenCategory: `\\x${props.category}` },
);
if (typeof address !== "string") {
return [];
diff --git a/src/components/token/Child.vue b/src/components/token/Child.vue
index 8c0eb39..de2555c 100644
--- a/src/components/token/Child.vue
+++ b/src/components/token/Child.vue
@@ -81,6 +81,7 @@ const childNfts = computed(() => {
const commitment = output.nonfungible_token_commitment?.substring(2) || "";
const address = formatLockingBytecodeAddress(
output.locking_bytecode.substring(2),
+ { tokenCategory: `\\x${props.category}` },
);
return {
@@ -112,6 +113,7 @@ const outputs = computed(() => {
// Convert locking bytecode to cash address
const address = formatLockingBytecodeAddress(
output.locking_bytecode.substring(2),
+ { tokenCategory: `\\x${props.category}` },
);
// Get nonfungible token commitment
const commitment = output.nonfungible_token_commitment?.substring(2);
diff --git a/src/hooks/addressDisplay.ts b/src/hooks/addressDisplay.ts
index 7c979cc..d66f86d 100644
--- a/src/hooks/addressDisplay.ts
+++ b/src/hooks/addressDisplay.ts
@@ -1,62 +1,107 @@
+import {
+ Base58AddressFormatVersion,
+ base58AddressToLockingBytecode,
+ cashAddressToLockingBytecode,
+ lockingBytecodeToCashAddress,
+} from "@bitauth/libauth";
+import { type InferOutput, picklist, safeParse } from "valibot";
import { useStorage } from "~/hooks/storage";
import {
addPrefixToAddress,
- addressToLockingBytecodeHex,
+ getAddressType,
removeAddressPrefix,
} from "~/module/bitcoin";
-import { useStateStore } from "~/store";
+import { useStateStore } from "~/store/state";
+import type { Utxo } from "~/types";
+
+const addressDisplayModeSchema = picklist(["auto", "token", "regular"]);
+export type AddressDisplayMode = InferOutput;
-export type AddressDisplayMode = "token" | "regular";
+export function useAddressDisplayPreference() {
+ const mode = useStorage("addressDisplayMode", "auto");
+ // Older versions also stored raw strings. useStorage reads both forms;
+ // validate here before a persisted value can control address encoding.
+ const saved = safeParse(addressDisplayModeSchema, mode.value);
+ mode.value = saved.success ? saved.output : "auto";
+ return mode;
+}
-export const addressDisplayMode = useStorage(
- "addressDisplayMode",
- "token",
-);
+export const addressDisplayMode = useAddressDisplayPreference();
type AddressFormatOptions = {
removePrefix?: boolean;
+ tokenCategory?: Utxo["token_category"];
};
-const withDefaultOptions = (opts?: AddressFormatOptions) => ({
- removePrefix: opts?.removePrefix ?? true,
-});
-
-export const formatLockingBytecodeAddress = (
+export function formatLockingBytecodeAddress(
lockingBytecodeHex: string,
opts?: AddressFormatOptions,
-) => {
- const stateStore = useStateStore();
- const tokenSupport = addressDisplayMode.value === "token";
- const address = stateStore.lockingBytecodeHexToCashAddress(
+) {
+ const tokenSupport = {
+ auto: Boolean(opts?.tokenCategory),
+ token: true,
+ regular: false,
+ }[addressDisplayMode.value];
+ const address = useStateStore().lockingBytecodeHexToCashAddress(
lockingBytecodeHex,
tokenSupport,
);
- if (typeof address !== "string") return;
- const options = withDefaultOptions(opts);
- return options.removePrefix ? removeAddressPrefix(address) : address;
-};
+ if (!address) return;
+ return opts?.removePrefix === false ? address : removeAddressPrefix(address);
+}
-export const normalizeDisplayAddress = (
+// The input is a previous output (outpoint) for "from", or a new output for
+// "to". Never infer token presence from the FT amount or address history.
+export function formatUtxoAddress(
+ utxo: Pick,
+) {
+ const bytecode = utxo.locking_bytecode.startsWith("\\x")
+ ? utxo.locking_bytecode.substring(2)
+ : utxo.locking_bytecode;
+ const fullAddress = formatLockingBytecodeAddress(bytecode, {
+ removePrefix: false,
+ tokenCategory: utxo.token_category,
+ });
+ if (!fullAddress) return;
+ const address = removeAddressPrefix(fullAddress);
+ return {
+ fullAddress,
+ address,
+ addressType: getAddressType(fullAddress),
+ url: `/address/${address}`,
+ };
+}
+
+export function normalizeDisplayAddress(
address: string,
- opts?: AddressFormatOptions,
-) => {
- const options = withDefaultOptions(opts);
- const lockingBytecodeHex = addressToLockingBytecodeHex(address);
-
- if (lockingBytecodeHex) {
- const convertedAddress = formatLockingBytecodeAddress(
- lockingBytecodeHex,
- options,
- );
- if (typeof convertedAddress === "string") {
- return convertedAddress;
- }
- }
-
- if (options.removePrefix) {
- return removeAddressPrefix(address);
- }
-
- return addPrefixToAddress(address);
-};
+ opts?: Pick,
+) {
+ const legacy = base58AddressToLockingBytecode(address);
+ const decoded =
+ typeof legacy === "string"
+ ? cashAddressToLockingBytecode(addPrefixToAddress(address))
+ : {
+ bytecode: legacy.bytecode,
+ prefix:
+ legacy.version === Base58AddressFormatVersion.p2pkhTestnet ||
+ legacy.version === Base58AddressFormatVersion.p2sh20Testnet
+ ? ("bchtest" as const)
+ : ("bitcoincash" as const),
+ tokenSupport: false,
+ };
+ if (typeof decoded === "string") return address;
+
+ // An address page has no single UTXO. In auto mode preserve the incoming
+ // encoding (including its network) so following a link retains QR semantics.
+ const tokenSupport = {
+ auto: decoded.tokenSupport,
+ token: true,
+ regular: false,
+ }[addressDisplayMode.value];
+ const encoded = lockingBytecodeToCashAddress({ ...decoded, tokenSupport });
+ if (typeof encoded === "string") return address;
+ return opts?.removePrefix === false
+ ? encoded.address
+ : removeAddressPrefix(encoded.address);
+}
diff --git a/src/pages/settings/index.vue b/src/pages/settings/index.vue
index 47d5a0e..88c300a 100644
--- a/src/pages/settings/index.vue
+++ b/src/pages/settings/index.vue
@@ -72,66 +72,7 @@
{{ $t("address_display_format") }}
-
-
-
-
-
+
@@ -145,6 +86,5 @@
diff --git a/src/pages/token/[category].vue b/src/pages/token/[category].vue
index 2004223..a412c99 100644
--- a/src/pages/token/[category].vue
+++ b/src/pages/token/[category].vue
@@ -188,7 +188,9 @@ const tokenInfo = computed(() => {
? null
: Number(reservedSupply.value);
const ownerAddress =
- lockingBytecode && formatLockingBytecodeAddress(lockingBytecode);
+ lockingBytecode && formatLockingBytecodeAddress(lockingBytecode, {
+ tokenCategory: `\\x${category.value}`,
+ });
const items: contentWarpItem[] = [
{
diff --git a/tests/address-components.test.ts b/tests/address-components.test.ts
new file mode 100644
index 0000000..0a32844
--- /dev/null
+++ b/tests/address-components.test.ts
@@ -0,0 +1,26 @@
+import { expect, test } from "bun:test";
+import { fileURLToPath } from "node:url";
+
+test("Vue address integration regressions", async () => {
+ // Nuxt composables are process globals in these Bun tests. Isolate the Vue
+ // compiler and network stubs from the existing store and USD-price tests.
+ const fixture = fileURLToPath(
+ new URL("./fixtures/address-components.ts", import.meta.url),
+ );
+ const child = Bun.spawn([process.execPath, "test", fixture], {
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const [stdout, stderr, exitCode] = await Promise.all([
+ new Response(child.stdout).text(),
+ new Response(child.stderr).text(),
+ child.exited,
+ ]);
+ expect({
+ exitCode,
+ output: exitCode === 0 ? "passed" : stdout + stderr,
+ }).toEqual({
+ exitCode: 0,
+ output: "passed",
+ });
+});
diff --git a/tests/address-display.test.ts b/tests/address-display.test.ts
new file mode 100644
index 0000000..df20807
--- /dev/null
+++ b/tests/address-display.test.ts
@@ -0,0 +1,237 @@
+import { afterAll, beforeEach, describe, expect, test } from "bun:test";
+import {
+ binToHex,
+ cashAddressToLockingBytecode,
+ encodeBase58Address,
+ hexToBin,
+} from "@bitauth/libauth";
+import { createPinia, setActivePinia } from "pinia";
+import { computed, effectScope, nextTick, ref, watch } from "vue";
+
+Object.assign(globalThis, {
+ computed,
+ ref,
+ watch,
+ gql: (source: string) => source,
+ useSubscription: () => ({ result: ref() }),
+});
+const {
+ addressDisplayMode,
+ formatLockingBytecodeAddress,
+ formatUtxoAddress,
+ normalizeDisplayAddress,
+ useAddressDisplayPreference,
+} = await import("../src/hooks/addressDisplay");
+const { useStateStore } = await import("../src/store/state");
+
+const scripts = [
+ { bytecode: `76a914${"12".repeat(20)}88ac`, label: "P2PKH" },
+ { bytecode: `a914${"12".repeat(20)}87`, label: "P2SH" },
+ { bytecode: `aa20${"12".repeat(32)}87`, label: "P2SH" },
+] as const;
+const category = `\\x${"34".repeat(32)}` as const;
+const holdings = [
+ { name: "BCH only", token_category: null, fungible_token_amount: "0" },
+ { name: "missing category", fungible_token_amount: "500" },
+ { name: "FT", token_category: category, fungible_token_amount: "100" },
+ {
+ name: "NFT without FTs",
+ token_category: category,
+ fungible_token_amount: "0",
+ nonfungible_token_capability: "none",
+ nonfungible_token_commitment: "\\x",
+ },
+];
+
+beforeEach(() => {
+ setActivePinia(createPinia());
+ addressDisplayMode.value = "auto";
+});
+
+for (const mode of ["auto", "token", "regular"] as const) {
+ for (const network of ["mainnet", "chipnet"] as const) {
+ for (const { bytecode, label } of scripts) {
+ for (const holding of holdings) {
+ test(`${mode} ${network} ${bytecode.slice(0, 6)} ${holding.name}`, () => {
+ addressDisplayMode.value = mode;
+ useStateStore().network = network;
+ const output = { ...holding, locking_bytecode: `\\x${bytecode}` };
+ const result = formatUtxoAddress(output);
+ expect(result).toBeDefined();
+ if (!result) throw new Error("Expected a supported address");
+ const decoded = cashAddressToLockingBytecode(result.fullAddress);
+ if (typeof decoded === "string") throw new Error(decoded);
+ expect(binToHex(decoded.bytecode)).toBe(bytecode);
+ expect(decoded.prefix).toBe(
+ network === "mainnet" ? "bitcoincash" : "bchtest",
+ );
+ expect(decoded.tokenSupport).toBe(
+ mode === "token" ||
+ (mode === "auto" && Boolean(output.token_category)),
+ );
+ // Script labels must never imply token holdings, even under override.
+ expect(result.addressType).toBe(label);
+ expect(
+ formatUtxoAddress({ ...output, locking_bytecode: bytecode }),
+ ).toEqual(result);
+
+ // Copy text and the link destination lead to the same full QR payload.
+ const destination = result.url.slice("/address/".length);
+ expect(destination).toBe(result.address);
+ expect(
+ normalizeDisplayAddress(destination, { removePrefix: false }),
+ ).toBe(result.fullAddress);
+ expect(normalizeDisplayAddress(destination)).toBe(result.address);
+ });
+ }
+ }
+ }
+}
+
+test("the same address can have independent BCH-only and token UTXOs", () => {
+ const locking_bytecode = scripts[0].bytecode;
+ const token = formatUtxoAddress({
+ locking_bytecode,
+ token_category: category,
+ });
+ const regular = formatUtxoAddress({ locking_bytecode });
+ expect(regular?.address).not.toBe(token?.address);
+ expect(formatUtxoAddress({ locking_bytecode })).toEqual(regular);
+ expect(formatLockingBytecodeAddress(locking_bytecode)).toBe(regular?.address);
+ const reactiveAddress = computed(() =>
+ formatUtxoAddress({ locking_bytecode }),
+ );
+ expect(reactiveAddress.value).toEqual(regular);
+ addressDisplayMode.value = "token";
+ expect(reactiveAddress.value).toEqual(token);
+ addressDisplayMode.value = "auto";
+ expect(reactiveAddress.value).toEqual(regular);
+});
+
+test("address pages retain the incoming network and encoding independently of selected network", () => {
+ useStateStore().network = "chipnet";
+ const source = formatUtxoAddress({
+ locking_bytecode: scripts[2].bytecode,
+ token_category: category,
+ });
+ if (!source) throw new Error("Expected P2SH32 address");
+ useStateStore().network = "mainnet";
+ expect(normalizeDisplayAddress(source.address, { removePrefix: false })).toBe(
+ source.fullAddress,
+ );
+ addressDisplayMode.value = "regular";
+ const regular = cashAddressToLockingBytecode(
+ normalizeDisplayAddress(source.address, { removePrefix: false }),
+ );
+ if (typeof regular === "string") throw new Error(regular);
+ expect(regular.prefix).toBe("bchtest");
+ expect(regular.tokenSupport).toBe(false);
+ expect(binToHex(regular.bytecode)).toBe(scripts[2].bytecode);
+});
+
+for (const type of [
+ "p2pkh",
+ "p2pkhTestnet",
+ "p2sh20",
+ "p2sh20Testnet",
+] as const) {
+ test(`legacy ${type} becomes regular CashAddr on its original network`, () => {
+ const legacy = encodeBase58Address(type, hexToBin("12".repeat(20)));
+ const fullAddress = normalizeDisplayAddress(legacy, {
+ removePrefix: false,
+ });
+ const decoded = cashAddressToLockingBytecode(fullAddress);
+ if (typeof decoded === "string") throw new Error(decoded);
+ expect(decoded.prefix).toBe(
+ type.endsWith("Testnet") ? "bchtest" : "bitcoincash",
+ );
+ expect(decoded.tokenSupport).toBe(false);
+ addressDisplayMode.value = "token";
+ const token = cashAddressToLockingBytecode(
+ normalizeDisplayAddress(legacy, { removePrefix: false }),
+ );
+ if (typeof token === "string") throw new Error(token);
+ expect(binToHex(token.bytecode)).toBe(binToHex(decoded.bytecode));
+ expect(token.prefix).toBe(decoded.prefix);
+ expect(token.tokenSupport).toBe(true);
+ });
+}
+
+test("unsupported locking bytecode never becomes an address or link", () => {
+ for (const locking_bytecode of ["", "6a", "\\x6a", "51"]) {
+ expect(formatUtxoAddress({ locking_bytecode })).toBeUndefined();
+ }
+});
+
+describe("browser preference migration", () => {
+ const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
+ const previousStorage = Object.getOwnPropertyDescriptor(
+ globalThis,
+ "localStorage",
+ );
+ const values = new Map
();
+ const storage = {
+ getItem: (key: string) => values.get(key) ?? null,
+ setItem: (key: string, value: string) => values.set(key, value),
+ };
+
+ afterAll(() => {
+ for (const [key, descriptor] of [
+ ["window", previousWindow],
+ ["localStorage", previousStorage],
+ ] as const) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else Reflect.deleteProperty(globalThis, key);
+ }
+ });
+
+ for (const saved of [
+ undefined,
+ '"auto"',
+ '"token"',
+ '"regular"',
+ "token",
+ "regular",
+ '"invalid"',
+ "broken-json{",
+ "null",
+ "false",
+ "42",
+ "{}",
+ "[]",
+ ]) {
+ test(`validates and persists saved value ${saved}`, async () => {
+ values.clear();
+ Object.assign(globalThis, {
+ window: { localStorage: storage },
+ localStorage: storage,
+ });
+ if (saved !== undefined) values.set("addressDisplayMode", saved);
+ const scope = effectScope();
+ try {
+ const preference = scope.run(useAddressDisplayPreference);
+ if (!preference) throw new Error("Expected a preference ref");
+ const expected =
+ saved === '"token"' || saved === "token"
+ ? "token"
+ : saved === '"regular"' || saved === "regular"
+ ? "regular"
+ : "auto";
+ expect(preference.value).toBe(expected);
+ await nextTick();
+ if (saved !== undefined && expected === "auto" && saved !== '"auto"') {
+ expect(values.get("addressDisplayMode")).toBe('"auto"');
+ }
+ preference.value = expected === "token" ? "regular" : "token";
+ await nextTick();
+ expect(values.get("addressDisplayMode")).toBe(
+ JSON.stringify(preference.value),
+ );
+ const reloaded = scope.run(useAddressDisplayPreference);
+ expect(reloaded?.value).toBe(preference.value);
+ } finally {
+ scope.stop();
+ }
+ });
+ }
+});
diff --git a/tests/fixtures/address-components.ts b/tests/fixtures/address-components.ts
new file mode 100644
index 0000000..5a4131d
--- /dev/null
+++ b/tests/fixtures/address-components.ts
@@ -0,0 +1,180 @@
+import { beforeEach, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { cashAddressToLockingBytecode } from "@bitauth/libauth";
+import { compileScript, parse } from "@vue/compiler-sfc";
+import { renderToString } from "@vue/server-renderer";
+import { plugin } from "bun";
+import { createPinia, setActivePinia } from "pinia";
+import {
+ computed,
+ createSSRApp,
+ defineComponent,
+ h,
+ onBeforeUnmount,
+ onMounted,
+ reactive,
+ ref,
+ shallowReactive,
+ useId,
+ watch,
+} from "vue";
+
+// Compile the actual Vue components, rather than duplicating their mapping logic.
+plugin({
+ name: "vue-address-regressions",
+ setup(build) {
+ build.onLoad({ filter: /\.vue$/ }, ({ path }) => {
+ const { descriptor } = parse(readFileSync(path, "utf8"), {
+ filename: path,
+ });
+ const script = compileScript(descriptor, {
+ id: path,
+ inlineTemplate: true,
+ });
+ return { contents: script.content, loader: "ts" };
+ });
+ },
+});
+Object.assign(globalThis, {
+ computed,
+ ref,
+ reactive,
+ shallowReactive,
+ watch,
+ onMounted,
+ onBeforeUnmount,
+ useId,
+ gql: (source: string) => source,
+ useSubscription: () => ({ result: ref() }),
+ useQuery: () => ({ onResult: () => undefined }),
+ useFetch: () => ({ data: ref() }),
+});
+const { addressDisplayMode } = await import("../../src/hooks/addressDisplay");
+const { default: TransactionList } = await import(
+ "../../src/components/Transaction/TransactionList.vue"
+);
+const { default: TransactionListOperation } = await import(
+ "../../src/components/Transaction/TransactionListOperation.vue"
+);
+const { default: AddressHeader } = await import(
+ "../../src/components/address/AddressHeader.vue"
+);
+const { default: AddressFormatSettings } = await import(
+ "../../src/components/AddressFormatSettings.vue"
+);
+
+const locking_bytecode = `\\x76a914${"12".repeat(20)}88ac`;
+const category = `\\x${"34".repeat(32)}` as const;
+const bch = { locking_bytecode, value_satoshis: "1000", token_category: null };
+const nft = {
+ ...bch,
+ token_category: category,
+ fungible_token_amount: "0",
+ nonfungible_token_capability: "none" as const,
+ nonfungible_token_commitment: "\\x" as const,
+};
+
+beforeEach(() => {
+ setActivePinia(createPinia());
+ addressDisplayMode.value = "auto";
+});
+
+for (const mode of ["auto", "token", "regular"] as const) {
+ for (const direction of ["spend NFT", "receive FT"] as const) {
+ test(`actual transaction copy, link and destination QR stay consistent: ${mode}, ${direction}`, async () => {
+ addressDisplayMode.value = mode;
+ const copies: { text: string; url?: string; copy: boolean }[] = [];
+ const qrPayloads: string[] = [];
+ const app = createSSRApp(TransactionList, {
+ transactions: [
+ {
+ hash: `\\x${"56".repeat(32)}`,
+ is_coinbase: false,
+ // Same script, different token data on the spent and created output.
+ inputs: [{ outpoint: direction === "spend NFT" ? nft : bch }],
+ outputs: [
+ direction === "spend NFT"
+ ? bch
+ : { ...nft, fungible_token_amount: "100" },
+ { locking_bytecode: "\\x6a0161", value_satoshis: "0" },
+ ],
+ },
+ ],
+ });
+ app.config.globalProperties.$t = (key: string) => key;
+ app.component("TransactionListOperation", TransactionListOperation);
+ app.component(
+ "SliderUpDown",
+ defineComponent({
+ props: { active: Boolean },
+ setup:
+ (_, { slots }) =>
+ () =>
+ slots.default?.(),
+ }),
+ );
+ app.component(
+ "TransactionOperationToken",
+ defineComponent({ setup: () => () => null }),
+ );
+ const Copy = defineComponent({
+ props: {
+ text: { type: String, default: "" },
+ url: String,
+ copy: Boolean,
+ },
+ setup(props) {
+ copies.push({ text: props.text, url: props.url, copy: props.copy });
+ return () => h("span", props.text);
+ },
+ });
+ app.component("BaseCopy", Copy);
+ await renderToString(app);
+ const addresses = copies.filter(({ url }) =>
+ url?.startsWith("/address/"),
+ );
+ expect(addresses).toHaveLength(4); // two summaries and two expanded rows
+ const inputSupport =
+ mode === "token" || (mode === "auto" && direction === "spend NFT");
+ const outputSupport =
+ mode === "token" || (mode === "auto" && direction === "receive FT");
+ const expectedSupport = [
+ inputSupport,
+ outputSupport,
+ inputSupport,
+ outputSupport,
+ ];
+ for (const [index, copy] of addresses.entries()) {
+ expect(copy.url).toBe(`/address/${copy.text}`);
+ const destination = createSSRApp(AddressHeader, { address: copy.text });
+ destination.component("BaseCopy", Copy);
+ destination.component(
+ "VueQrCode",
+ defineComponent({
+ props: { content: { type: String, required: true } },
+ setup(props) {
+ qrPayloads.push(props.content);
+ return () => null;
+ },
+ }),
+ );
+ await renderToString(destination);
+ const decoded = cashAddressToLockingBytecode(qrPayloads[index] || "");
+ if (typeof decoded === "string") throw new Error(decoded);
+ expect(decoded.tokenSupport).toBe(expectedSupport[index] === true);
+ expect(copies.at(-1)?.text).toBe(copy.text);
+ }
+ expect(addresses.slice(2).every(({ copy }) => copy)).toBe(true);
+ });
+ }
+}
+
+test("settings render three native radio choices with the effective preference selected", async () => {
+ for (const mode of ["auto", "token", "regular"] as const) {
+ addressDisplayMode.value = mode;
+ const html = await renderToString(createSSRApp(AddressFormatSettings));
+ expect(html.match(/type="radio"/g)).toHaveLength(3);
+ expect(html.match(/ checked/g)).toHaveLength(1);
+ expect(html.match(/]+checked>/)?.[0]).toContain(`value="${mode}"`);
+ }
+});
From a9bb934b996b8f7fe508f12013f9d0ffe51b7fc2 Mon Sep 17 00:00:00 2001
From: Salem Mohammed Shamakh <58360393+salemkode@users.noreply.github.com>
Date: Sat, 14 Nov 2026 23:10:32 +0300
Subject: [PATCH 4/7] fix: complete NFT galleries for collections and addresses
---
docs/nft-gallery.md | 65 ++++
src/components/NavPills.vue | 3 +-
src/components/address/AddressNFTs.vue | 88 +++--
src/components/token/Child.vue | 67 ++--
src/components/token/NFTGallery.vue | 126 ++++---
src/components/token/NFTImage.vue | 83 +++++
src/hooks/nftPagination.ts | 36 ++
src/module/chaingraph.ts | 6 +
tests/fixtures/nft-gallery.ts | 475 +++++++++++++++++++++++++
tests/nft-gallery.test.ts | 26 ++
tests/vue-fixture.ts | 119 +++++++
11 files changed, 969 insertions(+), 125 deletions(-)
create mode 100644 docs/nft-gallery.md
create mode 100644 src/components/token/NFTImage.vue
create mode 100644 src/hooks/nftPagination.ts
create mode 100644 tests/fixtures/nft-gallery.ts
create mode 100644 tests/nft-gallery.test.ts
create mode 100644 tests/vue-fixture.ts
diff --git a/docs/nft-gallery.md b/docs/nft-gallery.md
new file mode 100644
index 0000000..31742a8
--- /dev/null
+++ b/docs/nft-gallery.md
@@ -0,0 +1,65 @@
+# NFT gallery
+
+On a token collection page, choose **Grid View** above the child NFT list. On an
+address page, open **Cash token**, then choose **Grid View** above **Address NFTs**.
+**Table View** remains available in both contexts. The collection view preference
+continues to be saved by the token page; the address view starts as a table.
+
+The gallery shows up to 24 unspent NFT outputs per page. Previous/next buttons
+load adjacent pages; switching views, addresses, collections, or networks returns
+to the first page. Queries use a transaction-hash/output-index ordering and fetch
+one extra output to detect another page. Holdings can change between requests;
+this is offset pagination over current holdings, not a historical snapshot.
+The existing child collection query excludes minting outputs; address NFTs include
+them. This change does not alter those filters or token totals.
+
+Each card shows its category, exact hexadecimal commitment, capability, owner
+when the locking script can be represented as a CashAddr, and output outpoint.
+Category, owner, and output link to their explorer pages. Two NFTs with the same
+commitment are separate cards because their outpoints differ. An empty commitment
+is a valid NFT state and is labeled **Empty commitment**.
+
+Collection names and artwork follow the selected registry. Artwork uses the registered full image, then the token icon, then a generated
+category placeholder. Image and metadata loading are labeled separately. Missing
+metadata does not remove the NFT or hide its on-chain details. A generated
+placeholder is labeled **Image unavailable** and cannot open an image preview.
+
+Activate **View token image** with a pointer, Enter, or Space after artwork loads.
+The full image opens in a native modal dialog. Close it using **Close**, Escape,
+or the backdrop. The browser confines focus to the dialog and restores it to the
+trigger on dismissal. No animation is required. The card layout uses the existing
+slate/zinc surfaces, emerald focus/link colors, and responsive grid.
+
+## Regression checks
+
+Run from the repository root:
+
+```bash
+bun install --frozen-lockfile
+bun run lint
+bun run test
+bun run lint:type
+bun run build
+```
+
+`tests/nft-gallery.test.ts` compiles the actual Vue components using the Vue
+compiler and runs them through a small Vue host fixture without adding a browser
+test dependency. It checks duplicate-commitment reconciliation, missing metadata,
+empty commitments, query binding and retry, first/last pages and lookahead,
+context/view/network resets, disabled loading navigation, image fallback/reset,
+and image-dialog open/close event handlers.
+
+These fixtures do not verify browser focus management or CSS layout. For browser
+QA, use an allowed built-in browser session and verify:
+
+- A collection and an address with NFTs switch between both views. Navigate
+ forward/back, including the final partial page; no lookahead card is rendered.
+- Distinct outputs with identical commitments stay separate, including after
+ pagination. Confirm full commitments and owner/category/output destinations.
+- A metadata-free NFT remains visible with on-chain details. Check a failed image,
+ an icon-only NFT, and a fully missing image; the placeholder does not loop.
+- Query loading hides stale cards, an empty result is explained, and a failed
+ query offers **Try again** and a previous-page action when applicable.
+- At narrow and desktop widths in light/dark themes, long commitments and names
+ stay within cards. Keyboard focus remains visible; Enter/Space opens artwork,
+ Tab stays within the dialog, Escape closes it, and focus returns to the trigger.
diff --git a/src/components/NavPills.vue b/src/components/NavPills.vue
index d9a7263..55e4b0c 100644
--- a/src/components/NavPills.vue
+++ b/src/components/NavPills.vue
@@ -4,7 +4,8 @@
v-for="(item, index) in props.items"
:key="index"
type="button"
- class="flex-1 py-2 px-3 sm:px-4 rounded-xl text-xs sm:text-sm font-semibold text-center transition-all cursor-pointer select-none"
+ :aria-pressed="navItem === index"
+ class="flex-1 py-2 px-3 sm:px-4 rounded-xl text-xs sm:text-sm font-semibold text-center transition-all motion-reduce:transition-none cursor-pointer select-none focus-visible:outline-2 focus-visible:outline-emerald-500"
:class="
navItem === index
? 'bg-white dark:bg-zinc-800 text-slate-900 dark:text-white shadow-xs border border-slate-200/60 dark:border-zinc-700/60'
diff --git a/src/components/address/AddressNFTs.vue b/src/components/address/AddressNFTs.vue
index 38c5084..ebb0da7 100644
--- a/src/components/address/AddressNFTs.vue
+++ b/src/components/address/AddressNFTs.vue
@@ -1,30 +1,62 @@
-
+
+
+
+
+
diff --git a/src/components/token/Child.vue b/src/components/token/Child.vue
index de2555c..dadb19a 100644
--- a/src/components/token/Child.vue
+++ b/src/components/token/Child.vue
@@ -8,18 +8,20 @@
:has-next-page="!!hasNextPage"
:loading="loading"
:error="error?.message"
- @next="offset += pageSize"
- @previous="offset -= pageSize"
+ @next="next(loading, hasNextPage && !error)"
+ @previous="previous(loading)"
/>
@@ -27,29 +29,31 @@
import type { GetTokenChildQuery } from "@/module/chaingraph";
import { GetTokenChild } from "@/module/chaingraph";
import { formatLockingBytecodeAddress } from "~/hooks/addressDisplay";
+import { nftPage, useNftPagination } from "~/hooks/nftPagination";
import { useStateStore } from "~/store";
import type { IdentitySnapshot, tableColumn } from "~/types/index.js";
import NFTGallery, { type ChildNftItem } from "./NFTGallery.vue";
const stateStore = useStateStore();
-const offset = ref(0);
const props = defineProps<{
category: string;
- identitySnapshot?: IdentitySnapshot;
+ identitySnapshot?: IdentitySnapshot | null;
viewMode?: "table" | "grid";
}>();
const effectiveViewMode = computed(() =>
props.viewMode === "grid" ? "grid" : "table",
);
-const pageSize = computed(() => (effectiveViewMode.value === "grid" ? 24 : 8));
-const limit = computed(() => pageSize.value + 1);
+const { offset, pageSize, limit, next, previous } = useNftPagination(
+ () => `${stateStore.network}:${props.category}`,
+ () => effectiveViewMode.value,
+);
const variable = computed(() => ({
network: stateStore.network,
tokenCategory: `\\x${props.category}` as const,
offset: offset.value,
limit: limit.value,
}));
-const { result, loading, error } = useQuery(GetTokenChild, variable);
+const { result, loading, error, refetch } = useQuery(GetTokenChild, variable);
const types = computed(() => props.identitySnapshot?.token?.nfts?.parse.types);
const showTokenColumn = computed(() => {
@@ -64,52 +68,37 @@ const column = computed(() => {
}
return result;
});
-const hasNextPage = computed(() => {
- if (result.value) {
- return result.value.output.length === limit.value;
- }
- return false;
-});
+const page = computed(() => nftPage(result.value?.output || [], pageSize.value));
+const hasNextPage = computed(() => page.value.hasNextPage);
type ChildOutput = GetTokenChildQuery["output"][number];
-const childNfts = computed(() => {
- if (!result.value) {
- return [];
- }
+const childNfts = computed(() =>
+ page.value.items.flatMap((output) => {
+ if (!output.nonfungible_token_capability) return [];
- let items = result.value.output.map((output: ChildOutput) => {
const commitment = output.nonfungible_token_commitment?.substring(2) || "";
const address = formatLockingBytecodeAddress(
output.locking_bytecode.substring(2),
{ tokenCategory: `\\x${props.category}` },
);
- return {
+
+ return [{
+ id: `${output.transaction_hash.substring(2)}:${output.output_index}`,
category: props.category,
capability: output.nonfungible_token_capability,
commitment,
- address: typeof address === "string" ? address : undefined,
- name: types.value?.[commitment]?.name || "N/A",
- };
- });
-
- if (items.length === limit.value) {
- items = items.slice(0, -1);
- }
-
- return items;
-});
-
-watch(effectiveViewMode, () => {
- offset.value = 0;
-});
+ address,
+ }];
+ }),
+);
const outputs = computed(() => {
if (!result.value) {
return [];
}
- let items = result.value?.output.map((output: ChildOutput) => {
+ const items = page.value.items.map((output: ChildOutput) => {
// Convert locking bytecode to cash address
const address = formatLockingBytecodeAddress(
output.locking_bytecode.substring(2),
@@ -155,10 +144,6 @@ const outputs = computed(() => {
return item;
});
- // Remove last item if it reaches the limit
- if (items.length === limit.value) {
- items = items.slice(0, -1);
- }
return items;
});
diff --git a/src/components/token/NFTGallery.vue b/src/components/token/NFTGallery.vue
index 5beeb8d..0e430f6 100644
--- a/src/components/token/NFTGallery.vue
+++ b/src/components/token/NFTGallery.vue
@@ -1,90 +1,98 @@
-
-
-
-
- {{ $t("nft_gallery") }}
-
+
+
+
{{ $t("nft_gallery") }}
-
- {{ error }}
+
+
Could not load NFTs. Try again.
+
{{ error }}
+
-
-
-
-
-
-
+
+
+ Loading NFTs…
+
+
No NFTs found on this page.
+
+
+
+
+
+ {{ item.name }}
+ Loading metadata…
+ Metadata unavailable
+
+
+
- {{ $t("category") }}
+
-
-
- {{ item.name }}
+
+
- {{ $t("commitment") }}
+
+ - Empty commitment
-
-
-
- {{ $t("category") }}
-
-
-
-
- {{ $t("commitment") }}
-
-
+
+
- {{ $t("capability") }}
+ - {{ item.capability }}
-
-
+
+
- {{ $t("tokenstats_nft_owner") }}
+
+
+
+
- Output
+
+
+
+
-
-
-
+
diff --git a/src/components/token/NFTImage.vue b/src/components/token/NFTImage.vue
new file mode 100644
index 0000000..b06fbeb
--- /dev/null
+++ b/src/components/token/NFTImage.vue
@@ -0,0 +1,83 @@
+
+
+
+
Loading image…
+
Image unavailable
+
+
+
+
+
+
diff --git a/src/hooks/nftPagination.ts b/src/hooks/nftPagination.ts
new file mode 100644
index 0000000..13d8ffb
--- /dev/null
+++ b/src/hooks/nftPagination.ts
@@ -0,0 +1,36 @@
+import { computed, ref, watch } from "vue";
+
+// Fetch one extra output to detect the next page without a separate count query.
+export function useNftPagination(
+ context: () => string,
+ viewMode: () => string,
+) {
+ const offset = ref(0);
+ const pageSize = computed(() => (viewMode() === "grid" ? 24 : 8));
+ const limit = computed(() => pageSize.value + 1);
+
+ watch(
+ [context, viewMode],
+ () => {
+ offset.value = 0;
+ },
+ { flush: "sync" },
+ );
+
+ function next(loading: boolean, hasNextPage: boolean) {
+ if (!loading && hasNextPage) offset.value += pageSize.value;
+ }
+
+ function previous(loading: boolean) {
+ if (!loading) offset.value = Math.max(0, offset.value - pageSize.value);
+ }
+
+ return { offset, pageSize, limit, next, previous };
+}
+
+export function nftPage
(outputs: readonly T[], pageSize: number) {
+ return {
+ items: outputs.slice(0, pageSize),
+ hasNextPage: outputs.length > pageSize,
+ };
+}
diff --git a/src/module/chaingraph.ts b/src/module/chaingraph.ts
index a9c118a..ce0cbfc 100644
--- a/src/module/chaingraph.ts
+++ b/src/module/chaingraph.ts
@@ -406,6 +406,7 @@ export const GetTokenChild = gql(`
output(
limit: $limit
offset: $offset
+ order_by: [{ transaction_hash: asc }, { output_index: asc }]
where: {
transaction: {
block_inclusions: {
@@ -417,6 +418,8 @@ export const GetTokenChild = gql(`
_not: { spent_by: { transaction: { hash: { _gt: "" } } } }
}
) {
+ transaction_hash
+ output_index
locking_bytecode
nonfungible_token_capability
nonfungible_token_commitment
@@ -434,6 +437,7 @@ export const GetAddressNFTs = gql(`
search_output(
limit: $limit
offset: $offset
+ order_by: [{ transaction_hash: asc }, { output_index: asc }]
args: { locking_bytecode_hex: $lockingBytecode }
where: {
token_category: { _is_null: false }
@@ -446,6 +450,8 @@ export const GetAddressNFTs = gql(`
_not: { spent_by: { transaction: { hash: { _gt: "" } } } }
}
) {
+ transaction_hash
+ output_index
token_category
nonfungible_token_capability
nonfungible_token_commitment
diff --git a/tests/fixtures/nft-gallery.ts b/tests/fixtures/nft-gallery.ts
new file mode 100644
index 0000000..3b2e4b2
--- /dev/null
+++ b/tests/fixtures/nft-gallery.ts
@@ -0,0 +1,475 @@
+import { afterEach, describe, expect, mock, test } from "bun:test";
+import {
+ computed,
+ defineComponent,
+ effectScope,
+ h,
+ nextTick,
+ reactive,
+ ref,
+ toRef,
+ watchEffect,
+} from "vue";
+import { nftPage, useNftPagination } from "../../src/hooks/nftPagination";
+import type { IdentitySnapshot } from "../../src/types";
+import { dispatch, mountFixture, nodes, text } from "../vue-fixture";
+
+const network = reactive({ network: "mainnet" });
+const metadata = reactive({ loading: false, available: false });
+mock.module("../../src/store/index.ts", () => ({
+ useStateStore: () => network,
+ useRegistryStore: () => ({
+ getToken: () =>
+ metadata.available
+ ? {
+ loading: false,
+ token: {
+ name: "Fixture NFT",
+ icon: "https://example.com/icon.png",
+ image: "https://example.com/full.png",
+ },
+ }
+ : { loading: metadata.loading },
+ }),
+}));
+mock.module("../../src/module/utils.ts", () => ({
+ getHttpsUrl: (url: string) => url,
+ svgToBase64: (svg: string) => `data:image/svg+xml;base64,${btoa(svg)}`,
+}));
+
+mock.module("../../src/hooks/addressDisplay.ts", () => ({
+ formatLockingBytecodeAddress: (
+ _bytecode: string,
+ context?: { tokenCategory?: string },
+ ) => (context?.tokenCategory ? "zowner" : "qowner"),
+}));
+mock.module("../../src/hooks/authchains.ts", () => ({
+ useAuthChains: () => undefined,
+}));
+const fixtureOutputs = Array.from({ length: 25 }, (_, index) => ({
+ transaction_hash: `\\x${"01".repeat(32)}`,
+ output_index: String(index),
+ token_category: `\\x${"ab".repeat(32)}`,
+ nonfungible_token_commitment: "\\x00ff",
+ nonfungible_token_capability: "none",
+ locking_bytecode: "\\x76a914fixture88ac",
+}));
+const query = {
+ result: ref({ output: fixtureOutputs, search_output: fixtureOutputs }),
+ loading: ref(false),
+ error: ref(),
+ refetch: mock(),
+};
+const queryVariables = ref({ offset: 0, limit: 0 });
+Object.assign(globalThis, {
+ computed,
+ ref,
+ toRef,
+ gql: (source: string) => source,
+ useQuery: (
+ _document: unknown,
+ variables: { value: { offset: number; limit: number } },
+ ) => {
+ watchEffect(() => {
+ queryVariables.value = variables.value;
+ });
+ return query;
+ },
+});
+
+const { default: NFTGallery } = await import(
+ "../../src/components/token/NFTGallery.vue"
+);
+const { default: NFTImage } = await import(
+ "../../src/components/token/NFTImage.vue"
+);
+const { default: BasePagination } = await import(
+ "../../src/components/BasePagination.vue"
+);
+const { default: TokenChild } = await import(
+ "../../src/components/token/Child.vue"
+);
+const { default: AddressNFTs } = await import(
+ "../../src/components/address/AddressNFTs.vue"
+);
+const CopyFixture = defineComponent({
+ props: { text: String, url: String },
+ setup: (props) => () => h("a", { href: props.url }, props.text),
+});
+const cleanup = new Set<() => void>();
+afterEach(() => {
+ for (const unmount of cleanup) unmount();
+ cleanup.clear();
+ metadata.loading = false;
+ metadata.available = false;
+});
+
+function mountGallery(items = [nft("01", "0"), nft("01", "1")]) {
+ const events = { next: mock(), previous: mock(), retry: mock() };
+ const props = reactive({
+ identitySnapshot: undefined as IdentitySnapshot | null | undefined,
+ items,
+ loading: false,
+ error: "",
+ hasPrevPage: false,
+ hasNextPage: true,
+ onNext: events.next,
+ onPrevious: events.previous,
+ onRetry: events.retry,
+ });
+ const mounted = mountFixture(NFTGallery, props, {
+ BasePagination,
+ LoadingSpinner: { render: () => h("span", "spinner") },
+ BaseCopy: CopyFixture,
+ });
+ cleanup.add(mounted.unmount);
+ return { ...mounted, props, events };
+}
+
+function nft(hash: string, index: string) {
+ return {
+ id: `${hash.repeat(32)}:${index}`,
+ category: "ab".repeat(32),
+ commitment: "00ff",
+ capability: "none" as const,
+ address: "qowner",
+ };
+}
+
+describe("NFT gallery fixtures", () => {
+ test("identical commitments retain separate card and image state during a page update", async () => {
+ metadata.available = true;
+ const { root, props } = mountGallery();
+ const articles = nodes(root, "article");
+ expect(articles).toHaveLength(2);
+ props.items = [nft("01", "1"), nft("02", "0")];
+ await nextTick();
+ expect(nodes(root, "article")[0]).toBe(articles[1]);
+ expect(nodes(root, "article")[1]).not.toBe(articles[0]);
+ expect(nodes(root, "a").map((link) => link.props.href)).toContain(
+ `/token/${"ab".repeat(32)}`,
+ );
+ expect(nodes(root, "a").map((link) => link.props.href)).toContain(
+ "/address/qowner",
+ );
+ expect(text(root)).toContain("00ff");
+ expect(text(root)).toContain("none");
+ });
+
+ test("metadata unavailable and empty commitments do not hide NFTs", async () => {
+ const { root, props } = mountGallery([
+ { ...nft("01", "0"), commitment: "" },
+ ]);
+ expect(text(root)).toContain("Unnamed NFT");
+ expect(text(root)).toContain("Metadata unavailable");
+ expect(text(root)).toContain("Empty commitment");
+ metadata.loading = true;
+ await nextTick();
+ expect(text(root)).toContain("Loading metadata…");
+ expect(nodes(root, "article")).toHaveLength(1);
+ props.items = [];
+ await nextTick();
+ expect(text(root)).toContain("No NFTs found on this page.");
+ });
+
+ test("loading hides stale cards and blocks page actions; errors offer retry and previous", async () => {
+ const { root, props, events } = mountGallery();
+ props.loading = true;
+ await nextTick();
+ expect(nodes(root, "article")).toHaveLength(0);
+ expect(text(root)).toContain("Loading NFTs…");
+ expect(
+ nodes(root, "button").find(
+ (node) => node.props["aria-label"] === "Next page",
+ )?.props.disabled,
+ ).toBe(true);
+ props.loading = false;
+ props.error = "Indexer offline";
+ props.hasPrevPage = true;
+ await nextTick();
+ expect(text(root)).toContain("Indexer offline");
+ dispatch(
+ nodes(root, "button").find((node) => node.text === "Try again"),
+ "onClick",
+ );
+ expect(events.retry).toHaveBeenCalledTimes(1);
+ dispatch(
+ nodes(root, "button").find(
+ (node) => node.props["aria-label"] === "Previous page",
+ ),
+ "onClick",
+ );
+ expect(events.previous).toHaveBeenCalledTimes(1);
+ });
+ test("explicit missing selected metadata never falls back to an unrelated registry", async () => {
+ metadata.available = true;
+ const { root, props } = mountGallery();
+ expect(text(root)).toContain("Fixture NFT");
+ props.identitySnapshot = {
+ name: "Selected revision",
+ uris: { image: "https://example.com/selected.png" },
+ };
+ await nextTick();
+ expect(text(root)).toContain("Selected revision");
+ props.identitySnapshot = null;
+ await nextTick();
+ expect(text(root)).toContain("Metadata unavailable");
+ expect(text(root)).not.toContain("Fixture NFT");
+ expect(text(root)).not.toContain("Selected revision");
+ expect(nodes(root, "img")[0]?.props.src).toStartWith(
+ "data:image/svg+xml;base64,",
+ );
+ props.identitySnapshot = undefined;
+ await nextTick();
+ expect(text(root)).toContain("Fixture NFT");
+ });
+});
+
+describe("NFT image behavior", () => {
+ function mountImage() {
+ const props = reactive({
+ category: "ab".repeat(32),
+ name: "Fixture NFT",
+ image: "https://example.com/full.png",
+ icon: "https://example.com/icon.png",
+ });
+ const mounted = mountFixture(NFTImage, props);
+ cleanup.add(mounted.unmount);
+ return { ...mounted, props };
+ }
+
+ test("full artwork opens after load and closes by button or Escape", async () => {
+ const { root } = mountImage();
+ const trigger = nodes(root, "button")[0];
+ expect(trigger?.props.disabled).toBe(true);
+ dispatch(nodes(root, "img")[0], "onLoad");
+ await nextTick();
+ expect(trigger?.props.disabled).toBe(false);
+ dispatch(trigger, "onClick");
+ const dialog = nodes(root, "dialog")[0];
+ expect(dialog?.open).toBe(true);
+ expect(nodes(root, "img")[1]?.props.src).toBe(
+ "https://example.com/full.png",
+ );
+ dispatch(dialog, "onKeydown", { key: "Escape" });
+ expect(dialog?.open).toBe(false);
+ dispatch(trigger, "onClick");
+ dispatch(nodes(root, "button")[1], "onClick");
+ expect(dialog?.open).toBe(false);
+ });
+
+ test("changing only an inactive icon preserves loaded artwork and dialog readiness", async () => {
+ const { root, props } = mountImage();
+ dispatch(nodes(root, "img")[0], "onLoad");
+ await nextTick();
+ const image = nodes(root, "img")[0];
+ props.icon = "https://example.com/new-icon.png";
+ await nextTick();
+ expect(nodes(root, "img")[0]).toBe(image);
+ expect(nodes(root, "button")[0]?.props.disabled).toBe(false);
+ dispatch(nodes(root, "button")[0], "onClick");
+ expect(nodes(root, "dialog")[0]?.open).toBe(true);
+ dispatch(image, "onError");
+ await nextTick();
+ expect(nodes(root, "img")[0]?.props.src).toBe(props.icon);
+ expect(nodes(root, "button")[0]?.props.disabled).toBe(true);
+ expect(nodes(root, "dialog")[0]?.open).toBe(false);
+ dispatch(nodes(root, "img")[0], "onLoad");
+ await nextTick();
+ expect(nodes(root, "button")[0]?.props.disabled).toBe(false);
+ });
+
+ test("failed artwork falls back to icon, then a bounded generated placeholder; new URLs reset", async () => {
+ const { root, props } = mountImage();
+ dispatch(nodes(root, "img")[0], "onError");
+ await nextTick();
+ expect(nodes(root, "img")[0]?.props.src).toBe(
+ "https://example.com/icon.png",
+ );
+ dispatch(nodes(root, "img")[0], "onError");
+ await nextTick();
+ expect(nodes(root, "img")[0]?.props.src).toStartWith(
+ "data:image/svg+xml;base64,",
+ );
+ dispatch(nodes(root, "img")[0], "onError");
+ await nextTick();
+ expect(text(root)).toContain("Image unavailable");
+ expect(nodes(root, "button")[0]?.props.disabled).toBe(true);
+ props.image = "https://example.com/recovered.png";
+ await nextTick();
+ expect(nodes(root, "img")[0]?.props.src).toBe(props.image);
+ expect(text(root)).toContain("Loading image…");
+ });
+});
+
+describe("NFT page navigation", () => {
+ test("lookahead is not rendered and adjacent pages preserve repeated commitments", () => {
+ const outputs = Array.from({ length: 49 }, (_, index) =>
+ nft("01", String(index)),
+ );
+ const first = nftPage(outputs.slice(0, 25), 24);
+ const second = nftPage(outputs.slice(24, 49), 24);
+ const last = nftPage(outputs.slice(48), 24);
+ expect(first.items).toHaveLength(24);
+ expect(first.hasNextPage).toBe(true);
+ expect(second.hasNextPage).toBe(true);
+ expect(last.hasNextPage).toBe(false);
+ expect(
+ new Set(
+ [...first.items, ...second.items, ...last.items].map((item) => item.id),
+ ).size,
+ ).toBe(49);
+ expect(nftPage(outputs.slice(0, 24), 24).hasNextPage).toBe(false);
+ expect(nftPage([], 24).items).toEqual([]);
+ });
+
+ test("mode, address/category and network changes reset offset; loading blocks navigation", () => {
+ const scope = effectScope();
+ scope.run(() => {
+ const context = reactive({
+ network: "mainnet",
+ identity: "collection-a",
+ mode: "grid",
+ });
+ const pager = useNftPagination(
+ () => `${context.network}:${context.identity}`,
+ () => context.mode,
+ );
+ expect(pager.limit.value).toBe(25);
+ pager.next(false, true);
+ expect(pager.offset.value).toBe(24);
+ pager.next(true, true);
+ pager.previous(true);
+ expect(pager.offset.value).toBe(24);
+ context.mode = "table";
+ expect(pager.offset.value).toBe(0);
+ expect(pager.limit.value).toBe(9);
+ pager.next(false, false);
+ expect(pager.offset.value).toBe(0);
+ pager.next(false, true);
+ context.identity = "address-b";
+ expect(pager.offset.value).toBe(0);
+ pager.next(false, true);
+ context.network = "chipnet";
+ expect(pager.offset.value).toBe(0);
+ pager.previous(false);
+ expect(pager.offset.value).toBe(0);
+ });
+ scope.stop();
+ });
+});
+
+describe("address and collection gallery integration", () => {
+ const components = {
+ BasePagination,
+ LoadingSpinner: { render: () => h("span", "spinner") },
+ BaseCopy: CopyFixture,
+ TableView: { render: () => h("div", "NFT table") },
+ };
+
+ test("address NFTs switch from table to gallery, paginate and retry using the real query bindings", async () => {
+ const props = reactive({ lockingBytecode: "76a914fixture88ac" });
+ const { root, unmount } = mountFixture(AddressNFTs, props, components);
+ cleanup.add(unmount);
+ expect(text(root)).toContain("NFT table");
+ expect(queryVariables.value.limit).toBe(9);
+ dispatch(
+ nodes(root, "button").find((node) => node.text === "grid_view"),
+ "onClick",
+ );
+ await nextTick();
+ expect(queryVariables.value.limit).toBe(25);
+ expect(nodes(root, "article")).toHaveLength(24);
+ expect(
+ nodes(root, "a").filter((node) => node.props.href === "/address/zowner"),
+ ).toHaveLength(24);
+ dispatch(
+ nodes(root, "button").find(
+ (node) => node.props["aria-label"] === "Next page",
+ ),
+ "onClick",
+ );
+ await nextTick();
+ expect(queryVariables.value.offset).toBe(24);
+ query.result.value = {
+ output: fixtureOutputs.slice(24),
+ search_output: fixtureOutputs.slice(24),
+ };
+ await nextTick();
+ expect(nodes(root, "article")).toHaveLength(1);
+ expect(
+ nodes(root, "button").find(
+ (node) => node.props["aria-label"] === "Next page",
+ )?.props.disabled,
+ ).toBe(true);
+ query.error.value = new Error("Indexer offline");
+ await nextTick();
+ dispatch(
+ nodes(root, "button").find((node) => node.text === "Try again"),
+ "onClick",
+ );
+ expect(query.refetch).toHaveBeenCalledTimes(1);
+ query.error.value = undefined;
+ props.lockingBytecode = "other-address";
+ await nextTick();
+ expect(queryVariables.value.offset).toBe(0);
+ });
+
+ test("collection outputs become distinct outpoints and reset pages on category or view changes", async () => {
+ query.result.value = {
+ output: fixtureOutputs,
+ search_output: fixtureOutputs,
+ };
+ const props = reactive({
+ category: "ab".repeat(32),
+ viewMode: "grid",
+ identitySnapshot: {
+ name: "Selected collection",
+ token: {
+ category: "ab".repeat(32),
+ symbol: "NFT",
+ nfts: {
+ parse: {
+ types: {
+ "00ff": {
+ name: "Selected NFT",
+ uris: { image: "https://example.com/selected.png" },
+ },
+ },
+ },
+ },
+ },
+ },
+ });
+ const { root, unmount } = mountFixture(TokenChild, props, components);
+ cleanup.add(unmount);
+ expect(nodes(root, "article")).toHaveLength(24);
+ expect(
+ nodes(root, "a").filter((node) => node.props.href === "/address/zowner"),
+ ).toHaveLength(24);
+ expect(text(root)).toContain("Selected NFT");
+ expect(text(root)).not.toContain("Metadata unavailable");
+ expect(nodes(root, "img")[0]?.props.src).toBe(
+ "https://example.com/selected.png",
+ );
+ const outputLinks = nodes(root, "a").filter((node) =>
+ String(node.props.href).startsWith("/tx/"),
+ );
+ expect(new Set(outputLinks.map((node) => node.text)).size).toBe(24);
+ dispatch(
+ nodes(root, "button").find(
+ (node) => node.props["aria-label"] === "Next page",
+ ),
+ "onClick",
+ );
+ await nextTick();
+ expect(queryVariables.value.offset).toBe(24);
+ props.category = "cd".repeat(32);
+ await nextTick();
+ expect(queryVariables.value.offset).toBe(0);
+ props.viewMode = "table";
+ await nextTick();
+ expect(queryVariables.value.limit).toBe(9);
+ expect(text(root)).toContain("NFT table");
+ });
+});
diff --git a/tests/nft-gallery.test.ts b/tests/nft-gallery.test.ts
new file mode 100644
index 0000000..0750474
--- /dev/null
+++ b/tests/nft-gallery.test.ts
@@ -0,0 +1,26 @@
+import { expect, test } from "bun:test";
+import { fileURLToPath } from "node:url";
+
+test("Vue NFT gallery integration regressions", async () => {
+ // Nuxt composables are process globals in these Bun tests. Isolate the Vue
+ // compiler and network stubs from the existing store and USD-price tests.
+ const fixture = fileURLToPath(
+ new URL("./fixtures/nft-gallery.ts", import.meta.url),
+ );
+ const child = Bun.spawn([process.execPath, "test", fixture], {
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const [stdout, stderr, exitCode] = await Promise.all([
+ new Response(child.stdout).text(),
+ new Response(child.stderr).text(),
+ child.exited,
+ ]);
+ expect({
+ exitCode,
+ output: exitCode === 0 ? "passed" : stdout + stderr,
+ }).toEqual({
+ exitCode: 0,
+ output: "passed",
+ });
+});
diff --git a/tests/vue-fixture.ts b/tests/vue-fixture.ts
new file mode 100644
index 0000000..49fccff
--- /dev/null
+++ b/tests/vue-fixture.ts
@@ -0,0 +1,119 @@
+import { readFile } from "node:fs/promises";
+import { resolve } from "node:path";
+import { compileScript, parse } from "@vue/compiler-sfc";
+import { plugin } from "bun";
+import { type Component, createRenderer, h, markRaw } from "vue";
+
+// Compile the actual SFCs; exercise Vue updates without a browser or a test-only UI copy.
+plugin({
+ name: "vue-fixture",
+ setup(build) {
+ build.onResolve({ filter: /^[~@]\// }, ({ path }) => ({
+ path: Bun.resolveSync(
+ resolve(import.meta.dir, "../src", path.slice(2)),
+ import.meta.dir,
+ ),
+ }));
+ build.onLoad({ filter: /\.vue$/ }, async ({ path }) => {
+ const { descriptor } = parse(await readFile(path, "utf8"), {
+ filename: path,
+ });
+ return {
+ contents: compileScript(descriptor, { id: path, inlineTemplate: true })
+ .content,
+ loader: "ts",
+ };
+ });
+ },
+});
+
+// Only the host boundary is simulated. Component setup, templates, event handlers,
+// computed state, keyed reconciliation, and watchers are Vue's real implementation.
+class FixtureNode {
+ children: FixtureNode[] = [];
+ parent: FixtureNode | null = null;
+ props: Record = {};
+ text = "";
+ open = false;
+ constructor(public tag: string) {}
+ showModal() {
+ this.open = true;
+ }
+ close() {
+ this.open = false;
+ }
+}
+
+const renderer = createRenderer({
+ createElement: (tag) => markRaw(new FixtureNode(tag)),
+ createText: (text) => Object.assign(new FixtureNode("#text"), { text }),
+ createComment: () => new FixtureNode("#comment"),
+ setText: (node, text) => {
+ node.text = text;
+ },
+ setElementText: (node, text) => {
+ node.text = text;
+ node.children = [];
+ },
+ parentNode: (node) => node.parent,
+ nextSibling: (node) =>
+ node.parent?.children[node.parent.children.indexOf(node) + 1] || null,
+ patchProp: (node, key, _previous, value) => {
+ node.props[key] = value;
+ },
+ insert(node, parent, anchor) {
+ if (node.parent)
+ node.parent.children.splice(node.parent.children.indexOf(node), 1);
+ node.parent = parent;
+ const index = anchor ? parent.children.indexOf(anchor) : -1;
+ parent.children.splice(index < 0 ? parent.children.length : index, 0, node);
+ },
+ remove(node) {
+ if (node.parent)
+ node.parent.children.splice(node.parent.children.indexOf(node), 1);
+ node.parent = null;
+ },
+});
+
+export function nodes(root: FixtureNode, tag?: string) {
+ const found = [root];
+ for (const node of found) found.push(...node.children);
+ return tag ? found.filter((node) => node.tag === tag) : found;
+}
+
+export function text(root: FixtureNode) {
+ return nodes(root)
+ .map((node) => node.text)
+ .join(" ");
+}
+
+export function dispatch(
+ node: FixtureNode | undefined,
+ event: string,
+ value = {},
+) {
+ const handler = node?.props[event];
+ if (typeof handler !== "function")
+ throw new Error(`Missing ${event} handler`);
+ handler({
+ target: node,
+ currentTarget: node,
+ stopPropagation() {},
+ preventDefault() {},
+ ...value,
+ });
+}
+
+export function mountFixture(
+ component: Component,
+ props: object,
+ components: Record = {},
+) {
+ const root = new FixtureNode("root");
+ const app = renderer.createApp({ render: () => h(component, props) });
+ app.config.globalProperties.$t = (key: string) => key;
+ for (const [name, value] of Object.entries(components))
+ app.component(name, value);
+ app.mount(root);
+ return { root, unmount: () => app.unmount() };
+}
From 548c5dfaf57cfaad927d92c73c75750e75cc3f63 Mon Sep 17 00:00:00 2001
From: Salem Mohammed Shamakh <58360393+salemkode@users.noreply.github.com>
Date: Sat, 14 Nov 2026 23:12:00 +0300
Subject: [PATCH 5/7] fix: isolate token and transaction navigation context
---
docs/token-transaction-context.md | 52 +++
src/components/bcmr/Icon.vue | 9 +-
src/components/bcmr/Info.vue | 1 +
src/hooks/activeMinting.ts | 28 +-
src/hooks/authchains.ts | 47 +-
src/hooks/confirmedNode.ts | 18 +
src/hooks/nftSupply.ts | 62 ++-
src/hooks/nonSpentToken.ts | 76 +++-
src/hooks/scopedQuery.ts | 44 ++
src/hooks/transactionMetadata.ts | 60 +++
src/module/bcmr.ts | 40 +-
src/module/chaingraph.ts | 1 +
src/pages/token/[category].vue | 73 ++-
src/pages/tx/[txid].vue | 66 +--
src/store/registry.ts | 21 +-
tests/fixtures/address-components.ts | 8 +-
tests/fixtures/selected-metadata.ts | 84 ++++
tests/fixtures/token-navigation.ts | 636 +++++++++++++++++++++++++++
tests/helpers/token-fixtures.ts | 110 +++++
tests/helpers/vue-renderer.ts | 57 +++
tests/selected-metadata.test.ts | 26 ++
tests/state.test.ts | 3 +-
tests/token-navigation.test.ts | 26 ++
23 files changed, 1421 insertions(+), 127 deletions(-)
create mode 100644 docs/token-transaction-context.md
create mode 100644 src/hooks/confirmedNode.ts
create mode 100644 src/hooks/scopedQuery.ts
create mode 100644 src/hooks/transactionMetadata.ts
create mode 100644 tests/fixtures/selected-metadata.ts
create mode 100644 tests/fixtures/token-navigation.ts
create mode 100644 tests/helpers/token-fixtures.ts
create mode 100644 tests/helpers/vue-renderer.ts
create mode 100644 tests/selected-metadata.test.ts
create mode 100644 tests/token-navigation.test.ts
diff --git a/docs/token-transaction-context.md b/docs/token-transaction-context.md
new file mode 100644
index 0000000..1e11571
--- /dev/null
+++ b/docs/token-transaction-context.md
@@ -0,0 +1,52 @@
+# Token and transaction navigation (#18)
+
+Issue [#18](https://github.com/salemkode/explorer/issues/18) only says
+“Check is open token page still show in tx page.” This fix interprets it as
+context leaking between token and transaction pages, including parameter changes
+without a full reload. It does not change transaction status or search behavior.
+
+## Expected behavior
+
+- Navigating token A → transaction B → token C removes the previous page's data.
+- Replacing a token ID or transaction ID updates requests, even when Vue reuses
+ the page component and the router replaces its `params` object.
+- A network change resets auth-chain metadata, supply totals and pagination.
+ Delayed results from the previous context cannot restore cards or trigger a
+ global error page. Shared registry providers remain available.
+- A token's registry selection and mobile tab reset when its ID/network changes.
+ Token address, child and transaction lists start with fresh pagination.
+- “Open Token Page” remains available for a transaction hash that is a known
+ token category. It does not imply that transaction publishes BCMR metadata.
+- The transaction BCMR card appears only when that transaction's own outputs
+ contain the valid, latest publication decoded from its category's auth chain.
+ Its identity comes from the auth-chain registry for that category, rather than
+ another configured provider. A later descendant's publication is not presented
+ as metadata published by the selected transaction. Historical publication
+ browsing and discovering other categories published by a transaction are
+ outside this fix.
+- Failed requests display a connection/reload instruction. Only a successfully
+ completed empty lookup displays “not found.” Missing or failed token registry
+ metadata has an explicit empty state rather than a previous token's card.
+
+## Regression checks
+
+Run `bun install --frozen-lockfile`, then `bun test tests/token-navigation.test.ts`.
+These tests compile the actual Vue pages and BCMR card and render them with a
+small in-memory Vue host. They use real Apollo queries with controlled responses;
+external registry fetches are isolated. They cover navigation, replaced params,
+delayed old responses/errors, metadata publication gating, network isolation,
+and supply pagination without duplicate accumulation.
+
+Full checks: `bun run lint`, `bun run test`, `bun run lint:type`, `bun run build`.
+Code generation uses `schema/chaingraph.graphql`; no live schema pull is needed.
+Apollo 3 emits upstream deprecation notices during the intentional error test
+because Vue Apollo calls its legacy error recovery methods.
+
+For browser QA, use two known token IDs and an unrelated transaction on the
+selected network. Open A, choose a registry/mobile tab, then navigate to the
+transaction and C using in-app links or the search bar without reloading. Repeat
+with two token URLs and two transaction URLs while delaying requests. Check that
+old cards disappear immediately, the new page stays usable after an old request
+fails, and only the current successful empty lookup shows “not found.” Repeat
+after switching networks and check both light/dark themes and narrow/wide layouts.
+The in-memory renderer checks behavior, not browser layout or live indexer data.
diff --git a/src/components/bcmr/Icon.vue b/src/components/bcmr/Icon.vue
index c257fa7..465399b 100644
--- a/src/components/bcmr/Icon.vue
+++ b/src/components/bcmr/Icon.vue
@@ -48,15 +48,17 @@
diff --git a/src/components/token/Child.vue b/src/components/token/Child.vue
index dadb19a..fb6ac06 100644
--- a/src/components/token/Child.vue
+++ b/src/components/token/Child.vue
@@ -135,6 +135,7 @@ const outputs = computed(() => {
text: types.value?.[commitment]?.name || "N/A",
token: {
category: props.category,
+ identitySnapshot: props.identitySnapshot || null,
commitment,
capability: output.nonfungible_token_capability || undefined,
},
diff --git a/src/components/token/Provider.vue b/src/components/token/Provider.vue
index 67113f4..194930f 100644
--- a/src/components/token/Provider.vue
+++ b/src/components/token/Provider.vue
@@ -1,126 +1,39 @@
-
-
- BCMR Registry Source
-
+
+ BCMR registry source
+ Choose whose metadata to display. Auth-chain history is selected separately above.
-
-
+
diff --git a/src/components/token/TokenId.vue b/src/components/token/TokenId.vue
index 4564c89..7438d13 100644
--- a/src/components/token/TokenId.vue
+++ b/src/components/token/TokenId.vue
@@ -1,7 +1,7 @@
-
+
@@ -14,7 +14,7 @@
import type { IdentitySnapshot } from "~/types";
const props = defineProps<{
- identitySnapshot?: IdentitySnapshot;
+ identitySnapshot?: IdentitySnapshot | null;
category: string;
loading: boolean;
}>();
diff --git a/src/hooks/authChainSelection.ts b/src/hooks/authChainSelection.ts
new file mode 100644
index 0000000..5c92cab
--- /dev/null
+++ b/src/hooks/authChainSelection.ts
@@ -0,0 +1,44 @@
+import type { Ref } from "vue";
+import { computed, ref, watch } from "vue";
+import type { GetAuthChainsQuery } from "~/graphql/graphql";
+import {
+ listAuthChains,
+ loadAuthChainMetadata,
+ selectAuthChain,
+} from "~/module/authchains";
+
+export function useAuthChainSelection(
+ data: Ref
,
+ category: Ref,
+ chainId: Ref,
+ revisionId: Ref,
+) {
+ const chains = computed(() =>
+ data.value ? listAuthChains(data.value, category.value) : [],
+ );
+ const selection = computed(() =>
+ selectAuthChain(chains.value, chainId.value, revisionId.value),
+ );
+ const metadata = ref<
+ | Awaited>
+ | { status: "loading" }
+ | { status: "idle" }
+ >({ status: "idle" });
+ watch(
+ [selection, category],
+ async ([selected, tokenCategory], _previous, onCleanup) => {
+ const controller = new AbortController();
+ onCleanup(() => controller.abort());
+ metadata.value = { status: "loading" };
+ const result = await loadAuthChainMetadata(
+ selected.publicationRevision?.publication || { status: "none" },
+ tokenCategory,
+ controller.signal,
+ );
+ // A slow response for the old selection must never replace the new metadata.
+ if (!controller.signal.aborted) metadata.value = result;
+ },
+ { immediate: true, flush: "sync" },
+ );
+ return { chains, selection, metadata };
+}
diff --git a/src/module/authchains.ts b/src/module/authchains.ts
new file mode 100644
index 0000000..9e4cd2d
--- /dev/null
+++ b/src/module/authchains.ts
@@ -0,0 +1,185 @@
+import { binToHex, hexToBin, sha256 } from "@bitauth/libauth";
+import type { GetAuthChainsQuery } from "~/graphql/graphql";
+import type { Registry } from "~/types";
+import { opreturnToAuthChainElement, parseBinary } from "./bitcoin";
+import { validateBcmrSchema } from "./utils";
+
+function getPublication(
+ outputs: NonNullable<
+ GetAuthChainsQuery["transaction"][number]["authchains"][number]["migrations"][number]["transaction"]
+ >[number]["outputs"],
+) {
+ const opreturn = outputs
+ .map((output) => output.locking_bytecode.substring(2))
+ .find((script) => /^6a(?:04|4c04|4d0400|4e04000000)42434d52/.test(script));
+ if (!opreturn) return { status: "none" as const };
+ const publication = opreturnToAuthChainElement(opreturn);
+ if (typeof publication === "string") {
+ return { status: "invalid" as const, opreturn };
+ }
+ return {
+ status: "published" as const,
+ opreturn,
+ ...publication,
+ checkHash: parseBinary(hexToBin(opreturn)).length >= 3,
+ };
+}
+
+export function listAuthChains(data: GetAuthChainsQuery, category: string) {
+ const transaction = data.transaction.find(
+ ({ hash }) => hash.substring(2) === category,
+ );
+ return (transaction?.authchains || [])
+ .flatMap((chain) => {
+ const id = (
+ chain.authhead_transaction_hash || chain.authhead?.hash
+ )?.substring(2);
+ if (!id) return [];
+ const revisions = chain.migrations
+ .flatMap((migration) =>
+ (migration.transaction || []).map((tx) => ({
+ id: tx.hash.substring(2),
+ index: migration.migration_index,
+ timestamp: tx.block_inclusions
+ .map(({ block }) => block.timestamp)
+ .sort((a, b) => Number(b) - Number(a))
+ .at(0),
+ publication: getPublication(tx.outputs),
+ transaction: tx,
+ })),
+ )
+ .sort((a, b) => {
+ // Migration order, rather than block time, also orders updates in one block.
+ const first = BigInt(a.index || "0");
+ const second = BigInt(b.index || "0");
+ return first === second
+ ? a.id.localeCompare(b.id)
+ : first > second
+ ? -1
+ : 1;
+ });
+ return [
+ {
+ id,
+ length: chain.authchain_length,
+ unspent: chain.unspent_authhead,
+ reservedSupply:
+ chain.authhead?.identity_output?.at(0)?.fungible_token_amount,
+ revisions,
+ },
+ ];
+ })
+ .sort(
+ (a, b) =>
+ Number(b.unspent) - Number(a.unspent) || a.id.localeCompare(b.id),
+ );
+}
+
+export function selectAuthChain(
+ chains: ReturnType,
+ chainId?: string,
+ revisionId?: string,
+) {
+ const chain = chainId
+ ? chains.find(({ id }) => id === chainId)
+ : chains.at(0);
+ const revision = revisionId
+ ? chain?.revisions.find(({ id }) => id === revisionId)
+ : chain?.revisions.at(0);
+ const position = chain?.revisions.findIndex(({ id }) => id === revision?.id);
+ // Migrations without a publication retain the preceding publication on this chain only.
+ const publicationRevision =
+ position !== undefined && position >= 0
+ ? chain?.revisions
+ .slice(position)
+ .find(({ publication }) => publication.status !== "none")
+ : undefined;
+ return {
+ chain,
+ revision,
+ publicationRevision,
+ missing: Boolean((chainId && !chain) || (revisionId && !revision)),
+ };
+}
+
+export function getRegistryIdentity(registry: Registry, category: string) {
+ const history = registry.identities?.[category];
+ if (!history) return;
+ const revision = Object.keys(history)
+ .filter((timestamp) => Date.parse(timestamp) <= Date.now())
+ .sort((a, b) => Date.parse(b) - Date.parse(a) || a.localeCompare(b))
+ .at(0);
+ const identity = revision ? history[revision] : undefined;
+ return identity?.token?.category === category ? identity : undefined;
+}
+
+export async function loadAuthChainMetadata(
+ publication: ReturnType,
+ category: string,
+ signal?: AbortSignal,
+) {
+ if (publication.status !== "published") {
+ return {
+ status: "unavailable" as const,
+ message:
+ publication.status === "invalid"
+ ? "This migration has a malformed BCMR publication."
+ : "No metadata has been published at this migration.",
+ };
+ }
+ try {
+ const response = await fetch(publication.url, { signal });
+ if (!response.ok)
+ return {
+ status: "unavailable" as const,
+ message: `Metadata could not be loaded (HTTP ${response.status}).`,
+ };
+ const bytes = new Uint8Array(await response.arrayBuffer());
+ const actualHash = binToHex(sha256.hash(bytes));
+ const hashStatus = publication.checkHash
+ ? actualHash === publication.contentHash
+ ? ("match" as const)
+ : ("mismatch" as const)
+ : ("not-checked" as const);
+ if (hashStatus === "mismatch")
+ return {
+ status: "unavailable" as const,
+ hashStatus,
+ actualHash,
+ message:
+ "Metadata hash mismatch. This content does not match the publication and is not displayed.",
+ };
+ const registry = await validateBcmrSchema(
+ JSON.parse(new TextDecoder().decode(bytes)),
+ );
+ if (!registry.success)
+ return {
+ status: "unavailable" as const,
+ hashStatus,
+ actualHash,
+ message: "The published document is not a valid BCMR registry.",
+ };
+ const identity = getRegistryIdentity(registry.value, category);
+ if (!identity)
+ return {
+ status: "unavailable" as const,
+ hashStatus,
+ actualHash,
+ message:
+ "The published registry has no current metadata for this token category.",
+ };
+ return {
+ status: "ready" as const,
+ hashStatus,
+ actualHash,
+ registry: registry.value,
+ identity,
+ };
+ } catch {
+ return {
+ status: "unavailable" as const,
+ message:
+ "Metadata could not be read. The server may be unreachable, block browser requests, or return invalid JSON.",
+ };
+ }
+}
diff --git a/src/module/bcmr.ts b/src/module/bcmr.ts
index e9774e1..0c05a3c 100644
--- a/src/module/bcmr.ts
+++ b/src/module/bcmr.ts
@@ -1,98 +1,56 @@
import type { GetAuthChainsQuery, GetTxQuery } from "~/graphql/graphql";
-import type { Capability, IdentitySnapshot, tokenCapability } from "~/types";
-import { opreturnToAuthChainElement } from "./bitcoin";
+import type { IdentitySnapshot, tokenCapability } from "~/types";
+import { listAuthChains, selectAuthChain } from "./authchains";
-/**
- * Retrieves the genesis transaction and opreturn for a given category from an authchain.
- * @param {GetAuthChainsQuery} authchain - provide authchain from GetAuthChain.
- * @param {string} category - token category to get it for in the authchain object.
- */
-export const decodeAuthChain = (
- authchain: GetAuthChainsQuery,
+/** Decode an explicit chain/migration, or a deterministic default for list views. */
+export function decodeAuthChain(
+ data: GetAuthChainsQuery,
category: string,
-) => {
- const genesesTx = {
- hash: undefined as string | undefined,
- genesisSupply: 0,
- lockingBytecode: undefined as string | undefined,
- nftCapability: undefined as Capability | null | undefined,
- };
-
- let result = {
- timestamp: "0",
- opreturn: "",
- };
-
- const migrations =
- authchain?.transaction
- .find(({ hash }) => hash.substring(2) === category)
- ?.authchains.at(0)?.migrations || [];
-
- for (const migration of migrations) {
- const transaction = migration?.transaction?.at(0);
-
- // Get token genesis information
- const isGenesesTx = transaction?.inputs.some(
- (input) =>
- String(input.outpoint_index) === "0" &&
- input.outpoint_transaction_hash.substring(2) === category,
- );
-
- if (
- transaction &&
- isGenesesTx &&
- transaction.outputs.some(
- (output) => output.token_category?.substring(2) === category,
- )
- ) {
- genesesTx.hash = transaction?.hash.substring(2) || "";
- genesesTx.genesisSupply = transaction.outputs.reduce(
- (total: number, { fungible_token_amount }) =>
- fungible_token_amount
- ? total + Number.parseInt(fungible_token_amount, 10)
- : total,
- 0,
- );
- const output = transaction.outputs?.find(
- (tokenCategory) =>
- tokenCategory.token_category?.substring(2) === category,
- );
- genesesTx.nftCapability = transaction.outputs.find(
+ chainId?: string,
+ revisionId?: string,
+) {
+ const { chain, publicationRevision } = selectAuthChain(
+ listAuthChains(data, category),
+ chainId,
+ revisionId,
+ );
+ const transaction = chain?.revisions.find(({ transaction }) =>
+ transaction.inputs.some(
+ ({ outpoint_transaction_hash, outpoint_index }) =>
+ String(outpoint_index) === "0" &&
+ outpoint_transaction_hash.substring(2) === category,
+ ),
+ )?.transaction;
+ if (!transaction) return;
+ const output = transaction.outputs.find(
+ ({ token_category }) => token_category?.substring(2) === category,
+ );
+ if (!output) return;
+ return {
+ genesesTx: {
+ hash: transaction.hash.substring(2),
+ genesisSupply: transaction.outputs
+ .filter(
+ ({ token_category }) => token_category?.substring(2) === category,
+ )
+ .reduce(
+ (total, { fungible_token_amount }) =>
+ total + Number(fungible_token_amount || 0),
+ 0,
+ ),
+ lockingBytecode: output?.locking_bytecode.substring(2),
+ nftCapability: transaction.outputs.find(
(output) =>
output.token_category?.substring(2) === category &&
output.nonfungible_token_capability,
- )?.nonfungible_token_capability;
- genesesTx.lockingBytecode = output?.locking_bytecode.substring(2);
- }
-
- // Get the opreturn from the first output
- const opreturn = transaction?.outputs
- ?.find((vout) => vout.locking_bytecode.startsWith("\\x6a"))
- ?.locking_bytecode.substring(2);
- const timestamp = transaction?.block_inclusions.at(0)?.block.timestamp;
- const registryElement = opreturn && opreturnToAuthChainElement(opreturn);
- if (
- timestamp &&
- registryElement &&
- typeof registryElement !== "string" &&
- +result.timestamp < +timestamp
- ) {
- result = {
- timestamp: timestamp,
- opreturn,
- };
- }
- }
-
- if (genesesTx.genesisSupply === 0 && !genesesTx.nftCapability) {
- return undefined;
- }
-
- return {
- genesesTx,
- opreturn: result.opreturn,
+ )?.nonfungible_token_capability,
+ },
+ opreturn:
+ publicationRevision?.publication.status === "published"
+ ? publicationRevision.publication.opreturn
+ : "",
};
-};
+}
export const getChildToken = (
identitySnapshot: IdentitySnapshot,
diff --git a/src/module/chaingraph.ts b/src/module/chaingraph.ts
index e66c63d..66c91be 100644
--- a/src/module/chaingraph.ts
+++ b/src/module/chaingraph.ts
@@ -347,31 +347,16 @@ export const GetAuthChains = gql(`
hash
authchains {
authchain_length
+ authhead_transaction_hash
+ unspent_authhead
authhead {
hash
identity_output {
fungible_token_amount
}
}
- migrations(
- where: {
- _or: [
- {
- transaction: {
- outputs: { locking_bytecode_pattern: { _regex: "6a04" } }
- }
- }
- {
- transaction: {
- inputs: {
- outpoint_transaction_hash: { _in: $tokenCategory }
- outpoint_index: { _eq: 0 }
- }
- }
- }
- ]
- }
- ) {
+ migrations(order_by: { migration_index: desc }) {
+ migration_index
transaction {
hash
block_inclusions {
diff --git a/src/pages/token/[category].vue b/src/pages/token/[category].vue
index 56d02e4..73edf5d 100644
--- a/src/pages/token/[category].vue
+++ b/src/pages/token/[category].vue
@@ -1,5 +1,16 @@
+
Token details could not be loaded. Check your connection and reload the page.
@@ -9,10 +20,11 @@
No token genesis was found for this ID on the selected network.
+
@@ -36,6 +48,7 @@
:loading="authchainLoading"
/>
@@ -46,7 +59,8 @@
{{ metadata.failed ? 'Auth-chain metadata could not be loaded. You can choose another registry below.' : 'No token metadata is available from the selected registry.' }}
(selectedRegistryName = url)"
/>
@@ -61,7 +75,7 @@
>
@@ -84,7 +98,7 @@
@@ -97,6 +111,7 @@