+
diff --git a/src/components/Transaction/TransactionOperationToken.vue b/src/components/Transaction/TransactionOperationToken.vue
index 91d3f18..1c58873 100644
--- a/src/components/Transaction/TransactionOperationToken.vue
+++ b/src/components/Transaction/TransactionOperationToken.vue
@@ -3,6 +3,7 @@ import { calculateDecimal } from "~/module/bitcoin";
import { shortTx } from "~/module/utils";
import { useRegistryStore } from "~/store";
import type { Capability } from "~/types";
+
type Maybe = 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/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/src/store/registry.ts b/src/store/registry.ts
index ac96c0b..3d3dc0b 100644
--- a/src/store/registry.ts
+++ b/src/store/registry.ts
@@ -115,7 +115,7 @@ export const useRegistryStore = defineStore("registry", () => {
const tokenIdentities = registry?.identities?.[tokenCategory];
if (tokenIdentities) {
const timestamp = Object.keys(tokenIdentities)
- .filter((revision) => +new Date(revision) < +new Date())
+ .filter((revision) => +new Date(revision) < Date.now())
.reduce(
(timestamp1, timestamp2) =>
new Date(timestamp1) > new Date(timestamp2)
@@ -134,8 +134,7 @@ export const useRegistryStore = defineStore("registry", () => {
const getRegistryHasCategory = (category: string) => {
const opreturnResult = authchains.get(category);
// for in array
- for (let i = 0; i < registryList.value.length; i++) {
- const { url } = registryList.value[i];
+ for (const { url } of registryList.value) {
const isAuthChain = url === "auth_chain";
const registry = isAuthChain
? opreturnResult
diff --git a/src/store/state.ts b/src/store/state.ts
index 2df2e69..d2f3168 100644
--- a/src/store/state.ts
+++ b/src/store/state.ts
@@ -17,15 +17,13 @@ export const useStateStore = defineStore("state", () => {
tokenSupport = true,
) => {
const bytecode = hexToBin(hexCode);
- const address = lockingBytecodeToCashAddress(
+ const address = lockingBytecodeToCashAddress({
bytecode,
- network.value === "mainnet" ? "bitcoincash" : "bchtest",
- {
- tokenSupport,
- },
- );
+ prefix: network.value === "mainnet" ? "bitcoincash" : "bchtest",
+ tokenSupport,
+ });
- return typeof address === "string" ? address : undefined;
+ return typeof address === "string" ? undefined : address.address;
};
return {
diff --git a/src/types/electrum.d.ts b/src/types/electrum.d.ts
deleted file mode 100644
index d9a4530..0000000
--- a/src/types/electrum.d.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import type { SubscribeCallback } from "electrum-cash";
-
-declare module "electrum-cash" {
- type balance = { confirmed: number; unconfirmed: number };
- type history = {
- height: number;
- tx_hash: string;
- }[];
-
- export class ElectrumClient extends this.ElectrumClient {
- constructor(
- application: string,
- version: string,
- host: string,
- port?: number,
- scheme?: TransportScheme,
- timeout?: number,
- pingInterval?: number,
- );
-
- request(
- method: "blockchain.address.get_balance",
- address: string,
- ): Promise;
-
- request(
- method: "blockchain.address.get_history",
- address: string,
- ): Promise;
-
- request(method: string, ...parameters: string[]): Promise;
-
- subscribe(
- callback: SubscribeCallback,
- method: string,
- ...parameters: string[]
- ): Promise;
- }
-}
diff --git a/src/types/gql.d.ts b/src/types/gql.d.ts
index 4741246..588f1c7 100644
--- a/src/types/gql.d.ts
+++ b/src/types/gql.d.ts
@@ -1,4 +1,5 @@
-import { gql as gqlType } from "@/graphql/gql";
+import type { gql as gqlType } from "@/graphql/gql";
+
declare global {
- const gql = gqlType;
+ const gql: typeof gqlType;
}
diff --git a/src/types/index.d.ts b/src/types/index.d.ts
index 82a6482..e6f299a 100644
--- a/src/types/index.d.ts
+++ b/src/types/index.d.ts
@@ -1,3 +1,4 @@
+import type BigNumber from "bignumber.js";
import type { Scalars } from "~/graphql/graphql";
export type bigNum = number | string | BigNumber;
export type bytea = `\\x${string}`;
diff --git a/tailwind.config.ts b/tailwind.config.ts
deleted file mode 100644
index b99dfbb..0000000
--- a/tailwind.config.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import type { Config } from "tailwindcss";
-
-export default {
- darkMode: "class",
- content: [
- "./src/components/**/*.{vue,js,ts}",
- "./src/layouts/**/*.vue",
- "./src/pages/**/*.vue",
- "./src/plugins/**/*.{js,ts}",
- "./src/app.vue",
- "./src/error.vue",
- ],
- theme: {
- extend: {
- colors: {
- bch: {
- 50: "#f0fdf4",
- 100: "#dcfce7",
- 200: "#bbf7d0",
- 300: "#86efac",
- 400: "#4ade80",
- 500: "#22c55e",
- 600: "#16a34a",
- 700: "#15803d",
- 800: "#166534",
- 900: "#14532d",
- 950: "#052e16",
- green: "#0d8514",
- accent: "#0ac18e",
- },
- },
- fontFamily: {
- sans: [
- "Inter",
- "-apple-system",
- "BlinkMacSystemFont",
- '"Segoe UI"',
- "Roboto",
- "Oxygen",
- "Ubuntu",
- "Cantarell",
- '"Fira Sans"',
- '"Droid Sans"',
- '"Helvetica Neue"',
- "sans-serif",
- ],
- mono: [
- "ui-monospace",
- "SFMono-Regular",
- "Menlo",
- "Monaco",
- "Consolas",
- '"Liberation Mono"',
- '"Courier New"',
- "monospace",
- ],
- },
- boxShadow: {
- card: "0 1px 3px 0 rgb(0 0 0 / 0.05), 0 1px 2px -1px rgb(0 0 0 / 0.05)",
- "card-hover":
- "0 4px 12px 0 rgb(0 0 0 / 0.08), 0 2px 4px -1px rgb(0 0 0 / 0.06)",
- glow: "0 0 25px -5px rgba(16, 185, 129, 0.25)",
- },
- },
- },
- plugins: [],
-} satisfies Config;
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/bitcoin.test.ts b/tests/bitcoin.test.ts
new file mode 100644
index 0000000..9e89bb2
--- /dev/null
+++ b/tests/bitcoin.test.ts
@@ -0,0 +1,184 @@
+import { describe, expect, test } from "bun:test";
+import {
+ binToHex,
+ hexToBin,
+ lockingBytecodeToCashAddress,
+ utf8ToBin,
+} from "@bitauth/libauth";
+
+// Nuxt auto-imports these at runtime; use real Vue primitives for pure helpers.
+Object.assign(globalThis, {
+ ref,
+ watch,
+ useRuntimeConfig: () => ({
+ public: { ipfsGateway: "https://gateway.example" },
+ }),
+});
+
+import { ref, watch } from "vue";
+
+const {
+ addPrefixToAddress,
+ addressToLockingBytecodeHex,
+ calculateDecimal,
+ getAddressType,
+ isValidAddress,
+ normalizeMetadataUrl,
+ opreturnToAuthChainElement,
+ parseBinary,
+ satToBch,
+} = await import("../src/module/bitcoin");
+
+const addresses = [
+ {
+ cash: "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a",
+ legacy: "1BpEi6DfDAUFd7GtittLSdBeYJvcoaVggu",
+ bytecode: "76a91476a04053bda0a88bda5177b86a15c3b29f55987388ac",
+ type: "P2PKH",
+ },
+ {
+ cash: "bitcoincash:ppm2qsznhks23z7629mms6s4cwef74vcwvn0h829pq",
+ legacy: "3CWFddi6m4ndiGyKqzYvsFYagqDLPVMTzC",
+ bytecode: "a91476a04053bda0a88bda5177b86a15c3b29f55987387",
+ type: "P2SH",
+ },
+];
+
+describe("address conversion with Libauth 3", () => {
+ test("retains P2SH32 scripts for ordinary and token-aware addresses", () => {
+ const bytecode = `aa20${"0123456789abcdef".repeat(4)}87`;
+ for (const address of [
+ "bitcoincash:pvqjx3t83x4ummcpydzk0zdtehhszg69v7y6hn00qy352euf40x77nngu7utv",
+ "bitcoincash:rvqjx3t83x4ummcpydzk0zdtehhszg69v7y6hn00qy352euf40x77pq5a8aj8",
+ ]) {
+ expect(isValidAddress(address)).toBe(true);
+ expect(getAddressType(address)).toBe("P2SH");
+ expect(addressToLockingBytecodeHex(address)).toBe(bytecode);
+ }
+ });
+
+ for (const { cash, legacy, bytecode, type } of addresses) {
+ test(`${type} CashAddr and legacy addresses identify the same script`, () => {
+ const withoutPrefix = cash.slice("bitcoincash:".length);
+ expect(isValidAddress(cash)).toBe(true);
+ expect(isValidAddress(withoutPrefix)).toBe(true);
+ expect(isValidAddress(legacy)).toBe(true);
+ expect(addPrefixToAddress(withoutPrefix)).toBe(cash);
+ expect(getAddressType(cash)).toBe(type);
+ expect(addressToLockingBytecodeHex(cash)).toBe(bytecode);
+ expect(addressToLockingBytecodeHex(withoutPrefix)).toBe(bytecode);
+ expect(addressToLockingBytecodeHex(legacy)).toBe(bytecode);
+
+ const tokenAddress = lockingBytecodeToCashAddress({
+ bytecode: hexToBin(bytecode),
+ tokenSupport: true,
+ });
+ expect(typeof tokenAddress).toBe("object");
+ if (typeof tokenAddress !== "string") {
+ expect(isValidAddress(tokenAddress.address)).toBe(true);
+ expect(getAddressType(tokenAddress.address)).toBe(type);
+ expect(addressToLockingBytecodeHex(tokenAddress.address)).toBe(
+ bytecode,
+ );
+ }
+ });
+ }
+
+ test.each([
+ "",
+ "not-an-address",
+ "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6x",
+ ])("rejects invalid addresses: %s", (address) =>
+ expect(isValidAddress(address)).toBe(false),
+ );
+});
+
+describe("decimal conversion with BigNumber 11", () => {
+ test("retains satoshi precision beyond JavaScript's safe integer range", () => {
+ expect(satToBch("9007199254740993", 8)).toBe("90071992.54740993");
+ expect(satToBch("1", 8)).toBe("1e-8");
+ expect(satToBch("123456789")).toBe("1.234568");
+ });
+
+ test("scales large token decimal counts without numeric overflow", () => {
+ expect(calculateDecimal("1", 309).toString()).toBe("1e-309");
+ expect(calculateDecimal("not-a-number", 8).toString()).toBe("0");
+ });
+});
+
+describe("BCMR publication decoding", () => {
+ const contentHash = "0123456789abcdef".repeat(4);
+ const domain = binToHex(utf8ToBin("example.com"));
+
+ test("decodes a direct-push HTTPS publication without reversing its hash", () => {
+ expect(
+ opreturnToAuthChainElement(`6a0442434d5220${contentHash}0b${domain}`),
+ ).toEqual({
+ contentHash,
+ url: "https://example.com/.well-known/bitcoin-cash-metadata-registry.json",
+ });
+ });
+
+ test("decodes OP_PUSHDATA1 and OP_PUSHDATA2 pushes", () => {
+ expect(
+ opreturnToAuthChainElement(
+ `6a4c0442434d524d2000${contentHash}4c0b${domain}`,
+ ),
+ ).toEqual({
+ contentHash,
+ url: "https://example.com/.well-known/bitcoin-cash-metadata-registry.json",
+ });
+ });
+
+ test("preserves CID publication outputs", () => {
+ const cid = "QmYwAPJzv5CZsnAzt8auVTLQzUKfyzQGzuJDn8GmRbKJfQ";
+ const encodedCid = binToHex(utf8ToBin(cid));
+ expect(opreturnToAuthChainElement(`6a0442434d522e${encodedCid}`)).toEqual({
+ contentHash: encodedCid,
+ url: `https://dweb.link/ipfs/${cid}`,
+ });
+ });
+
+ test("normalizes explicit HTTP and IPFS URLs", () => {
+ expect(normalizeMetadataUrl("https://example.com/registry.json")).toBe(
+ "https://example.com/registry.json",
+ );
+ expect(normalizeMetadataUrl("http://example.com/registry.json")).toBe(
+ "http://example.com/registry.json",
+ );
+ expect(normalizeMetadataUrl("ipfs://bafy/registry.json")).toBe(
+ "https://gateway.example/ipfs/bafy/registry.json",
+ );
+ });
+
+ test.each([
+ "",
+ "zz",
+ "6",
+ "6a",
+ "6a0442434d52",
+ "6a0442434d5220",
+ "6a4c",
+ "6a4d20",
+ "6a0442434d5220abcd",
+ `6a0442434d5220${contentHash}0b6578`,
+ "6a0442434d5200",
+ `6a0442434d5220${contentHash}00`,
+ `760442434d5220${contentHash}0b${domain}`,
+ "6a0442434d5251",
+ `6a044e4f504520${contentHash}0b${domain}`,
+ ])("rejects incomplete or malformed publication %s", (hex) => {
+ expect(opreturnToAuthChainElement(hex)).toBe("Invalid BCMR OP_RETURN");
+ });
+
+ test("does not silently accept partial or non-push scripts", () => {
+ expect(parseBinary(hexToBin("6a030102"))).toEqual([]);
+ expect(parseBinary(hexToBin("6a4c02aa"))).toEqual([]);
+ expect(parseBinary(hexToBin("6a4d0200aa"))).toEqual([]);
+ expect(parseBinary(hexToBin("6a51"))).toEqual([]);
+ expect(parseBinary(hexToBin("6a000161"))).toEqual([
+ new Uint8Array(),
+ utf8ToBin("a"),
+ ]);
+ });
+});
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}"`);
+ }
+});
diff --git a/tests/state.test.ts b/tests/state.test.ts
new file mode 100644
index 0000000..375a1fd
--- /dev/null
+++ b/tests/state.test.ts
@@ -0,0 +1,59 @@
+import { beforeEach, describe, expect, test } from "bun:test";
+import {
+ binToHex,
+ cashAddressToLockingBytecode,
+ decodeCashAddress,
+} from "@bitauth/libauth";
+import { createPinia, setActivePinia } from "pinia";
+import { computed, ref } from "vue";
+
+Object.assign(globalThis, {
+ ref,
+ computed,
+ gql: (source: string) => source,
+ useSubscription: () => ({ result: ref() }),
+});
+const { useStateStore } = await import("../src/store/state");
+
+beforeEach(() => setActivePinia(createPinia()));
+
+describe("Libauth 3 store address conversion", () => {
+ const bytecodes = [
+ `76a914${"12".repeat(20)}88ac`,
+ `a914${"12".repeat(20)}87`,
+ `aa20${"12".repeat(32)}87`,
+ ];
+
+ for (const bytecode of bytecodes) {
+ for (const network of ["mainnet", "chipnet"] as const) {
+ for (const tokenSupport of [false, true]) {
+ test(`${bytecode.slice(0, 6)} ${network} tokens=${tokenSupport}`, () => {
+ const store = useStateStore();
+ store.network = network;
+ const address = store.lockingBytecodeHexToCashAddress(
+ bytecode,
+ tokenSupport,
+ );
+ expect(address).toBeDefined();
+ if (!address) throw new Error("Expected a valid address");
+ const decoded = cashAddressToLockingBytecode(address);
+ expect(typeof decoded).toBe("object");
+ if (typeof decoded === "string") throw new Error(decoded);
+ expect(binToHex(decoded.bytecode)).toBe(bytecode);
+ expect(decoded.prefix).toBe(
+ network === "mainnet" ? "bitcoincash" : "bchtest",
+ );
+ const cashAddress = decodeCashAddress(address);
+ if (typeof cashAddress === "string") throw new Error(cashAddress);
+ expect(cashAddress.type.endsWith("WithTokens")).toBe(tokenSupport);
+ });
+ }
+ }
+ }
+
+ test("unsupported locking bytecode does not expose an error as an address", () => {
+ expect(
+ useStateStore().lockingBytecodeHexToCashAddress("6a"),
+ ).toBeUndefined();
+ });
+});
diff --git a/tests/usd-price.test.ts b/tests/usd-price.test.ts
new file mode 100644
index 0000000..7182ca9
--- /dev/null
+++ b/tests/usd-price.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, test } from "bun:test";
+import { computed, ref, watch } from "vue";
+
+const response = ref();
+Object.assign(globalThis, {
+ computed,
+ ref,
+ watch,
+ useFetch: () => ({ data: response }),
+});
+const { useUsdPrice } = await import("../src/hooks/usdPrice");
+
+describe("USD price formatting with BigNumber 11", () => {
+ test("pending and failed prices keep BCH amounts usable", () => {
+ for (const unavailable of [
+ undefined,
+ null,
+ {},
+ { error: "rate limited" },
+ ]) {
+ response.value = unavailable;
+ const price = useUsdPrice();
+ expect(price.calculatePrice("100000000")).toBe("0");
+ expect(price.formatPrice("100000000")).toBe("1 BCH");
+ }
+ });
+
+ test("validated prices include the USD amount", () => {
+ response.value = { "bitcoin-cash": { usd: 500 } };
+ const price = useUsdPrice();
+ expect(price.formatPrice("100000000")).toBe("1 BCH • $500");
+ expect(price.formatPrice("0")).toBeUndefined();
+ });
+});
diff --git a/tsconfig.json b/tsconfig.json
index 3775aa5..e7fff15 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,9 +1,5 @@
{
// https://nuxt.com/docs/guide/concepts/typescript
"extends": "./.nuxt/tsconfig.json",
- "files": [
- "src/types/gql.d.ts",
- "src/types/electrum.d.ts",
- "src/types/reset.d.ts"
- ]
+ "files": ["src/types/gql.d.ts", "src/types/reset.d.ts"]
}
diff --git a/wrangler.jsonc b/wrangler.jsonc
index c5dc2c0..60b8504 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -3,7 +3,7 @@
"compatibility_date": "2024-12-01",
"account_id": "1d3930570e889d7ef9339cba4ff202b5",
"routes": [{ "pattern": "explorer.salemkode.com", "custom_domain": true }],
- "build": { "command": "npm run generate" },
+ "build": { "command": "bun run build" },
"assets": {
"directory": "./.output/public",
"not_found_handling": "single-page-application"