Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions .claude/rules/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/`)
Expand All @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 3 additions & 1 deletion .claude/rules/patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
38 changes: 38 additions & 0 deletions src/config/zcashConstants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* 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;

// 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];
69 changes: 69 additions & 0 deletions src/services/DataService.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
38 changes: 35 additions & 3 deletions src/services/DataService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
type SupportedChainId,
type SupportedSolanaChainId,
type SupportedZcashChainId,
ArbitrumClient,
BaseClient,
BitcoinClient,
Expand All @@ -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 { 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";

Expand All @@ -41,19 +43,21 @@ const EVM_TESTNET_CLIENTS: Record<number, (config: EVMClientConfig) => 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,
Expand All @@ -73,6 +77,17 @@ 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<typeof zcashChainId>(zcashChainId, {
rpcUrls,
type: strategy,
});
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
const solanaChainId = network.networkId as SupportedSolanaChainId;
Expand Down Expand Up @@ -107,6 +122,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
*/
Expand Down Expand Up @@ -134,6 +156,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)
*/
Expand Down
44 changes: 44 additions & 0 deletions src/services/MetadataService.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
});
13 changes: 11 additions & 2 deletions src/services/MetadataService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -81,6 +81,13 @@ const BTC_NETWORK_SLUGS: Record<string, string> = {
"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<string, string> = {
"00040fe8ec8471911baa1db1266ea15d": "mainnet",
"05a60a92d99d85997cce3b87616c089f": "testnet",
};

// Solana CAIP-2 chain IDs (first 32 chars of genesis hash) → friendly file names
const SOLANA_NETWORK_SLUGS: Record<string, string> = {
"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": "mainnet",
Expand All @@ -91,7 +98,7 @@ const SOLANA_NETWORK_SLUGS: Record<string, string> = {
/**
* 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 {
Expand All @@ -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`;
Expand Down
Loading