From 127f30903577bce322540df13024330423f5cada Mon Sep 17 00:00:00 2001 From: Mati OS Date: Mon, 14 Sep 2026 19:09:07 -0300 Subject: [PATCH 1/7] feat(types): add zcash network type and domain types --- src/types/index.ts | 258 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 256 insertions(+), 2 deletions(-) diff --git a/src/types/index.ts b/src/types/index.ts index cb11010f..79c27525 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -4,9 +4,9 @@ import type React from "react"; // ==================== NETWORK TYPES ==================== /** - * Network type - EVM, Bitcoin, or Solana + * Network type - EVM, Bitcoin, Zcash, or Solana */ -export type NetworkType = "evm" | "bitcoin" | "solana"; +export type NetworkType = "evm" | "bitcoin" | "zcash" | "solana"; /** * All EVM chain IDs supported by the app. @@ -279,6 +279,260 @@ export interface BitcoinAddress { txids?: string[]; } +// ==================== ZCASH TYPES ==================== + +/** + * Zcash value pools, in the order the protocol introduced them + */ +export type ZcashValuePoolId = + | "transparent" + | "sprout" + | "sapling" + | "orchard" + | "lockbox" + | "ironwood"; + +/** + * Shielded pools a transaction can move value through + */ +export type ZcashShieldedPool = "sprout" | "sapling" | "orchard" | "ironwood"; + +/** + * Pools a transaction touches: transparent inputs/outputs plus its shielded bundles + */ +export type ZcashTxPool = "transparent" | ZcashShieldedPool; + +/** + * Balance of a single value pool, in zatoshis (1 ZEC = 100,000,000 zat) + */ +export interface ZcashValuePool { + id: ZcashValuePoolId; + valueZat: number; +} + +/** + * Zcash network statistics from getblockchaininfo + getmempoolinfo + */ +export interface ZcashNetworkStats { + blockHeight: number; + bestBlockHash: string; + difficulty: number; + chain: string; + estimatedHeight?: number; + verificationProgress?: number; + mempoolSize: number; + mempoolBytes: number; + chainSupplyZat?: number; + valuePools: ZcashValuePool[]; +} + +/** + * Note commitment tree sizes at a block + */ +export interface ZcashTreeSizes { + sapling?: number; + orchard?: number; + ironwood?: number; +} + +/** + * Transparent output of a coinbase transaction (miner reward or funding stream) + */ +export interface ZcashCoinbaseOutput { + address?: string; + valueZat: number; +} + +/** + * Zcash block data + */ +export interface ZcashBlock { + hash: string; + height: number; + time: number; + nTx: number; + size: number; + version: number; + merkleRoot: string; + previousBlockHash?: string; + nextBlockHash?: string; + bits: string; + nonce: string; // 32-byte hex string, unlike Bitcoin's numeric nonce + difficulty: number; + confirmations?: number; + solution?: string; // Equihash solution (hex) + blockCommitments?: string; + finalSaplingRoot?: string; + finalOrchardRoot?: string; // Only on post-NU5 blocks + trees?: ZcashTreeSizes; + chainSupplyZat?: number; + valuePools?: ZcashValuePool[]; + txids?: string[]; + // Derived from full transaction data (getblock verbosity 2) + coinbaseOutputs?: ZcashCoinbaseOutput[]; + shieldedTxCounts?: Partial>; + transparentOutputZat?: number; +} + +/** + * Transparent transaction input. Zebra doesn't return the output being spent, so value and + * address stay undefined until the previous transaction is looked up. + */ +export interface ZcashTransparentInput { + txid?: string; + vout?: number; + coinbase?: string; + sequence: number; + valueZat?: number; + address?: string; +} + +/** + * Transparent transaction output + */ +export interface ZcashTransparentOutput { + n: number; + valueZat: number; + address?: string; + scriptType: string; +} + +/** + * Sapling spends and outputs; valueBalanceZat is the net value leaving the pool + */ +export interface ZcashSaplingBundle { + spends: number; + outputs: number; + valueBalanceZat: number; +} + +/** + * Orchard or Ironwood actions (each action combines a spend and an output) + */ +export interface ZcashActionBundle { + actions: number; + valueBalanceZat: number; +} + +/** + * Sprout-era JoinSplits + */ +export interface ZcashSproutBundle { + joinSplits: number; + vpubOldZat: number; // Value entering the Sprout pool + vpubNewZat: number; // Value leaving the Sprout pool +} + +/** + * Shielded bundles of a transaction; a bundle is present only when it carries data + */ +export interface ZcashShieldedBundles { + sprout?: ZcashSproutBundle; + sapling?: ZcashSaplingBundle; + orchard?: ZcashActionBundle; + ironwood?: ZcashActionBundle; +} + +/** + * How a transaction moves value between the transparent and shielded pools + */ +export type ZcashTxKind = + | "coinbase" + | "transparent" + | "shielding" + | "deshielding" + | "shielded" + | "mixed"; + +/** + * Zcash transaction data + */ +export interface ZcashTransaction { + txid: string; + version: number; + versionGroupId?: string; + size: number; + locktime: number; + expiryHeight?: number; + vin: ZcashTransparentInput[]; + vout: ZcashTransparentOutput[]; + shielded: ZcashShieldedBundles; + blockhash?: string; + blockheight?: number; + confirmations?: number; + blocktime?: number; + time?: number; +} + +/** + * A block together with its decoded transactions (from a single getblock call) + */ +export interface ZcashBlockWithTransactions { + block: ZcashBlock; + transactions: ZcashTransaction[]; +} + +/** + * Pending transaction from getrawmempool (verbose) + */ +export interface ZcashMempoolEntry { + txid: string; + size: number; + feeZat: number; + time: number; + height: number; +} + +/** + * Zcash address encodings + */ +export type ZcashAddressType = + | "p2pkh" + | "p2sh" + | "tex" + | "sprout" + | "sapling" + | "unified" + | "unknown"; + +/** + * Whether the RPC endpoint served a section: "unsupported" when it doesn't expose the method + * (hosted gateways block the address index), "error" for any other failure + */ +export type ZcashRpcAvailability = "ok" | "unsupported" | "error"; + +export interface ZcashRpcSection { + availability: ZcashRpcAvailability; + data?: T; +} + +export interface ZcashAddressUtxo { + txid: string; + outputIndex: number; + valueZat: number; + height: number; +} + +export interface ZcashUnifiedReceivers { + orchard?: string; + sapling?: string; + p2pkh?: string; + p2sh?: string; +} + +/** + * Zcash address data; each section is only present when it applies to the address type + */ +export interface ZcashAddress { + address: string; + type: ZcashAddressType; + transparentAddress?: string; // Address the index queries ran against + receivers?: ZcashRpcSection; + balance?: ZcashRpcSection<{ balanceZat: number; receivedZat?: number }>; + utxos?: ZcashRpcSection; + txids?: ZcashRpcSection; +} + // ==================== SOLANA TYPES ==================== /** From d9c7c04eb7eb8fb89acb36981d64684d79afb2df Mon Sep 17 00:00:00 2001 From: Mati OS Date: Mon, 14 Sep 2026 19:09:08 -0300 Subject: [PATCH 2/7] feat(adapter): add ZcashAdapter with rate-limit aware RPC calls Zebra calls throw a typed ZcashRpcError instead of returning empty data, retry after a 429 with backoff, and report unsupported methods so address pages can degrade on hosted gateways. --- src/config/zcashConstants.ts | 11 + .../ZcashAdapter/ZcashAdapter.test.ts | 373 ++++++++++++++++++ .../adapters/ZcashAdapter/ZcashAdapter.ts | 305 ++++++++++++++ .../adapters/ZcashAdapter/fixtures.ts | 321 +++++++++++++++ src/services/adapters/ZcashAdapter/index.ts | 1 + src/services/adapters/ZcashAdapter/utils.ts | 336 ++++++++++++++++ src/utils/zcashFormatters.ts | 30 ++ src/utils/zcashUtils.test.ts | 174 ++++++++ src/utils/zcashUtils.ts | 118 ++++++ 9 files changed, 1669 insertions(+) create mode 100644 src/config/zcashConstants.ts create mode 100644 src/services/adapters/ZcashAdapter/ZcashAdapter.test.ts create mode 100644 src/services/adapters/ZcashAdapter/ZcashAdapter.ts create mode 100644 src/services/adapters/ZcashAdapter/fixtures.ts create mode 100644 src/services/adapters/ZcashAdapter/index.ts create mode 100644 src/services/adapters/ZcashAdapter/utils.ts create mode 100644 src/utils/zcashFormatters.ts create mode 100644 src/utils/zcashUtils.test.ts create mode 100644 src/utils/zcashUtils.ts diff --git a/src/config/zcashConstants.ts b/src/config/zcashConstants.ts new file mode 100644 index 00000000..91993415 --- /dev/null +++ b/src/config/zcashConstants.ts @@ -0,0 +1,11 @@ +/** + * Zcash-specific constants + */ + +export const ZATOSHIS_PER_ZEC = 100_000_000; + +// Transparent input values cost one getrawtransaction per previous transaction +export const MAX_INPUT_LOOKUPS = 10; + +// Backoff before retrying a rate-limited call (hosted gateways allow ~5 requests/min per IP) +export const RATE_LIMIT_RETRY_DELAYS_MS = [15_000, 30_000]; diff --git a/src/services/adapters/ZcashAdapter/ZcashAdapter.test.ts b/src/services/adapters/ZcashAdapter/ZcashAdapter.test.ts new file mode 100644 index 00000000..84b9621d --- /dev/null +++ b/src/services/adapters/ZcashAdapter/ZcashAdapter.test.ts @@ -0,0 +1,373 @@ +import type { ZcashClient } from "@openscan/network-connectors"; +import { describe, expect, it, vi } from "vitest"; +import type { ZcashTransaction } from "../../../types"; +import { computeFeeZat } from "../../../utils/zcashUtils"; +import { + BLOCK_3483400, + COINBASE_TX, + IRONWOOD_ONLY_TX, + SAPLING_IRONWOOD_TX, + SHIELDING_TX, +} from "./fixtures"; +import { ZcashAdapter, ZcashRpcError } from "./ZcashAdapter"; + +const NETWORK_ID = "bip122:00040fe8ec8471911baa1db1266ea15d"; +const T_ADDRESS = "t1KAuVfS2r2hc7RwSh6GTuyfqCGMFEpwkZ2"; +const METHOD_NOT_FOUND = "RPC error: Method not found: getaddressbalance"; + +const ok = (data: T) => ({ success: true, data }); +const fail = (...errors: string[]) => ({ + success: false, + errors: errors.map((error) => ({ + url: "https://rpc.test", + status: "error", + responseTime: 1, + error, + })), +}); + +function createClient() { + return { + getBlockCount: vi.fn(), + getBlockchainInfo: vi.fn(), + getMempoolInfo: vi.fn(), + getBlock: vi.fn(), + getRawTransaction: vi.fn(), + getRawMempool: vi.fn(), + getAddressBalance: vi.fn(), + getAddressUtxos: vi.fn(), + getAddressTxIds: vi.fn(), + zListUnifiedReceivers: vi.fn(), + }; +} + +function setup() { + const client = createClient(); + const sleep = vi.fn().mockResolvedValue(undefined); + const adapter = new ZcashAdapter(NETWORK_ID, client as unknown as ZcashClient, { sleep }); + return { adapter, client, sleep }; +} + +function findTx(transactions: ZcashTransaction[], txid: string | undefined): ZcashTransaction { + const match = transactions.find((transaction) => transaction.txid === txid); + if (!match) throw new Error(`Transaction ${txid} not found`); + return match; +} + +describe("ZcashAdapter blocks", () => { + it("fetches a block by height as a decimal string with full transactions", async () => { + const { adapter, client } = setup(); + client.getBlock.mockResolvedValue(ok(BLOCK_3483400)); + + const { data } = await adapter.getBlock(3483400); + + expect(client.getBlock).toHaveBeenCalledTimes(1); + expect(client.getBlock).toHaveBeenCalledWith("3483400", 2); + expect(data.block).toMatchObject({ + height: 3483400, + nTx: 18, + nonce: BLOCK_3483400.nonce, + trees: { sapling: 73958787, orchard: 50458646, ironwood: 318976 }, + shieldedTxCounts: { sapling: 2, ironwood: 2 }, + }); + expect(data.block.coinbaseOutputs).toEqual([ + { address: "t1SqwRAAdSig6dE4EBPLonAait219VmkUjP", valueZat: 125_490_751 }, + { address: "t3cFfPt1Bcvgez9ZbMBFWeZsskxTkPzGCow", valueZat: 12_500_000 }, + ]); + }); + + it("derives shielded fees from value balances", async () => { + const { adapter, client } = setup(); + client.getBlock.mockResolvedValue(ok(BLOCK_3483400)); + + const { transactions } = (await adapter.getBlock(3483400)).data; + + expect(computeFeeZat(findTx(transactions, IRONWOOD_ONLY_TX.txid))).toBe(10_000); + expect(computeFeeZat(findTx(transactions, SAPLING_IRONWOOD_TX.txid))).toBe(20_000); + expect(computeFeeZat(findTx(transactions, SHIELDING_TX.txid))).toBeNull(); + expect(computeFeeZat(findTx(transactions, COINBASE_TX.txid))).toBeNull(); + }); + + it("fetches block summaries one at a time and skips blocks that fail", async () => { + const { adapter, client } = setup(); + const summary = (height: number) => ({ ...BLOCK_3483400, height, tx: ["a".repeat(64)] }); + client.getBlock + .mockResolvedValueOnce(ok(summary(3483399))) + .mockResolvedValueOnce(fail("RPC error: Block not found")) + .mockResolvedValueOnce(ok(summary(3483400))); + + const blocks = await adapter.getBlockSummaries([3483399, 3483398, 3483400]); + + expect(client.getBlock.mock.calls).toEqual([ + ["3483399", 1], + ["3483398", 1], + ["3483400", 1], + ]); + expect(blocks.map((block) => block.height)).toEqual([3483400, 3483399]); + expect(blocks[0]?.txids).toEqual(["a".repeat(64)]); + }); +}); + +describe("ZcashAdapter transactions", () => { + it("requests verbose transactions with numeric verbosity", async () => { + const { adapter, client } = setup(); + client.getRawTransaction.mockResolvedValue(ok(SHIELDING_TX)); + + const { data } = await adapter.getTransaction(SHIELDING_TX.txid ?? ""); + + expect(client.getRawTransaction).toHaveBeenCalledWith(SHIELDING_TX.txid, 1); + expect(data.blockheight).toBe(3483400); + expect(data.vin).toHaveLength(15); + expect(data.vout).toHaveLength(0); + expect(data.shielded).toEqual({ + sapling: { spends: 0, outputs: 2, valueBalanceZat: -1_877_663_138 }, + }); + }); + + describe("resolveTransparentInputs", () => { + const firstTxid = "c".repeat(64); + const secondTxid = "d".repeat(64); + const spending: ZcashTransaction = { + txid: "e".repeat(64), + version: 4, + size: 0, + locktime: 0, + vin: [ + { txid: firstTxid, vout: 0, sequence: 0 }, + { txid: firstTxid, vout: 1, sequence: 0 }, + { txid: secondTxid, vout: 0, sequence: 0 }, + ], + vout: [{ n: 0, valueZat: 60_000, scriptType: "pubkeyhash" }], + shielded: {}, + }; + const previousTx = (txid: string, values: number[]) => ({ + txid, + vin: [], + vout: values.map((value, n) => ({ + value, + n, + scriptPubKey: { type: "pubkeyhash", addresses: [T_ADDRESS] }, + })), + }); + + it("fills input values from the transactions they spend", async () => { + const { adapter, client } = setup(); + client.getRawTransaction.mockImplementation(async (txid: string) => + ok(txid === firstTxid ? previousTx(txid, [0.0003, 0.0002]) : previousTx(txid, [0.0002])), + ); + const onProgress = vi.fn(); + + const result = await adapter.resolveTransparentInputs(spending, { onProgress }); + + expect(client.getRawTransaction).toHaveBeenCalledTimes(2); + expect(result).toMatchObject({ resolved: 2, total: 2 }); + expect(onProgress).toHaveBeenLastCalledWith(2, 2); + expect(result.transaction.vin.map((vin) => vin.valueZat)).toEqual([30_000, 20_000, 20_000]); + expect(result.transaction.vin[0]?.address).toBe(T_ADDRESS); + expect(computeFeeZat(result.transaction)).toBe(10_000); + }); + + it("stops at the lookup cap and leaves the fee unknown", async () => { + const { adapter, client } = setup(); + client.getRawTransaction.mockResolvedValue(ok(previousTx(firstTxid, [0.0003, 0.0002]))); + + const result = await adapter.resolveTransparentInputs(spending, { max: 1 }); + + expect(client.getRawTransaction).toHaveBeenCalledTimes(1); + expect(result).toMatchObject({ resolved: 1, total: 2 }); + expect(computeFeeZat(result.transaction)).toBeNull(); + }); + }); +}); + +describe("ZcashAdapter RPC failures", () => { + it("retries rate-limited calls after a backoff", async () => { + const { adapter, client, sleep } = setup(); + client.getBlockCount + .mockResolvedValueOnce(fail("HTTP error! status: 429", "HTTP error! status: 429")) + .mockResolvedValueOnce(ok(3483464)); + + await expect(adapter.getLatestBlockNumber()).resolves.toBe(3483464); + expect(sleep).toHaveBeenCalledWith(15_000); + }); + + it("gives up after the last backoff", async () => { + const { adapter, client, sleep } = setup(); + client.getBlockCount.mockResolvedValue(fail("HTTP error! status: 429")); + + await expect(adapter.getLatestBlockNumber()).rejects.toMatchObject({ + name: "ZcashRpcError", + kind: "rateLimited", + }); + expect(sleep.mock.calls).toEqual([[15_000], [30_000]]); + expect(client.getBlockCount).toHaveBeenCalledTimes(3); + }); + + it("throws instead of returning empty data when every endpoint fails", async () => { + const { adapter, client, sleep } = setup(); + client.getBlock.mockResolvedValue(fail("RPC error: Block not found")); + + const error = await adapter.getBlock("0").catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ZcashRpcError); + expect(error).toMatchObject({ kind: "failed", messages: ["RPC error: Block not found"] }); + expect(sleep).not.toHaveBeenCalled(); + }); +}); + +describe("ZcashAdapter addresses", () => { + it("marks address index sections unsupported when the gateway blocks them", async () => { + const { adapter, client } = setup(); + client.getAddressBalance.mockResolvedValue(fail(METHOD_NOT_FOUND, METHOD_NOT_FOUND)); + client.getAddressUtxos.mockResolvedValue(fail(METHOD_NOT_FOUND, METHOD_NOT_FOUND)); + client.getAddressTxIds.mockResolvedValue(fail(METHOD_NOT_FOUND, METHOD_NOT_FOUND)); + + const result = await adapter.getAddress(T_ADDRESS); + + expect(client.getAddressBalance).toHaveBeenCalledWith({ addresses: [T_ADDRESS] }); + expect(result).toEqual({ + address: T_ADDRESS, + type: "p2pkh", + transparentAddress: T_ADDRESS, + balance: { availability: "unsupported" }, + utxos: { availability: "unsupported" }, + txids: { availability: "unsupported" }, + }); + }); + + it("reports other address index failures as errors", async () => { + const { adapter, client } = setup(); + client.getAddressBalance.mockResolvedValue(fail("RPC error: invalid address")); + client.getAddressUtxos.mockResolvedValue(ok([])); + client.getAddressTxIds.mockResolvedValue(ok([])); + + const result = await adapter.getAddress(T_ADDRESS); + + expect(result.balance).toEqual({ availability: "error" }); + expect(result.utxos).toEqual({ availability: "ok", data: [] }); + }); + + it("maps address index data when the node exposes it", async () => { + const { adapter, client } = setup(); + const txid = "f".repeat(64); + client.getAddressBalance.mockResolvedValue(ok({ balance: 9_514_810, received: 19_029_620 })); + client.getAddressUtxos.mockResolvedValue( + ok([ + { + address: T_ADDRESS, + txid, + outputIndex: 0, + script: "76a9", + satoshis: 9_514_810, + height: 3483400, + }, + ]), + ); + client.getAddressTxIds.mockResolvedValue(ok([txid])); + + const result = await adapter.getAddress(T_ADDRESS); + + expect(result.balance).toEqual({ + availability: "ok", + data: { balanceZat: 9_514_810, receivedZat: 19_029_620 }, + }); + expect(result.utxos).toEqual({ + availability: "ok", + data: [{ txid, outputIndex: 0, valueZat: 9_514_810, height: 3483400 }], + }); + expect(result.txids).toEqual({ availability: "ok", data: [txid] }); + }); + + it("queries the transparent receiver of a unified address", async () => { + const { adapter, client } = setup(); + const unified = `u1${"q".repeat(100)}`; + client.zListUnifiedReceivers.mockResolvedValue( + ok({ orchard: `u1${"p".repeat(60)}`, p2pkh: T_ADDRESS }), + ); + client.getAddressBalance.mockResolvedValue(ok({ balance: 1 })); + client.getAddressUtxos.mockResolvedValue(ok([])); + client.getAddressTxIds.mockResolvedValue(ok([])); + + const result = await adapter.getAddress(unified); + + expect(client.zListUnifiedReceivers).toHaveBeenCalledWith(unified); + expect(result.transparentAddress).toBe(T_ADDRESS); + expect(client.getAddressBalance).toHaveBeenCalledWith({ addresses: [T_ADDRESS] }); + }); + + it("makes no RPC calls for Sapling addresses", async () => { + const { adapter, client } = setup(); + const sapling = `zs1${"q".repeat(75)}`; + + const result = await adapter.getAddress(sapling); + + expect(result).toEqual({ address: sapling, type: "sapling" }); + for (const method of Object.values(client)) { + expect(method).not.toHaveBeenCalled(); + } + }); +}); + +describe("ZcashAdapter network data", () => { + it("maps value pools and chain supply to zatoshis", async () => { + const { adapter, client } = setup(); + client.getBlockchainInfo.mockResolvedValue( + ok({ + chain: "main", + blocks: 3483461, + bestblockhash: "0".repeat(64), + difficulty: 241391812.2, + chainSupply: { chainValue: 16932540.7905448, chainValueZat: 1_693_254_079_054_480 }, + valuePools: [ + { + id: "transparent", + chainValue: 11974617.26829416, + chainValueZat: 1_197_461_726_829_416, + }, + { id: "ironwood", chainValue: 3943491.88711218, chainValueZat: 394_349_188_711_218 }, + { id: "future", chainValue: 1, chainValueZat: 100_000_000 }, + ], + }), + ); + client.getMempoolInfo.mockResolvedValue(ok({ size: 9, bytes: 4_512, usage: 9_000 })); + + const { data } = await adapter.getNetworkStats(); + + expect(data).toMatchObject({ + blockHeight: 3483461, + mempoolSize: 9, + mempoolBytes: 4_512, + chainSupplyZat: 1_693_254_079_054_480, + }); + expect(data.valuePools).toEqual([ + { id: "transparent", valueZat: 1_197_461_726_829_416 }, + { id: "ironwood", valueZat: 394_349_188_711_218 }, + ]); + }); + + it("sorts mempool entries by fee rate", async () => { + const { adapter, client } = setup(); + const entry = (size: number, fee: number) => ({ + size, + fee, + modifiedfee: fee, + time: 1789416139, + height: 3483464, + descendantcount: 1, + descendantsize: size, + descendantfees: 0, + depends: [], + }); + client.getRawMempool.mockResolvedValue( + ok({ ["a".repeat(64)]: entry(1000, 0.0001), ["b".repeat(64)]: entry(245, 0.000113) }), + ); + + const { data } = await adapter.getMempoolEntries(); + + expect(client.getRawMempool).toHaveBeenCalledWith(true); + expect(data).toEqual([ + { txid: "b".repeat(64), size: 245, feeZat: 11_300, time: 1789416139, height: 3483464 }, + { txid: "a".repeat(64), size: 1000, feeZat: 10_000, time: 1789416139, height: 3483464 }, + ]); + }); +}); diff --git a/src/services/adapters/ZcashAdapter/ZcashAdapter.ts b/src/services/adapters/ZcashAdapter/ZcashAdapter.ts new file mode 100644 index 00000000..3c069b4d --- /dev/null +++ b/src/services/adapters/ZcashAdapter/ZcashAdapter.ts @@ -0,0 +1,305 @@ +import type { ZcashClient } from "@openscan/network-connectors"; +import { MAX_INPUT_LOOKUPS, RATE_LIMIT_RETRY_DELAYS_MS } from "../../../config/zcashConstants"; +import type { + DataWithMetadata, + ZcashAddress, + ZcashBlock, + ZcashBlockWithTransactions, + ZcashMempoolEntry, + ZcashNetworkStats, + ZcashRpcSection, + ZcashTransaction, +} from "../../../types"; +import { logger } from "../../../utils/logger"; +import { + classifyRpcErrors, + detectZcashAddressType, + type ZcashRpcErrorKind, +} from "../../../utils/zcashUtils"; +import { + applyResolvedInputs, + transformBlock, + transformBlockSummary, + transformMempoolEntries, + transformNetworkStats, + transformTransaction, + type ZcashRawBlock, + type ZcashRawBlockchainInfo, + type ZcashRawBlockSummary, + type ZcashRawMempoolEntry, + type ZcashRawTransaction, +} from "./utils"; + +/** The part of the connector's StrategyResult the adapter reads */ +interface RpcResult { + success: boolean; + data?: T; + errors?: Array<{ error?: string }>; + metadata?: unknown; +} + +/** + * Thrown when a Zcash RPC call fails on every configured endpoint + */ +export class ZcashRpcError extends Error { + readonly method: string; + readonly kind: ZcashRpcErrorKind; + readonly messages: string[]; + + constructor(method: string, kind: ZcashRpcErrorKind, messages: string[]) { + super(`${method} failed: ${messages.length > 0 ? messages.join("; ") : "no response"}`); + this.name = "ZcashRpcError"; + this.method = method; + this.kind = kind; + this.messages = messages; + } +} + +export interface ZcashAdapterOptions { + /** Wait between rate-limit retries (injectable for tests) */ + sleep?: (ms: number) => Promise; +} + +const defaultSleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +function mapSection(section: ZcashRpcSection, map: (data: T) => U): ZcashRpcSection { + return section.data === undefined + ? { availability: section.availability } + : { availability: section.availability, data: map(section.data) }; +} + +/** + * Zcash blockchain adapter (Zebra RPC) + * + * Hosted gateways allow only a few requests per minute, so methods spend as few calls as + * possible: heights go straight to getblock as decimal strings (no getblockhash round trip), + * and block data comes from a single getblock call. + */ +export class ZcashAdapter { + readonly networkId: string; + private client: ZcashClient; + private sleep: (ms: number) => Promise; + + constructor(networkId: string, client: ZcashClient, options: ZcashAdapterOptions = {}) { + this.networkId = networkId; + this.client = client; + this.sleep = options.sleep ?? defaultSleep; + } + + /** + * Check if this is a Zcash network + */ + isZcash(): boolean { + return true; + } + + /** + * Get the network ID (CAIP-2 format) + */ + getNetworkId(): string { + return this.networkId; + } + + /** + * Run an RPC call, retrying rate-limited failures with backoff. + * Throws ZcashRpcError when every endpoint fails, rather than returning empty data. + */ + private async call( + method: string, + request: () => Promise>, + ): Promise> { + for (let attempt = 0; ; attempt++) { + const result = await request(); + if (result.success) { + return { + data: result.data as T, + metadata: result.metadata as DataWithMetadata["metadata"], + }; + } + + const messages = (result.errors ?? []).flatMap((response) => + response.error ? [response.error] : [], + ); + const kind = classifyRpcErrors(messages); + const delay = RATE_LIMIT_RETRY_DELAYS_MS[attempt]; + if (kind !== "rateLimited" || delay === undefined) { + throw new ZcashRpcError(method, kind, messages); + } + + logger.warn(`Zcash ${method} was rate limited, retrying in ${delay / 1000}s`); + await this.sleep(delay); + } + } + + /** + * Run an optional RPC call for one section of a page. Methods the endpoint doesn't expose + * are reported as "unsupported" so the page can degrade instead of failing. + */ + private async section( + method: string, + request: () => Promise>, + ): Promise> { + try { + const { data } = await this.call(method, request); + return { availability: "ok", data }; + } catch (error) { + if (error instanceof ZcashRpcError && error.kind === "unsupported") { + return { availability: "unsupported" }; + } + logger.warn(`Zcash ${method} failed:`, error); + return { availability: "error" }; + } + } + + /** + * Get the latest block height (1 call) + */ + async getLatestBlockNumber(): Promise { + const { data } = await this.call("getblockcount", () => this.client.getBlockCount()); + return data; + } + + /** + * Get chain, value pool and mempool statistics (2 calls) + */ + async getNetworkStats(): Promise> { + const [info, mempool] = await Promise.all([ + this.call("getblockchaininfo", () => this.client.getBlockchainInfo()), + this.call("getmempoolinfo", () => this.client.getMempoolInfo()), + ]); + + return { data: transformNetworkStats(info.data, mempool.data), metadata: info.metadata }; + } + + /** + * Get a block and its transactions by hash or height (1 call) + */ + async getBlock( + hashOrHeight: string | number, + ): Promise> { + const result = await this.call("getblock", () => + this.client.getBlock(String(hashOrHeight), 2), + ); + return { data: transformBlock(result.data), metadata: result.metadata }; + } + + /** + * Get lightweight block summaries (1 call per block). Requests run one at a time so they + * don't burst past hosted rate limits; blocks that still fail are skipped. + */ + async getBlockSummaries(heights: number[]): Promise { + const blocks: ZcashBlock[] = []; + + for (const height of heights) { + try { + const { data } = await this.call("getblock", () => + this.client.getBlock(String(height), 1), + ); + blocks.push(transformBlockSummary(data)); + } catch (error) { + logger.warn(`Failed to fetch Zcash block ${height}:`, error); + } + } + + return blocks.sort((a, b) => b.height - a.height); + } + + /** + * Get all transactions of a block (1 call) + */ + async getBlockTransactions(height: number): Promise { + const { data } = await this.getBlock(height); + return data.transactions; + } + + /** + * Get a confirmed or mempool transaction (1 call) + */ + async getTransaction(txid: string): Promise> { + const result = await this.call("getrawtransaction", () => + this.client.getRawTransaction(txid, 1), + ); + return { data: transformTransaction(result.data), metadata: result.metadata }; + } + + /** + * Fill in transparent input values and addresses by fetching the transactions they spend. + * Zebra omits them from verbose transactions, so this costs one call per previous + * transaction (capped) and is meant to run on demand. + */ + async resolveTransparentInputs( + tx: ZcashTransaction, + options: { max?: number; onProgress?: (resolved: number, total: number) => void } = {}, + ): Promise<{ transaction: ZcashTransaction; resolved: number; total: number }> { + const { max = MAX_INPUT_LOOKUPS, onProgress } = options; + const previousTxids = [...new Set(tx.vin.flatMap((input) => (input.txid ? [input.txid] : [])))]; + const previous = new Map(); + + for (const previousTxid of previousTxids.slice(0, max)) { + const { data } = await this.getTransaction(previousTxid); + previous.set(previousTxid, data); + onProgress?.(previous.size, previousTxids.length); + } + + return { + transaction: applyResolvedInputs(tx, previous), + resolved: previous.size, + total: previousTxids.length, + }; + } + + /** + * Get pending transactions, highest fee rate first (1 call) + */ + async getMempoolEntries(): Promise> { + const result = await this.call>("getrawmempool", () => + this.client.getRawMempool(true), + ); + return { data: transformMempoolEntries(result.data), metadata: result.metadata }; + } + + /** + * Get address data. Balance, UTXOs and history come from Zebra's address index, which hosted + * gateways block, so each section reports its own availability. + */ + async getAddress(address: string): Promise { + const type = detectZcashAddressType(address); + const result: ZcashAddress = { address, type }; + + if (type === "unified") { + result.receivers = await this.section("z_listunifiedreceivers", () => + this.client.zListUnifiedReceivers(address), + ); + result.transparentAddress = result.receivers.data?.p2pkh ?? result.receivers.data?.p2sh; + } else if (type === "p2pkh" || type === "p2sh") { + result.transparentAddress = address; + } + + if (!result.transparentAddress) { + return result; + } + + const request = { addresses: [result.transparentAddress] }; + const [balance, utxos, txids] = await Promise.all([ + this.section("getaddressbalance", () => this.client.getAddressBalance(request)), + this.section("getaddressutxos", () => this.client.getAddressUtxos(request)), + this.section("getaddresstxids", () => this.client.getAddressTxIds(request)), + ]); + + result.balance = mapSection(balance, (data) => ({ + balanceZat: data.balance, + receivedZat: data.received, + })); + result.utxos = mapSection(utxos, (data) => + data.map((utxo) => ({ + txid: utxo.txid, + outputIndex: utxo.outputIndex, + valueZat: utxo.satoshis, + height: utxo.height, + })), + ); + result.txids = txids; + + return result; + } +} diff --git a/src/services/adapters/ZcashAdapter/fixtures.ts b/src/services/adapters/ZcashAdapter/fixtures.ts new file mode 100644 index 00000000..97bdb523 --- /dev/null +++ b/src/services/adapters/ZcashAdapter/fixtures.ts @@ -0,0 +1,321 @@ +/** + * Trimmed Zebra responses from Zcash mainnet block 3,483,400. Scripts, proofs and ciphertexts + * are stripped; every value the explorer reads is unchanged. + */ + +import type { ZcashRawBlock, ZcashRawTransaction } from "./utils"; + +export const COINBASE_TX: ZcashRawTransaction = { + txid: "fb24341c1e2462111af99701034b4749d3e1cb6f7d5c640a3895c3b80ab18731", + version: 6, + versiongroupid: "d884b698", + locktime: 0, + expiryheight: 3483400, + size: 181, + height: 3483400, + confirmations: 66, + time: 1789411472, + blocktime: 1789411472, + blockhash: "00000000005cba2d18fb12ef13dc7245eccb5708a590ceaad47ff76fc7fc2af3", + valueBalance: 0.0, + valueBalanceZat: 0, + vin: [ + { + coinbase: + "0308273504f09fa693049040a86a466f756e647279205a6361736820506f6f6c2023507269766163794d617474657273", + sequence: 4294967295, + }, + ], + vout: [ + { + value: 1.25490751, + valueZat: 125490751, + n: 0, + scriptPubKey: { + type: "pubkeyhash", + addresses: ["t1SqwRAAdSig6dE4EBPLonAait219VmkUjP"], + }, + }, + { + value: 0.125, + valueZat: 12500000, + n: 1, + scriptPubKey: { + type: "scripthash", + addresses: ["t3cFfPt1Bcvgez9ZbMBFWeZsskxTkPzGCow"], + }, + }, + ], + vShieldedSpend: [], + vShieldedOutput: [], + vjoinsplit: [], + orchard: { + valueBalance: 0.0, + valueBalanceZat: 0, + actions: [], + }, +}; + +// Ironwood only: empty vin and vout, fee 10,000 zat +export const IRONWOOD_ONLY_TX: ZcashRawTransaction = { + txid: "36a167f602a15015593130974e0942179e7e394e0e0e6e239752533e2b5ce2e3", + version: 6, + versiongroupid: "d884b698", + locktime: 0, + expiryheight: 3483438, + size: 9166, + height: 3483400, + confirmations: 66, + time: 1789411472, + blocktime: 1789411472, + blockhash: "00000000005cba2d18fb12ef13dc7245eccb5708a590ceaad47ff76fc7fc2af3", + valueBalance: 0.0, + valueBalanceZat: 0, + vin: [], + vout: [], + vShieldedSpend: [], + vShieldedOutput: [], + vjoinsplit: [], + orchard: { + valueBalance: 0.0, + valueBalanceZat: 0, + actions: [], + }, + ironwood: { + valueBalance: 0.0001, + valueBalanceZat: 10000, + actions: [ + { + nullifier: "8b0699aa83c550f0", + cmx: "1799a87705a8e412", + }, + { + nullifier: "5b6ce4d4da7dc886", + cmx: "7d1721e30df6e182", + }, + ], + }, +}; + +// 15 transparent inputs shielded into 2 Sapling outputs +export const SHIELDING_TX: ZcashRawTransaction = { + txid: "717b54c39d4cf2d40cdaabd783117c4b2d644287a3bf824b70b254a51e2c361d", + version: 4, + versiongroupid: "892f2085", + locktime: 0, + expiryheight: 3483440, + size: 4202, + height: 3483400, + confirmations: 66, + time: 1789411472, + blocktime: 1789411472, + blockhash: "00000000005cba2d18fb12ef13dc7245eccb5708a590ceaad47ff76fc7fc2af3", + valueBalance: -18.77663138, + valueBalanceZat: -1877663138, + vin: [ + { + txid: "d49bb002c3dca980499a02f5e099f0eddf5c8e210ed400147c1d886f8627a319", + vout: 0, + sequence: 4294967295, + }, + { + txid: "f19a8e77cb9618d05fd6febefc953eb402a741b7f4fb86c8d86ff1c2e343a61e", + vout: 0, + sequence: 4294967295, + }, + { + txid: "eae9fc2d4aa264963897e3a895b746ebed27d5505653c285b7c8790a4744f022", + vout: 0, + sequence: 4294967295, + }, + { + txid: "210b4a3a6fcefd4f168389a97bbd04eef60f8847f0b57faa9e90cef512413f23", + vout: 0, + sequence: 4294967295, + }, + { + txid: "4b75819beecc6729e38bf3cfd887d1689b7645acc7290e91b90ccd963f84d723", + vout: 0, + sequence: 4294967295, + }, + { + txid: "fcb63c28b6c811190e382db55e73f9a36d14cf9cdaeb3db1c0e41baa48154e27", + vout: 0, + sequence: 4294967295, + }, + { + txid: "9f844da1ead75567e5aebe15fb8963f9666c0c4487d31d27a2a6e4d866453a28", + vout: 0, + sequence: 4294967295, + }, + { + txid: "9598a5918e3f8f657cc80e0fb26ca78de39d90c0bbbcd7c59338af82bb37b828", + vout: 0, + sequence: 4294967295, + }, + { + txid: "ac76874914fb7a06d09021e441afd0580eff14b8b2c0f6abc82c82162647be2a", + vout: 0, + sequence: 4294967295, + }, + { + txid: "56a7e8a961bbf98c7df3a396b6f20bf69c1bd7f64f8f55039335a2276c53072c", + vout: 0, + sequence: 4294967295, + }, + { + txid: "4d8f562b31330402b891c8b38ae21ee82bdaba1381b55ea066b8ebe4db0d4f31", + vout: 0, + sequence: 4294967295, + }, + { + txid: "bd64ab853a8d20a089ec97a50bd54a21863b1ce8b173f2d64d0e787a82102935", + vout: 0, + sequence: 4294967295, + }, + { + txid: "e4fc6026760e92bf881596e18464c4deb9f21efb514d22a0c219ef4a31ef5035", + vout: 0, + sequence: 4294967295, + }, + { + txid: "d1fc555cb1fe314b4a6f2ea9d6e6d9e9ff3799d4f88e38d81ba9c31278c1323d", + vout: 0, + sequence: 4294967295, + }, + { + txid: "d6e46010f1273d205080c65299543f9299ed18419019753b197dfca53527863e", + vout: 0, + sequence: 4294967295, + }, + ], + vout: [], + vShieldedSpend: [], + vShieldedOutput: [ + { + cmu: "2822d719f971ea71", + }, + { + cmu: "323de81cde3119e3", + }, + ], + vjoinsplit: [], + orchard: { + valueBalance: 0.0, + valueBalanceZat: 0, + actions: [], + }, +}; + +// Ironwood value moved into 2 Sapling outputs: empty vin and vout, fee 20,000 zat +export const SAPLING_IRONWOOD_TX: ZcashRawTransaction = { + txid: "c973d2f1273608f2bcd708172924c47b4b378ee3748b3caa2c69cd8f194aa7db", + version: 6, + versiongroupid: "d884b698", + locktime: 0, + expiryheight: 3483438, + size: 11134, + height: 3483400, + confirmations: 66, + time: 1789411472, + blocktime: 1789411472, + blockhash: "00000000005cba2d18fb12ef13dc7245eccb5708a590ceaad47ff76fc7fc2af3", + valueBalance: -0.03, + valueBalanceZat: -3000000, + vin: [], + vout: [], + vShieldedSpend: [], + vShieldedOutput: [ + { + cmu: "19b76b4088552954", + }, + { + cmu: "4a9d9e16298871d4", + }, + ], + vjoinsplit: [], + orchard: { + valueBalance: 0.0, + valueBalanceZat: 0, + actions: [], + }, + ironwood: { + valueBalance: 0.0302, + valueBalanceZat: 3020000, + actions: [ + { + nullifier: "6ee4627eb7c0ed1a", + cmx: "cd5b59fb5cc9e169", + }, + { + nullifier: "df18b27f2a5f3ca9", + cmx: "9327d58a24440dea", + }, + ], + }, +}; + +const BLOCK_HEADER: Omit = { + hash: "00000000005cba2d18fb12ef13dc7245eccb5708a590ceaad47ff76fc7fc2af3", + confirmations: 66, + height: 3483400, + version: 4, + merkleroot: "c4388ee51d0651c116ccfab9a5521b5b6ed73e97d1d74f16e0662729b3e268f4", + blockcommitments: "2fcfe1dcb6405b7e884a0719eadfc6f7b467b35471b092be94dec32c89c71e9f", + finalsaplingroot: "6a6e75909903c7478239a74aade9b263407c5b2566918a08c8a019a450ef6209", + finalorchardroot: "0c38d8b2ced64ebf2d0d16d266c096886225ffae3ccd8368929ada511414de2f", + time: 1789411472, + nonce: "a9a10440000000000000000000820000000000000000000000000000b3030002", + solution: "009b1e12cac2a2dfd38de20f0660113d9745bb51740a17fd3fcc9d91298b5523", + bits: "1c008816", + difficulty: 252485109.5066307, + previousblockhash: "0000000000590aedad2fef0aa96f90624327bb4697c17196072e996ed38af672", + nextblockhash: "00000000001e0766b207e1399ce4ced7f1750e1e2826e9dd070d79dd134e377e", + size: 84186, + nTx: 18, + trees: { + sapling: { + size: 73958787, + }, + orchard: { + size: 50458646, + }, + ironwood: { + size: 318976, + }, + }, + chainSupply: { + chainValueZat: 1693244547804480, + }, + valuePools: [ + { + id: "transparent", + chainValueZat: 1197462293176688, + }, + { + id: "sprout", + chainValueZat: 2259146261837, + }, + { + id: "sapling", + chainValueZat: 51143793106239, + }, + { + id: "orchard", + chainValueZat: 41721442478352, + }, + { + id: "lockbox", + chainValueZat: 6318768750000, + }, + { + id: "ironwood", + chainValueZat: 394339104031364, + }, + ], +}; + +export const BLOCK_3483400: ZcashRawBlock = { + ...BLOCK_HEADER, + tx: [COINBASE_TX, IRONWOOD_ONLY_TX, SHIELDING_TX, SAPLING_IRONWOOD_TX], +}; diff --git a/src/services/adapters/ZcashAdapter/index.ts b/src/services/adapters/ZcashAdapter/index.ts new file mode 100644 index 00000000..4e3f8fc2 --- /dev/null +++ b/src/services/adapters/ZcashAdapter/index.ts @@ -0,0 +1 @@ +export { ZcashAdapter, ZcashRpcError } from "./ZcashAdapter"; diff --git a/src/services/adapters/ZcashAdapter/utils.ts b/src/services/adapters/ZcashAdapter/utils.ts new file mode 100644 index 00000000..a6e2ac8e --- /dev/null +++ b/src/services/adapters/ZcashAdapter/utils.ts @@ -0,0 +1,336 @@ +import type { + ZcashActionBundle, + ZcashBlock, + ZcashBlockWithTransactions, + ZcashMempoolEntry, + ZcashNetworkStats, + ZcashShieldedBundles, + ZcashShieldedPool, + ZcashTransaction, + ZcashValuePool, + ZcashValuePoolId, +} from "../../../types"; +import { + getShieldedPools, + getTransparentOutputZat, + isCoinbaseTransaction, + zecToZat, +} from "../../../utils/zcashUtils"; + +/* + * Raw Zebra RPC shapes, limited to the fields the explorer reads. They are looser than the + * connector's types on purpose: they also cover the NU6.3 Ironwood bundle and note commitment + * tree, which @openscan/network-connectors does not model yet. + */ + +export interface ZcashRawActionBundle { + actions?: unknown[]; + valueBalance?: number; + valueBalanceZat?: number; +} + +export interface ZcashRawVin { + txid?: string; + vout?: number; + coinbase?: string; + sequence: number; +} + +export interface ZcashRawVout { + value: number; + valueZat?: number; + n: number; + scriptPubKey: { type: string; addresses?: string[] }; +} + +export interface ZcashRawJoinSplit { + vpub_old: number; + vpub_new: number; + vpub_oldZat?: number; + vpub_newZat?: number; +} + +export interface ZcashRawTransaction { + txid?: string; + size?: number; + version?: number; + versiongroupid?: string; + locktime?: number; + expiryheight?: number; + vin: ZcashRawVin[]; + vout: ZcashRawVout[]; + valueBalance?: number; + valueBalanceZat?: number; + vShieldedSpend?: unknown[]; + vShieldedOutput?: unknown[]; + vjoinsplit?: ZcashRawJoinSplit[]; + orchard?: ZcashRawActionBundle; + ironwood?: ZcashRawActionBundle; + blockhash?: string; + height?: number; + confirmations?: number; + time?: number; + blocktime?: number; +} + +export interface ZcashRawValuePool { + id: string; + chainValueZat: number; +} + +interface ZcashRawBlockCommon { + hash: string; + confirmations?: number; + height: number; + version: number; + merkleroot: string; + blockcommitments?: string; + finalsaplingroot?: string; + finalorchardroot?: string; + time: number; + nonce: string; + solution?: string; + bits: string; + difficulty: number; + previousblockhash?: string; + nextblockhash?: string; + size?: number; + nTx?: number; + trees?: { + sapling?: { size: number }; + orchard?: { size: number }; + ironwood?: { size: number }; + }; + chainSupply?: { chainValueZat: number }; + valuePools?: ZcashRawValuePool[]; +} + +/** getblock with verbosity 1 (transaction ids only) */ +export interface ZcashRawBlockSummary extends ZcashRawBlockCommon { + tx: string[]; +} + +/** getblock with verbosity 2 (full transactions) */ +export interface ZcashRawBlock extends ZcashRawBlockCommon { + tx: ZcashRawTransaction[]; +} + +export interface ZcashRawBlockchainInfo { + chain: string; + blocks: number; + bestblockhash: string; + difficulty: number; + estimatedheight?: number; + verificationprogress?: number; + chainSupply?: { chainValueZat: number }; + valuePools?: ZcashRawValuePool[]; +} + +export interface ZcashRawMempoolEntry { + size: number; + fee: number; + time: number; + height: number; +} + +const VALUE_POOL_IDS: ZcashValuePoolId[] = [ + "transparent", + "sprout", + "sapling", + "orchard", + "lockbox", + "ironwood", +]; + +function isValuePoolId(id: string): id is ZcashValuePoolId { + return (VALUE_POOL_IDS as string[]).includes(id); +} + +export function transformValuePools(pools: ZcashRawValuePool[] | undefined): ZcashValuePool[] { + return (pools ?? []).flatMap((pool) => + isValuePoolId(pool.id) ? [{ id: pool.id, valueZat: pool.chainValueZat }] : [], + ); +} + +function toActionBundle(raw: ZcashRawActionBundle | undefined): ZcashActionBundle | undefined { + const actions = raw?.actions?.length ?? 0; + const valueBalanceZat = raw?.valueBalanceZat ?? zecToZat(raw?.valueBalance ?? 0); + return actions > 0 || valueBalanceZat !== 0 ? { actions, valueBalanceZat } : undefined; +} + +function toShieldedBundles(raw: ZcashRawTransaction): ZcashShieldedBundles { + const bundles: ZcashShieldedBundles = {}; + + const joinSplits = raw.vjoinsplit ?? []; + if (joinSplits.length > 0) { + bundles.sprout = { + joinSplits: joinSplits.length, + vpubOldZat: joinSplits.reduce( + (sum, js) => sum + (js.vpub_oldZat ?? zecToZat(js.vpub_old)), + 0, + ), + vpubNewZat: joinSplits.reduce( + (sum, js) => sum + (js.vpub_newZat ?? zecToZat(js.vpub_new)), + 0, + ), + }; + } + + const spends = raw.vShieldedSpend?.length ?? 0; + const outputs = raw.vShieldedOutput?.length ?? 0; + const saplingBalanceZat = raw.valueBalanceZat ?? zecToZat(raw.valueBalance ?? 0); + if (spends > 0 || outputs > 0 || saplingBalanceZat !== 0) { + bundles.sapling = { spends, outputs, valueBalanceZat: saplingBalanceZat }; + } + + const orchard = toActionBundle(raw.orchard); + if (orchard) bundles.orchard = orchard; + + const ironwood = toActionBundle(raw.ironwood); + if (ironwood) bundles.ironwood = ironwood; + + return bundles; +} + +export function transformTransaction(raw: ZcashRawTransaction): ZcashTransaction { + return { + txid: raw.txid ?? "", + version: raw.version ?? 0, + versionGroupId: raw.versiongroupid, + size: raw.size ?? 0, + locktime: raw.locktime ?? 0, + expiryHeight: raw.expiryheight, + vin: raw.vin.map((input) => ({ + txid: input.txid, + vout: input.vout, + coinbase: input.coinbase, + sequence: input.sequence, + })), + vout: raw.vout.map((output) => ({ + n: output.n, + valueZat: output.valueZat ?? zecToZat(output.value), + address: output.scriptPubKey.addresses?.[0], + scriptType: output.scriptPubKey.type, + })), + shielded: toShieldedBundles(raw), + blockhash: raw.blockhash, + blockheight: raw.height, + confirmations: raw.confirmations, + blocktime: raw.blocktime, + time: raw.time, + }; +} + +function transformBlockCommon(raw: ZcashRawBlockCommon, txCount: number): ZcashBlock { + return { + hash: raw.hash, + height: raw.height, + time: raw.time, + nTx: raw.nTx ?? txCount, + size: raw.size ?? 0, + version: raw.version, + merkleRoot: raw.merkleroot, + previousBlockHash: raw.previousblockhash, + nextBlockHash: raw.nextblockhash, + bits: raw.bits, + nonce: raw.nonce, + difficulty: raw.difficulty, + confirmations: raw.confirmations, + solution: raw.solution, + blockCommitments: raw.blockcommitments, + finalSaplingRoot: raw.finalsaplingroot, + finalOrchardRoot: raw.finalorchardroot, + trees: raw.trees && { + sapling: raw.trees.sapling?.size, + orchard: raw.trees.orchard?.size, + ironwood: raw.trees.ironwood?.size, + }, + chainSupplyZat: raw.chainSupply?.chainValueZat, + valuePools: raw.valuePools && transformValuePools(raw.valuePools), + }; +} + +export function transformBlockSummary(raw: ZcashRawBlockSummary): ZcashBlock { + return { ...transformBlockCommon(raw, raw.tx.length), txids: raw.tx }; +} + +export function transformBlock(raw: ZcashRawBlock): ZcashBlockWithTransactions { + const transactions = raw.tx.map(transformTransaction); + const coinbase = transactions[0]; + + const shieldedTxCounts: Partial> = {}; + for (const tx of transactions) { + for (const pool of getShieldedPools(tx)) { + shieldedTxCounts[pool] = (shieldedTxCounts[pool] ?? 0) + 1; + } + } + + return { + block: { + ...transformBlockCommon(raw, transactions.length), + txids: transactions.map((tx) => tx.txid), + coinbaseOutputs: + coinbase && isCoinbaseTransaction(coinbase) + ? coinbase.vout.map((output) => ({ address: output.address, valueZat: output.valueZat })) + : [], + shieldedTxCounts, + transparentOutputZat: transactions.reduce((sum, tx) => sum + getTransparentOutputZat(tx), 0), + }, + transactions, + }; +} + +export function transformNetworkStats( + info: ZcashRawBlockchainInfo, + mempool: { size: number; bytes: number }, +): ZcashNetworkStats { + return { + blockHeight: info.blocks, + bestBlockHash: info.bestblockhash, + difficulty: info.difficulty, + chain: info.chain, + estimatedHeight: info.estimatedheight, + verificationProgress: info.verificationprogress, + mempoolSize: mempool.size, + mempoolBytes: mempool.bytes, + chainSupplyZat: info.chainSupply?.chainValueZat, + valuePools: transformValuePools(info.valuePools), + }; +} + +/** + * Convert a verbose mempool listing, highest fee rate first + */ +export function transformMempoolEntries( + entries: Record, +): ZcashMempoolEntry[] { + const feeRate = (entry: ZcashMempoolEntry) => entry.feeZat / Math.max(entry.size, 1); + return Object.entries(entries) + .map(([txid, entry]) => ({ + txid, + size: entry.size, + feeZat: zecToZat(entry.fee), + time: entry.time, + height: entry.height, + })) + .sort((a, b) => feeRate(b) - feeRate(a)); +} + +/** + * Fill transparent input values and addresses from the transactions they spend + */ +export function applyResolvedInputs( + tx: ZcashTransaction, + previous: Map, +): ZcashTransaction { + return { + ...tx, + vin: tx.vin.map((input) => { + const spent = + input.txid === undefined + ? undefined + : previous.get(input.txid)?.vout.find((output) => output.n === input.vout); + return spent ? { ...input, valueZat: spent.valueZat, address: spent.address } : input; + }), + }; +} diff --git a/src/utils/zcashFormatters.ts b/src/utils/zcashFormatters.ts new file mode 100644 index 00000000..b3cab0fa --- /dev/null +++ b/src/utils/zcashFormatters.ts @@ -0,0 +1,30 @@ +/** + * Zcash formatting utilities. Amounts are integer zatoshis (1 ZEC = 100,000,000 zat). + */ + +import { ZATOSHIS_PER_ZEC } from "../config/zcashConstants"; + +export { + formatDifficulty, + formatNumber, + formatSize, + formatTimeAgo, + formatTimestamp, + truncateBlockHash, + truncateHash, +} from "./bitcoinFormatters"; + +/** + * Format a zatoshi amount as ZEC with 8 decimal places + * @param currency - Ticker to append (testnet uses TAZ) + */ +export function formatZEC(valueZat: number, currency = "ZEC"): string { + return `${(valueZat / ZATOSHIS_PER_ZEC).toFixed(8)} ${currency}`; +} + +/** + * Format a zatoshi amount with thousands separators + */ +export function formatZatoshis(valueZat: number): string { + return `${valueZat.toLocaleString()} zat`; +} diff --git a/src/utils/zcashUtils.test.ts b/src/utils/zcashUtils.test.ts new file mode 100644 index 00000000..5c5a7771 --- /dev/null +++ b/src/utils/zcashUtils.test.ts @@ -0,0 +1,174 @@ +import { describe, expect, it } from "vitest"; +import type { ZcashTransaction } from "../types"; +import { + classifyRpcErrors, + classifyTransaction, + computeFeeZat, + detectZcashAddressType, + getTransactionPools, + isZcashAddress, + zecToZat, +} from "./zcashUtils"; + +function tx(overrides: Partial): ZcashTransaction { + return { + txid: "a".repeat(64), + version: 5, + size: 0, + locktime: 0, + vin: [], + vout: [], + shielded: {}, + ...overrides, + }; +} + +const input = (valueZat?: number) => ({ + txid: "b".repeat(64), + vout: 0, + sequence: 0xffffffff, + valueZat, +}); + +const output = (n: number, valueZat: number) => ({ + n, + valueZat, + address: "t1KAuVfS2r2hc7RwSh6GTuyfqCGMFEpwkZ2", + scriptType: "pubkeyhash", +}); + +describe("detectZcashAddressType", () => { + it.each([ + ["t1KAuVfS2r2hc7RwSh6GTuyfqCGMFEpwkZ2", "p2pkh"], + [`tm${"a".repeat(33)}`, "p2pkh"], + ["t3cFfPt1Bcvgez9ZbMBFWeZsskxTkPzGCow", "p2sh"], + [`t2${"a".repeat(33)}`, "p2sh"], + [`zc${"a".repeat(93)}`, "sprout"], + [`zt${"a".repeat(93)}`, "sprout"], + [`zs1${"q".repeat(75)}`, "sapling"], + [`ztestsapling1${"q".repeat(75)}`, "sapling"], + [`tex1${"q".repeat(38)}`, "tex"], + [`textest1${"q".repeat(38)}`, "tex"], + [`u1${"q".repeat(100)}`, "unified"], + [`utest1${"q".repeat(100)}`, "unified"], + ])("detects %s as %s", (address, type) => { + expect(detectZcashAddressType(address)).toBe(type); + expect(isZcashAddress(address)).toBe(true); + }); + + it.each([ + "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", + "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", + "t1KAuVfS2r2hc7RwSh6GTuyfqCGMFEpwkZ", // one character short + `zs1${"b".repeat(75)}`, // "b" is outside the bech32 alphabet + "", + ])("rejects %s", (address) => { + expect(detectZcashAddressType(address)).toBe("unknown"); + expect(isZcashAddress(address)).toBe(false); + }); +}); + +describe("classifyTransaction and computeFeeZat", () => { + it("handles a fully shielded Ironwood transaction with empty vin and vout", () => { + // Mainnet tx 36a167f6…ce2e3, block 3,483,400 + const ironwoodOnly = tx({ shielded: { ironwood: { actions: 2, valueBalanceZat: 10_000 } } }); + + expect(classifyTransaction(ironwoodOnly)).toBe("shielded"); + expect(getTransactionPools(ironwoodOnly)).toEqual(["ironwood"]); + expect(computeFeeZat(ironwoodOnly)).toBe(10_000); + }); + + it("nets value balances across Sapling and Ironwood", () => { + // Mainnet tx c973d2f1…4aa7db, block 3,483,400 + const saplingIronwood = tx({ + shielded: { + sapling: { spends: 0, outputs: 2, valueBalanceZat: -3_000_000 }, + ironwood: { actions: 2, valueBalanceZat: 3_020_000 }, + }, + }); + + expect(classifyTransaction(saplingIronwood)).toBe("shielded"); + expect(getTransactionPools(saplingIronwood)).toEqual(["sapling", "ironwood"]); + expect(computeFeeZat(saplingIronwood)).toBe(20_000); + }); + + it("needs every transparent input value before computing a shielding fee", () => { + const shielding = tx({ + vin: [input(), input()], + shielded: { sapling: { spends: 0, outputs: 2, valueBalanceZat: -1_877_663_138 } }, + }); + + expect(classifyTransaction(shielding)).toBe("shielding"); + expect(computeFeeZat(shielding)).toBeNull(); + expect(computeFeeZat({ ...shielding, vin: [input(1_000_000_000), input()] })).toBeNull(); + expect(computeFeeZat({ ...shielding, vin: [input(1_000_000_000), input(877_673_138)] })).toBe( + 10_000, + ); + }); + + it("classifies deshielding, mixed and transparent transactions", () => { + const ironwood = { actions: 1, valueBalanceZat: 25_010_000 }; + expect(classifyTransaction(tx({ vout: [output(0, 25_000_000)], shielded: { ironwood } }))).toBe( + "deshielding", + ); + expect( + classifyTransaction(tx({ vin: [input(5)], vout: [output(0, 1)], shielded: { ironwood } })), + ).toBe("mixed"); + + const transparent = tx({ vin: [input(50_000)], vout: [output(0, 30_000), output(1, 10_000)] }); + expect(classifyTransaction(transparent)).toBe("transparent"); + expect(getTransactionPools(transparent)).toEqual(["transparent"]); + expect(computeFeeZat(transparent)).toBe(10_000); + }); + + it("does not compute a fee for coinbase transactions", () => { + const coinbase = tx({ + vin: [{ coinbase: "0308273504", sequence: 0xffffffff }], + vout: [output(0, 125_490_751), output(1, 12_500_000)], + }); + + expect(classifyTransaction(coinbase)).toBe("coinbase"); + expect(computeFeeZat(coinbase)).toBeNull(); + }); + + it("accounts for Sprout JoinSplit public values", () => { + const sprout = tx({ + vin: [input(100_000)], + shielded: { sprout: { joinSplits: 1, vpubOldZat: 90_000, vpubNewZat: 0 } }, + }); + + expect(classifyTransaction(sprout)).toBe("shielding"); + expect(computeFeeZat(sprout)).toBe(10_000); + }); +}); + +describe("classifyRpcErrors", () => { + it("reports unsupported when every endpoint rejects the method", () => { + expect( + classifyRpcErrors([ + "RPC error: Method not found: getaddressbalance", + "RPC error: Method not found: getaddressbalance", + ]), + ).toBe("unsupported"); + }); + + it("reports rate limiting when any endpoint returns 429", () => { + expect( + classifyRpcErrors(["HTTP error! status: 429", "RPC error: Method not found: getblock"]), + ).toBe("rateLimited"); + }); + + it("reports other failures as failed", () => { + expect(classifyRpcErrors(["RPC error: No such mempool or main chain transaction"])).toBe( + "failed", + ); + expect(classifyRpcErrors([])).toBe("failed"); + }); +}); + +describe("zecToZat", () => { + it("rounds away floating point drift", () => { + expect(zecToZat(18.77663138)).toBe(1_877_663_138); + expect(zecToZat(0.0001)).toBe(10_000); + }); +}); diff --git a/src/utils/zcashUtils.ts b/src/utils/zcashUtils.ts new file mode 100644 index 00000000..13119627 --- /dev/null +++ b/src/utils/zcashUtils.ts @@ -0,0 +1,118 @@ +/** + * Zcash helpers: address detection, transaction classification, fees and RPC error handling + */ + +import { ZATOSHIS_PER_ZEC } from "../config/zcashConstants"; +import type { + ZcashAddressType, + ZcashShieldedPool, + ZcashTransaction, + ZcashTxKind, + ZcashTxPool, +} from "../types"; + +const BASE58 = "[1-9A-HJ-NP-Za-km-z]"; +const BECH32 = "[02-9ac-hj-np-z]"; + +// Mainnet and testnet prefixes. Only prefix, alphabet and length are checked, not checksums. +const ADDRESS_PATTERNS: Array<{ type: ZcashAddressType; pattern: RegExp }> = [ + { type: "p2pkh", pattern: new RegExp(`^(t1|tm)${BASE58}{33}$`) }, + { type: "p2sh", pattern: new RegExp(`^(t3|t2)${BASE58}{33}$`) }, + { type: "sprout", pattern: new RegExp(`^(zc|zt)${BASE58}{93}$`) }, + { type: "sapling", pattern: new RegExp(`^(zs|ztestsapling)1${BECH32}{75}$`) }, + { type: "tex", pattern: new RegExp(`^(tex|textest)1${BECH32}{38}$`) }, + { type: "unified", pattern: new RegExp(`^(u|utest)1${BECH32}{50,}$`) }, +]; + +/** + * Detect a Zcash address encoding from its prefix and shape + */ +export function detectZcashAddressType(address: string): ZcashAddressType { + return ADDRESS_PATTERNS.find(({ pattern }) => pattern.test(address))?.type ?? "unknown"; +} + +export function isZcashAddress(term: string): boolean { + return detectZcashAddressType(term) !== "unknown"; +} + +/** + * Convert a ZEC amount to integer zatoshis, removing floating point drift + */ +export function zecToZat(value: number): number { + return Math.round(value * ZATOSHIS_PER_ZEC); +} + +export function isCoinbaseTransaction(tx: ZcashTransaction): boolean { + return tx.vin[0]?.coinbase !== undefined; +} + +const SHIELDED_POOLS: ZcashShieldedPool[] = ["sprout", "sapling", "orchard", "ironwood"]; + +export function getShieldedPools(tx: ZcashTransaction): ZcashShieldedPool[] { + return SHIELDED_POOLS.filter((pool) => tx.shielded[pool] !== undefined); +} + +export function getTransactionPools(tx: ZcashTransaction): ZcashTxPool[] { + const shielded = getShieldedPools(tx); + return tx.vin.length > 0 || tx.vout.length > 0 ? ["transparent", ...shielded] : shielded; +} + +/** + * Classify how a transaction moves value between the transparent and shielded pools. + * A shielded transaction legitimately has empty vin and vout. + */ +export function classifyTransaction(tx: ZcashTransaction): ZcashTxKind { + if (isCoinbaseTransaction(tx)) return "coinbase"; + if (getShieldedPools(tx).length === 0) return "transparent"; + + const hasInputs = tx.vin.length > 0; + const hasOutputs = tx.vout.length > 0; + if (hasInputs && hasOutputs) return "mixed"; + if (hasInputs) return "shielding"; + if (hasOutputs) return "deshielding"; + return "shielded"; +} + +export function getTransparentOutputZat(tx: ZcashTransaction): number { + return tx.vout.reduce((sum, output) => sum + output.valueZat, 0); +} + +/** + * Fee in zatoshis, from the transparent value balance: + * inputs + value leaving the shielded pools = outputs + fee. + * Returns null for coinbase, and while any transparent input value is still unknown. + */ +export function computeFeeZat(tx: ZcashTransaction): number | null { + if (isCoinbaseTransaction(tx)) return null; + + let inputZat = 0; + for (const input of tx.vin) { + if (input.valueZat === undefined) return null; + inputZat += input.valueZat; + } + + const { sprout, sapling, orchard, ironwood } = tx.shielded; + const shieldedNetZat = + (sprout ? sprout.vpubNewZat - sprout.vpubOldZat : 0) + + (sapling?.valueBalanceZat ?? 0) + + (orchard?.valueBalanceZat ?? 0) + + (ironwood?.valueBalanceZat ?? 0); + + return inputZat + shieldedNetZat - getTransparentOutputZat(tx); +} + +export type ZcashRpcErrorKind = "unsupported" | "rateLimited" | "failed"; + +const RATE_LIMITED_PATTERN = /status: 429/; +const UNSUPPORTED_PATTERN = /method not found|-32601/i; + +/** + * Classify the per-endpoint error messages of a failed RPC call + */ +export function classifyRpcErrors(messages: string[]): ZcashRpcErrorKind { + if (messages.some((message) => RATE_LIMITED_PATTERN.test(message))) return "rateLimited"; + if (messages.length > 0 && messages.every((message) => UNSUPPORTED_PATTERN.test(message))) { + return "unsupported"; + } + return "failed"; +} From a7fec1078a3fde7546b2aaf753a30e760f8a7ca4 Mon Sep 17 00:00:00 2001 From: Mati OS Date: Mon, 14 Sep 2026 19:09:09 -0300 Subject: [PATCH 3/7] feat(network): wire zcash into DataService, metadata and RPC defaults --- src/services/DataService.ts | 36 ++++++++++++++++++++++-- src/services/MetadataService.ts | 11 +++++++- src/services/adapters/adaptersFactory.ts | 9 ++++++ src/utils/networkResolver.ts | 7 +++++ src/utils/rpcStorage.ts | 12 +++++++- 5 files changed, 70 insertions(+), 5 deletions(-) diff --git a/src/services/DataService.ts b/src/services/DataService.ts index 6c8d5dab..ecdf58fe 100644 --- a/src/services/DataService.ts +++ b/src/services/DataService.ts @@ -1,6 +1,7 @@ import { type SupportedChainId, type SupportedSolanaChainId, + type SupportedZcashChainId, ArbitrumClient, BaseClient, BitcoinClient, @@ -14,7 +15,8 @@ import { AdapterFactory } from "./adapters/adaptersFactory"; import type { NetworkAdapter } from "./adapters/NetworkAdapter"; import type { BitcoinAdapter } from "./adapters/BitcoinAdapter/BitcoinAdapter"; import type { SolanaAdapter } from "./adapters/SolanaAdapter/SolanaAdapter"; -import type { NetworkConfig, RpcUrlsContextType } from "../types"; +import type { ZcashAdapter } from "./adapters/ZcashAdapter/ZcashAdapter"; +import type { NetworkConfig, NetworkType, RpcUrlsContextType } from "../types"; import { getRPCUrls } from "../config/rpcConfig"; import { getNetworkRpcKey, getChainIdFromNetwork } from "../utils/networkResolver"; @@ -41,19 +43,21 @@ const EVM_TESTNET_CLIENTS: Record EVMTestne }; /** - * DataService supports EVM, Bitcoin, and Solana networks + * DataService supports EVM, Bitcoin, Zcash, and Solana networks * The adapter type varies based on network type */ export class DataService { /** * The network adapter - use this directly for EVM networks * For Bitcoin networks, use getBitcoinAdapter() instead + * For Zcash networks, use getZcashAdapter() instead * For Solana networks, use getSolanaAdapter() instead */ networkAdapter: NetworkAdapter; private bitcoinAdapter?: BitcoinAdapter; + private zcashAdapter?: ZcashAdapter; private solanaAdapter?: SolanaAdapter; - readonly networkType: "evm" | "bitcoin" | "solana"; + readonly networkType: NetworkType; constructor( network: NetworkConfig, @@ -73,6 +77,15 @@ export class DataService { this.bitcoinAdapter = AdapterFactory.createBitcoinAdapter(network.networkId, bitcoinClient); // Create a placeholder adapter that throws for EVM methods this.networkAdapter = null as unknown as NetworkAdapter; + } else if (network.type === "zcash") { + // Zcash shares the bip122 namespace with Bitcoin; ClientFactory routes by registry membership + const zcashChainId = network.networkId as SupportedZcashChainId; + const zcashClient = ClientFactory.createTypedClient(zcashChainId, { + rpcUrls, + type: strategy, + }); + this.zcashAdapter = AdapterFactory.createZcashAdapter(network.networkId, zcashClient); + this.networkAdapter = null as unknown as NetworkAdapter; } else if (network.type === "solana") { // Create Solana client and adapter via ClientFactory const solanaChainId = network.networkId as SupportedSolanaChainId; @@ -107,6 +120,13 @@ export class DataService { return this.networkType === "bitcoin"; } + /** + * Check if this is a Zcash network service + */ + isZcash(): boolean { + return this.networkType === "zcash"; + } + /** * Check if this is a Solana network service */ @@ -134,6 +154,16 @@ export class DataService { return this.bitcoinAdapter; } + /** + * Get the adapter as a Zcash adapter (throws if not Zcash) + */ + getZcashAdapter(): ZcashAdapter { + if (!this.isZcash() || !this.zcashAdapter) { + throw new Error("Cannot get Zcash adapter for non-Zcash network"); + } + return this.zcashAdapter; + } + /** * Get the adapter as a Solana adapter (throws if not Solana) */ diff --git a/src/services/MetadataService.ts b/src/services/MetadataService.ts index 85660515..5cda555b 100644 --- a/src/services/MetadataService.ts +++ b/src/services/MetadataService.ts @@ -81,6 +81,13 @@ const BTC_NETWORK_SLUGS: Record = { "00000000da84f2bafbbc53dee25a72ae": "testnet4", }; +// Zcash genesis block hashes → friendly file names. Zcash shares the bip122 namespace with +// Bitcoin, so these are checked before the BTC mapping. +const ZEC_NETWORK_SLUGS: Record = { + "00040fe8ec8471911baa1db1266ea15d": "mainnet", + "05a60a92d99d85997cce3b87616c089f": "testnet", +}; + // Solana CAIP-2 chain IDs (first 32 chars of genesis hash) → friendly file names const SOLANA_NETWORK_SLUGS: Record = { "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": "mainnet", @@ -91,7 +98,7 @@ const SOLANA_NETWORK_SLUGS: Record = { /** * Parse a CAIP-2 networkId to determine the RPC file path * "eip155:{chainId}" → rpcs/evm/{chainId}.json - * "bip122:{hash}" → rpcs/btc/{slug}.json (using genesis hash → slug mapping) + * "bip122:{hash}" → rpcs/zec/{slug}.json or rpcs/btc/{slug}.json (genesis hash → slug mapping) * "solana:{hash}" → rpcs/solana/{slug}.json (using genesis hash → slug mapping) */ function getRpcPathFromNetworkId(networkId: string): string | null { @@ -101,6 +108,8 @@ function getRpcPathFromNetworkId(networkId: string): string | null { } if (networkId.startsWith("bip122:")) { const hash = networkId.slice(7); + const zecSlug = ZEC_NETWORK_SLUGS[hash]; + if (zecSlug) return `rpcs/zec/${zecSlug}.json`; const slug = BTC_NETWORK_SLUGS[hash]; if (!slug) return null; return `rpcs/btc/${slug}.json`; diff --git a/src/services/adapters/adaptersFactory.ts b/src/services/adapters/adaptersFactory.ts index faa3cbcc..8f444b03 100644 --- a/src/services/adapters/adaptersFactory.ts +++ b/src/services/adapters/adaptersFactory.ts @@ -7,6 +7,7 @@ import { PolygonAdapter } from "./PolygonAdapter/PolygonAdapter"; import { ArbitrumAdapter } from "./ArbitrumAdapter/ArbitrumAdapter"; import { HardhatAdapter } from "./HardhatAdapter/HardhatAdapter"; import { BitcoinAdapter } from "./BitcoinAdapter/BitcoinAdapter"; +import { ZcashAdapter } from "./ZcashAdapter/ZcashAdapter"; import { SolanaAdapter } from "./SolanaAdapter/SolanaAdapter"; import type { ArbitrumClient, @@ -21,6 +22,7 @@ import type { PolygonClient, SolanaClient, SupportedChainId, + ZcashClient, } from "@openscan/network-connectors"; // biome-ignore lint/complexity/noStaticOnlyClass: @@ -76,6 +78,13 @@ export class AdapterFactory { return new BitcoinAdapter(networkId, client); } + /** + * Create a Zcash network adapter + */ + static createZcashAdapter(networkId: string, client: ZcashClient): ZcashAdapter { + return new ZcashAdapter(networkId, client); + } + /** * Create a Solana network adapter */ diff --git a/src/utils/networkResolver.ts b/src/utils/networkResolver.ts index 041361ae..fb678e49 100644 --- a/src/utils/networkResolver.ts +++ b/src/utils/networkResolver.ts @@ -71,6 +71,13 @@ export function isBitcoinNetwork(network: NetworkConfig): boolean { return network.type === "bitcoin"; } +/** + * Check if a network is a Zcash network + */ +export function isZcashNetwork(network: NetworkConfig): boolean { + return network.type === "zcash"; +} + /** * Check if a network is a Solana network */ diff --git a/src/utils/rpcStorage.ts b/src/utils/rpcStorage.ts index 552189ae..0baf7802 100644 --- a/src/utils/rpcStorage.ts +++ b/src/utils/rpcStorage.ts @@ -9,7 +9,7 @@ const METADATA_RPC_TTL = 24 * 60 * 60 * 1000; // 24 hours /** * Hardcoded fallback defaults for networks that are never in the metadata service. - * Includes localhost, worker-proxied BTC, and worker-proxied EVM endpoints. + * Includes localhost, worker-proxied BTC and EVM, and public Zcash and Solana endpoints. * Metadata service RPCs and user-configured RPCs take priority via getEffectiveRpcUrls(). */ const BUILTIN_RPC_DEFAULTS: RpcUrlsContextType = { @@ -23,6 +23,16 @@ const BUILTIN_RPC_DEFAULTS: RpcUrlsContextType = { "bip122:00000000da84f2bafbbc53dee25a72ae": [ `${OPENSCAN_WORKER_URL}/btc/onfinality/bip122:00000000da84f2bafbbc53dee25a72ae`, ], + // Zcash — Tatum's public zebrad gateways. Both hosts share a ~5 requests/min per-IP limit + // and block the address index and z_* methods; add a self-hosted zebrad for those. + "bip122:00040fe8ec8471911baa1db1266ea15d": [ + "https://zcash-mainnet-zebrad.gateway.tatum.io", + "https://zcash-mainnet.gateway.tatum.io", + ], + "bip122:05a60a92d99d85997cce3b87616c089f": [ + "https://zcash-testnet-zebrad.gateway.tatum.io", + "https://zcash-testnet.gateway.tatum.io", + ], "eip155:1": [ `${OPENSCAN_WORKER_URL}/evm/alchemy/eip155:1`, `${OPENSCAN_WORKER_URL}/evm/infura/eip155:1`, From 3712ede6a29d747cb82b8c95cfbbf7fc0e99ac7f Mon Sep 17 00:00:00 2001 From: Mati OS Date: Mon, 14 Sep 2026 19:09:10 -0300 Subject: [PATCH 4/7] docs(claude): document zcash client and adapter --- .claude/rules/architecture.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.claude/rules/architecture.md b/.claude/rules/architecture.md index 43ee06d9..5858bb1c 100644 --- a/.claude/rules/architecture.md +++ b/.claude/rules/architecture.md @@ -9,6 +9,7 @@ Typed RPC clients for blockchain communication: - `EthereumClient` - Standard JSON-RPC for EVM chains - `HardhatClient` - Extended client with Hardhat-specific methods (`hardhat_*`, `evm_*`, `debug_*`) - `BitcoinClient` - Bitcoin JSON-RPC (`getblock`, `getrawtransaction`, etc.) +- `ZcashClient` - Zebra (`zebrad`) JSON-RPC. HTTP only; heights are passed to `getblock` as decimal strings - Supports `fallback`, `parallel`, and `race` strategies ### 2. Adapter Layer (`services/adapters/`) @@ -21,10 +22,11 @@ Abstract `NetworkAdapter` base class with chain-specific implementations: - `PolygonAdapter` - Polygon (137) + Amoy testnet (80002) - `HardhatAdapter` - Localhost (31337) with trace support via struct log conversion - `BitcoinAdapter` - Bitcoin networks (bip122:*) with UTXO model, mempool, and block explorer +- `ZcashAdapter` - Zcash networks (bip122:00040fe8…, bip122:05a60a92…) with shielded pools. Budgets RPC calls for rate-limited hosted gateways and throws `ZcashRpcError` instead of returning empty data - `SolanaAdapter` - Solana networks - Each adapter implements: `getBlock`, `getTransaction`, `getAddress`, `getNetworkStats`, trace methods -- `AdapterFactory` routes chain ID to the correct adapter via three entry points: - `createAdapter` (EVM), `createBitcoinAdapter`, `createSolanaAdapter` +- `AdapterFactory` routes chain ID to the correct adapter via four entry points: + `createAdapter` (EVM), `createBitcoinAdapter`, `createZcashAdapter`, `createSolanaAdapter` ### 3. Service Layer (`DataService.ts`) Orchestrates data fetching with caching and metadata: @@ -55,6 +57,7 @@ Chain ID detection in `AdapterFactory` determines which adapter to instantiate - **BSC** (56, 97): `BNBAdapter` - **Polygon** (137, 80002): `PolygonAdapter` - **Bitcoin** (bip122:*): `BitcoinAdapter` - UTXO model, mempool transactions, block rewards (constructed via `createBitcoinAdapter`) +- **Zcash** (bip122:00040fe8…, bip122:05a60a92…): `ZcashAdapter` - transparent UTXOs plus Sprout/Sapling/Orchard/Ironwood shielded bundles (constructed via `createZcashAdapter`). Zcash shares the bip122 namespace with Bitcoin, so routing keys off `type: "zcash"`, never the prefix - **Solana**: `SolanaAdapter` (constructed via `createSolanaAdapter`) - **Hardhat** (31337): `HardhatAdapter` - uses `HardhatClient` from `@openscan/network-connectors`; trace support via struct log conversion (`buildCallTreeFromStructLogs`, `buildPrestateFromStructLogs` in `src/utils/structLogConverter.ts`) since Hardhat v3 does not support `callTracer`/`prestateTracer` - **Default EVM**: `EVMAdapter` for Ethereum (1), Sepolia (11155111), Avalanche (43114, 43113) From b84b26922c43ede7083bba690dadf38b96f69f21 Mon Sep 17 00:00:00 2001 From: Mati OS Date: Tue, 15 Sep 2026 11:33:10 -0300 Subject: [PATCH 5/7] chore(metadata): bump metadata to 1.3.0-alpha.0 1.3.0-alpha.0 publishes the Zcash RPC lists (rpcs/zec/mainnet.json, rpcs/zec/testnet.json) and the Zcash network logo, so the explorer now loads both from metadata instead of falling back. It adds no other files. The metadata RPC cache is keyed by version and refreshes itself. --- src/services/MetadataService.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/MetadataService.ts b/src/services/MetadataService.ts index 5cda555b..8c1e3417 100644 --- a/src/services/MetadataService.ts +++ b/src/services/MetadataService.ts @@ -7,7 +7,7 @@ import networksData from "../config/networks.json"; import { logger } from "../utils/logger"; import { extractChainIdFromNetworkId } from "../utils/networkResolver"; -export const METADATA_VERSION = "1.2.1-alpha.0"; +export const METADATA_VERSION = "1.3.0-alpha.0"; const METADATA_BASE_URL = `https://cdn.jsdelivr.net/npm/@openscan/metadata@${METADATA_VERSION}/dist`; export interface NetworkLink { From 9fa879ef1dc171822459a88796bfe7267a272449 Mon Sep 17 00:00:00 2001 From: Mati OS Date: Fri, 20 Nov 2026 19:58:54 -0300 Subject: [PATCH 6/7] fix(adapter): harden zcash rpc calls for rate-limited gateways - Classify a definitive JSON-RPC answer before any 429, so a self-hosted "not found" no longer waits on Tatum's rate limit and ends as rateLimited. - Calls take an AbortSignal: retry waits and unsent calls stop on abort. - Remember methods the endpoints reject for the session (shared per network and endpoint list), so pages stop probing blocked methods. - getAddress asks getaddressbalance first and skips utxos/txids when the address index is unavailable. - getBlockSummaries reports failed heights instead of dropping them, and stops once a block stays rate limited. - resolveTransparentInputs spends no calls over the cap, keeps inputs resolved before a failure, and resumes from them. - computeFee returns coinbase | unknown | known instead of number | null. - Blocks carry the shielded coinbase reward. - Address detection is network-aware and accepts uppercase Bech32m. - Pool unions derive from as-const lists; raw Zebra types pick from the connector's types; parallel metadata is transformed per provider. - Drop unused getBlockTransactions and formatZatoshis. --- src/config/zcashConstants.ts | 27 ++ src/services/DataService.test.ts | 69 ++++ src/services/DataService.ts | 6 +- src/services/MetadataService.test.ts | 44 +++ .../ZcashAdapter/ZcashAdapter.test.ts | 284 +++++++++++++++-- .../adapters/ZcashAdapter/ZcashAdapter.ts | 298 ++++++++++++++---- src/services/adapters/ZcashAdapter/utils.ts | 235 +++++++------- src/services/adapters/adaptersFactory.ts | 10 +- src/types/index.ts | 33 +- src/utils/rpcStorage.ts | 7 +- src/utils/zcashFormatters.ts | 8 +- src/utils/zcashUtils.test.ts | 88 +++++- src/utils/zcashUtils.ts | 140 ++++++-- 13 files changed, 977 insertions(+), 272 deletions(-) create mode 100644 src/services/DataService.test.ts create mode 100644 src/services/MetadataService.test.ts diff --git a/src/config/zcashConstants.ts b/src/config/zcashConstants.ts index 91993415..2a985ee1 100644 --- a/src/config/zcashConstants.ts +++ b/src/config/zcashConstants.ts @@ -2,8 +2,35 @@ * Zcash-specific constants */ +import { ZCASH_TESTNET } from "@openscan/network-connectors"; + export const ZATOSHIS_PER_ZEC = 100_000_000; +// Value pools, in the order the protocol introduced them. The pool types derive from these. +export const ZCASH_VALUE_POOL_IDS = [ + "transparent", + "sprout", + "sapling", + "orchard", + "lockbox", + "ironwood", +] as const; + +// Shielded pools a transaction can move value through +export const ZCASH_SHIELDED_POOLS = ["sprout", "sapling", "orchard", "ironwood"] as const; + +// Pools with a note commitment tree reported by getblock (Sprout has none) +export const ZCASH_TREE_POOLS = ["sapling", "orchard", "ironwood"] as const; + +export type ZcashNetworkKind = "mainnet" | "testnet"; + +/** + * Mainnet or testnet, from a CAIP-2 network ID. Address prefixes differ between the two. + */ +export function getZcashNetworkKind(networkId: string): ZcashNetworkKind { + return networkId === ZCASH_TESTNET ? "testnet" : "mainnet"; +} + // Transparent input values cost one getrawtransaction per previous transaction export const MAX_INPUT_LOOKUPS = 10; diff --git a/src/services/DataService.test.ts b/src/services/DataService.test.ts new file mode 100644 index 00000000..488a5ef1 --- /dev/null +++ b/src/services/DataService.test.ts @@ -0,0 +1,69 @@ +import { ZCASH_MAINNET } from "@openscan/network-connectors"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { NetworkConfig } from "../types"; +import { ZcashAdapter } from "./adapters/ZcashAdapter/ZcashAdapter"; +import { DataService } from "./DataService"; + +const ZCASH: NetworkConfig = { + type: "zcash", + networkId: ZCASH_MAINNET, + slug: "zec", + name: "Zcash", + shortName: "ZEC", + currency: "ZEC", +}; + +const BITCOIN: NetworkConfig = { + type: "bitcoin", + networkId: "bip122:000000000019d6689c085ae165831e93", + slug: "btc", + name: "Bitcoin", + shortName: "BTC", + currency: "BTC", +}; + +const T_ADDRESS = "t1KAuVfS2r2hc7RwSh6GTuyfqCGMFEpwkZ2"; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("DataService for Zcash networks", () => { + it("builds a ZcashAdapter for type zcash, even though Zcash shares the bip122 namespace", () => { + const service = new DataService(ZCASH, { [ZCASH_MAINNET]: ["https://zebra.test"] }); + + expect(service.isZcash()).toBe(true); + expect(service.isBitcoin()).toBe(false); + expect(service.getZcashAdapter()).toBeInstanceOf(ZcashAdapter); + expect(service.getZcashAdapter().getNetworkId()).toBe(ZCASH_MAINNET); + }); + + it("refuses a Zcash adapter on other networks", () => { + const service = new DataService(BITCOIN, { [BITCOIN.networkId]: ["https://btc.test"] }); + + expect(() => service.getZcashAdapter()).toThrow("Cannot get Zcash adapter"); + }); + + it("stops probing a method the endpoints rejected, across page instances", async () => { + const fetchMock = vi.fn(async () => ({ + ok: true, + status: 200, + json: async () => ({ + jsonrpc: "2.0", + id: 1, + error: { code: -32601, message: "Method not found" }, + }), + })); + vi.stubGlobal("fetch", fetchMock); + const rpcUrls = { [ZCASH_MAINNET]: ["https://zebra.test/unsupported-memo"] }; + + const first = await new DataService(ZCASH, rpcUrls).getZcashAdapter().getAddress(T_ADDRESS); + const callsAfterFirst = fetchMock.mock.calls.length; + const second = await new DataService(ZCASH, rpcUrls).getZcashAdapter().getAddress(T_ADDRESS); + + expect(first.balance).toEqual({ availability: "unsupported" }); + expect(callsAfterFirst).toBe(1); + expect(second.balance).toEqual({ availability: "unsupported" }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/services/DataService.ts b/src/services/DataService.ts index ecdf58fe..9d444b7f 100644 --- a/src/services/DataService.ts +++ b/src/services/DataService.ts @@ -15,7 +15,7 @@ import { AdapterFactory } from "./adapters/adaptersFactory"; import type { NetworkAdapter } from "./adapters/NetworkAdapter"; import type { BitcoinAdapter } from "./adapters/BitcoinAdapter/BitcoinAdapter"; import type { SolanaAdapter } from "./adapters/SolanaAdapter/SolanaAdapter"; -import type { ZcashAdapter } from "./adapters/ZcashAdapter/ZcashAdapter"; +import { getUnsupportedMethods, type ZcashAdapter } from "./adapters/ZcashAdapter/ZcashAdapter"; import type { NetworkConfig, NetworkType, RpcUrlsContextType } from "../types"; import { getRPCUrls } from "../config/rpcConfig"; import { getNetworkRpcKey, getChainIdFromNetwork } from "../utils/networkResolver"; @@ -84,7 +84,9 @@ export class DataService { rpcUrls, type: strategy, }); - this.zcashAdapter = AdapterFactory.createZcashAdapter(network.networkId, zcashClient); + this.zcashAdapter = AdapterFactory.createZcashAdapter(network.networkId, zcashClient, { + unsupportedMethods: getUnsupportedMethods(network.networkId, rpcUrls), + }); this.networkAdapter = null as unknown as NetworkAdapter; } else if (network.type === "solana") { // Create Solana client and adapter via ClientFactory diff --git a/src/services/MetadataService.test.ts b/src/services/MetadataService.test.ts new file mode 100644 index 00000000..987f622b --- /dev/null +++ b/src/services/MetadataService.test.ts @@ -0,0 +1,44 @@ +import { ZCASH_MAINNET, ZCASH_TESTNET } from "@openscan/network-connectors"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { fetchAllRpcs } from "./MetadataService"; + +const BITCOIN_MAINNET = "bip122:000000000019d6689c085ae165831e93"; + +function jsonResponse(body: unknown) { + return { ok: true, statusText: "OK", json: async () => body }; +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("fetchAllRpcs", () => { + it("maps Zcash genesis hashes to rpcs/zec before the Bitcoin mapping", async () => { + const fetchMock = vi.fn(async (url: string) => { + if (url.endsWith("/rpcs/all.json")) { + return jsonResponse({ + networks: [ + { networkId: ZCASH_MAINNET, endpointCount: 1 }, + { networkId: ZCASH_TESTNET, endpointCount: 1 }, + { networkId: BITCOIN_MAINNET, endpointCount: 1 }, + ], + }); + } + return jsonResponse({ endpoints: [{ url: `https://rpc.test/${url.split("/rpcs/")[1]}` }] }); + }); + vi.stubGlobal("fetch", fetchMock); + + const rpcs = await fetchAllRpcs(); + + const fetched = fetchMock.mock.calls.map(([url]) => url.split("/dist/")[1]); + expect(fetched).toEqual( + expect.arrayContaining([ + "rpcs/zec/mainnet.json", + "rpcs/zec/testnet.json", + "rpcs/btc/mainnet.json", + ]), + ); + expect(rpcs[ZCASH_MAINNET]?.[0]?.url).toBe("https://rpc.test/zec/mainnet.json"); + expect(rpcs[ZCASH_TESTNET]?.[0]?.url).toBe("https://rpc.test/zec/testnet.json"); + }); +}); diff --git a/src/services/adapters/ZcashAdapter/ZcashAdapter.test.ts b/src/services/adapters/ZcashAdapter/ZcashAdapter.test.ts index 84b9621d..a211df80 100644 --- a/src/services/adapters/ZcashAdapter/ZcashAdapter.test.ts +++ b/src/services/adapters/ZcashAdapter/ZcashAdapter.test.ts @@ -1,7 +1,7 @@ import type { ZcashClient } from "@openscan/network-connectors"; -import { describe, expect, it, vi } from "vitest"; -import type { ZcashTransaction } from "../../../types"; -import { computeFeeZat } from "../../../utils/zcashUtils"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { RPCMetadata, ZcashTransaction } from "../../../types"; +import { computeFee } from "../../../utils/zcashUtils"; import { BLOCK_3483400, COINBASE_TX, @@ -9,11 +9,13 @@ import { SAPLING_IRONWOOD_TX, SHIELDING_TX, } from "./fixtures"; -import { ZcashAdapter, ZcashRpcError } from "./ZcashAdapter"; +import type { ZcashRawBlock, ZcashRawTransaction } from "./utils"; +import { getUnsupportedMethods, ZcashAdapter, ZcashRpcError } from "./ZcashAdapter"; const NETWORK_ID = "bip122:00040fe8ec8471911baa1db1266ea15d"; const T_ADDRESS = "t1KAuVfS2r2hc7RwSh6GTuyfqCGMFEpwkZ2"; const METHOD_NOT_FOUND = "RPC error: Method not found: getaddressbalance"; +const RATE_LIMITED = "HTTP error! status: 429"; const ok = (data: T) => ({ success: true, data }); const fail = (...errors: string[]) => ({ @@ -41,13 +43,20 @@ function createClient() { }; } -function setup() { +function setup(unsupportedMethods = new Set()) { const client = createClient(); const sleep = vi.fn().mockResolvedValue(undefined); - const adapter = new ZcashAdapter(NETWORK_ID, client as unknown as ZcashClient, { sleep }); + const adapter = new ZcashAdapter(NETWORK_ID, client as unknown as ZcashClient, { + sleep, + unsupportedMethods, + }); return { adapter, client, sleep }; } +afterEach(() => { + vi.useRealTimers(); +}); + function findTx(transactions: ZcashTransaction[], txid: string | undefined): ZcashTransaction { const match = transactions.find((transaction) => transaction.txid === txid); if (!match) throw new Error(`Transaction ${txid} not found`); @@ -82,13 +91,68 @@ describe("ZcashAdapter blocks", () => { const { transactions } = (await adapter.getBlock(3483400)).data; - expect(computeFeeZat(findTx(transactions, IRONWOOD_ONLY_TX.txid))).toBe(10_000); - expect(computeFeeZat(findTx(transactions, SAPLING_IRONWOOD_TX.txid))).toBe(20_000); - expect(computeFeeZat(findTx(transactions, SHIELDING_TX.txid))).toBeNull(); - expect(computeFeeZat(findTx(transactions, COINBASE_TX.txid))).toBeNull(); + expect(computeFee(findTx(transactions, IRONWOOD_ONLY_TX.txid))).toEqual({ + kind: "known", + zat: 10_000, + }); + expect(computeFee(findTx(transactions, SAPLING_IRONWOOD_TX.txid))).toEqual({ + kind: "known", + zat: 20_000, + }); + expect(computeFee(findTx(transactions, SHIELDING_TX.txid))).toEqual({ kind: "unknown" }); + expect(computeFee(findTx(transactions, COINBASE_TX.txid))).toEqual({ kind: "coinbase" }); + }); + + it("reports a transparent coinbase as paying nothing into the shielded pools", async () => { + const { adapter, client } = setup(); + client.getBlock.mockResolvedValue(ok(BLOCK_3483400)); + + const { block } = (await adapter.getBlock(3483400)).data; + + expect(block.coinbaseShieldedZat).toBe(0); + }); + + it("adds a shielded coinbase reward from the value entering the pools", async () => { + const { adapter, client } = setup(); + const shieldedCoinbase: ZcashRawTransaction = { + ...COINBASE_TX, + vout: COINBASE_TX.vout.slice(1), + orchard: { actions: [{}, {}], valueBalanceZat: -125_490_751 }, + }; + const block: ZcashRawBlock = { + ...BLOCK_3483400, + tx: [shieldedCoinbase, ...BLOCK_3483400.tx.slice(1)], + }; + client.getBlock.mockResolvedValue(ok(block)); + + const { data } = await adapter.getBlock(3483400); + + expect(data.block.coinbaseShieldedZat).toBe(125_490_751); + expect(data.block.coinbaseOutputs).toEqual([ + { address: "t3cFfPt1Bcvgez9ZbMBFWeZsskxTkPzGCow", valueZat: 12_500_000 }, + ]); + }); + + it("transforms each provider's response in parallel mode", async () => { + const { adapter, client } = setup(); + const metadata: RPCMetadata = { + strategy: "parallel", + timestamp: 0, + hasInconsistencies: false, + responses: [ + { url: "https://a.test", status: "success", responseTime: 1, data: BLOCK_3483400 }, + { url: "https://b.test", status: "error", responseTime: 1, error: "timeout" }, + ], + }; + client.getBlock.mockResolvedValue({ ...ok(BLOCK_3483400), metadata }); + + const result = await adapter.getBlock(3483400); + + expect(result.metadata?.responses[0]?.data.block.height).toBe(3483400); + expect(result.metadata?.responses[1]).toEqual(metadata.responses[1]); }); - it("fetches block summaries one at a time and skips blocks that fail", async () => { + it("fetches block summaries one at a time and reports blocks that fail", async () => { const { adapter, client } = setup(); const summary = (height: number) => ({ ...BLOCK_3483400, height, tx: ["a".repeat(64)] }); client.getBlock @@ -96,7 +160,7 @@ describe("ZcashAdapter blocks", () => { .mockResolvedValueOnce(fail("RPC error: Block not found")) .mockResolvedValueOnce(ok(summary(3483400))); - const blocks = await adapter.getBlockSummaries([3483399, 3483398, 3483400]); + const { blocks, failedHeights } = await adapter.getBlockSummaries([3483399, 3483398, 3483400]); expect(client.getBlock.mock.calls).toEqual([ ["3483399", 1], @@ -105,6 +169,20 @@ describe("ZcashAdapter blocks", () => { ]); expect(blocks.map((block) => block.height)).toEqual([3483400, 3483399]); expect(blocks[0]?.txids).toEqual(["a".repeat(64)]); + expect(failedHeights).toEqual([3483398]); + }); + + it("stops fetching summaries once a block stays rate limited", async () => { + const { adapter, client, sleep } = setup(); + client.getBlock.mockResolvedValue(fail(RATE_LIMITED)); + + const { blocks, failedHeights } = await adapter.getBlockSummaries([10, 9, 8]); + + // One block: the first attempt plus two retries, then the rest are reported untried + expect(client.getBlock).toHaveBeenCalledTimes(3); + expect(sleep).toHaveBeenCalledTimes(2); + expect(blocks).toEqual([]); + expect(failedHeights).toEqual([10, 9, 8]); }); }); @@ -124,6 +202,30 @@ describe("ZcashAdapter transactions", () => { }); }); + it("sums Sprout JoinSplit public values, preferring the integer zatoshi fields", async () => { + const { adapter, client } = setup(); + const sproutTx: ZcashRawTransaction = { + txid: "9".repeat(64), + version: 2, + vin: [], + vout: [], + vjoinsplit: [ + { vpub_old: 0, vpub_new: 0.4, vpub_newZat: 40_000_000 }, + { vpub_old: 0.10000001, vpub_new: 0 }, + ], + }; + client.getRawTransaction.mockResolvedValue(ok(sproutTx)); + + const { data } = await adapter.getTransaction(sproutTx.txid ?? ""); + + expect(data.shielded.sprout).toEqual({ + joinSplits: 2, + vpubOldZat: 10_000_001, + vpubNewZat: 40_000_000, + }); + expect(computeFee(data)).toEqual({ kind: "known", zat: 29_999_999 }); + }); + describe("resolveTransparentInputs", () => { const firstTxid = "c".repeat(64); const secondTxid = "d".repeat(64); @@ -160,22 +262,47 @@ describe("ZcashAdapter transactions", () => { const result = await adapter.resolveTransparentInputs(spending, { onProgress }); expect(client.getRawTransaction).toHaveBeenCalledTimes(2); - expect(result).toMatchObject({ resolved: 2, total: 2 }); + expect(result).toMatchObject({ resolved: 2, total: 2, exceedsCap: false }); expect(onProgress).toHaveBeenLastCalledWith(2, 2); expect(result.transaction.vin.map((vin) => vin.valueZat)).toEqual([30_000, 20_000, 20_000]); expect(result.transaction.vin[0]?.address).toBe(T_ADDRESS); - expect(computeFeeZat(result.transaction)).toBe(10_000); + expect(computeFee(result.transaction)).toEqual({ kind: "known", zat: 10_000 }); }); - it("stops at the lookup cap and leaves the fee unknown", async () => { + it("spends no calls when the inputs exceed the lookup cap", async () => { const { adapter, client } = setup(); - client.getRawTransaction.mockResolvedValue(ok(previousTx(firstTxid, [0.0003, 0.0002]))); const result = await adapter.resolveTransparentInputs(spending, { max: 1 }); - expect(client.getRawTransaction).toHaveBeenCalledTimes(1); - expect(result).toMatchObject({ resolved: 1, total: 2 }); - expect(computeFeeZat(result.transaction)).toBeNull(); + expect(client.getRawTransaction).not.toHaveBeenCalled(); + expect(result).toMatchObject({ resolved: 0, total: 2, exceedsCap: true }); + expect(computeFee(result.transaction)).toEqual({ kind: "unknown" }); + }); + + it("keeps inputs resolved before a failure and resumes from them", async () => { + const { adapter, client } = setup(); + client.getRawTransaction + .mockResolvedValueOnce(ok(previousTx(firstTxid, [0.0003, 0.0002]))) + .mockResolvedValueOnce(fail("HTTP error! status: 502")); + + const partial = await adapter.resolveTransparentInputs(spending); + + expect(partial).toMatchObject({ resolved: 1, total: 2, exceedsCap: false }); + expect(partial.error).toBeInstanceOf(ZcashRpcError); + expect(partial.transaction.vin.map((vin) => vin.valueZat)).toEqual([ + 30_000, + 20_000, + undefined, + ]); + + client.getRawTransaction.mockResolvedValueOnce(ok(previousTx(secondTxid, [0.0002]))); + const resumed = await adapter.resolveTransparentInputs(partial.transaction); + + expect(client.getRawTransaction).toHaveBeenLastCalledWith(secondTxid, 1); + expect(client.getRawTransaction).toHaveBeenCalledTimes(3); + expect(resumed).toMatchObject({ resolved: 2, total: 2 }); + expect(resumed.error).toBeUndefined(); + expect(computeFee(resumed.transaction)).toEqual({ kind: "known", zat: 10_000 }); }); }); }); @@ -188,7 +315,7 @@ describe("ZcashAdapter RPC failures", () => { .mockResolvedValueOnce(ok(3483464)); await expect(adapter.getLatestBlockNumber()).resolves.toBe(3483464); - expect(sleep).toHaveBeenCalledWith(15_000); + expect(sleep).toHaveBeenCalledWith(15_000, undefined); }); it("gives up after the last backoff", async () => { @@ -199,7 +326,7 @@ describe("ZcashAdapter RPC failures", () => { name: "ZcashRpcError", kind: "rateLimited", }); - expect(sleep.mock.calls).toEqual([[15_000], [30_000]]); + expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([15_000, 30_000]); expect(client.getBlockCount).toHaveBeenCalledTimes(3); }); @@ -213,6 +340,79 @@ describe("ZcashAdapter RPC failures", () => { expect(error).toMatchObject({ kind: "failed", messages: ["RPC error: Block not found"] }); expect(sleep).not.toHaveBeenCalled(); }); + + it("returns a definitive answer without waiting on a rate-limited endpoint", async () => { + const { adapter, client, sleep } = setup(); + client.getRawTransaction.mockResolvedValue( + fail("RPC error: No such mempool or main chain transaction", RATE_LIMITED), + ); + + await expect(adapter.getTransaction("a".repeat(64))).rejects.toMatchObject({ kind: "failed" }); + expect(sleep).not.toHaveBeenCalled(); + expect(client.getRawTransaction).toHaveBeenCalledTimes(1); + }); + + it("retries concurrent rate-limited calls and still combines their results", async () => { + const { adapter, client, sleep } = setup(); + client.getBlockchainInfo + .mockResolvedValueOnce(fail(RATE_LIMITED)) + .mockResolvedValueOnce( + ok({ chain: "main", blocks: 1, bestblockhash: "0".repeat(64), difficulty: 1 }), + ); + client.getMempoolInfo + .mockResolvedValueOnce(fail(RATE_LIMITED)) + .mockResolvedValueOnce(ok({ size: 2, bytes: 300, usage: 0 })); + + const { data } = await adapter.getNetworkStats(); + + expect(sleep.mock.calls).toEqual([ + [15_000, undefined], + [15_000, undefined], + ]); + expect(data).toMatchObject({ blockHeight: 1, mempoolSize: 2 }); + }); + + it("stops waiting to retry when aborted", async () => { + vi.useFakeTimers(); + const client = createClient(); + const adapter = new ZcashAdapter(NETWORK_ID, client as unknown as ZcashClient); + client.getBlockCount.mockResolvedValue(fail(RATE_LIMITED)); + const controller = new AbortController(); + + const pending = adapter.getLatestBlockNumber({ signal: controller.signal }); + const outcome = pending.catch((caught: unknown) => caught); + await vi.advanceTimersByTimeAsync(5_000); + controller.abort(); + + expect(await outcome).toMatchObject({ name: "AbortError" }); + await vi.advanceTimersByTimeAsync(60_000); + expect(client.getBlockCount).toHaveBeenCalledTimes(1); + }); + + it("doesn't send a call that was aborted before it started", async () => { + const { adapter, client } = setup(); + const controller = new AbortController(); + controller.abort(); + + await expect(adapter.getBlock(1, { signal: controller.signal })).rejects.toMatchObject({ + name: "AbortError", + }); + expect(client.getBlock).not.toHaveBeenCalled(); + }); + + it("remembers unsupported methods across adapters sharing an endpoint list", async () => { + const unsupported = getUnsupportedMethods(NETWORK_ID, ["https://rpc.test/remember"]); + const first = setup(unsupported); + first.client.getAddressBalance.mockResolvedValue(fail(METHOD_NOT_FOUND)); + await first.adapter.getAddress(T_ADDRESS); + + const second = setup(getUnsupportedMethods(NETWORK_ID, ["https://rpc.test/remember"])); + const result = await second.adapter.getAddress(T_ADDRESS); + + expect(result.balance).toEqual({ availability: "unsupported" }); + expect(second.client.getAddressBalance).not.toHaveBeenCalled(); + expect(getUnsupportedMethods(NETWORK_ID, ["https://other.test"]).size).toBe(0); + }); }); describe("ZcashAdapter addresses", () => { @@ -225,6 +425,9 @@ describe("ZcashAdapter addresses", () => { const result = await adapter.getAddress(T_ADDRESS); expect(client.getAddressBalance).toHaveBeenCalledWith({ addresses: [T_ADDRESS] }); + // The three methods share the address index, so one probe is enough + expect(client.getAddressUtxos).not.toHaveBeenCalled(); + expect(client.getAddressTxIds).not.toHaveBeenCalled(); expect(result).toEqual({ address: T_ADDRESS, type: "p2pkh", @@ -238,13 +441,46 @@ describe("ZcashAdapter addresses", () => { it("reports other address index failures as errors", async () => { const { adapter, client } = setup(); client.getAddressBalance.mockResolvedValue(fail("RPC error: invalid address")); - client.getAddressUtxos.mockResolvedValue(ok([])); - client.getAddressTxIds.mockResolvedValue(ok([])); const result = await adapter.getAddress(T_ADDRESS); expect(result.balance).toEqual({ availability: "error" }); - expect(result.utxos).toEqual({ availability: "ok", data: [] }); + expect(result.utxos).toEqual({ availability: "error" }); + expect(result.txids).toEqual({ availability: "error" }); + expect(client.getAddressUtxos).not.toHaveBeenCalled(); + }); + + it("reports one section's failure when the index is available", async () => { + const { adapter, client } = setup(); + client.getAddressBalance.mockResolvedValue(ok({ balance: 5 })); + client.getAddressUtxos.mockResolvedValue(fail("RPC error: index busy")); + client.getAddressTxIds.mockResolvedValue(ok([])); + + const result = await adapter.getAddress(T_ADDRESS); + + expect(result.utxos).toEqual({ availability: "error" }); + expect(result.txids).toEqual({ availability: "ok", data: [] }); + }); + + it("makes no RPC calls for an address of the other network", async () => { + const { adapter, client } = setup(); + const testnetAddress = `tm${"a".repeat(33)}`; + + const result = await adapter.getAddress(testnetAddress); + + expect(result).toEqual({ address: testnetAddress, type: "unknown" }); + expect(client.getAddressBalance).not.toHaveBeenCalled(); + }); + + it("normalizes an all-uppercase unified address before querying it", async () => { + const { adapter, client } = setup(); + const unified = `u1${"q".repeat(100)}`; + client.zListUnifiedReceivers.mockResolvedValue(ok({ orchard: `u1${"p".repeat(60)}` })); + + const result = await adapter.getAddress(unified.toUpperCase()); + + expect(client.zListUnifiedReceivers).toHaveBeenCalledWith(unified); + expect(result).toMatchObject({ address: unified, type: "unified" }); }); it("maps address index data when the node exposes it", async () => { diff --git a/src/services/adapters/ZcashAdapter/ZcashAdapter.ts b/src/services/adapters/ZcashAdapter/ZcashAdapter.ts index 3c069b4d..c6ab533c 100644 --- a/src/services/adapters/ZcashAdapter/ZcashAdapter.ts +++ b/src/services/adapters/ZcashAdapter/ZcashAdapter.ts @@ -1,5 +1,9 @@ import type { ZcashClient } from "@openscan/network-connectors"; -import { MAX_INPUT_LOOKUPS, RATE_LIMIT_RETRY_DELAYS_MS } from "../../../config/zcashConstants"; +import { + getZcashNetworkKind, + MAX_INPUT_LOOKUPS, + RATE_LIMIT_RETRY_DELAYS_MS, +} from "../../../config/zcashConstants"; import type { DataWithMetadata, ZcashAddress, @@ -14,10 +18,12 @@ import { logger } from "../../../utils/logger"; import { classifyRpcErrors, detectZcashAddressType, + normalizeZcashAddress, type ZcashRpcErrorKind, } from "../../../utils/zcashUtils"; import { applyResolvedInputs, + mapMetadata, transformBlock, transformBlockSummary, transformMempoolEntries, @@ -55,12 +61,75 @@ export class ZcashRpcError extends Error { } } +/** + * Per-call options. Aborting stops retry waits and any call not yet sent; a request already in + * flight still completes (the connector can't cancel it), but its result is discarded. + */ +export interface ZcashCallOptions { + signal?: AbortSignal; +} + export interface ZcashAdapterOptions { /** Wait between rate-limit retries (injectable for tests) */ - sleep?: (ms: number) => Promise; + sleep?: (ms: number, signal?: AbortSignal) => Promise; + /** + * Methods the configured endpoints reported as unsupported. Share one set per endpoint list + * (see getUnsupportedMethods) so pages stop probing methods a gateway blocks. + */ + unsupportedMethods?: Set; } -const defaultSleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +export interface ZcashBlockSummaries { + /** Newest first */ + blocks: ZcashBlock[]; + /** Heights that couldn't be fetched, so pages can show them instead of leaving gaps */ + failedHeights: number[]; +} + +export interface ZcashInputResolution { + transaction: ZcashTransaction; + /** Previous transactions whose outputs are known (including ones resolved earlier) */ + resolved: number; + /** Distinct previous transactions the inputs spend */ + total: number; + /** More previous transactions than the lookup cap: nothing was fetched */ + exceedsCap: boolean; + /** Set when a lookup failed; inputs resolved before it are kept, so a retry resumes */ + error?: unknown; +} + +const defaultSleep = (ms: number, signal?: AbortSignal) => + new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason); + return; + } + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason); + }; + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + signal?.addEventListener("abort", onAbort, { once: true }); + }); + +const unsupportedByEndpoints = new Map>(); + +/** + * The session-wide set of unsupported methods for one network and endpoint list. A new + * DataService is created per page, so the set lives here rather than on the adapter. + */ +export function getUnsupportedMethods(networkId: string, rpcUrls: string[]): Set { + const key = `${networkId}|${rpcUrls.join(",")}`; + let methods = unsupportedByEndpoints.get(key); + if (!methods) { + methods = new Set(); + unsupportedByEndpoints.set(key, methods); + } + return methods; +} function mapSection(section: ZcashRpcSection, map: (data: T) => U): ZcashRpcSection { return section.data === undefined @@ -73,17 +142,19 @@ function mapSection(section: ZcashRpcSection, map: (data: T) => U): Zca * * Hosted gateways allow only a few requests per minute, so methods spend as few calls as * possible: heights go straight to getblock as decimal strings (no getblockhash round trip), - * and block data comes from a single getblock call. + * block data comes from a single getblock call, and methods a gateway rejects are remembered. */ export class ZcashAdapter { readonly networkId: string; private client: ZcashClient; - private sleep: (ms: number) => Promise; + private sleep: (ms: number, signal?: AbortSignal) => Promise; + private unsupportedMethods: Set; constructor(networkId: string, client: ZcashClient, options: ZcashAdapterOptions = {}) { this.networkId = networkId; this.client = client; this.sleep = options.sleep ?? defaultSleep; + this.unsupportedMethods = options.unsupportedMethods ?? new Set(); } /** @@ -102,14 +173,24 @@ export class ZcashAdapter { /** * Run an RPC call, retrying rate-limited failures with backoff. - * Throws ZcashRpcError when every endpoint fails, rather than returning empty data. + * Throws ZcashRpcError when every endpoint fails, rather than returning empty data, and the + * signal's reason when aborted. */ private async call( method: string, request: () => Promise>, + signal?: AbortSignal, ): Promise> { + if (this.unsupportedMethods.has(method)) { + throw new ZcashRpcError(method, "unsupported", [ + `${method} is not supported by the configured endpoints`, + ]); + } + for (let attempt = 0; ; attempt++) { + signal?.throwIfAborted(); const result = await request(); + signal?.throwIfAborted(); if (result.success) { return { data: result.data as T, @@ -121,13 +202,15 @@ export class ZcashAdapter { response.error ? [response.error] : [], ); const kind = classifyRpcErrors(messages); + if (kind === "unsupported") this.unsupportedMethods.add(method); + const delay = RATE_LIMIT_RETRY_DELAYS_MS[attempt]; if (kind !== "rateLimited" || delay === undefined) { throw new ZcashRpcError(method, kind, messages); } logger.warn(`Zcash ${method} was rate limited, retrying in ${delay / 1000}s`); - await this.sleep(delay); + await this.sleep(delay, signal); } } @@ -138,11 +221,13 @@ export class ZcashAdapter { private async section( method: string, request: () => Promise>, + signal?: AbortSignal, ): Promise> { try { - const { data } = await this.call(method, request); + const { data } = await this.call(method, request, signal); return { availability: "ok", data }; } catch (error) { + if (signal?.aborted) throw error; if (error instanceof ZcashRpcError && error.kind === "unsupported") { return { availability: "unsupported" }; } @@ -154,21 +239,36 @@ export class ZcashAdapter { /** * Get the latest block height (1 call) */ - async getLatestBlockNumber(): Promise { - const { data } = await this.call("getblockcount", () => this.client.getBlockCount()); + async getLatestBlockNumber(options: ZcashCallOptions = {}): Promise { + const { data } = await this.call( + "getblockcount", + () => this.client.getBlockCount(), + options.signal, + ); return data; } /** * Get chain, value pool and mempool statistics (2 calls) */ - async getNetworkStats(): Promise> { + async getNetworkStats( + options: ZcashCallOptions = {}, + ): Promise> { const [info, mempool] = await Promise.all([ - this.call("getblockchaininfo", () => this.client.getBlockchainInfo()), - this.call("getmempoolinfo", () => this.client.getMempoolInfo()), + this.call( + "getblockchaininfo", + () => this.client.getBlockchainInfo(), + options.signal, + ), + this.call("getmempoolinfo", () => this.client.getMempoolInfo(), options.signal), ]); - return { data: transformNetworkStats(info.data, mempool.data), metadata: info.metadata }; + return { + data: transformNetworkStats(info.data, mempool.data), + metadata: mapMetadata(info.metadata, (raw: ZcashRawBlockchainInfo) => + transformNetworkStats(raw, mempool.data), + ), + }; } /** @@ -176,103 +276,163 @@ export class ZcashAdapter { */ async getBlock( hashOrHeight: string | number, + options: ZcashCallOptions = {}, ): Promise> { - const result = await this.call("getblock", () => - this.client.getBlock(String(hashOrHeight), 2), + const result = await this.call( + "getblock", + () => this.client.getBlock(String(hashOrHeight), 2), + options.signal, ); - return { data: transformBlock(result.data), metadata: result.metadata }; + return { + data: transformBlock(result.data), + metadata: mapMetadata(result.metadata, transformBlock), + }; } /** * Get lightweight block summaries (1 call per block). Requests run one at a time so they - * don't burst past hosted rate limits; blocks that still fail are skipped. + * don't burst past hosted rate limits. Failed heights are reported, not dropped; once a call + * stays rate limited after its retries, the remaining heights are reported without trying. */ - async getBlockSummaries(heights: number[]): Promise { + async getBlockSummaries( + heights: number[], + options: ZcashCallOptions = {}, + ): Promise { const blocks: ZcashBlock[] = []; + const failedHeights: number[] = []; - for (const height of heights) { + for (const [index, height] of heights.entries()) { try { - const { data } = await this.call("getblock", () => - this.client.getBlock(String(height), 1), + const { data } = await this.call( + "getblock", + () => this.client.getBlock(String(height), 1), + options.signal, ); blocks.push(transformBlockSummary(data)); } catch (error) { + if (options.signal?.aborted) throw error; logger.warn(`Failed to fetch Zcash block ${height}:`, error); + if (error instanceof ZcashRpcError && error.kind === "rateLimited") { + failedHeights.push(...heights.slice(index)); + break; + } + failedHeights.push(height); } } - return blocks.sort((a, b) => b.height - a.height); - } - - /** - * Get all transactions of a block (1 call) - */ - async getBlockTransactions(height: number): Promise { - const { data } = await this.getBlock(height); - return data.transactions; + return { blocks: blocks.sort((a, b) => b.height - a.height), failedHeights }; } /** * Get a confirmed or mempool transaction (1 call) */ - async getTransaction(txid: string): Promise> { - const result = await this.call("getrawtransaction", () => - this.client.getRawTransaction(txid, 1), + async getTransaction( + txid: string, + options: ZcashCallOptions = {}, + ): Promise> { + const result = await this.call( + "getrawtransaction", + () => this.client.getRawTransaction(txid, 1), + options.signal, ); - return { data: transformTransaction(result.data), metadata: result.metadata }; + return { + data: transformTransaction(result.data), + metadata: mapMetadata(result.metadata, transformTransaction), + }; } /** * Fill in transparent input values and addresses by fetching the transactions they spend. * Zebra omits them from verbose transactions, so this costs one call per previous - * transaction (capped) and is meant to run on demand. + * transaction and is meant to run on demand. + * + * - Over the cap, nothing is fetched: the fee couldn't be computed anyway. + * - Inputs that already carry a value are skipped, so passing a partly resolved transaction + * resumes where a failed run stopped. */ async resolveTransparentInputs( tx: ZcashTransaction, - options: { max?: number; onProgress?: (resolved: number, total: number) => void } = {}, - ): Promise<{ transaction: ZcashTransaction; resolved: number; total: number }> { - const { max = MAX_INPUT_LOOKUPS, onProgress } = options; - const previousTxids = [...new Set(tx.vin.flatMap((input) => (input.txid ? [input.txid] : [])))]; - const previous = new Map(); + options: ZcashCallOptions & { + max?: number; + onProgress?: (resolved: number, total: number) => void; + } = {}, + ): Promise { + const { max = MAX_INPUT_LOOKUPS, onProgress, signal } = options; + const distinct = (txids: Array) => + [...new Set(txids)].filter((txid): txid is string => txid !== undefined); + + const previousTxids = distinct(tx.vin.map((input) => input.txid)); + const pending = distinct( + tx.vin.map((input) => (input.valueZat === undefined ? input.txid : undefined)), + ); + const total = previousTxids.length; + let resolved = total - pending.length; - for (const previousTxid of previousTxids.slice(0, max)) { - const { data } = await this.getTransaction(previousTxid); - previous.set(previousTxid, data); - onProgress?.(previous.size, previousTxids.length); + if (total > max) { + return { transaction: tx, resolved, total, exceedsCap: true }; + } + + const previous = new Map(); + let error: unknown; + for (const previousTxid of pending) { + try { + const { data } = await this.getTransaction(previousTxid, { signal }); + previous.set(previousTxid, data); + resolved++; + onProgress?.(resolved, total); + } catch (caught) { + if (signal?.aborted) throw caught; + error = caught; + break; + } } return { transaction: applyResolvedInputs(tx, previous), - resolved: previous.size, - total: previousTxids.length, + resolved, + total, + exceedsCap: false, + error, }; } /** * Get pending transactions, highest fee rate first (1 call) */ - async getMempoolEntries(): Promise> { - const result = await this.call>("getrawmempool", () => - this.client.getRawMempool(true), + async getMempoolEntries( + options: ZcashCallOptions = {}, + ): Promise> { + const result = await this.call>( + "getrawmempool", + () => this.client.getRawMempool(true), + options.signal, ); - return { data: transformMempoolEntries(result.data), metadata: result.metadata }; + return { + data: transformMempoolEntries(result.data), + metadata: mapMetadata(result.metadata, transformMempoolEntries), + }; } /** * Get address data. Balance, UTXOs and history come from Zebra's address index, which hosted - * gateways block, so each section reports its own availability. + * gateways block, so each section reports its own availability. The balance is asked first: + * the three methods share the index, so when it's unavailable the others aren't requested. */ - async getAddress(address: string): Promise { - const type = detectZcashAddressType(address); - const result: ZcashAddress = { address, type }; + async getAddress(address: string, options: ZcashCallOptions = {}): Promise { + const { signal } = options; + const normalized = normalizeZcashAddress(address); + const type = detectZcashAddressType(normalized, getZcashNetworkKind(this.networkId)); + const result: ZcashAddress = { address: normalized, type }; if (type === "unified") { - result.receivers = await this.section("z_listunifiedreceivers", () => - this.client.zListUnifiedReceivers(address), + result.receivers = await this.section( + "z_listunifiedreceivers", + () => this.client.zListUnifiedReceivers(normalized), + signal, ); result.transparentAddress = result.receivers.data?.p2pkh ?? result.receivers.data?.p2sh; } else if (type === "p2pkh" || type === "p2sh") { - result.transparentAddress = address; + result.transparentAddress = normalized; } if (!result.transparentAddress) { @@ -280,16 +440,26 @@ export class ZcashAdapter { } const request = { addresses: [result.transparentAddress] }; - const [balance, utxos, txids] = await Promise.all([ - this.section("getaddressbalance", () => this.client.getAddressBalance(request)), - this.section("getaddressutxos", () => this.client.getAddressUtxos(request)), - this.section("getaddresstxids", () => this.client.getAddressTxIds(request)), - ]); - + const balance = await this.section( + "getaddressbalance", + () => this.client.getAddressBalance(request), + signal, + ); result.balance = mapSection(balance, (data) => ({ balanceZat: data.balance, receivedZat: data.received, })); + + if (balance.availability !== "ok") { + result.utxos = { availability: balance.availability }; + result.txids = { availability: balance.availability }; + return result; + } + + const [utxos, txids] = await Promise.all([ + this.section("getaddressutxos", () => this.client.getAddressUtxos(request), signal), + this.section("getaddresstxids", () => this.client.getAddressTxIds(request), signal), + ]); result.utxos = mapSection(utxos, (data) => data.map((utxo) => ({ txid: utxo.txid, diff --git a/src/services/adapters/ZcashAdapter/utils.ts b/src/services/adapters/ZcashAdapter/utils.ts index a6e2ac8e..ecd90aad 100644 --- a/src/services/adapters/ZcashAdapter/utils.ts +++ b/src/services/adapters/ZcashAdapter/utils.ts @@ -1,4 +1,19 @@ import type { + ZecBlock, + ZecBlockchainInfo, + ZecChainSupply, + ZecJoinSplit, + ZecMempoolEntry, + ZecOrchardBundle, + ZecRawTransaction, + ZecScriptPubKey, + ZecValuePoolBalance, + ZecVin, + ZecVout, +} from "@openscan/network-connectors"; +import { ZCASH_TREE_POOLS, ZCASH_VALUE_POOL_IDS } from "../../../config/zcashConstants"; +import type { + DataWithMetadata, ZcashActionBundle, ZcashBlock, ZcashBlockWithTransactions, @@ -7,10 +22,13 @@ import type { ZcashShieldedBundles, ZcashShieldedPool, ZcashTransaction, + ZcashTreePool, + ZcashTreeSizes, ZcashValuePool, ZcashValuePoolId, } from "../../../types"; import { + getShieldedNetZat, getShieldedPools, getTransparentOutputZat, isCoinbaseTransaction, @@ -18,132 +36,122 @@ import { } from "../../../utils/zcashUtils"; /* - * Raw Zebra RPC shapes, limited to the fields the explorer reads. They are looser than the - * connector's types on purpose: they also cover the NU6.3 Ironwood bundle and note commitment - * tree, which @openscan/network-connectors does not model yet. + * Raw Zebra RPC shapes, limited to the fields the explorer reads. They are picked from the + * connector's types so renamed fields fail to compile, and loosened where Zebra omits fields + * or where the NU6.3 Ironwood bundle and note commitment tree aren't modelled upstream yet. */ -export interface ZcashRawActionBundle { +export type ZcashRawActionBundle = Partial< + Pick +> & { actions?: unknown[]; - valueBalance?: number; - valueBalanceZat?: number; -} +}; -export interface ZcashRawVin { - txid?: string; - vout?: number; - coinbase?: string; - sequence: number; -} +export type ZcashRawVin = Pick; -export interface ZcashRawVout { - value: number; - valueZat?: number; - n: number; - scriptPubKey: { type: string; addresses?: string[] }; -} +export type ZcashRawVout = Pick & { + scriptPubKey: Pick; +}; -export interface ZcashRawJoinSplit { - vpub_old: number; - vpub_new: number; - vpub_oldZat?: number; - vpub_newZat?: number; -} +export type ZcashRawJoinSplit = Pick< + ZecJoinSplit, + "vpub_old" | "vpub_new" | "vpub_oldZat" | "vpub_newZat" +>; -export interface ZcashRawTransaction { - txid?: string; - size?: number; - version?: number; - versiongroupid?: string; - locktime?: number; - expiryheight?: number; +export type ZcashRawTransaction = Pick< + ZecRawTransaction, + | "txid" + | "size" + | "version" + | "versiongroupid" + | "locktime" + | "expiryheight" + | "valueBalance" + | "valueBalanceZat" + | "blockhash" + | "height" + | "confirmations" + | "time" + | "blocktime" +> & { vin: ZcashRawVin[]; vout: ZcashRawVout[]; - valueBalance?: number; - valueBalanceZat?: number; vShieldedSpend?: unknown[]; vShieldedOutput?: unknown[]; vjoinsplit?: ZcashRawJoinSplit[]; orchard?: ZcashRawActionBundle; - ironwood?: ZcashRawActionBundle; - blockhash?: string; - height?: number; - confirmations?: number; - time?: number; - blocktime?: number; -} + ironwood?: ZcashRawActionBundle; // NU6.3, not in the connector yet +}; -export interface ZcashRawValuePool { - id: string; - chainValueZat: number; -} +// Pool ids stay strings: a newer node may report pools this explorer doesn't know +export type ZcashRawValuePool = Pick & { id: string }; -interface ZcashRawBlockCommon { - hash: string; - confirmations?: number; - height: number; - version: number; - merkleroot: string; - blockcommitments?: string; - finalsaplingroot?: string; - finalorchardroot?: string; - time: number; - nonce: string; - solution?: string; - bits: string; - difficulty: number; - previousblockhash?: string; - nextblockhash?: string; - size?: number; - nTx?: number; - trees?: { - sapling?: { size: number }; - orchard?: { size: number }; - ironwood?: { size: number }; +type ZcashRawBlockCommon = Pick< + ZecBlock, + | "hash" + | "height" + | "version" + | "merkleroot" + | "finalorchardroot" + | "time" + | "nonce" + | "bits" + | "difficulty" + | "previousblockhash" + | "nextblockhash" + | "size" + | "nTx" +> & + Partial< + Pick + > & { + trees?: Partial>; + chainSupply?: Pick; + valuePools?: ZcashRawValuePool[]; }; - chainSupply?: { chainValueZat: number }; - valuePools?: ZcashRawValuePool[]; -} /** getblock with verbosity 1 (transaction ids only) */ -export interface ZcashRawBlockSummary extends ZcashRawBlockCommon { - tx: string[]; -} +export type ZcashRawBlockSummary = ZcashRawBlockCommon & { tx: string[] }; /** getblock with verbosity 2 (full transactions) */ -export interface ZcashRawBlock extends ZcashRawBlockCommon { - tx: ZcashRawTransaction[]; -} +export type ZcashRawBlock = ZcashRawBlockCommon & { tx: ZcashRawTransaction[] }; -export interface ZcashRawBlockchainInfo { - chain: string; - blocks: number; - bestblockhash: string; - difficulty: number; - estimatedheight?: number; - verificationprogress?: number; - chainSupply?: { chainValueZat: number }; - valuePools?: ZcashRawValuePool[]; -} +export type ZcashRawBlockchainInfo = Pick< + ZecBlockchainInfo, + "chain" | "blocks" | "bestblockhash" | "difficulty" +> & + Partial> & { + chainSupply?: Pick; + valuePools?: ZcashRawValuePool[]; + }; -export interface ZcashRawMempoolEntry { - size: number; - fee: number; - time: number; - height: number; -} +export type ZcashRawMempoolEntry = Pick; -const VALUE_POOL_IDS: ZcashValuePoolId[] = [ - "transparent", - "sprout", - "sapling", - "orchard", - "lockbox", - "ironwood", -]; +/** + * Apply a transform to every provider response in parallel-strategy metadata, so each provider + * carries a complete domain object rather than raw Zebra JSON + */ +export function mapMetadata( + metadata: unknown, + transform: (raw: never) => T, +): DataWithMetadata["metadata"] { + const typed = metadata as DataWithMetadata["metadata"]; + if (!typed?.responses) return typed; + return { + ...typed, + responses: typed.responses.map((response) => { + if (response.data === undefined) return response; + try { + return { ...response, data: transform(response.data as never) }; + } catch { + return response; + } + }), + }; +} function isValuePoolId(id: string): id is ZcashValuePoolId { - return (VALUE_POOL_IDS as string[]).includes(id); + return (ZCASH_VALUE_POOL_IDS as readonly string[]).includes(id); } export function transformValuePools(pools: ZcashRawValuePool[] | undefined): ZcashValuePool[] { @@ -221,6 +229,15 @@ export function transformTransaction(raw: ZcashRawTransaction): ZcashTransaction }; } +function transformTrees(trees: NonNullable): ZcashTreeSizes { + const sizes: ZcashTreeSizes = {}; + for (const pool of ZCASH_TREE_POOLS) { + const size = trees[pool]?.size; + if (size !== undefined) sizes[pool] = size; + } + return sizes; +} + function transformBlockCommon(raw: ZcashRawBlockCommon, txCount: number): ZcashBlock { return { hash: raw.hash, @@ -240,11 +257,7 @@ function transformBlockCommon(raw: ZcashRawBlockCommon, txCount: number): ZcashB blockCommitments: raw.blockcommitments, finalSaplingRoot: raw.finalsaplingroot, finalOrchardRoot: raw.finalorchardroot, - trees: raw.trees && { - sapling: raw.trees.sapling?.size, - orchard: raw.trees.orchard?.size, - ironwood: raw.trees.ironwood?.size, - }, + trees: raw.trees && transformTrees(raw.trees), chainSupplyZat: raw.chainSupply?.chainValueZat, valuePools: raw.valuePools && transformValuePools(raw.valuePools), }; @@ -257,6 +270,7 @@ export function transformBlockSummary(raw: ZcashRawBlockSummary): ZcashBlock { export function transformBlock(raw: ZcashRawBlock): ZcashBlockWithTransactions { const transactions = raw.tx.map(transformTransaction); const coinbase = transactions[0]; + const isCoinbase = coinbase !== undefined && isCoinbaseTransaction(coinbase); const shieldedTxCounts: Partial> = {}; for (const tx of transactions) { @@ -269,10 +283,11 @@ export function transformBlock(raw: ZcashRawBlock): ZcashBlockWithTransactions { block: { ...transformBlockCommon(raw, transactions.length), txids: transactions.map((tx) => tx.txid), - coinbaseOutputs: - coinbase && isCoinbaseTransaction(coinbase) - ? coinbase.vout.map((output) => ({ address: output.address, valueZat: output.valueZat })) - : [], + coinbaseOutputs: isCoinbase + ? coinbase.vout.map((output) => ({ address: output.address, valueZat: output.valueZat })) + : [], + // A shielded coinbase pays the miner into Sapling or Orchard: the value entering the pools + coinbaseShieldedZat: isCoinbase ? Math.max(0, -getShieldedNetZat(coinbase)) : 0, shieldedTxCounts, transparentOutputZat: transactions.reduce((sum, tx) => sum + getTransparentOutputZat(tx), 0), }, diff --git a/src/services/adapters/adaptersFactory.ts b/src/services/adapters/adaptersFactory.ts index 8f444b03..e7058e24 100644 --- a/src/services/adapters/adaptersFactory.ts +++ b/src/services/adapters/adaptersFactory.ts @@ -7,7 +7,7 @@ import { PolygonAdapter } from "./PolygonAdapter/PolygonAdapter"; import { ArbitrumAdapter } from "./ArbitrumAdapter/ArbitrumAdapter"; import { HardhatAdapter } from "./HardhatAdapter/HardhatAdapter"; import { BitcoinAdapter } from "./BitcoinAdapter/BitcoinAdapter"; -import { ZcashAdapter } from "./ZcashAdapter/ZcashAdapter"; +import { ZcashAdapter, type ZcashAdapterOptions } from "./ZcashAdapter/ZcashAdapter"; import { SolanaAdapter } from "./SolanaAdapter/SolanaAdapter"; import type { ArbitrumClient, @@ -81,8 +81,12 @@ export class AdapterFactory { /** * Create a Zcash network adapter */ - static createZcashAdapter(networkId: string, client: ZcashClient): ZcashAdapter { - return new ZcashAdapter(networkId, client); + static createZcashAdapter( + networkId: string, + client: ZcashClient, + options?: ZcashAdapterOptions, + ): ZcashAdapter { + return new ZcashAdapter(networkId, client, options); } /** diff --git a/src/types/index.ts b/src/types/index.ts index 79c27525..caa09c62 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -1,5 +1,10 @@ import type { EthLog, SupportedChainId } from "@openscan/network-connectors"; import type React from "react"; +import type { + ZCASH_SHIELDED_POOLS, + ZCASH_TREE_POOLS, + ZCASH_VALUE_POOL_IDS, +} from "../config/zcashConstants"; // ==================== NETWORK TYPES ==================== @@ -284,18 +289,17 @@ export interface BitcoinAddress { /** * Zcash value pools, in the order the protocol introduced them */ -export type ZcashValuePoolId = - | "transparent" - | "sprout" - | "sapling" - | "orchard" - | "lockbox" - | "ironwood"; +export type ZcashValuePoolId = (typeof ZCASH_VALUE_POOL_IDS)[number]; /** * Shielded pools a transaction can move value through */ -export type ZcashShieldedPool = "sprout" | "sapling" | "orchard" | "ironwood"; +export type ZcashShieldedPool = (typeof ZCASH_SHIELDED_POOLS)[number]; + +/** + * Shielded pools with a note commitment tree + */ +export type ZcashTreePool = (typeof ZCASH_TREE_POOLS)[number]; /** * Pools a transaction touches: transparent inputs/outputs plus its shielded bundles @@ -329,11 +333,7 @@ export interface ZcashNetworkStats { /** * Note commitment tree sizes at a block */ -export interface ZcashTreeSizes { - sapling?: number; - orchard?: number; - ironwood?: number; -} +export type ZcashTreeSizes = Partial>; /** * Transparent output of a coinbase transaction (miner reward or funding stream) @@ -370,6 +370,7 @@ export interface ZcashBlock { txids?: string[]; // Derived from full transaction data (getblock verbosity 2) coinbaseOutputs?: ZcashCoinbaseOutput[]; + coinbaseShieldedZat?: number; // Reward paid into shielded pools (shielded coinbase, NU5+) shieldedTxCounts?: Partial>; transparentOutputZat?: number; } @@ -444,6 +445,12 @@ export type ZcashTxKind = | "shielded" | "mixed"; +/** + * Transaction fee: coinbase transactions pay none, and it stays unknown until every transparent + * input value has been looked up + */ +export type ZcashFee = { kind: "coinbase" } | { kind: "unknown" } | { kind: "known"; zat: number }; + /** * Zcash transaction data */ diff --git a/src/utils/rpcStorage.ts b/src/utils/rpcStorage.ts index 0baf7802..21c1bc69 100644 --- a/src/utils/rpcStorage.ts +++ b/src/utils/rpcStorage.ts @@ -8,9 +8,10 @@ const METADATA_RPC_STORAGE_KEY = "OPENSCAN_METADATA_RPCS"; const METADATA_RPC_TTL = 24 * 60 * 60 * 1000; // 24 hours /** - * Hardcoded fallback defaults for networks that are never in the metadata service. - * Includes localhost, worker-proxied BTC and EVM, and public Zcash and Solana endpoints. - * Metadata service RPCs and user-configured RPCs take priority via getEffectiveRpcUrls(). + * Built-in RPC endpoints, appended after the metadata service's endpoints for each network. + * They cover what the metadata service doesn't list (localhost), worker-proxied BTC and EVM + * endpoints, and public Zcash and Solana gateways. User-configured RPCs come first; these are + * still appended to them, so a built-in endpoint is always available as a fallback. */ const BUILTIN_RPC_DEFAULTS: RpcUrlsContextType = { "eip155:31337": ["http://localhost:8545"], diff --git a/src/utils/zcashFormatters.ts b/src/utils/zcashFormatters.ts index b3cab0fa..ba54bfcc 100644 --- a/src/utils/zcashFormatters.ts +++ b/src/utils/zcashFormatters.ts @@ -4,6 +4,7 @@ import { ZATOSHIS_PER_ZEC } from "../config/zcashConstants"; +// Re-exported so Zcash UI imports its formatters from one module instead of the Bitcoin one export { formatDifficulty, formatNumber, @@ -21,10 +22,3 @@ export { export function formatZEC(valueZat: number, currency = "ZEC"): string { return `${(valueZat / ZATOSHIS_PER_ZEC).toFixed(8)} ${currency}`; } - -/** - * Format a zatoshi amount with thousands separators - */ -export function formatZatoshis(valueZat: number): string { - return `${valueZat.toLocaleString()} zat`; -} diff --git a/src/utils/zcashUtils.test.ts b/src/utils/zcashUtils.test.ts index 5c5a7771..d50ab5f2 100644 --- a/src/utils/zcashUtils.test.ts +++ b/src/utils/zcashUtils.test.ts @@ -3,10 +3,12 @@ import type { ZcashTransaction } from "../types"; import { classifyRpcErrors, classifyTransaction, - computeFeeZat, + computeFee, detectZcashAddressType, + getShieldedNetZat, getTransactionPools, isZcashAddress, + normalizeZcashAddress, zecToZat, } from "./zcashUtils"; @@ -56,6 +58,31 @@ describe("detectZcashAddressType", () => { expect(isZcashAddress(address)).toBe(true); }); + it.each([ + ["t1KAuVfS2r2hc7RwSh6GTuyfqCGMFEpwkZ2", "mainnet", "p2pkh"], + ["t1KAuVfS2r2hc7RwSh6GTuyfqCGMFEpwkZ2", "testnet", "unknown"], + [`tm${"a".repeat(33)}`, "testnet", "p2pkh"], + [`tm${"a".repeat(33)}`, "mainnet", "unknown"], + [`utest1${"q".repeat(100)}`, "mainnet", "unknown"], + [`ztestsapling1${"q".repeat(75)}`, "testnet", "sapling"], + [`zs1${"q".repeat(75)}`, "testnet", "unknown"], + ] as const)("detects %s on %s as %s", (address, network, type) => { + expect(detectZcashAddressType(address, network)).toBe(type); + }); + + it("accepts all-uppercase Bech32m addresses and normalizes them to lowercase", () => { + const unified = `u1${"q".repeat(100)}`; + expect(detectZcashAddressType(unified.toUpperCase())).toBe("unified"); + expect(detectZcashAddressType(`ZS1${"Q".repeat(75)}`, "mainnet")).toBe("sapling"); + expect(normalizeZcashAddress(unified.toUpperCase())).toBe(unified); + }); + + it("keeps Base58 addresses case-sensitive", () => { + const transparent = "t1KAuVfS2r2hc7RwSh6GTuyfqCGMFEpwkZ2"; + expect(detectZcashAddressType(transparent.toUpperCase())).toBe("unknown"); + expect(normalizeZcashAddress(transparent)).toBe(transparent); + }); + it.each([ "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", @@ -68,14 +95,14 @@ describe("detectZcashAddressType", () => { }); }); -describe("classifyTransaction and computeFeeZat", () => { +describe("classifyTransaction and computeFee", () => { it("handles a fully shielded Ironwood transaction with empty vin and vout", () => { // Mainnet tx 36a167f6…ce2e3, block 3,483,400 const ironwoodOnly = tx({ shielded: { ironwood: { actions: 2, valueBalanceZat: 10_000 } } }); expect(classifyTransaction(ironwoodOnly)).toBe("shielded"); expect(getTransactionPools(ironwoodOnly)).toEqual(["ironwood"]); - expect(computeFeeZat(ironwoodOnly)).toBe(10_000); + expect(computeFee(ironwoodOnly)).toEqual({ kind: "known", zat: 10_000 }); }); it("nets value balances across Sapling and Ironwood", () => { @@ -89,7 +116,7 @@ describe("classifyTransaction and computeFeeZat", () => { expect(classifyTransaction(saplingIronwood)).toBe("shielded"); expect(getTransactionPools(saplingIronwood)).toEqual(["sapling", "ironwood"]); - expect(computeFeeZat(saplingIronwood)).toBe(20_000); + expect(computeFee(saplingIronwood)).toEqual({ kind: "known", zat: 20_000 }); }); it("needs every transparent input value before computing a shielding fee", () => { @@ -99,11 +126,14 @@ describe("classifyTransaction and computeFeeZat", () => { }); expect(classifyTransaction(shielding)).toBe("shielding"); - expect(computeFeeZat(shielding)).toBeNull(); - expect(computeFeeZat({ ...shielding, vin: [input(1_000_000_000), input()] })).toBeNull(); - expect(computeFeeZat({ ...shielding, vin: [input(1_000_000_000), input(877_673_138)] })).toBe( - 10_000, - ); + expect(computeFee(shielding)).toEqual({ kind: "unknown" }); + expect(computeFee({ ...shielding, vin: [input(1_000_000_000), input()] })).toEqual({ + kind: "unknown", + }); + expect(computeFee({ ...shielding, vin: [input(1_000_000_000), input(877_673_138)] })).toEqual({ + kind: "known", + zat: 10_000, + }); }); it("classifies deshielding, mixed and transparent transactions", () => { @@ -118,7 +148,7 @@ describe("classifyTransaction and computeFeeZat", () => { const transparent = tx({ vin: [input(50_000)], vout: [output(0, 30_000), output(1, 10_000)] }); expect(classifyTransaction(transparent)).toBe("transparent"); expect(getTransactionPools(transparent)).toEqual(["transparent"]); - expect(computeFeeZat(transparent)).toBe(10_000); + expect(computeFee(transparent)).toEqual({ kind: "known", zat: 10_000 }); }); it("does not compute a fee for coinbase transactions", () => { @@ -128,7 +158,7 @@ describe("classifyTransaction and computeFeeZat", () => { }); expect(classifyTransaction(coinbase)).toBe("coinbase"); - expect(computeFeeZat(coinbase)).toBeNull(); + expect(computeFee(coinbase)).toEqual({ kind: "coinbase" }); }); it("accounts for Sprout JoinSplit public values", () => { @@ -138,7 +168,20 @@ describe("classifyTransaction and computeFeeZat", () => { }); expect(classifyTransaction(sprout)).toBe("shielding"); - expect(computeFeeZat(sprout)).toBe(10_000); + expect(computeFee(sprout)).toEqual({ kind: "known", zat: 10_000 }); + }); + + it("nets value moving into and out of every shielded pool", () => { + const multiPool = tx({ + shielded: { + sprout: { joinSplits: 1, vpubOldZat: 0, vpubNewZat: 50_000 }, + sapling: { spends: 1, outputs: 0, valueBalanceZat: 20_000 }, + orchard: { actions: 2, valueBalanceZat: -40_000 }, + ironwood: { actions: 1, valueBalanceZat: 5_000 }, + }, + }); + + expect(getShieldedNetZat(multiPool)).toBe(35_000); }); }); @@ -152,10 +195,29 @@ describe("classifyRpcErrors", () => { ).toBe("unsupported"); }); - it("reports rate limiting when any endpoint returns 429", () => { + it("reports rate limiting when no endpoint gave a definitive answer", () => { expect( classifyRpcErrors(["HTTP error! status: 429", "RPC error: Method not found: getblock"]), ).toBe("rateLimited"); + expect(classifyRpcErrors(["HTTP error! status: 429", "HTTP error! status: 502"])).toBe( + "rateLimited", + ); + }); + + it("prefers a definitive answer over a rate-limited endpoint", () => { + // A self-hosted node says the transaction doesn't exist while a hosted gateway returns 429 + expect( + classifyRpcErrors([ + "RPC error: No such mempool or main chain transaction", + "HTTP error! status: 429", + ]), + ).toBe("failed"); + }); + + it("reports unsupported only when every endpoint rejects the method", () => { + expect( + classifyRpcErrors(["RPC error: Method not found: getaddressbalance", "Failed to fetch"]), + ).toBe("failed"); }); it("reports other failures as failed", () => { diff --git a/src/utils/zcashUtils.ts b/src/utils/zcashUtils.ts index 13119627..41bb5a70 100644 --- a/src/utils/zcashUtils.ts +++ b/src/utils/zcashUtils.ts @@ -2,9 +2,14 @@ * Zcash helpers: address detection, transaction classification, fees and RPC error handling */ -import { ZATOSHIS_PER_ZEC } from "../config/zcashConstants"; +import { + ZATOSHIS_PER_ZEC, + ZCASH_SHIELDED_POOLS, + type ZcashNetworkKind, +} from "../config/zcashConstants"; import type { ZcashAddressType, + ZcashFee, ZcashShieldedPool, ZcashTransaction, ZcashTxKind, @@ -14,25 +19,75 @@ import type { const BASE58 = "[1-9A-HJ-NP-Za-km-z]"; const BECH32 = "[02-9ac-hj-np-z]"; -// Mainnet and testnet prefixes. Only prefix, alphabet and length are checked, not checksums. -const ADDRESS_PATTERNS: Array<{ type: ZcashAddressType; pattern: RegExp }> = [ - { type: "p2pkh", pattern: new RegExp(`^(t1|tm)${BASE58}{33}$`) }, - { type: "p2sh", pattern: new RegExp(`^(t3|t2)${BASE58}{33}$`) }, - { type: "sprout", pattern: new RegExp(`^(zc|zt)${BASE58}{93}$`) }, - { type: "sapling", pattern: new RegExp(`^(zs|ztestsapling)1${BECH32}{75}$`) }, - { type: "tex", pattern: new RegExp(`^(tex|textest)1${BECH32}{38}$`) }, - { type: "unified", pattern: new RegExp(`^(u|utest)1${BECH32}{50,}$`) }, +interface AddressPattern { + type: ZcashAddressType; + network: ZcashNetworkKind; + // Bech32(m) is case-insensitive (all-uppercase is valid, e.g. in QR codes); Base58 is not + bech32: boolean; + pattern: RegExp; +} + +// Only prefix, alphabet and length are checked, not checksums +const ADDRESS_PATTERNS: AddressPattern[] = [ + { type: "p2pkh", network: "mainnet", bech32: false, pattern: new RegExp(`^t1${BASE58}{33}$`) }, + { type: "p2pkh", network: "testnet", bech32: false, pattern: new RegExp(`^tm${BASE58}{33}$`) }, + { type: "p2sh", network: "mainnet", bech32: false, pattern: new RegExp(`^t3${BASE58}{33}$`) }, + { type: "p2sh", network: "testnet", bech32: false, pattern: new RegExp(`^t2${BASE58}{33}$`) }, + { type: "sprout", network: "mainnet", bech32: false, pattern: new RegExp(`^zc${BASE58}{93}$`) }, + { type: "sprout", network: "testnet", bech32: false, pattern: new RegExp(`^zt${BASE58}{93}$`) }, + { type: "sapling", network: "mainnet", bech32: true, pattern: new RegExp(`^zs1${BECH32}{75}$`) }, + { + type: "sapling", + network: "testnet", + bech32: true, + pattern: new RegExp(`^ztestsapling1${BECH32}{75}$`), + }, + { type: "tex", network: "mainnet", bech32: true, pattern: new RegExp(`^tex1${BECH32}{38}$`) }, + { type: "tex", network: "testnet", bech32: true, pattern: new RegExp(`^textest1${BECH32}{38}$`) }, + { type: "unified", network: "mainnet", bech32: true, pattern: new RegExp(`^u1${BECH32}{50,}$`) }, + { + type: "unified", + network: "testnet", + bech32: true, + pattern: new RegExp(`^utest1${BECH32}{50,}$`), + }, ]; +function matchAddress( + address: string, + network?: ZcashNetworkKind, +): { pattern: AddressPattern; address: string } | undefined { + const candidates = ADDRESS_PATTERNS.filter((entry) => !network || entry.network === network); + const exact = candidates.find(({ pattern }) => pattern.test(address)); + if (exact) return { pattern: exact, address }; + + if (address !== address.toUpperCase()) return undefined; + const lowered = address.toLowerCase(); + const bech32 = candidates.find((entry) => entry.bech32 && entry.pattern.test(lowered)); + return bech32 && { pattern: bech32, address: lowered }; +} + /** - * Detect a Zcash address encoding from its prefix and shape + * Detect a Zcash address encoding from its prefix and shape. With a network, addresses of the + * other network (e.g. a testnet `tm…` address on mainnet) are reported as unknown. */ -export function detectZcashAddressType(address: string): ZcashAddressType { - return ADDRESS_PATTERNS.find(({ pattern }) => pattern.test(address))?.type ?? "unknown"; +export function detectZcashAddressType( + address: string, + network?: ZcashNetworkKind, +): ZcashAddressType { + return matchAddress(address, network)?.pattern.type ?? "unknown"; +} + +export function isZcashAddress(term: string, network?: ZcashNetworkKind): boolean { + return detectZcashAddressType(term, network) !== "unknown"; } -export function isZcashAddress(term: string): boolean { - return detectZcashAddressType(term) !== "unknown"; +/** + * Canonical form of an address: all-uppercase Bech32(m) addresses are lowercased, everything + * else is returned as is + */ +export function normalizeZcashAddress(address: string): string { + return matchAddress(address)?.address ?? address; } /** @@ -42,14 +97,16 @@ export function zecToZat(value: number): number { return Math.round(value * ZATOSHIS_PER_ZEC); } +/** + * Zebra marks the coinbase input with a `coinbase` field, so check for it directly rather than + * Bitcoin's "single input without a txid" heuristic (shielded transactions can have no inputs) + */ export function isCoinbaseTransaction(tx: ZcashTransaction): boolean { return tx.vin[0]?.coinbase !== undefined; } -const SHIELDED_POOLS: ZcashShieldedPool[] = ["sprout", "sapling", "orchard", "ironwood"]; - export function getShieldedPools(tx: ZcashTransaction): ZcashShieldedPool[] { - return SHIELDED_POOLS.filter((pool) => tx.shielded[pool] !== undefined); + return ZCASH_SHIELDED_POOLS.filter((pool) => tx.shielded[pool] !== undefined); } export function getTransactionPools(tx: ZcashTransaction): ZcashTxPool[] { @@ -78,38 +135,55 @@ export function getTransparentOutputZat(tx: ZcashTransaction): number { } /** - * Fee in zatoshis, from the transparent value balance: - * inputs + value leaving the shielded pools = outputs + fee. - * Returns null for coinbase, and while any transparent input value is still unknown. + * Net value leaving the shielded pools into the transparent value balance, in zatoshis. + * Negative when the transaction moves value into the shielded pools. + */ +export function getShieldedNetZat(tx: ZcashTransaction): number { + const { sprout, sapling, orchard, ironwood } = tx.shielded; + return ( + (sprout ? sprout.vpubNewZat - sprout.vpubOldZat : 0) + + (sapling?.valueBalanceZat ?? 0) + + (orchard?.valueBalanceZat ?? 0) + + (ironwood?.valueBalanceZat ?? 0) + ); +} + +/** + * Fee from the transparent value balance: inputs + value leaving the shielded pools = + * outputs + fee. Unknown while any transparent input value is still unresolved. */ -export function computeFeeZat(tx: ZcashTransaction): number | null { - if (isCoinbaseTransaction(tx)) return null; +export function computeFee(tx: ZcashTransaction): ZcashFee { + if (isCoinbaseTransaction(tx)) return { kind: "coinbase" }; let inputZat = 0; for (const input of tx.vin) { - if (input.valueZat === undefined) return null; + if (input.valueZat === undefined) return { kind: "unknown" }; inputZat += input.valueZat; } - const { sprout, sapling, orchard, ironwood } = tx.shielded; - const shieldedNetZat = - (sprout ? sprout.vpubNewZat - sprout.vpubOldZat : 0) + - (sapling?.valueBalanceZat ?? 0) + - (orchard?.valueBalanceZat ?? 0) + - (ironwood?.valueBalanceZat ?? 0); - - return inputZat + shieldedNetZat - getTransparentOutputZat(tx); + return { kind: "known", zat: inputZat + getShieldedNetZat(tx) - getTransparentOutputZat(tx) }; } export type ZcashRpcErrorKind = "unsupported" | "rateLimited" | "failed"; const RATE_LIMITED_PATTERN = /status: 429/; -const UNSUPPORTED_PATTERN = /method not found|-32601/i; +// The connector reports JSON-RPC errors as "RPC error: " and drops the code, so an +// unsupported method (-32601) can only be recognised by its message +const UNSUPPORTED_PATTERN = /method not found/i; +const RPC_ERROR_PATTERN = /^RPC error:/; /** - * Classify the per-endpoint error messages of a failed RPC call + * Classify the per-endpoint error messages of a failed RPC call: + * 1. Any endpoint answered with a JSON-RPC error other than "method not found": that answer is + * definitive (e.g. "No such transaction"), so retrying a rate-limited endpoint can't help. + * 2. Otherwise any HTTP 429: rate limited, worth retrying. + * 3. Otherwise every endpoint rejected the method: unsupported. */ export function classifyRpcErrors(messages: string[]): ZcashRpcErrorKind { + const definitive = messages.some( + (message) => RPC_ERROR_PATTERN.test(message) && !UNSUPPORTED_PATTERN.test(message), + ); + if (definitive) return "failed"; if (messages.some((message) => RATE_LIMITED_PATTERN.test(message))) return "rateLimited"; if (messages.length > 0 && messages.every((message) => UNSUPPORTED_PATTERN.test(message))) { return "unsupported"; From 3d9138d3b4017876d1dba0142cac53d5bdd3a31e Mon Sep 17 00:00:00 2001 From: Mati OS Date: Fri, 20 Nov 2026 19:58:54 -0300 Subject: [PATCH 7/7] docs(claude): note non-evm adapters are standalone classes --- .claude/rules/patterns.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.claude/rules/patterns.md b/.claude/rules/patterns.md index 24ebd72e..73477148 100644 --- a/.claude/rules/patterns.md +++ b/.claude/rules/patterns.md @@ -3,7 +3,9 @@ ## When Modifying Data Fetching - Always maintain the adapter pattern: Client → Adapter → Service -- All adapters extend the abstract `NetworkAdapter` class (`services/adapters/NetworkAdapter.ts`) +- EVM adapters extend the abstract `NetworkAdapter` class (`services/adapters/NetworkAdapter.ts`). + Non-EVM adapters (`BitcoinAdapter`, `ZcashAdapter`, `SolanaAdapter`) are standalone classes with + chain-specific types, reached through `DataService` getters such as `getZcashAdapter()` - If adding parallel strategy support, ensure complete objects are built for each provider - Test `fallback`, `parallel`, and `race` strategies - Update TypeScript types in `src/types/index.ts` if adding new fields