+
= 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/9] 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/9] 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 @@
diff --git a/src/components/table/View.vue b/src/components/table/View.vue
index 5b22107..b4bd005 100644
--- a/src/components/table/View.vue
+++ b/src/components/table/View.vue
@@ -1,6 +1,7 @@
+
+ {{ emptyMessage }}
+
+
,
- required: true,
- },
- rows: {
- type: Array as PropType,
- required: true,
- },
- loading: {
- type: Boolean,
- default: false,
- },
- headerLess: {
- type: Boolean,
- default: false,
- },
- error: {
- type: String,
- default: "",
- },
- hasNextPage: {
- type: Boolean,
- },
- hasPrevPage: {
- type: Boolean,
- },
-});
+const props = withDefaults(
+ defineProps<{
+ title: string;
+ columns: string[];
+ rows: tableColumn[][];
+ rowKeys?: string[];
+ emptyMessage?: string;
+ loading?: boolean;
+ headerLess?: boolean;
+ error?: string;
+ hasNextPage?: boolean;
+ hasPrevPage?: boolean;
+ }>(),
+ { loading: false, headerLess: false, error: "", emptyMessage: "" },
+);
const event = (emitName: emitName) => {
if (change.navigate) return;
diff --git a/src/components/token/Address.vue b/src/components/token/Address.vue
index 2a003e8..914289f 100644
--- a/src/components/token/Address.vue
+++ b/src/components/token/Address.vue
@@ -1,12 +1,14 @@
@@ -14,81 +16,42 @@
diff --git a/src/components/token/BalanceStatus.vue b/src/components/token/BalanceStatus.vue
new file mode 100644
index 0000000..fcd848b
--- /dev/null
+++ b/src/components/token/BalanceStatus.vue
@@ -0,0 +1,25 @@
+
+
+
+ Loading complete confirmed balances…
+ {{ state.message }}
+ Confirmed at block {{ state.height }}. Pending transactions are not included.
+ Balances are unavailable.
+
+
Refresh balances
+
+
+
+
diff --git a/src/hooks/activeMinting.ts b/src/hooks/activeMinting.ts
deleted file mode 100644
index 567db3f..0000000
--- a/src/hooks/activeMinting.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { computed, type MaybeRefOrGetter, toValue } from "vue";
-import type { bytea } from "~/types";
-import { useConfirmedNode } from "./confirmedNode";
-import { useScopedQuery } from "./scopedQuery";
-
-export const GetMintingToken = gql(`
- query GetMintingToken($tokenCategory: bytea, $node: Int!) {
- output(
- limit: 1
- where: {
- token_category: { _eq: $tokenCategory }
- transaction: { block_inclusions: { block: { accepted_by: { node_internal_id: { _eq: $node } } } } }
- _and: { nonfungible_token_capability: { _eq: "minting" } }
- _not: { spent_by: { transaction: { block_inclusions: { block: { accepted_by: { node_internal_id: { _eq: $node } } } } } } }
- }
- ) {
- locking_bytecode
- }
- }
-`);
-
-export const useIsActiveMinting = (tokenCategory: MaybeRefOrGetter) => {
- const confirmed = useConfirmedNode();
- const { loading, result, error } = useScopedQuery(GetMintingToken, () => ({
- tokenCategory: toValue(tokenCategory),
- node: confirmed.node.value,
- }));
-
- // Check if there is an active minting token
- // If there is, then the minting token is active
- const isActiveMinting = computed(
- () => (result.value?.output.length || 0) > 0,
- );
- return {
- loading: computed(() => loading.value || confirmed.loading.value),
- error: computed(() => error.value || confirmed.error.value),
- isActiveMinting,
- };
-};
diff --git a/src/hooks/confirmedTokenBalances.ts b/src/hooks/confirmedTokenBalances.ts
new file mode 100644
index 0000000..8e3bafc
--- /dev/null
+++ b/src/hooks/confirmedTokenBalances.ts
@@ -0,0 +1,47 @@
+import {
+ GetTokenBalanceBlock,
+ GetTokenBalanceOutputs,
+} from "~/module/tokenBalanceQueries";
+import { loadTokenBalances, TokenBalanceError } from "~/module/tokenBalances";
+import { useTokenBalanceSnapshot } from "./tokenBalances";
+
+export function useConfirmedTokenBalances(
+ scope: Readonly[[0] | null>>,
+) {
+ const { clients } = useApollo();
+ const client = clients?.default;
+ return useTokenBalanceSnapshot(scope, (current, signal) =>
+ loadTokenBalances(
+ current,
+ {
+ async block(height, node) {
+ const result = await client?.query({
+ query: GetTokenBalanceBlock,
+ variables: {
+ network: current.network,
+ height: height ? { _eq: height } : {},
+ node: node === undefined ? {} : { _eq: node },
+ },
+ fetchPolicy: "no-cache",
+ context: { fetchOptions: { signal }, queryDeduplication: false },
+ });
+ if (!result)
+ throw new TokenBalanceError("The balance service is unavailable.");
+ return result.data.block;
+ },
+ async outputs(where) {
+ const result = await client?.query({
+ query: GetTokenBalanceOutputs,
+ variables: { where, limit: 500 },
+ fetchPolicy: "no-cache",
+ context: { fetchOptions: { signal }, queryDeduplication: false },
+ });
+ if (!result)
+ throw new TokenBalanceError("The balance service is unavailable.");
+ return result.data.output;
+ },
+ },
+ signal,
+ ),
+ );
+}
diff --git a/src/hooks/nftSupply.ts b/src/hooks/nftSupply.ts
deleted file mode 100644
index 6143f9a..0000000
--- a/src/hooks/nftSupply.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { computed, type MaybeRefOrGetter, ref, toValue, watch } from "vue";
-import { useStateStore } from "~/store";
-import type { bytea } from "~/types";
-import { useConfirmedNode } from "./confirmedNode";
-import { useScopedQuery } from "./scopedQuery";
-
-export const GetSupplyNFTs = gql(`
- query GetSupplyNFTs($offset: Int, $tokenCategory: bytea, $limit: Int, $node: Int!) {
- output(
- offset: $offset
- limit: $limit
- order_by: [{ transaction_hash: asc }, { output_index: asc }]
- where: {
- token_category: { _eq: $tokenCategory }
- transaction: { block_inclusions: { block: { accepted_by: { node_internal_id: { _eq: $node } } } } }
- _and: [{ nonfungible_token_capability: { _eq: "none" } }]
- _not: { spent_by: { transaction: { block_inclusions: { block: { accepted_by: { node_internal_id: { _eq: $node } } } } } } }
- }
- ) {
- locking_bytecode
- }
- }
-`);
-
-export const useNftSupply = (tokenCategory: MaybeRefOrGetter) => {
- const stateStore = useStateStore();
- const confirmed = useConfirmedNode();
- const offset = ref(0);
- const pages = ref(new Map());
- watch(
- () => [toValue(tokenCategory), stateStore.network],
- () => {
- offset.value = 0;
- pages.value.clear();
- },
- { flush: "sync" },
- );
- const { loading, result, error } = useScopedQuery(GetSupplyNFTs, () => ({
- offset: offset.value,
- limit: 5000,
- tokenCategory: toValue(tokenCategory),
- node: confirmed.node.value,
- }));
-
- watch(
- result,
- (data) => {
- if (!data) return;
- pages.value.set(offset.value, data.output.length);
- if (data.output.length === 5000) offset.value += 5000;
- },
- { immediate: true },
- );
- const supplyNFTs = computed(() =>
- Array.from(pages.value.values()).reduce((total, value) => total + value, 0),
- );
- return {
- loading: computed(() => loading.value || confirmed.loading.value),
- error: computed(() => error.value || confirmed.error.value),
- supplyNFTs,
- };
-};
diff --git a/src/hooks/nonSpentToken.ts b/src/hooks/nonSpentToken.ts
deleted file mode 100644
index a616c04..0000000
--- a/src/hooks/nonSpentToken.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { computed, type MaybeRefOrGetter, ref, toValue, watch } from "vue";
-import { useStateStore } from "~/store";
-import type { bytea } from "~/types";
-import { useConfirmedNode } from "./confirmedNode";
-import { useScopedQuery } from "./scopedQuery";
-
-export const GetUseNonBurnTokens = gql(`
- query GetUseNonBurnTokens($tokenCategory: bytea, $offset: Int, $limit: Int, $node: Int!) {
- output(
- offset: $offset
- limit: $limit
- order_by: [{ transaction_hash: asc }, { output_index: asc }]
- where: {
- token_category: { _eq: $tokenCategory }
- transaction: { block_inclusions: { block: { accepted_by: { node_internal_id: { _eq: $node } } } } }
- _not: { spent_by: { transaction: { block_inclusions: { block: { accepted_by: { node_internal_id: { _eq: $node } } } } } } }
- }
- ) {
- locking_bytecode
- fungible_token_amount
- }
- }
-`);
-
-export const useNonBurnTokens = (tokenCategory: MaybeRefOrGetter) => {
- const stateStore = useStateStore();
- const confirmed = useConfirmedNode();
- const offset = ref(0);
- const pages = ref(new Map());
- watch(
- () => [toValue(tokenCategory), stateStore.network],
- () => {
- offset.value = 0;
- pages.value.clear();
- },
- { flush: "sync" },
- );
- const { loading, result, error } = useScopedQuery(
- GetUseNonBurnTokens,
- () => ({
- offset: offset.value,
- limit: 5000,
- tokenCategory: toValue(tokenCategory),
- node: confirmed.node.value,
- }),
- );
-
- watch(
- result,
- (data) => {
- if (!data) return;
- pages.value.set(
- offset.value,
- data.output.reduce(
- (total, output) =>
- total + Number(output.fungible_token_amount || "0"),
- 0,
- ),
- );
- if (data.output.length === 5000) offset.value += 5000;
- },
- { immediate: true },
- );
- const nonBurnTokens = computed(() =>
- Array.from(pages.value.values()).reduce((total, value) => total + value, 0),
- );
- return {
- loading: computed(() => loading.value || confirmed.loading.value),
- error: computed(() => error.value || confirmed.error.value),
- nonBurnTokens,
- };
-};
diff --git a/src/hooks/tokenBalances.ts b/src/hooks/tokenBalances.ts
new file mode 100644
index 0000000..86f2096
--- /dev/null
+++ b/src/hooks/tokenBalances.ts
@@ -0,0 +1,45 @@
+import { type Ref, ref, shallowRef, watch } from "vue";
+import type { loadTokenBalances } from "../module/tokenBalances";
+
+/** Discard in-flight results immediately when the address, category or network changes. */
+export function useTokenBalanceSnapshot(
+ scope: Readonly][[0] | null>>,
+ load: (
+ current: Parameters[0],
+ signal: AbortSignal,
+ ) => ReturnType,
+) {
+ const state = shallowRef<
+ | Awaited>
+ | { status: "unavailable" }
+ | { status: "loading" }
+ | { status: "error"; message: string }
+ >({ status: "loading" });
+ const revision = ref(0);
+ watch(
+ [scope, revision],
+ async ([current], _, onCleanup) => {
+ if (!current) {
+ state.value = { status: "unavailable" };
+ return;
+ }
+ const controller = new AbortController();
+ onCleanup(() => controller.abort());
+ state.value = { status: "loading" };
+ try {
+ const result = await load(current, controller.signal);
+ if (!controller.signal.aborted) state.value = result;
+ } catch {
+ if (!controller.signal.aborted) {
+ state.value = {
+ status: "error",
+ message:
+ "Complete confirmed balances could not be loaded. Refresh to try again.",
+ };
+ }
+ }
+ },
+ { immediate: true, flush: "sync" },
+ );
+ return { state, refresh: () => revision.value++ };
+}
diff --git a/src/module/bcmr.ts b/src/module/bcmr.ts
index 0c05a3c..949d475 100644
--- a/src/module/bcmr.ts
+++ b/src/module/bcmr.ts
@@ -1,6 +1,8 @@
+import BigNumber from "bignumber.js";
import type { GetAuthChainsQuery, GetTxQuery } from "~/graphql/graphql";
import type { IdentitySnapshot, tokenCapability } from "~/types";
import { listAuthChains, selectAuthChain } from "./authchains";
+import { exactTokenAmount } from "./tokenBalances";
/** Decode an explicit chain/migration, or a deterministic default for list views. */
export function decodeAuthChain(
@@ -26,18 +28,27 @@ export function decodeAuthChain(
({ token_category }) => token_category?.substring(2) === category,
);
if (!output) return;
- return {
- genesesTx: {
- hash: transaction.hash.substring(2),
- genesisSupply: transaction.outputs
+ const genesisSupply = (() => {
+ try {
+ return transaction.outputs
.filter(
({ token_category }) => token_category?.substring(2) === category,
)
.reduce(
(total, { fungible_token_amount }) =>
- total + Number(fungible_token_amount || 0),
- 0,
- ),
+ total.plus(exactTokenAmount(fungible_token_amount)),
+ new BigNumber("0"),
+ )
+ .toFixed();
+ } catch {
+ return undefined;
+ }
+ })();
+ if (genesisSupply === undefined) return;
+ return {
+ genesesTx: {
+ hash: transaction.hash.substring(2),
+ genesisSupply,
lockingBytecode: output?.locking_bytecode.substring(2),
nftCapability: transaction.outputs.find(
(output) =>
diff --git a/src/module/chaingraph.ts b/src/module/chaingraph.ts
index 66c91be..10517c2 100644
--- a/src/module/chaingraph.ts
+++ b/src/module/chaingraph.ts
@@ -270,41 +270,6 @@ export const GetTransactions = gql(`
}
`);
-export const GetTokenAddress = gql(`
- query GetTokenAddress(
- $limit: Int
- $offset: Int
- $network: String
- $tokenCategory: bytea
- ) {
- output(
- limit: $limit
- offset: $offset
- order_by: { fungible_token_amount: desc_nulls_last }
- where: {
- token_category: { _eq: $tokenCategory }
- transaction: {
- block_inclusions: {
- block: { accepted_by: { node: { name: { _regex: $network } } } }
- }
- }
- _not: { spent_by: { transaction: { hash: { _gt: "" } } } }
- }
- ) {
- value_satoshis
- locking_bytecode
- transaction_hash
- output_index
- fungible_token_amount
- spent_by {
- transaction {
- hash
- }
- }
- }
- }
-`);
-
export const GetTokenTxs = gql(`
query GetTokenTxs(
$limit: Int
@@ -364,11 +329,12 @@ export const GetAuthChains = gql(`
timestamp
}
}
- inputs(where: { outpoint_index: { _eq: 0 } }) {
+ inputs(limit: 1, order_by: { input_index: asc }) {
+ outpoint_index
outpoint_transaction_hash
outpoint_index
}
- outputs {
+ outputs(order_by: { output_index: asc }) {
token_category
locking_bytecode
fungible_token_amount
@@ -445,33 +411,5 @@ export const GetAddressNFTs = gql(`
}
`);
-export const GetAddressTokens = gql(`
- query GetAddressTokens(
- $limit: Int
- $offset: Int
- $network: String
- $lockingBytecode: _text
- ) {
- search_output(
- limit: $limit
- offset: $offset
- args: { locking_bytecode_hex: $lockingBytecode }
- where: {
- token_category: { _is_null: false }
- transaction: {
- block_inclusions: {
- block: { accepted_by: { node: { name: { _regex: $network } } } }
- }
- }
- nonfungible_token_capability: { _is_null: true }
- _not: { spent_by: { transaction: { hash: { _gt: "" } } } }
- }
- ) {
- token_category
- fungible_token_amount
- }
- }
-`);
-
// Export types
export * from "~/graphql/graphql";
diff --git a/src/module/tokenBalanceQueries.ts b/src/module/tokenBalanceQueries.ts
new file mode 100644
index 0000000..fcd33d4
--- /dev/null
+++ b/src/module/tokenBalanceQueries.ts
@@ -0,0 +1,33 @@
+export const GetTokenBalanceBlock = gql(`
+ query GetTokenBalanceBlock($network: String!, $height: bigint_comparison_exp!, $node: Int_comparison_exp!) {
+ block(
+ limit: 1
+ order_by: { height: desc }
+ where: {
+ height: $height
+ accepted_by: { node_internal_id: $node, node: { name: { _regex: $network } } }
+ }
+ ) {
+ hash
+ height
+ accepted_by(where: { node_internal_id: $node, node: { name: { _regex: $network } } }, order_by: { node_internal_id: asc }, limit: 1) { node_internal_id }
+ }
+ }
+`);
+
+export const GetTokenBalanceOutputs = gql(`
+ query GetTokenBalanceOutputs($where: output_bool_exp!, $limit: Int!) {
+ output(
+ limit: $limit
+ order_by: [{ transaction_hash: asc }, { output_index: asc }]
+ where: $where
+ ) {
+ transaction_hash
+ output_index
+ token_category
+ locking_bytecode
+ fungible_token_amount
+ nonfungible_token_capability
+ }
+ }
+`);
diff --git a/src/module/tokenBalances.ts b/src/module/tokenBalances.ts
new file mode 100644
index 0000000..63178bf
--- /dev/null
+++ b/src/module/tokenBalances.ts
@@ -0,0 +1,147 @@
+import BigNumber from "bignumber.js";
+import type {
+ GetTokenBalanceBlockQuery,
+ GetTokenBalanceOutputsQuery,
+ Output_Bool_Exp,
+} from "../graphql/graphql";
+
+export class TokenBalanceError extends Error {}
+
+/** JSON numbers above the safe integer range have already lost information. */
+export function exactTokenAmount(value: unknown) {
+ if (value === null || value === undefined) return "0";
+ if (typeof value === "string" && /^\d+$/.test(value)) return value;
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0)
+ return String(value);
+ throw new TokenBalanceError("Invalid or unsafe integer scalar.");
+}
+
+/** Read one confirmed-chain snapshot, never a page subtotal. Include spent outputs only for genesis totals. */
+export async function loadTokenBalances(
+ scope: { network: string; filter: Output_Bool_Exp; includeSpent?: boolean },
+ queries: {
+ block: (
+ height?: string,
+ node?: number,
+ ) => Promise;
+ outputs: (
+ where: Output_Bool_Exp,
+ ) => Promise;
+ },
+ signal: AbortSignal,
+) {
+ const tip = (await queries.block()).at(0);
+ if (!tip) throw new TokenBalanceError("No accepted block is available.");
+ const node = tip.accepted_by[0]?.node_internal_id;
+ if (!Number.isSafeInteger(node) || node === undefined || node < 0)
+ throw new TokenBalanceError("No accepted node is available.");
+ const height = exactTokenAmount(tip.height);
+ const confirmed = {
+ block_inclusions: {
+ block: {
+ height: { _lte: height },
+ accepted_by: { node_internal_id: { _eq: node } },
+ },
+ },
+ };
+ const outputs = new Map<
+ string,
+ GetTokenBalanceOutputsQuery["output"][number]
+ >();
+ const cursor: { after: Output_Bool_Exp[] } = { after: [] };
+ while (true) {
+ signal.throwIfAborted();
+ const page = await queries.outputs({
+ _and: [scope.filter, ...cursor.after],
+ token_category: { _is_null: false },
+ transaction: confirmed,
+ _not: scope.includeSpent
+ ? undefined
+ : { spent_by: { transaction: confirmed } },
+ });
+ signal.throwIfAborted();
+ // Continue even after a short page: servers may cap the requested limit.
+ if (page.length === 0) break;
+ const last = page.at(-1);
+ if (!last) break;
+ const key = `${last.transaction_hash}:${last.output_index}`;
+ if (outputs.has(key)) {
+ throw new TokenBalanceError("The balance query did not advance.");
+ }
+ for (const output of page) {
+ outputs.set(
+ `${output.transaction_hash}:${exactTokenAmount(output.output_index)}`,
+ {
+ ...output,
+ fungible_token_amount: exactTokenAmount(output.fungible_token_amount),
+ },
+ );
+ }
+ cursor.after = [
+ {
+ _or: [
+ { transaction_hash: { _gt: last.transaction_hash } },
+ {
+ transaction_hash: { _eq: last.transaction_hash },
+ output_index: { _gt: last.output_index },
+ },
+ ],
+ },
+ ];
+ }
+ const accepted = (await queries.block(height, node)).at(0);
+ signal.throwIfAborted();
+ if (
+ accepted?.hash !== tip.hash ||
+ accepted?.accepted_by[0]?.node_internal_id !== node
+ ) {
+ throw new TokenBalanceError(
+ "The accepted chain changed. Refresh balances.",
+ );
+ }
+ return {
+ status: "ready" as const,
+ height: tip.height,
+ outputs: [...outputs.values()],
+ };
+}
+
+/** Group only after all outputs are loaded; NFT-bearing outputs can hold FT too. */
+export function groupTokenBalances(
+ outputs: GetTokenBalanceOutputsQuery["output"],
+ by: "token_category" | "locking_bytecode",
+) {
+ const balances = new Map();
+ for (const output of outputs) {
+ const key = output[by];
+ if (!key) continue;
+ balances.set(
+ key,
+ (balances.get(key) || new BigNumber("0")).plus(
+ exactTokenAmount(output.fungible_token_amount),
+ ),
+ );
+ }
+ return [...balances]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([key, amount]) => ({
+ key,
+ amount: amount.toFixed(),
+ }));
+}
+
+export function summarizeTokenBalances(
+ outputs: GetTokenBalanceOutputsQuery["output"],
+) {
+ return outputs.reduce(
+ (total, output) => ({
+ fungible: total.fungible.plus(
+ exactTokenAmount(output.fungible_token_amount),
+ ),
+ nfts: total.nfts.plus(output.nonfungible_token_capability ? "1" : "0"),
+ minting:
+ total.minting || output.nonfungible_token_capability === "minting",
+ }),
+ { fungible: new BigNumber("0"), nfts: new BigNumber("0"), minting: false },
+ );
+}
diff --git a/src/pages/token/[category].vue b/src/pages/token/[category].vue
index 73edf5d..b59edfa 100644
--- a/src/pages/token/[category].vue
+++ b/src/pages/token/[category].vue
@@ -88,10 +88,9 @@
@@ -109,15 +108,14 @@
]
diff --git a/tests/authchains.test.ts b/tests/authchains.test.ts
index ef1430a..49fd17b 100644
--- a/tests/authchains.test.ts
+++ b/tests/authchains.test.ts
@@ -142,7 +142,7 @@ describe("auth-chain and migration selection", () => {
},
);
expect(decodeAuthChain(fixture, category)?.genesesTx.genesisSupply).toBe(
- 1000,
+ "1000",
);
});
});
diff --git a/tests/bitcoin.test.ts b/tests/bitcoin.test.ts
index 9e89bb2..6756549 100644
--- a/tests/bitcoin.test.ts
+++ b/tests/bitcoin.test.ts
@@ -16,6 +16,9 @@ Object.assign(globalThis, {
});
import { ref, watch } from "vue";
+import type { GetAuthChainsQuery } from "../src/graphql/graphql";
+
+const { decodeAuthChain } = await import("../src/module/bcmr");
const {
addPrefixToAddress,
@@ -182,3 +185,142 @@ describe("BCMR publication decoding", () => {
]);
});
});
+
+describe("BCMR genesis supply", () => {
+ function authchain(amount: string | null) {
+ const tokenOutput = {
+ token_category: "\\xaaaa" as const,
+ locking_bytecode: "\\x0011" as const,
+ fungible_token_amount: amount,
+ nonfungible_token_capability: "none" as const,
+ nonfungible_token_commitment: "\\x" as const,
+ };
+ return {
+ transaction: [
+ {
+ hash: "\\xaaaa" as const,
+ authchains: [
+ {
+ authchain_length: 1,
+ authhead_transaction_hash: "\\xcccc" as const,
+ unspent_authhead: true,
+ authhead: null,
+ migrations: [
+ {
+ migration_index: "0",
+ transaction: [
+ {
+ hash: "\\xcccc" as const,
+ block_inclusions: [],
+ inputs: [
+ {
+ outpoint_index: "0",
+ outpoint_transaction_hash: "\\xaaaa" as const,
+ },
+ ],
+ outputs: [
+ tokenOutput,
+ {
+ ...tokenOutput,
+ fungible_token_amount: amount ? "7" : null,
+ },
+ {
+ ...tokenOutput,
+ token_category: "\\xbbbb" as const,
+ fungible_token_amount: "9223372036854775807",
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ } satisfies GetAuthChainsQuery;
+ }
+
+ test("sums only the requested category without rounding large amounts", () => {
+ const genesis = decodeAuthChain(authchain("9007199254740993"), "aaaa");
+ expect(genesis?.genesesTx.genesisSupply).toBe("9007199254741000");
+ expect(genesis?.genesesTx.lockingBytecode).toBe("0011");
+ expect(
+ calculateDecimal(genesis?.genesesTx.genesisSupply || "0", 8).toFixed(),
+ ).toBe("90071992.54741");
+ });
+
+ test("does not treat a nonzero first outpoint as token genesis", () => {
+ const data = authchain("9007199254740993");
+ const input =
+ data.transaction[0]?.authchains[0]?.migrations[0]?.transaction[0]
+ ?.inputs[0];
+ if (input) input.outpoint_index = "1";
+ expect(decodeAuthChain(data, "aaaa")).toBeUndefined();
+ });
+
+ test("retains a zero fungible supply for NFT-only categories", () => {
+ expect(
+ decodeAuthChain(authchain(null), "aaaa")?.genesesTx.genesisSupply,
+ ).toBe("0");
+ expect(decodeAuthChain(authchain(null), "absent")).toBeUndefined();
+ });
+});
+
+test("a later index-zero input authorizes genesis with either safe numeric or string indices", () => {
+ const data: GetAuthChainsQuery = {
+ transaction: [
+ {
+ hash: "\\xaaaa",
+ authchains: [
+ {
+ authchain_length: 1,
+ authhead_transaction_hash: "\\xcccc",
+ unspent_authhead: true,
+ authhead: null,
+ migrations: [
+ {
+ migration_index: "0",
+ transaction: [
+ {
+ hash: "\\xcccc",
+ block_inclusions: [],
+ inputs: [
+ {
+ outpoint_transaction_hash: "\\xffff",
+ outpoint_index: "0",
+ },
+ {
+ outpoint_transaction_hash: "\\xaaaa",
+ outpoint_index: "0",
+ },
+ ],
+ outputs: [
+ {
+ token_category: "\\xaaaa",
+ locking_bytecode: "\\x51",
+ fungible_token_amount: null,
+ nonfungible_token_capability: "none",
+ nonfungible_token_commitment: "\\x",
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+ const input =
+ data.transaction[0]!.authchains[0]!.migrations[0]!.transaction![0]!
+ .inputs[1]!;
+ for (const index of ["0", 0]) {
+ Object.defineProperty(input, "outpoint_index", {
+ value: index,
+ configurable: true,
+ });
+ expect(decodeAuthChain(data, "aaaa")?.genesesTx.nftCapability).toBe("none");
+ }
+});
diff --git a/tests/fixtures/token-navigation.ts b/tests/fixtures/token-navigation.ts
index 1083b90..a4dc842 100644
--- a/tests/fixtures/token-navigation.ts
+++ b/tests/fixtures/token-navigation.ts
@@ -97,18 +97,26 @@ const { default: ContentWarp } = await import(
"../../src/components/ContentWarp.vue"
);
-const { GetSupplyNFTs } = await import("../../src/hooks/nftSupply");
-const { GetUseNonBurnTokens } = await import("../../src/hooks/nonSpentToken");
-const { GetMintingToken } = await import("../../src/hooks/activeMinting");
-const { GetAccountingNode } = await import("../../src/hooks/confirmedNode");
const { GetAuthChains } = await import("../../src/module/chaingraph");
const { decodeAuthChain } = await import("../../src/module/bcmr");
+const balanceRows = new Map<
+ string,
+ import("../../src/graphql/graphql").GetTokenBalanceOutputsQuery["output"]
+>();
+const apolloClients = new Map<
+ string,
+ ApolloClient
+>();
+Object.assign(globalThis, {
+ useApollo: () => ({ clients: { default: apolloClients.get("default") } }),
+});
const requests = new Map>();
const cleanup: (() => void)[] = [];
beforeEach(() => {
requests.clear();
+ balanceRows.clear();
route.params = { category: tokenA, txid: txB };
route.query = {};
});
@@ -122,7 +130,7 @@ async function settle() {
await nextTick();
}
-function mountPages(initial = "token", cachedCount = 0) {
+function mountPages(initial = "token") {
const pinia = createPinia();
setActivePinia(pinia);
const client = new ApolloClient({
@@ -131,53 +139,69 @@ function mountPages(initial = "token", cachedCount = 0) {
(operation) =>
new Observable((observer) => {
requests.set(operation, observer);
- if (operation.operationName === "GetAccountingNode")
+ if (operation.operationName === "GetTokenBalanceBlock")
observer.next({
data: {
- node: [
+ block: [
{
- internal_id:
- operation.variables.network === "chipnet" ? 2 : 1,
+ hash: "\\xdead",
+ height: "100",
+ accepted_by: [
+ {
+ node_internal_id:
+ operation.variables.node._eq ??
+ (operation.variables.network === "chipnet" ? 2 : 1),
+ },
+ ],
},
],
},
});
+ if (operation.operationName === "GetTokenBalanceBlock")
+ observer.complete();
+ if (operation.operationName === "GetTokenBalanceOutputs") {
+ const where = operation.variables.where;
+ const category = where._and[0].token_category._eq;
+ const genesis = where._and[0].transaction_hash;
+ const rows = genesis
+ ? [
+ {
+ transaction_hash: genesis._eq,
+ output_index: "0",
+ token_category: category,
+ locking_bytecode: "\\x51",
+ fungible_token_amount: "100",
+ nonfungible_token_capability: null,
+ },
+ ]
+ : (balanceRows.get(category) ?? [
+ {
+ transaction_hash: "\\xab",
+ output_index: "0",
+ token_category: category,
+ locking_bytecode: "\\x51",
+ fungible_token_amount: "60",
+ nonfungible_token_capability: null,
+ },
+ ]);
+ const cursor = where._and[1]?._or[1]?.output_index?._gt;
+ observer.next({
+ data: {
+ output: rows
+ .filter(
+ (row) =>
+ cursor === undefined ||
+ BigInt(row.output_index) > BigInt(cursor),
+ )
+ .slice(0, 500),
+ },
+ });
+ observer.complete();
+ }
}),
),
});
- if (cachedCount) {
- client.cache.writeQuery({
- query: GetAccountingNode,
- variables: { network: "mainnet" },
- data: { node: [{ internal_id: 1 }] },
- });
- client.cache.writeQuery({
- query: GetAuthChains,
- variables: { network: "mainnet", tokenCategory: [`\\x${tokenA}`] },
- data: chainResponse(tokenA),
- });
- client.cache.writeQuery({
- query: GetMintingToken,
- variables: { node: 1, tokenCategory: `\\x${tokenA}` },
- data: { output: [] },
- });
- for (const query of [GetSupplyNFTs, GetUseNonBurnTokens])
- client.cache.writeQuery({
- query,
- variables: {
- node: 1,
- tokenCategory: `\\x${tokenA}`,
- offset: 0,
- limit: 5000,
- },
- data: {
- output: Array.from({ length: cachedCount }, () => ({
- locking_bytecode: "\\x51" as const,
- fungible_token_amount: "50",
- })),
- },
- });
- }
+ apolloClients.set("default", client);
const page = ref(initial);
const root = createNode("root");
const app = renderer.createApp({
@@ -267,9 +291,13 @@ function request(
({ operation }) =>
operation.operationName === name &&
(operation.variables.network === network ||
- operation.variables.node === (network === "chipnet" ? 2 : 1)) &&
+ operation.variables.where?.transaction?.block_inclusions?.block
+ ?.accepted_by?.node_internal_id?._eq ===
+ (network === "chipnet" ? 2 : 1)) &&
(operation.variables.hash === `\\x${category}` ||
operation.variables.tokenCategory === `\\x${category}` ||
+ operation.variables.where?._and?.[0]?.token_category?._eq ===
+ `\\x${category}` ||
operation.variables.tokenCategory?.includes(`\\x${category}`)) &&
(operation.variables.offset || 0) === offset,
);
@@ -285,17 +313,6 @@ async function answerToken(category: string, network = "mainnet") {
request("GetAuthChains", category, network).observer.next?.({
data: chainResponse(category),
});
- request("GetMintingToken", category, network).observer.next?.({
- data: { output: [] },
- });
- request("GetSupplyNFTs", category, network).observer.next?.({
- data: { output: [] },
- });
- request("GetUseNonBurnTokens", category, network).observer.next?.({
- data: {
- output: [{ locking_bytecode: "\\x51", fungible_token_amount: "60" }],
- },
- });
await settle();
}
@@ -330,7 +347,7 @@ describe("token and transaction navigation", () => {
const screen = mountPages();
await settle();
const old = request("GetAuthChains", tokenA);
- const oldSupply = request("GetUseNonBurnTokens", tokenA);
+ const oldSupply = request("GetTokenBalanceOutputs", tokenA);
screen.store.authchains.set(tokenC, registry(tokenC, "Token Charlie"));
route.params = { category: tokenC, txid: txB };
await settle();
@@ -345,7 +362,7 @@ describe("token and transaction navigation", () => {
expect(screen.text()).toContain("Token Charlie");
expect(screen.text()).not.toContain("not found");
expect(screen.text()).not.toContain("could not be loaded");
- expect(screen.text()).toMatch(/Supply Excluding Burns\s+60/);
+ expect(screen.text()).toMatch(/Unspent fungible supply\s+60/);
expect(screen.text()).not.toContain("9999");
});
@@ -412,56 +429,6 @@ describe("token and transaction navigation", () => {
await settle();
expect(screen.text()).not.toContain("Mainnet Alpha");
});
- test("paginated supplies count each page once and reset for a new token", async () => {
- const screen = mountPages();
- await settle();
- screen.store.authchains.set(tokenA, registry(tokenA, "Token Alpha"));
- screen.store.authchains.set(tokenC, registry(tokenC, "Token Charlie"));
- request("GetAuthChains", tokenA).observer.next?.({
- data: chainResponse(tokenA),
- });
- request("GetMintingToken", tokenA).observer.next?.({
- data: { output: [] },
- });
- request("GetSupplyNFTs", tokenA).observer.next?.({
- data: {
- output: Array.from({ length: 5000 }, () => ({
- locking_bytecode: "\\x51",
- })),
- },
- });
- request("GetUseNonBurnTokens", tokenA).observer.next?.({
- data: {
- output: Array.from({ length: 5000 }, () => ({
- locking_bytecode: "\\x51",
- fungible_token_amount: "2",
- })),
- },
- });
- await settle();
- const nfts = request("GetSupplyNFTs", tokenA, "mainnet", 5000);
- const supply = request("GetUseNonBurnTokens", tokenA, "mainnet", 5000);
- const lastNfts = {
- output: [{ locking_bytecode: "\\x51" }, { locking_bytecode: "\\x52" }],
- };
- const lastSupply = {
- output: [{ locking_bytecode: "\\x51", fungible_token_amount: "7" }],
- };
- nfts.observer.next?.({ data: lastNfts });
- supply.observer.next?.({ data: lastSupply });
- await settle();
- expect(screen.text()).toMatch(/Total Amount NFTs\s+5002/);
- expect(screen.text()).toMatch(/Supply Excluding Burns\s+10007/);
- nfts.observer.next?.({ data: lastNfts });
- supply.observer.next?.({ data: lastSupply });
- await settle();
- expect(screen.text()).toMatch(/Supply Excluding Burns\s+10007/);
- route.params = { category: tokenC, txid: txB };
- await settle();
- await answerToken(tokenC);
- expect(screen.text()).toMatch(/Supply Excluding Burns\s+60/);
- expect(screen.text()).not.toContain("10007");
- });
test("a pending registry fetch cannot repopulate a different network, even after switching back", async () => {
const screen = mountPages();
@@ -509,11 +476,11 @@ describe("token and transaction navigation", () => {
);
cleanup.push(() => fetchMock.mockRestore());
await answerToken(tokenA);
- expect(screen.text()).toContain("Genesis Transaction");
+ expect(screen.text()).toContain("Genesis transaction");
expect(screen.text()).toContain("Loading token metadata");
deferred.resolve(new Response("Unavailable", { status: 503 }));
await settle();
- expect(screen.text()).toContain("Genesis Transaction");
+ expect(screen.text()).toContain("Genesis transaction");
expect(screen.text()).toContain("Auth-chain metadata could not be loaded");
expect(screen.text()).not.toContain("Loading token metadata");
});
@@ -530,48 +497,39 @@ describe("token and transaction navigation", () => {
request("GetAuthChains", tokenC).observer.next?.({
data: { transaction: [] },
});
- request("GetMintingToken", tokenC).observer.next?.({
- data: { output: [] },
- });
- request("GetSupplyNFTs", tokenC).observer.next?.({ data: { output: [] } });
- request("GetUseNonBurnTokens", tokenC).observer.next?.({
- data: { output: [] },
- });
await settle();
expect(screen.text()).toContain("Token not found");
expect(screen.text()).not.toContain("could not be loaded");
});
});
-test("initial cached complete balances and auth-chain results are consumed without a network response", async () => {
- const screen = mountPages("token", 2);
+test("complete paged balances count each outpoint once and reset across token changes", async () => {
+ balanceRows.set(
+ `\\x${tokenA}`,
+ Array.from({ length: 1002 }, (_, index) => ({
+ transaction_hash: "\\xab",
+ output_index: String(index),
+ token_category: `\\x${tokenA}`,
+ locking_bytecode: "\\x51",
+ fungible_token_amount: index === 1001 ? "7" : "2",
+ nonfungible_token_capability: "none",
+ })),
+ );
+ const screen = mountPages();
await settle();
- expect(screen.text()).toMatch(/Supply Excluding Burns\s+100/);
- expect(screen.text()).toMatch(/Total Amount NFTs\s+2/);
- expect(screen.text()).toContain("1 available");
- expect(
- [...requests.keys()].some(
- (op) => op.operationName === "GetUseNonBurnTokens",
- ),
- ).toBe(false);
-});
-
-test("cached first pages advance and repeated terminal emissions are counted once", async () => {
- const screen = mountPages("token", 5000);
+ await answerToken(tokenA);
await settle();
- const nfts = request("GetSupplyNFTs", tokenA, "mainnet", 5000);
- const supply = request("GetUseNonBurnTokens", tokenA, "mainnet", 5000);
- const finalNfts = { output: [{ locking_bytecode: "\\x51" }] };
- const finalSupply = {
- output: [{ locking_bytecode: "\\x51", fungible_token_amount: "7" }],
- };
- for (const _ of [0, 1]) {
- nfts.observer.next?.({ data: finalNfts });
- supply.observer.next?.({ data: finalSupply });
- await settle();
- expect(screen.text()).toMatch(/Supply Excluding Burns\s+250007/);
- expect(screen.text()).toMatch(/Total Amount NFTs\s+5001/);
- }
+ expect(screen.text()).toMatch(/Unspent fungible supply\s+2009/);
+ expect(screen.text()).toMatch(/Unspent NFTs \(all capabilities\)\s+1002/);
+ const old = request("GetTokenBalanceOutputs", tokenA);
+ old.observer.next?.({ data: { output: [] } });
+ await settle();
+ expect(screen.text()).toMatch(/Unspent fungible supply\s+2009/);
+ route.params = { category: tokenC, txid: txB };
+ await settle();
+ await answerToken(tokenC);
+ expect(screen.text()).toMatch(/Unspent fungible supply\s+60/);
+ expect(screen.text()).not.toContain("2009");
});
test("genesis checks every authorizing input and rejects BCH-only or foreign category outputs", () => {
@@ -583,7 +541,7 @@ test("genesis checks every authorizing input and rejects BCH-only or foreign cat
outpoint_transaction_hash: `\\x${txB}`,
outpoint_index: "0",
});
- expect(decodeAuthChain(data, tokenA)?.genesesTx.genesisSupply).toBe(100);
+ expect(decodeAuthChain(data, tokenA)?.genesesTx.genesisSupply).toBe("100");
tx.outputs[0]!.fungible_token_amount = "0";
tx.outputs[0]!.nonfungible_token_capability = "none";
expect(decodeAuthChain(data, tokenA)).toBeDefined();
@@ -628,26 +586,6 @@ test("transaction metadata is publication-specific across A → B → A and igno
}
});
-test("confirmed accounting queries pin the same node for creations and spends, retaining pending transfers", async () => {
- const { print } = await import("graphql");
- for (const query of [GetSupplyNFTs, GetUseNonBurnTokens, GetMintingToken]) {
- const source = print(query);
- expect(source).toContain("node_internal_id: {_eq: $node}");
- expect(source).toContain(
- "spent_by: {transaction: {block_inclusions: {block: {accepted_by:",
- );
- }
- const screen = mountPages();
- await settle();
- await answerToken(tokenA);
- expect(screen.text()).toMatch(/Supply Excluding Burns\s+60/);
- request("GetMintingToken", tokenA).observer.next?.({
- data: { output: [{ locking_bytecode: "\\x51" }] },
- });
- await settle();
- expect(screen.text()).toMatch(/Is Active Minting\s+Yes/);
-});
-
test("missing revisions retain recovery controls and network rejection clears selected identity", async () => {
const screen = mountPages();
await settle();
diff --git a/tests/token-balances.test.ts b/tests/token-balances.test.ts
new file mode 100644
index 0000000..feac059
--- /dev/null
+++ b/tests/token-balances.test.ts
@@ -0,0 +1,500 @@
+import { describe, expect, test } from "bun:test";
+import { effectScope, nextTick, ref } from "vue";
+import type {
+ GetTokenBalanceOutputsQuery,
+ Output_Bool_Exp,
+ Transaction_Bool_Exp,
+} from "../src/graphql/graphql";
+import { useTokenBalanceSnapshot } from "../src/hooks/tokenBalances";
+import {
+ groupTokenBalances,
+ loadTokenBalances,
+ summarizeTokenBalances,
+ TokenBalanceError,
+} from "../src/module/tokenBalances";
+
+const category = "\\xaaaa";
+const foreignCategory = "\\xbbbb";
+const script = "\\x0011";
+
+function output(
+ hash: string,
+ index: string,
+ amount: string | null,
+ capability: GetTokenBalanceOutputsQuery["output"][number]["nonfungible_token_capability"] = null,
+) {
+ return {
+ transaction_hash: `\\x${hash}` as const,
+ output_index: index,
+ token_category: category,
+ locking_bytecode: script,
+ fungible_token_amount: amount,
+ nonfungible_token_capability: capability,
+ } satisfies GetTokenBalanceOutputsQuery["output"][number];
+}
+
+function confirmed(network = "mainnet", height = "90", accepted = true) {
+ return { network, height, accepted, node: network === "chipnet" ? 2 : 1 };
+}
+
+function fixture(
+ row: GetTokenBalanceOutputsQuery["output"][number],
+ transaction = confirmed(),
+ spentBy: ReturnType[] = [],
+) {
+ return { row, transaction, spentBy };
+}
+
+const firstOutput = output("01", "2", "9007199254740993");
+const fixtures = [
+ fixture(firstOutput),
+ fixture(output("01", "10", "7", "mutable")),
+ fixture(output("02", "0", "5", "none"), confirmed(), [confirmed("chipnet")]),
+ fixture(output("03", "0", "3", "minting"), confirmed(), [
+ confirmed("mainnet", "101"),
+ ]),
+ fixture(output("04", "0", null, "none")),
+ fixture(output("05", "0", "11"), confirmed(), [
+ confirmed("mainnet", "80", false),
+ ]),
+ fixture(output("06", "0", "100"), confirmed("chipnet")),
+ fixture(output("07", "0", "200"), confirmed("mainnet", "80", false)),
+ fixture(output("08", "0", "300"), confirmed(), [confirmed()]),
+ fixture(output("09", "0", "400"), confirmed("mainnet", "101")),
+ fixture({ ...output("0a", "0", "13"), token_category: foreignCategory }),
+ fixture({ ...output("0b", "0", "17"), locking_bytecode: "\\x0022" }),
+];
+
+// Fixture backend: model accepted-chain relationships and Hasura's keyset predicates.
+function matchesTransaction(
+ transaction: ReturnType,
+ where: Transaction_Bool_Exp,
+) {
+ const block = where.block_inclusions?.block;
+ if (!block) return true;
+ const network = block.accepted_by?.node?.name?._regex;
+ return (
+ transaction.accepted &&
+ (!block.accepted_by?.node_internal_id?._eq ||
+ transaction.node === block.accepted_by.node_internal_id._eq) &&
+ (!network || new RegExp(network).test(transaction.network)) &&
+ (!block.height?._lte ||
+ BigInt(transaction.height) <= BigInt(block.height._lte))
+ );
+}
+
+function matches(item: (typeof fixtures)[number], where: Output_Bool_Exp) {
+ const { row } = item;
+ if (where._and && !where._and.every((filter) => matches(item, filter)))
+ return false;
+ if (where._or && !where._or.some((filter) => matches(item, filter)))
+ return false;
+ if (
+ where.transaction &&
+ !matchesTransaction(item.transaction, where.transaction)
+ )
+ return false;
+ const spend = where._not?.spent_by?.transaction;
+ if (
+ spend &&
+ item.spentBy.some((transaction) => matchesTransaction(transaction, spend))
+ )
+ return false;
+ if (
+ where.token_category?._eq &&
+ row.token_category !== where.token_category._eq
+ )
+ return false;
+ if (
+ where.locking_bytecode?._eq &&
+ row.locking_bytecode !== where.locking_bytecode._eq
+ )
+ return false;
+ if (
+ where.transaction_hash?._eq &&
+ row.transaction_hash !== where.transaction_hash._eq
+ )
+ return false;
+ if (
+ where.transaction_hash?._gt &&
+ row.transaction_hash <= where.transaction_hash._gt
+ )
+ return false;
+ if (
+ where.output_index?._gt &&
+ BigInt(row.output_index) <= BigInt(where.output_index._gt)
+ )
+ return false;
+ return true;
+}
+
+function backend(rows = fixtures) {
+ const calls: Output_Bool_Exp[] = [];
+ return {
+ calls,
+ async block() {
+ return [
+ {
+ hash: "\\xdead" as const,
+ height: "100",
+ accepted_by: [{ node_internal_id: 1 }],
+ },
+ ];
+ },
+ async outputs(where: Output_Bool_Exp) {
+ calls.push(where);
+ // Deliberately cap at two rows, less than the production request limit.
+ return rows
+ .filter((item) => matches(item, where))
+ .sort(
+ (a, b) =>
+ a.row.transaction_hash.localeCompare(b.row.transaction_hash) ||
+ Number(BigInt(a.row.output_index) - BigInt(b.row.output_index)),
+ )
+ .slice(0, 2)
+ .map((item) => item.row);
+ },
+ };
+}
+
+const scope = {
+ network: "mainnet",
+ filter: { token_category: { _eq: category } },
+} satisfies Parameters[0];
+
+async function load(
+ queries: Parameters[1] = backend(),
+ current: Parameters[0] = scope,
+) {
+ return loadTokenBalances(current, queries, new AbortController().signal);
+}
+
+describe("complete, exact confirmed token balances", () => {
+ test("reads all capped pages, including the empty terminator and same-tx output indices", async () => {
+ const queries = backend();
+ const snapshot = await load(queries);
+ expect(snapshot.height).toBe("100");
+ expect(
+ snapshot.outputs.map(
+ (row) => `${row.transaction_hash}:${row.output_index}`,
+ ),
+ ).toEqual([
+ "\\x01:2",
+ "\\x01:10",
+ "\\x02:0",
+ "\\x03:0",
+ "\\x04:0",
+ "\\x05:0",
+ "\\x0b:0",
+ ]);
+ expect(queries.calls).toHaveLength(5);
+ const totals = summarizeTokenBalances(snapshot.outputs);
+ expect(totals.fungible.toFixed()).toBe("9007199254741036");
+ expect(totals.nfts.toFixed()).toBe("4");
+ expect(totals.minting).toBe(true);
+ expect(groupTokenBalances(snapshot.outputs, "locking_bytecode")).toEqual([
+ { key: script, amount: "9007199254741019" },
+ { key: "\\x0022", amount: "17" },
+ ]);
+ });
+
+ test("aggregates an address across categories and pages, including FT in NFT outputs", async () => {
+ const snapshot = await loadTokenBalances(
+ { network: "mainnet", filter: { locking_bytecode: { _eq: script } } },
+ backend(),
+ new AbortController().signal,
+ );
+ expect(groupTokenBalances(snapshot.outputs, "token_category")).toEqual([
+ { key: category, amount: "9007199254741019" },
+ { key: foreignCategory, amount: "13" },
+ ]);
+ });
+
+ test("complete genesis scans include spent outputs and exclude foreign categories", async () => {
+ const queries = backend([
+ fixture(output("01", "0", "9007199254740993"), confirmed(), [
+ confirmed(),
+ ]),
+ fixture(output("01", "1", "7", "mutable")),
+ fixture({ ...output("01", "2", "99"), token_category: foreignCategory }),
+ fixture(output("02", "0", "200")),
+ ]);
+ const snapshot = await load(queries, {
+ ...scope,
+ includeSpent: true,
+ filter: {
+ token_category: { _eq: category },
+ transaction_hash: { _eq: "\\x01" },
+ },
+ });
+ expect(snapshot.outputs).toHaveLength(2);
+ expect(snapshot.outputs[0]?.output_index).toBe("0");
+ expect(summarizeTokenBalances(snapshot.outputs).fungible.toFixed()).toBe(
+ "9007199254741000",
+ );
+ });
+
+ test("re-fetching the same snapshot replaces totals rather than adding them", async () => {
+ const queries = backend();
+ const first = await load(queries);
+ const second = await load(queries);
+ expect(groupTokenBalances(second.outputs, "locking_bytecode")).toEqual(
+ groupTokenBalances(first.outputs, "locking_bytecode"),
+ );
+ });
+
+ test("a repeated page fails visibly instead of doubling or looping forever", async () => {
+ const queries = backend();
+ await expect(
+ load({ ...queries, outputs: async () => [firstOutput] }),
+ ).rejects.toThrow("did not advance");
+ });
+
+ test("empty is an exact zero, while an error after a partial page has no total", async () => {
+ const empty = await load(backend([]));
+ expect(empty.outputs).toEqual([]);
+ expect(summarizeTokenBalances(empty.outputs).fungible.toFixed()).toBe("0");
+ const queries = backend();
+ await expect(
+ load({
+ ...queries,
+ outputs: async (where) => {
+ if (queries.calls.length > 0) throw new TokenBalanceError("Offline");
+ return queries.outputs(where);
+ },
+ }),
+ ).rejects.toThrow("Offline");
+ });
+
+ test("rejects a changed or unavailable accepted block", async () => {
+ const queries = backend();
+ await expect(load({ ...queries, block: async () => [] })).rejects.toThrow(
+ "No accepted block",
+ );
+ await expect(
+ load({
+ ...queries,
+ block: async (height?: string) =>
+ height
+ ? [
+ {
+ hash: "\\xbeef",
+ height,
+ accepted_by: [{ node_internal_id: 1 }],
+ },
+ ]
+ : queries.block(),
+ }),
+ ).rejects.toThrow("accepted chain changed");
+ });
+
+ test("network selection changes both creation and spending semantics", async () => {
+ const snapshot = await load(
+ {
+ ...backend(),
+ block: async () => [
+ {
+ hash: "\\xdead",
+ height: "100",
+ accepted_by: [{ node_internal_id: 2 }],
+ },
+ ],
+ },
+ { ...scope, network: "chipnet" },
+ );
+ expect(summarizeTokenBalances(snapshot.outputs).fungible.toFixed()).toBe(
+ "100",
+ );
+ });
+});
+
+async function settle() {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await nextTick();
+}
+
+describe("snapshot lifecycle", () => {
+ test("clears ready values on refresh; partial failure stays unavailable; retry is idempotent", async () => {
+ const owner = effectScope();
+ const current = ref[0]>(scope);
+ const control = { fail: false };
+ const result = owner.run(() =>
+ useTokenBalanceSnapshot(current, (selected, signal) => {
+ if (control.fail)
+ return Promise.reject(new TokenBalanceError("Offline"));
+ return loadTokenBalances(selected, backend(), signal);
+ }),
+ );
+ if (!result) throw new TokenBalanceError("Missing test scope");
+ try {
+ expect(result.state.value.status).toBe("loading");
+ await settle();
+ const initial = result.state.value;
+ expect(initial.status).toBe("ready");
+ control.fail = true;
+ result.refresh();
+ expect(result.state.value).toEqual({ status: "loading" });
+ await settle();
+ expect(result.state.value.status).toBe("error");
+ control.fail = false;
+ result.refresh();
+ await settle();
+ expect(result.state.value).toEqual(initial);
+ } finally {
+ owner.stop();
+ }
+ });
+
+ test("does not request incomplete genesis scopes", async () => {
+ const owner = effectScope();
+ const calls: string[] = [];
+ const result = owner.run(() =>
+ useTokenBalanceSnapshot(ref(null), async () => {
+ calls.push("loaded");
+ return { status: "ready", height: "100", outputs: [] };
+ }),
+ );
+ try {
+ await settle();
+ expect(result?.state.value).toEqual({ status: "unavailable" });
+ expect(calls).toEqual([]);
+ } finally {
+ owner.stop();
+ }
+ });
+
+ test("category/network changes and disposal discard late responses", async () => {
+ const owner = effectScope();
+ const current = ref[0]>(scope);
+ const pending: {
+ signal: AbortSignal;
+ resolve: (value: Awaited>) => void;
+ }[] = [];
+ const result = owner.run(() =>
+ useTokenBalanceSnapshot(
+ current,
+ (_, signal) =>
+ new Promise((resolve) => pending.push({ signal, resolve })),
+ ),
+ );
+ if (!result) throw new TokenBalanceError("Missing test scope");
+ try {
+ current.value = { ...scope, network: "chipnet" };
+ expect(pending[0]?.signal.aborted).toBe(true);
+ expect(result.state.value.status).toBe("loading");
+ pending[1]?.resolve({ status: "ready", height: "2", outputs: [] });
+ await settle();
+ pending[0]?.resolve({
+ status: "ready",
+ height: "1",
+ outputs: [firstOutput],
+ });
+ await settle();
+ expect(result.state.value).toEqual({
+ status: "ready",
+ height: "2",
+ outputs: [],
+ });
+ current.value = {
+ ...scope,
+ filter: { token_category: { _eq: foreignCategory } },
+ };
+ expect(result.state.value).toEqual({ status: "loading" });
+ owner.stop();
+ expect(pending[2]?.signal.aborted).toBe(true);
+ pending[2]?.resolve({ status: "ready", height: "3", outputs: [] });
+ await settle();
+ expect(result.state.value.status).toBe("loading");
+ } finally {
+ owner.stop();
+ }
+ });
+});
+
+test("raw JSON unsafe numeric amounts cannot become an exact ready snapshot", async () => {
+ const row = output("01", "0", "0");
+ Object.defineProperty(row, "fungible_token_amount", {
+ value: JSON.parse("9007199254740993"),
+ });
+ await expect(load(backend([fixture(row)]))).rejects.toThrow("unsafe integer");
+});
+
+test("integer scalar boundaries retain strings and safe numbers, rejecting untrusted values", () => {
+ for (const amount of [
+ "0",
+ "9007199254740993",
+ "72624976668144285",
+ "9223372036854775807",
+ 0,
+ Number.MAX_SAFE_INTEGER,
+ ]) {
+ const row = output("01", "0", "0");
+ Object.defineProperty(row, "fungible_token_amount", { value: amount });
+ expect(groupTokenBalances([row], "token_category")[0]?.amount).toBe(
+ String(amount),
+ );
+ }
+ for (const amount of [
+ -1,
+ 1.5,
+ Number.MAX_SAFE_INTEGER + 1,
+ true,
+ {},
+ [],
+ "1e3",
+ "-1",
+ "NaN",
+ "",
+ ]) {
+ const row = output("01", "0", "0");
+ Object.defineProperty(row, "fungible_token_amount", { value: amount });
+ expect(() => summarizeTokenBalances([row])).toThrow("unsafe integer");
+ }
+});
+
+test("one accepted node scopes creation, spends, and final snapshot verification", async () => {
+ const first = { ...confirmed(), node: 1 };
+ const competing = { ...confirmed(), node: 3 };
+ const queries = backend([
+ fixture(output("01", "0", "100"), first, [competing]),
+ fixture(output("02", "0", "100"), competing),
+ fixture(output("03", "0", "100"), first, [{ ...first, accepted: false }]),
+ ]);
+ const verification: (number | undefined)[] = [];
+ const snapshot = await load({
+ ...queries,
+ block: async (_height, node) => {
+ verification.push(node);
+ return queries.block();
+ },
+ });
+ expect(summarizeTokenBalances(snapshot.outputs).fungible.toFixed()).toBe(
+ "200",
+ );
+ expect(verification).toEqual([undefined, 1]);
+ for (const where of queries.calls) {
+ expect(
+ where.transaction?.block_inclusions?.block?.accepted_by?.node_internal_id
+ ?._eq,
+ ).toBe(1);
+ expect(
+ where._not?.spent_by?.transaction?.block_inclusions?.block?.accepted_by
+ ?.node_internal_id?._eq,
+ ).toBe(1);
+ }
+ await expect(
+ load({
+ ...queries,
+ block: async (height) =>
+ height
+ ? [
+ {
+ hash: "\\xdead",
+ height,
+ accepted_by: [{ node_internal_id: 3 }],
+ },
+ ]
+ : queries.block(),
+ }),
+ ).rejects.toThrow("accepted chain changed");
+});
From e261e56237b95976204ad50bfec7129b5c148540 Mon Sep 17 00:00:00 2001
From: Salem Mohammed Shamakh <58360393+salemkode@users.noreply.github.com>
Date: Sun, 15 Nov 2026 06:13:55 +0300
Subject: [PATCH 9/9] fix: retain later genesis inputs at the GraphQL boundary
---
docs/token-balances.md | 6 ++++
src/module/chaingraph.ts | 3 +-
tests/genesis-query.test.ts | 65 +++++++++++++++++++++++++++++++++++++
3 files changed, 72 insertions(+), 2 deletions(-)
create mode 100644 tests/genesis-query.test.ts
diff --git a/docs/token-balances.md b/docs/token-balances.md
index 87c0bc4..06e3abe 100644
--- a/docs/token-balances.md
+++ b/docs/token-balances.md
@@ -91,3 +91,9 @@ spends and another node’s competing branch cannot remove or duplicate outputs.
Genesis authorization checks every input spending the category’s output zero,
consistent with the CashTokens specification’s Token Categories section:
https://github.com/bitjson/cashtokens#token-categories
+
+The auth-chain query fetches all inputs spending output zero, without a first-input
+row limit. `tests/genesis-query.test.ts` executes the generated query against the
+schema and applies its actual input filters and limits before decoding the
+fixture. It covers an authorizing input after unrelated inputs, including numeric
+and string indices; restoring the first-input cap makes the regression fail.
diff --git a/src/module/chaingraph.ts b/src/module/chaingraph.ts
index 10517c2..64e8266 100644
--- a/src/module/chaingraph.ts
+++ b/src/module/chaingraph.ts
@@ -329,8 +329,7 @@ export const GetAuthChains = gql(`
timestamp
}
}
- inputs(limit: 1, order_by: { input_index: asc }) {
- outpoint_index
+ inputs(where: { outpoint_index: { _eq: 0 } }) {
outpoint_transaction_hash
outpoint_index
}
diff --git a/tests/genesis-query.test.ts b/tests/genesis-query.test.ts
new file mode 100644
index 0000000..605da44
--- /dev/null
+++ b/tests/genesis-query.test.ts
@@ -0,0 +1,65 @@
+import { expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { buildSchema, defaultFieldResolver, execute } from "graphql";
+import { ref, watch } from "vue";
+import { GetAuthChainsDocument } from "../src/graphql/graphql";
+import { chainResponse, tokenA } from "./helpers/token-fixtures";
+
+Object.assign(globalThis, { ref, watch });
+const { decodeAuthChain } = await import("../src/module/bcmr");
+const schema = buildSchema(
+ readFileSync(
+ new URL("../schema/chaingraph.graphql", import.meta.url),
+ "utf8",
+ ),
+);
+
+test("the generated auth-chain query retains later genesis-authorizing inputs", async () => {
+ for (const index of ["0", 0]) {
+ const data = chainResponse(tokenA);
+ const transaction =
+ data.transaction[0]?.authchains[0]?.migrations[0]?.transaction[0];
+ if (!transaction) throw new Error("Missing genesis fixture");
+ const authorizingInput = transaction.inputs[0];
+ if (!authorizingInput) throw new Error("Missing authorizing input");
+ Object.defineProperty(authorizingInput, "outpoint_index", { value: index });
+ transaction.inputs.unshift(
+ {
+ outpoint_transaction_hash: `\\x${"11".repeat(32)}`,
+ outpoint_index: "3",
+ },
+ {
+ outpoint_transaction_hash: `\\x${"22".repeat(32)}`,
+ outpoint_index: "0",
+ },
+ );
+ const fetchedInputs = [transaction.inputs];
+ const result = await execute({
+ schema,
+ document: GetAuthChainsDocument,
+ variableValues: { network: "mainnet", tokenCategory: [`\\x${tokenA}`] },
+ rootValue: data,
+ fieldResolver(source, args, context, info) {
+ if (info.fieldName !== "inputs") {
+ return defaultFieldResolver(source, args, context, info);
+ }
+ // Model the backend's filtering and row cap from the actual query.
+ // Returning every fixture input would hide the original limit: 1 bug.
+ const matching = transaction.inputs.filter(
+ (input) =>
+ args.where?.outpoint_index?._eq === undefined ||
+ String(input.outpoint_index) ===
+ String(args.where.outpoint_index._eq),
+ );
+ const selected = matching.slice(0, args.limit ?? matching.length);
+ fetchedInputs.push(selected);
+ return selected;
+ },
+ });
+ expect(result.errors).toBeUndefined();
+ const selected = fetchedInputs.at(-1);
+ if (!selected) throw new Error("Query did not resolve inputs");
+ transaction.inputs.splice(0, transaction.inputs.length, ...selected);
+ expect(decodeAuthChain(data, tokenA)?.genesesTx.genesisSupply).toBe("100");
+ }
+});