@anywalletkit/wallet-zcash 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as SpentOutput, Z as ZcashNetwork, a as ZcashTxDescription, b as ZcashClient, U as Utxo, c as ZcashTxInfo, d as ZcashConfig, e as ZcashSpend, f as ZcashTransferOptions, g as ZcashMaxSpendableResult, h as ZcashReceipt, i as ZcashTransaction } from './history-BpA-R7Tf.cjs';
2
- export { B as BLOCKCHAIR_URL, j as BlockchairClient, k as BlockchairTxDashboard, C as CAIP2, H as HistoryUnavailableError, l as ZcashChainTx, m as ZcashClientConfig, n as ZcashHistoryCursor, o as ZcashHistoryOptions, p as ZcashHistoryPage, q as ZcashHistoryRaw, r as ZcashHistorySource, s as ZcashTxInputDescription, t as ZcashTxOutputDescription, u as ZcashWarning, v as blockchairTime, w as createZcashHistory, x as decodeHistoryCursor, y as encodeHistoryCursor, z as mapDashboardTx, A as zcashExplorerTxUrl } from './history-BpA-R7Tf.cjs';
1
+ import { S as SpentOutput, Z as ZcashNetwork, a as ZcashTxDescription, b as ZcashClient, U as Utxo, c as ZcashTxInfo, d as ZcashConfig, e as ZcashSpend, f as ZcashTransferOptions, g as ZcashMaxSpendableResult, h as ZcashReceipt, i as ZcashTransaction } from './history-CiZ6aFMT.cjs';
2
+ export { B as BLOCKCHAIR_URL, j as BlockchairClient, k as BlockchairInput, l as BlockchairOutput, m as BlockchairTxDashboard, n as BlockchairTxRow, C as CAIP2, H as HistoryUnavailableError, o as ZcashChainTx, p as ZcashClientConfig, q as ZcashHistoryCursor, r as ZcashHistoryOptions, s as ZcashHistoryPage, t as ZcashHistoryRaw, u as ZcashHistorySource, v as ZcashTxInputDescription, w as ZcashTxOutputDescription, x as ZcashWarning, y as blockchairTime, z as createZcashHistory, A as decodeHistoryCursor, D as encodeHistoryCursor, E as mapDashboardTx, F as zcashExplorerTxUrl } from './history-CiZ6aFMT.cjs';
3
3
  import { Signer, IWalletAccountReadOnly, IWalletAccount, WriteOptions, TransferResult, WalletManager, FeeRates } from '@anywalletkit/core';
4
4
 
5
5
  declare const TX_VERSION_V5 = 2147483653;
@@ -450,4 +450,4 @@ declare class WalletManagerZcash extends WalletManager<WalletAccountZcash, Zcash
450
450
  getFeeRates(): Promise<FeeRates>;
451
451
  }
452
452
 
453
- export { type BlockbookTxDetails, type BlockbookVin, type BlockbookVout, BroadcastUnknownError, CURRENT_BRANCH_ID, type CoinSelectOptions, type CoinSelection, DEFAULT_EXPIRY_DELTA, DEFAULT_MAX_FEE, DUST_LIMIT, type DecodedAddress, type DescribeContext, FINAL_SEQUENCE, GRACE_ACTIONS, MAINNET_UPGRADES, MARGINAL_FEE, MAX_SEQUENCE, MAX_UTXO_INPUTS, P2PKH_INPUT_SIZE, SIGHASH_ALL, type ScriptKind, type SpendPlan, SpentOutput, TX_VERSION_V5, TooManyInputsError, type TransparentTxV5, type TxInput, type TxOutput, type UnsafeTransactionCode, UnsafeTransactionError, Utxo, VERSION_GROUP_ID_V5, WalletAccountReadOnlyZcash, WalletAccountZcash, WalletManagerZcash, ZcashBlockbookClient, ZcashClient, ZcashConfig, ZcashMaxSpendableResult, ZcashNetwork, ZcashReceipt, ZcashSpend, ZcashTransaction, ZcashTransferOptions, ZcashTxDescription, ZcashTxInfo, addressFor, addressFromPublicKey, addressFromScript, addressPrefix, assertSafe, branchIdForHeight, coinType, conventionalFee, createClient, decodeAddress, WalletManagerZcash as default, describeTransaction, encodeAddress, encodeMessageSignature, estimateSize, hash160, headerDigest, isAnsweredRefusal, logicalActions, magicHash, outputSize, outputsDigest, p2pkhScriptSig, parseP2pkhScriptSig, parseTx, prevoutsDigest, recoverMessagePublicKey, scriptFor, scriptKind, selectAll, selectCoins, sequenceDigest, serializeTx, sighashAll, signMessageWith, spendableUtxos, transparentDigest, txHashPersonalization, txid, txidDigest };
453
+ export { type BlockbookTxDetails, type BlockbookVin, type BlockbookVout, BroadcastUnknownError, type Built, CURRENT_BRANCH_ID, type CoinSelectOptions, type CoinSelection, DEFAULT_EXPIRY_DELTA, DEFAULT_MAX_FEE, DUST_LIMIT, type DecodedAddress, type DescribeContext, FINAL_SEQUENCE, GRACE_ACTIONS, MAINNET_UPGRADES, MARGINAL_FEE, MAX_SEQUENCE, MAX_UTXO_INPUTS, P2PKH_INPUT_SIZE, SIGHASH_ALL, type ScriptKind, type SpendPlan, SpentOutput, TX_VERSION_V5, TooManyInputsError, type TransparentTxV5, type TxInput, type TxOutput, type UnsafeTransactionCode, UnsafeTransactionError, Utxo, VERSION_GROUP_ID_V5, WalletAccountReadOnlyZcash, WalletAccountZcash, WalletManagerZcash, ZcashBlockbookClient, ZcashClient, ZcashConfig, ZcashMaxSpendableResult, ZcashNetwork, ZcashReceipt, ZcashSpend, ZcashTransaction, ZcashTransferOptions, ZcashTxDescription, ZcashTxInfo, addressFor, addressFromPublicKey, addressFromScript, addressPrefix, assertSafe, branchIdForHeight, coinType, conventionalFee, createClient, decodeAddress, WalletManagerZcash as default, describeTransaction, encodeAddress, encodeMessageSignature, estimateSize, hash160, headerDigest, isAnsweredRefusal, logicalActions, magicHash, outputSize, outputsDigest, p2pkhScriptSig, parseP2pkhScriptSig, parseTx, prevoutsDigest, recoverMessagePublicKey, scriptFor, scriptKind, selectAll, selectCoins, sequenceDigest, serializeTx, sighashAll, signMessageWith, spendableUtxos, transparentDigest, txHashPersonalization, txid, txidDigest };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as SpentOutput, Z as ZcashNetwork, a as ZcashTxDescription, b as ZcashClient, U as Utxo, c as ZcashTxInfo, d as ZcashConfig, e as ZcashSpend, f as ZcashTransferOptions, g as ZcashMaxSpendableResult, h as ZcashReceipt, i as ZcashTransaction } from './history-BpA-R7Tf.js';
2
- export { B as BLOCKCHAIR_URL, j as BlockchairClient, k as BlockchairTxDashboard, C as CAIP2, H as HistoryUnavailableError, l as ZcashChainTx, m as ZcashClientConfig, n as ZcashHistoryCursor, o as ZcashHistoryOptions, p as ZcashHistoryPage, q as ZcashHistoryRaw, r as ZcashHistorySource, s as ZcashTxInputDescription, t as ZcashTxOutputDescription, u as ZcashWarning, v as blockchairTime, w as createZcashHistory, x as decodeHistoryCursor, y as encodeHistoryCursor, z as mapDashboardTx, A as zcashExplorerTxUrl } from './history-BpA-R7Tf.js';
1
+ import { S as SpentOutput, Z as ZcashNetwork, a as ZcashTxDescription, b as ZcashClient, U as Utxo, c as ZcashTxInfo, d as ZcashConfig, e as ZcashSpend, f as ZcashTransferOptions, g as ZcashMaxSpendableResult, h as ZcashReceipt, i as ZcashTransaction } from './history-CiZ6aFMT.js';
2
+ export { B as BLOCKCHAIR_URL, j as BlockchairClient, k as BlockchairInput, l as BlockchairOutput, m as BlockchairTxDashboard, n as BlockchairTxRow, C as CAIP2, H as HistoryUnavailableError, o as ZcashChainTx, p as ZcashClientConfig, q as ZcashHistoryCursor, r as ZcashHistoryOptions, s as ZcashHistoryPage, t as ZcashHistoryRaw, u as ZcashHistorySource, v as ZcashTxInputDescription, w as ZcashTxOutputDescription, x as ZcashWarning, y as blockchairTime, z as createZcashHistory, A as decodeHistoryCursor, D as encodeHistoryCursor, E as mapDashboardTx, F as zcashExplorerTxUrl } from './history-CiZ6aFMT.js';
3
3
  import { Signer, IWalletAccountReadOnly, IWalletAccount, WriteOptions, TransferResult, WalletManager, FeeRates } from '@anywalletkit/core';
4
4
 
5
5
  declare const TX_VERSION_V5 = 2147483653;
@@ -450,4 +450,4 @@ declare class WalletManagerZcash extends WalletManager<WalletAccountZcash, Zcash
450
450
  getFeeRates(): Promise<FeeRates>;
451
451
  }
452
452
 
453
- export { type BlockbookTxDetails, type BlockbookVin, type BlockbookVout, BroadcastUnknownError, CURRENT_BRANCH_ID, type CoinSelectOptions, type CoinSelection, DEFAULT_EXPIRY_DELTA, DEFAULT_MAX_FEE, DUST_LIMIT, type DecodedAddress, type DescribeContext, FINAL_SEQUENCE, GRACE_ACTIONS, MAINNET_UPGRADES, MARGINAL_FEE, MAX_SEQUENCE, MAX_UTXO_INPUTS, P2PKH_INPUT_SIZE, SIGHASH_ALL, type ScriptKind, type SpendPlan, SpentOutput, TX_VERSION_V5, TooManyInputsError, type TransparentTxV5, type TxInput, type TxOutput, type UnsafeTransactionCode, UnsafeTransactionError, Utxo, VERSION_GROUP_ID_V5, WalletAccountReadOnlyZcash, WalletAccountZcash, WalletManagerZcash, ZcashBlockbookClient, ZcashClient, ZcashConfig, ZcashMaxSpendableResult, ZcashNetwork, ZcashReceipt, ZcashSpend, ZcashTransaction, ZcashTransferOptions, ZcashTxDescription, ZcashTxInfo, addressFor, addressFromPublicKey, addressFromScript, addressPrefix, assertSafe, branchIdForHeight, coinType, conventionalFee, createClient, decodeAddress, WalletManagerZcash as default, describeTransaction, encodeAddress, encodeMessageSignature, estimateSize, hash160, headerDigest, isAnsweredRefusal, logicalActions, magicHash, outputSize, outputsDigest, p2pkhScriptSig, parseP2pkhScriptSig, parseTx, prevoutsDigest, recoverMessagePublicKey, scriptFor, scriptKind, selectAll, selectCoins, sequenceDigest, serializeTx, sighashAll, signMessageWith, spendableUtxos, transparentDigest, txHashPersonalization, txid, txidDigest };
453
+ export { type BlockbookTxDetails, type BlockbookVin, type BlockbookVout, BroadcastUnknownError, type Built, CURRENT_BRANCH_ID, type CoinSelectOptions, type CoinSelection, DEFAULT_EXPIRY_DELTA, DEFAULT_MAX_FEE, DUST_LIMIT, type DecodedAddress, type DescribeContext, FINAL_SEQUENCE, GRACE_ACTIONS, MAINNET_UPGRADES, MARGINAL_FEE, MAX_SEQUENCE, MAX_UTXO_INPUTS, P2PKH_INPUT_SIZE, SIGHASH_ALL, type ScriptKind, type SpendPlan, SpentOutput, TX_VERSION_V5, TooManyInputsError, type TransparentTxV5, type TxInput, type TxOutput, type UnsafeTransactionCode, UnsafeTransactionError, Utxo, VERSION_GROUP_ID_V5, WalletAccountReadOnlyZcash, WalletAccountZcash, WalletManagerZcash, ZcashBlockbookClient, ZcashClient, ZcashConfig, ZcashMaxSpendableResult, ZcashNetwork, ZcashReceipt, ZcashSpend, ZcashTransaction, ZcashTransferOptions, ZcashTxDescription, ZcashTxInfo, addressFor, addressFromPublicKey, addressFromScript, addressPrefix, assertSafe, branchIdForHeight, coinType, conventionalFee, createClient, decodeAddress, WalletManagerZcash as default, describeTransaction, encodeAddress, encodeMessageSignature, estimateSize, hash160, headerDigest, isAnsweredRefusal, logicalActions, magicHash, outputSize, outputsDigest, p2pkhScriptSig, parseP2pkhScriptSig, parseTx, prevoutsDigest, recoverMessagePublicKey, scriptFor, scriptKind, selectAll, selectCoins, sequenceDigest, serializeTx, sighashAll, signMessageWith, spendableUtxos, transparentDigest, txHashPersonalization, txid, txidDigest };
package/dist/index.js CHANGED
@@ -26,7 +26,7 @@ import {
26
26
  u32le,
27
27
  utf8ToBytes,
28
28
  zcashExplorerTxUrl
29
- } from "./chunk-KICTVRL7.js";
29
+ } from "./chunk-JIJF3MGJ.js";
30
30
 
31
31
  // src/address.ts
32
32
  import { sha256 } from "@noble/hashes/sha2.js";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/address.ts","../src/fee.ts","../src/tx.ts","../src/describe.ts","../src/blockbook.ts","../src/client.ts","../src/errors.ts","../src/message.ts","../src/manager.ts","../src/account.ts","../src/read-only-account.ts"],"sourcesContent":["/**\n * Zcash transparent addresses: Base58Check with a two-byte version prefix.\n * mainnet t1… P2PKH 0x1CB8 t3… P2SH 0x1CBD\n * testnet tm… P2PKH 0x1D25 t2… P2SH 0x1CBA\n * Shielded (zs…, u1…) and Sprout (zc…) addresses are recognised and refused\n * with a message — this package sends transparent value only.\n */\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { ripemd160 } from '@noble/hashes/legacy.js'\nimport { base58check } from '@scure/base'\nimport type { ZcashNetwork } from './types.js'\n\nconst b58 = base58check(sha256)\n\n/** Transparent address type: pay-to-pubkey-hash (`t1…`) or pay-to-script-hash (`t3…`). */\nexport type ScriptKind = 'p2pkh' | 'p2sh'\n\n/** A transparent address decoded to its type and 20-byte hash. */\nexport interface DecodedAddress {\n kind: ScriptKind\n /** 20-byte hash (pubkey hash or script hash). */\n hash: Uint8Array\n /** The scriptPubKey. */\n script: Uint8Array\n}\n\nconst PREFIX: Record<ZcashNetwork, Record<ScriptKind, readonly [number, number]>> = {\n mainnet: { p2pkh: [0x1c, 0xb8], p2sh: [0x1c, 0xbd] },\n testnet: { p2pkh: [0x1d, 0x25], p2sh: [0x1c, 0xba] },\n}\n\n/** Base58Check version prefix for a transparent address kind on a network (exported for tests / tooling). */\nexport function addressPrefix(network: ZcashNetwork, kind: ScriptKind): readonly [number, number] {\n return PREFIX[network][kind]\n}\n\n/** RIPEMD-160 of SHA-256, the hash inside a transparent address. */\nexport function hash160(data: Uint8Array): Uint8Array {\n return ripemd160(sha256(data))\n}\n\n/** OP_DUP OP_HASH160 <20> OP_EQUALVERIFY OP_CHECKSIG, or OP_HASH160 <20> OP_EQUAL. */\nexport function scriptFor(kind: ScriptKind, hash: Uint8Array): Uint8Array {\n if (hash.length !== 20) throw new Error('A transparent script needs a 20-byte hash')\n if (kind === 'p2pkh') return Uint8Array.of(0x76, 0xa9, 0x14, ...hash, 0x88, 0xac)\n return Uint8Array.of(0xa9, 0x14, ...hash, 0x87)\n}\n\n/** Type of an output script; `unknown` for anything but p2pkh and p2sh. */\nexport function scriptKind(script: Uint8Array): ScriptKind | 'unknown' {\n if (script.length === 25 && script[0] === 0x76 && script[1] === 0xa9 && script[2] === 0x14 && script[23] === 0x88 && script[24] === 0xac) return 'p2pkh'\n if (script.length === 23 && script[0] === 0xa9 && script[1] === 0x14 && script[22] === 0x87) return 'p2sh'\n return 'unknown'\n}\n\n/** Transparent address of a 20-byte hash. */\nexport function encodeAddress(kind: ScriptKind, hash: Uint8Array, network: ZcashNetwork): string {\n if (hash.length !== 20) throw new Error('A transparent address needs a 20-byte hash')\n const [a, b] = PREFIX[network][kind]\n return b58.encode(Uint8Array.of(a, b, ...hash))\n}\n\n/** Decode and validate a transparent address for `network`; throws a message that names the problem. */\nexport function decodeAddress(address: string, network: ZcashNetwork): DecodedAddress {\n const a = address.trim()\n if (/^u1|^utest/i.test(a)) throw new Error(`Unified address (${a.slice(0, 6)}…) — shielded receivers are not supported; use a transparent t-address.`)\n if (/^zs1|^ztestsapling/i.test(a)) throw new Error('Sapling shielded address (zs1…) — this wallet sends to transparent t-addresses only.')\n if (/^zc/i.test(a) && a.length > 90) throw new Error('Sprout address (zc…) — the Sprout pool is deprecated; use a transparent t-address.')\n let payload: Uint8Array\n try { payload = b58.decode(a) } catch (e) {\n throw new Error(`Invalid Zcash address: ${a}`, { cause: e })\n }\n if (payload.length !== 22) throw new Error(`Invalid Zcash address: ${a}`)\n const p0 = payload[0]!, p1 = payload[1]!\n for (const net of ['mainnet', 'testnet'] as const) {\n for (const kind of ['p2pkh', 'p2sh'] as const) {\n const [a0, a1] = PREFIX[net][kind]\n if (p0 === a0 && p1 === a1) {\n if (net !== network) throw new Error(`${a} is a Zcash ${net} address; this wallet is on ${network}.`)\n const hash = payload.slice(2)\n return { kind, hash, script: scriptFor(kind, hash) }\n }\n }\n }\n throw new Error(`Invalid Zcash address: ${a} (unknown version prefix)`)\n}\n\n/** Address for an output script, or undefined when the script has no address form. */\nexport function addressFromScript(script: Uint8Array, network: ZcashNetwork): string | undefined {\n const kind = scriptKind(script)\n if (kind === 'unknown') return undefined\n return encodeAddress(kind, kind === 'p2pkh' ? script.slice(3, 23) : script.slice(2, 22), network)\n}\n\n/** P2PKH address of a compressed secp256k1 public key (what `m/44'/133'/0'/0/i` yields). */\nexport function addressFromPublicKey(publicKey: Uint8Array, network: ZcashNetwork = 'mainnet'): string {\n if (publicKey.length !== 33) throw new Error('Expected a 33-byte compressed public key')\n return encodeAddress('p2pkh', hash160(publicKey), network)\n}\n\n/** Output size in bytes: 8 (value) + CompactSize + script. */\nexport function outputSize(script: Uint8Array): number {\n return 8 + (script.length < 0xfd ? 1 : 3) + script.length\n}\n\n/** Below this an output is uneconomic to spend (Bitcoin Core's P2PKH dust floor; zatoshis). */\nexport const DUST_LIMIT = 546n\n","/**\n * ZIP-317 fees and coin selection.\n *\n * conventional_fee = marginal_fee · max(grace_actions, logical_actions)\n * marginal_fee = 5000 zatoshis, grace_actions = 2,\n * transparent logical actions = max(ceil(Σ tx_in bytes / 150), ceil(Σ tx_out bytes / 34)).\n *\n * The fee depends on the number of inputs and outputs, not on a market rate,\n * so selection is simple: largest-first accumulation until the inputs cover\n * amount + fee, change kept when it clears the dust floor.\n */\nimport { InsufficientFundsError } from '@anywalletkit/core'\nimport { DUST_LIMIT } from './address.js'\nimport type { Utxo } from './types.js'\n\nexport const MARGINAL_FEE = 5_000n\nexport const GRACE_ACTIONS = 2\nexport const P2PKH_STANDARD_INPUT_SIZE = 150\nexport const P2PKH_STANDARD_OUTPUT_SIZE = 34\n/** Serialized size of one signed P2PKH input: prevout 36 + CompactSize 1 + scriptSig (1+73+1+33) + sequence 4. */\nexport const P2PKH_INPUT_SIZE = 149\n/** Most inputs one spend may use. */\nexport const MAX_UTXO_INPUTS = 200\n\nexport function logicalActions(inputSizes: readonly number[], outputSizes: readonly number[]): number {\n const inBytes = inputSizes.reduce((s, n) => s + n, 0)\n const outBytes = outputSizes.reduce((s, n) => s + n, 0)\n return Math.max(Math.ceil(inBytes / P2PKH_STANDARD_INPUT_SIZE), Math.ceil(outBytes / P2PKH_STANDARD_OUTPUT_SIZE))\n}\n\n/** The fee a transaction of this shape should pay (zatoshis). */\nexport function conventionalFee(inputSizes: readonly number[], outputSizes: readonly number[]): bigint {\n return MARGINAL_FEE * BigInt(Math.max(GRACE_ACTIONS, logicalActions(inputSizes, outputSizes)))\n}\n\n/** Transaction size estimate: v5 header 20 + counts 2 + inputs + outputs + 3 empty bundle counts. */\nexport function estimateSize(inputs: number, outputSizes: readonly number[]): number {\n const cs = (n: number) => (n < 0xfd ? 1 : 3)\n return 20 + cs(inputs) + inputs * P2PKH_INPUT_SIZE + cs(outputSizes.length) + outputSizes.reduce((s, n) => s + n, 0) + 3\n}\n\n/** A spend would need more inputs than allowed; consolidate the UTXOs first. */\nexport class TooManyInputsError extends Error {\n readonly maxInputs: number\n constructor(maxInputs: number) {\n super(`The spend needs more than ${maxInputs} inputs; consolidate the UTXOs first or raise maxInputs.`)\n this.name = 'TooManyInputsError'\n this.maxInputs = maxInputs\n }\n}\n\n/** Input to {@link selectCoins}. */\nexport interface CoinSelectOptions {\n utxos: Utxo[]\n /** Zatoshis the recipient gets. */\n target: bigint\n /** Serialized size of the recipient output. */\n recipientOutputSize: number\n /** Serialized size of a change output to our own address. */\n changeOutputSize: number\n changeDust?: bigint\n maxInputs?: number\n /** Caller-chosen fee (replaces the conventional fee; still has to be covered by the inputs). */\n fee?: bigint\n}\n\n/** UTXOs chosen for a spend, the ZIP-317 fee and the change. */\nexport interface CoinSelection {\n utxos: Utxo[]\n fee: bigint\n /** The ZIP-317 fee for the chosen shape (equals `fee` unless the caller overrode it or change was folded in). */\n conventionalFee: bigint\n /** Change back to us; 0n when folded into the fee. */\n change: bigint\n /** True when change existed but fell below dust and became fee. */\n changeFolded: boolean\n size: number\n}\n\nconst cmpUtxo = (a: Utxo, b: Utxo): number =>\n a.value > b.value ? -1 : a.value < b.value ? 1 : a.txid < b.txid ? -1 : a.txid > b.txid ? 1 : a.vout - b.vout\n\n/** UTXOs worth spending (each adds at most one logical action = 5000 zatoshis), largest first. */\nexport function spendableUtxos(utxos: Utxo[]): Utxo[] {\n return utxos.filter((u) => u.value > MARGINAL_FEE).sort(cmpUtxo)\n}\n\n/**\n * Pick UTXOs to fund `target` at the ZIP-317 fee; change below dust joins the fee.\n *\n * @throws `InsufficientFundsError` (core) when the UTXOs cannot cover target plus fee,\n * `TooManyInputsError` above `maxInputs`.\n */\nexport function selectCoins(o: CoinSelectOptions): CoinSelection {\n const maxInputs = o.maxInputs ?? MAX_UTXO_INPUTS\n const dust = o.changeDust ?? DUST_LIMIT\n const candidates = spendableUtxos(o.utxos)\n const available = o.utxos.reduce((s, u) => s + u.value, 0n)\n const inputs = (n: number) => Array.from({ length: n }, () => P2PKH_INPUT_SIZE)\n const selected: Utxo[] = []\n let sum = 0n\n for (const u of candidates) {\n if (selected.length >= maxInputs) throw new TooManyInputsError(maxInputs)\n selected.push(u)\n sum += u.value\n const n = selected.length\n const convNoChange = conventionalFee(inputs(n), [o.recipientOutputSize])\n const feeNoChange = o.fee ?? convNoChange\n if (sum < o.target + feeNoChange) continue\n const convWithChange = conventionalFee(inputs(n), [o.recipientOutputSize, o.changeOutputSize])\n const feeWithChange = o.fee ?? convWithChange\n const change = sum - o.target - feeWithChange\n if (change >= dust) {\n return { utxos: selected, fee: feeWithChange, conventionalFee: convWithChange, change, changeFolded: false, size: estimateSize(n, [o.recipientOutputSize, o.changeOutputSize]) }\n }\n return { utxos: selected, fee: sum - o.target, conventionalFee: convNoChange, change: 0n, changeFolded: sum - o.target > feeNoChange, size: estimateSize(n, [o.recipientOutputSize]) }\n }\n const need = o.target + (o.fee ?? conventionalFee(inputs(Math.max(selected.length, 1)), [o.recipientOutputSize]))\n throw new InsufficientFundsError(need, available, 'ZEC')\n}\n\n/** Sweep: every spendable input (largest first, capped), one output, no change. */\nexport function selectAll(o: { utxos: Utxo[]; outputSize: number; maxInputs?: number; fee?: bigint }): { utxos: Utxo[]; fee: bigint; amount: bigint; size: number } {\n const maxInputs = o.maxInputs ?? MAX_UTXO_INPUTS\n const utxos = spendableUtxos(o.utxos).slice(0, maxInputs)\n if (utxos.length === 0) return { utxos, fee: 0n, amount: 0n, size: 0 }\n const fee = o.fee ?? conventionalFee(Array.from({ length: utxos.length }, () => P2PKH_INPUT_SIZE), [o.outputSize])\n const amount = utxos.reduce((s, u) => s + u.value, 0n) - fee\n return { utxos, fee, amount: amount > 0n ? amount : 0n, size: estimateSize(utxos.length, [o.outputSize]) }\n}\n","/**\n * Zcash v5 transactions (ZIP-225 format) carrying transparent inputs and\n * outputs only — the shielded bundles are serialized empty. Transaction ids and\n * signature hashes follow ZIP-244 (BLAKE2b-256 digest tree); the consensus\n * branch id is part of both, so a transaction signed for one network upgrade\n * is invalid under the next.\n */\nimport { blake2b } from '@noble/hashes/blake2.js'\nimport { Reader, Writer, bytesToHex, compactSize, hexToBytes, i64le, reverseBytes, u32le, utf8ToBytes } from './encoding.js'\nimport type { SpentOutput } from './types.js'\n\nexport const TX_VERSION_V5 = 0x80000005 // fOverwintered | 5\nexport const VERSION_GROUP_ID_V5 = 0x26a7270a\nexport const SIGHASH_ALL = 0x01\n\n/** Mainnet network upgrades and their consensus branch ids (ZIP-200 table), oldest first. */\nexport const MAINNET_UPGRADES: ReadonlyArray<{ name: string; height: number; branchId: number }> = Object.freeze([\n { name: 'NU5', height: 1_687_104, branchId: 0xc2d6d0b4 },\n { name: 'NU6', height: 2_726_400, branchId: 0xc8e71055 },\n { name: 'NU6.1', height: 3_146_400, branchId: 0x4dec4df0 },\n { name: 'NU6.3', height: 3_428_143, branchId: 0x37a5165b },\n])\n\n/** The branch id the current mainnet tip signs under (NU6.3 \"Ironwood\", active since block 3 428 143, 2026-07-28). */\nexport const CURRENT_BRANCH_ID = MAINNET_UPGRADES[MAINNET_UPGRADES.length - 1]!.branchId\n\n/** Branch id in force at `height` on mainnet (the newest upgrade when the height is unknown or ahead of the table). */\nexport function branchIdForHeight(height: number | undefined): number {\n if (height === undefined || !Number.isFinite(height)) return CURRENT_BRANCH_ID\n let id = MAINNET_UPGRADES[0]!.branchId\n for (const u of MAINNET_UPGRADES) if (height >= u.height) id = u.branchId\n return id\n}\n\nexport interface TxInput {\n /** Display-order hex (as explorers show it). */\n txid: string\n vout: number\n scriptSig: Uint8Array\n sequence: number\n}\n\nexport interface TxOutput {\n value: bigint\n script: Uint8Array\n}\n\n/**\n * A v5 (NU5) transaction with transparent inputs and outputs only, as signed and serialized here.\n */\nexport interface TransparentTxV5 {\n consensusBranchId: number\n lockTime: number\n expiryHeight: number\n inputs: TxInput[]\n outputs: TxOutput[]\n}\n\nexport const FINAL_SEQUENCE = 0xfffffffe\nexport const MAX_SEQUENCE = 0xffffffff\n\nconst assertTxid = (txid: string) => { if (!/^[0-9a-fA-F]{64}$/.test(txid)) throw new Error(`Invalid txid: ${txid}`) }\n\nfunction writeTransparent(w: Writer, tx: TransparentTxV5): void {\n w.compact(tx.inputs.length)\n for (const i of tx.inputs) {\n assertTxid(i.txid)\n w.bytes(reverseBytes(hexToBytes(i.txid))).u32(i.vout).varBytes(i.scriptSig).u32(i.sequence)\n }\n w.compact(tx.outputs.length)\n for (const o of tx.outputs) {\n if (o.value < 0n) throw new Error('Negative output value')\n w.i64(o.value).varBytes(o.script)\n }\n}\n\n/** ZIP-225 wire format with empty Sapling and Orchard bundles. */\nexport function serializeTx(tx: TransparentTxV5): Uint8Array {\n const w = new Writer()\n w.u32(TX_VERSION_V5).u32(VERSION_GROUP_ID_V5).u32(tx.consensusBranchId >>> 0).u32(tx.lockTime).u32(tx.expiryHeight)\n writeTransparent(w, tx)\n w.compact(0) // nSpendsSapling\n w.compact(0) // nOutputsSapling (no valueBalanceSapling / anchor / proofs when both are zero)\n w.compact(0) // nActionsOrchard\n return w.finish()\n}\n\n/** Parse raw hex / bytes. Accepts v5 transactions whose shielded bundles are empty; anything else is refused by name. */\nexport function parseTx(raw: string | Uint8Array): TransparentTxV5 {\n const r = new Reader(typeof raw === 'string' ? hexToBytes(raw) : raw)\n const header = r.u32()\n const overwintered = (header & 0x80000000) !== 0\n const version = header & 0x7fffffff\n if (!overwintered || version !== 5) throw new Error(`Only v5 Zcash transactions are supported here (got version ${version}${overwintered ? '' : ', not overwintered'}).`)\n const vgid = r.u32()\n if (vgid !== VERSION_GROUP_ID_V5) throw new Error(`Unexpected version group id 0x${vgid.toString(16)} for a v5 transaction.`)\n const consensusBranchId = r.u32()\n const lockTime = r.u32()\n const expiryHeight = r.u32()\n const nIn = r.compact()\n const inputs: TxInput[] = []\n for (let i = 0; i < nIn; i++) {\n const txid = bytesToHex(reverseBytes(r.bytes(32)))\n const vout = r.u32()\n const scriptSig = r.varBytes()\n const sequence = r.u32()\n inputs.push({ txid, vout, scriptSig, sequence })\n }\n const nOut = r.compact()\n const outputs: TxOutput[] = []\n for (let i = 0; i < nOut; i++) outputs.push({ value: r.i64(), script: r.varBytes() })\n const nSpends = r.compact()\n const nOutputs = r.compact()\n if (nSpends !== 0 || nOutputs !== 0) throw new Error('This transaction carries a Sapling bundle; shielded transactions are not supported.')\n const nActions = r.compact()\n if (nActions !== 0) throw new Error('This transaction carries an Orchard bundle; shielded transactions are not supported.')\n if (r.remaining !== 0) throw new Error(`Trailing bytes after the transaction (${r.remaining}).`)\n return { consensusBranchId, lockTime, expiryHeight, inputs, outputs }\n}\n\n// ── ZIP-244 digests ──────────────────────────────────────────────────────────\n\nfunction personal(tag: string): Uint8Array {\n const p = utf8ToBytes(tag)\n if (p.length !== 16) throw new Error(`BLAKE2b personalization must be 16 bytes: ${tag}`)\n return p\n}\n\nfunction h(tag: string | Uint8Array, data: Uint8Array): Uint8Array {\n return blake2b(data, { dkLen: 32, personalization: typeof tag === 'string' ? personal(tag) : tag })\n}\n\nconst EMPTY = new Uint8Array(0)\n\n/** `ZcashTxHash_` ‖ consensus branch id (LE) — the personalization of both the txid and the signature digest. */\nexport function txHashPersonalization(consensusBranchId: number): Uint8Array {\n const p = new Uint8Array(16)\n p.set(utf8ToBytes('ZcashTxHash_'), 0)\n p.set(u32le(consensusBranchId >>> 0), 12)\n return p\n}\n\nexport function headerDigest(tx: TransparentTxV5): Uint8Array {\n const w = new Writer().u32(TX_VERSION_V5).u32(VERSION_GROUP_ID_V5).u32(tx.consensusBranchId >>> 0).u32(tx.lockTime).u32(tx.expiryHeight)\n return h('ZTxIdHeadersHash', w.finish())\n}\n\nexport function prevoutsDigest(tx: TransparentTxV5): Uint8Array {\n const w = new Writer()\n for (const i of tx.inputs) { assertTxid(i.txid); w.bytes(reverseBytes(hexToBytes(i.txid))).u32(i.vout) }\n return h('ZTxIdPrevoutHash', w.finish())\n}\n\nexport function sequenceDigest(tx: TransparentTxV5): Uint8Array {\n const w = new Writer()\n for (const i of tx.inputs) w.u32(i.sequence)\n return h('ZTxIdSequencHash', w.finish())\n}\n\nexport function outputsDigest(tx: TransparentTxV5): Uint8Array {\n const w = new Writer()\n for (const o of tx.outputs) w.i64(o.value).varBytes(o.script)\n return h('ZTxIdOutputsHash', w.finish())\n}\n\n/** T.2: hash of the three transparent digests; the hash of the empty string when there are no inputs AND no outputs. */\nexport function transparentDigest(tx: TransparentTxV5): Uint8Array {\n if (tx.inputs.length === 0 && tx.outputs.length === 0) return h('ZTxIdTranspaHash', EMPTY)\n const w = new Writer().bytes(prevoutsDigest(tx)).bytes(sequenceDigest(tx)).bytes(outputsDigest(tx))\n return h('ZTxIdTranspaHash', w.finish())\n}\n\nexport const saplingDigestEmpty = (): Uint8Array => h('ZTxIdSaplingHash', EMPTY)\nexport const orchardDigestEmpty = (): Uint8Array => h('ZTxIdOrchardHash', EMPTY)\n\n/** Non-malleable transaction id (ZIP-244 T.1 … T.4), internal byte order. */\nexport function txidDigest(tx: TransparentTxV5): Uint8Array {\n const w = new Writer().bytes(headerDigest(tx)).bytes(transparentDigest(tx)).bytes(saplingDigestEmpty()).bytes(orchardDigestEmpty())\n return h(txHashPersonalization(tx.consensusBranchId), w.finish())\n}\n\n/** Transaction id as explorers display it (byte-reversed hex). */\nexport function txid(tx: TransparentTxV5): string {\n return bytesToHex(reverseBytes(txidDigest(tx)))\n}\n\n/**\n * ZIP-244 S.2 transparent signature digest + S.1 … S.4 wrapper for SIGHASH_ALL\n * over input `index`. `spent[i]` is the output input `i` spends (value and\n * scriptPubKey are both committed to, so a lying transport cannot make us sign\n * for a different amount).\n */\nexport function sighashAll(tx: TransparentTxV5, index: number, spent: SpentOutput[]): Uint8Array {\n if (spent.length !== tx.inputs.length) throw new Error(`sighash: ${tx.inputs.length} inputs but ${spent.length} spent outputs`)\n const input = tx.inputs[index]\n const coin = spent[index]\n if (!input || !coin) throw new Error(`sighash: input ${index} does not exist`)\n const amounts = new Writer()\n const scripts = new Writer()\n for (const s of spent) { amounts.i64(s.value); scripts.varBytes(s.script) }\n const txin = new Writer().bytes(reverseBytes(hexToBytes(input.txid))).u32(input.vout).i64(coin.value).varBytes(coin.script).u32(input.sequence)\n const t = new Writer()\n .u8(SIGHASH_ALL)\n .bytes(prevoutsDigest(tx))\n .bytes(h('ZTxTrAmountsHash', amounts.finish()))\n .bytes(h('ZTxTrScriptsHash', scripts.finish()))\n .bytes(sequenceDigest(tx))\n .bytes(outputsDigest(tx))\n .bytes(h('Zcash___TxInHash', txin.finish()))\n const transparentSig = h('ZTxIdTranspaHash', t.finish())\n const w = new Writer().bytes(headerDigest(tx)).bytes(transparentSig).bytes(saplingDigestEmpty()).bytes(orchardDigestEmpty())\n return h(txHashPersonalization(tx.consensusBranchId), w.finish())\n}\n\n/** `<sig ‖ 0x01> <pubkey>` — the scriptSig of a P2PKH spend. */\nexport function p2pkhScriptSig(derSignature: Uint8Array, publicKey: Uint8Array): Uint8Array {\n const sig = new Uint8Array(derSignature.length + 1)\n sig.set(derSignature, 0)\n sig[derSignature.length] = SIGHASH_ALL\n return new Writer().bytes(compactSize(sig.length)).bytes(sig).bytes(compactSize(publicKey.length)).bytes(publicKey).finish()\n}\n\n/** Split a P2PKH scriptSig back into DER signature (hash type stripped) and public key; undefined when it is not one. */\nexport function parseP2pkhScriptSig(scriptSig: Uint8Array): { signature: Uint8Array; hashType: number; publicKey: Uint8Array } | undefined {\n try {\n const r = new Reader(scriptSig)\n const sig = r.varBytes()\n const pub = r.varBytes()\n if (r.remaining !== 0 || sig.length < 9 || (pub.length !== 33 && pub.length !== 65)) return undefined\n return { signature: sig.slice(0, -1), hashType: sig[sig.length - 1]!, publicKey: pub }\n } catch { return undefined }\n}\n\nexport { i64le }\n","import { DUST_LIMIT, addressFromScript, decodeAddress, outputSize, scriptKind } from './address.js'\nimport { bytesToHex } from './encoding.js'\nimport { conventionalFee } from './fee.js'\nimport { serializeTx, txid as txidOf, type TransparentTxV5 } from './tx.js'\nimport type { SpentOutput, ZcashNetwork, ZcashTxDescription, ZcashTxOutputDescription, ZcashWarning } from './types.js'\n\n/** Default hard fee ceiling: 0.01 ZEC. */\nexport const DEFAULT_MAX_FEE = 1_000_000n\n\n/** Why a spend was refused before signing. */\nexport type UnsafeTransactionCode =\n /** Fee above `maxFee`. */\n | 'fee-too-high'\n /** Outputs exceed inputs. */\n | 'outputs-exceed-inputs'\n /** An output that is neither the requested recipient/amount nor our change. */\n | 'unexpected-output'\n /** The recipient output is missing or carries a different amount. */\n | 'recipient-mismatch'\n /** A change output pays an address that is not ours. */\n | 'change-not-ours'\n /** Off mainnet without a configured `consensusBranchId`: the branch id cannot be known. */\n | 'unknown-branch-id'\n\n/** A transaction failed a hard safety check and was not signed / broadcast. */\nexport class UnsafeTransactionError extends Error {\n readonly code: UnsafeTransactionCode\n constructor(code: UnsafeTransactionCode, message: string) {\n super(message)\n this.name = 'UnsafeTransactionError'\n this.code = code\n }\n}\n\n/** What a description needs to tell recipient, change and unknown outputs apart. */\nexport interface DescribeContext {\n network: ZcashNetwork\n /** Our own address: outputs paying it are tagged `change`. */\n ownAddress: string\n /** The spend the caller asked for. Outputs matching it are `recipient`; anything else is `unknown`. */\n intended?: { to: string; value: bigint } | undefined\n maxFee?: bigint | undefined\n}\n\n/** Byte size of a serialized input (what ZIP-317 counts). */\nfunction inputSizes(tx: TransparentTxV5): number[] {\n return tx.inputs.map((i) => 32 + 4 + (i.scriptSig.length < 0xfd ? 1 : 3) + i.scriptSig.length + 4)\n}\n\n/** Describe a (signed or unsigned) transaction given the output every input spends. Pure: no network, no signing. */\nexport function describeTransaction(tx: TransparentTxV5, spent: SpentOutput[], ctx: DescribeContext): ZcashTxDescription {\n if (spent.length !== tx.inputs.length) throw new Error(`describeTransaction: ${tx.inputs.length} inputs but ${spent.length} spent outputs`)\n const inputs = tx.inputs.map((i, k) => ({ txid: i.txid, vout: i.vout, value: spent[k]!.value, address: addressFromScript(spent[k]!.script, ctx.network) }))\n const outputs: ZcashTxOutputDescription[] = []\n const warnings = new Set<ZcashWarning>()\n // Outputs are matched by script, the recipient first: a transfer to oneself pays our own script\n // twice, recipient and change (round 3, L9).\n const scriptOf = (address: string): string | undefined => { try { return bytesToHex(decodeAddress(address, ctx.network).script) } catch { return undefined } }\n const ownScript = scriptOf(ctx.ownAddress)\n const intendedScript = ctx.intended ? scriptOf(ctx.intended.to) : undefined\n let recipientSeen = false\n for (const o of tx.outputs) {\n const address = addressFromScript(o.script, ctx.network)\n const script = bytesToHex(o.script)\n const mine = script === ownScript\n let role: ZcashTxOutputDescription['role']\n if (ctx.intended === undefined) role = mine ? 'change' : 'recipient'\n else if (!recipientSeen && script === intendedScript && o.value === ctx.intended.value) { role = 'recipient'; recipientSeen = true }\n else role = mine ? 'change' : 'unknown'\n if (scriptKind(o.script) !== 'unknown' && o.value < DUST_LIMIT) warnings.add('dust-output')\n outputs.push({ address, value: o.value, role })\n }\n const inputSum = spent.reduce((s, c) => s + c.value, 0n)\n const outputSum = tx.outputs.reduce((s, o) => s + o.value, 0n)\n const fee = inputSum - outputSum\n const amount = outputs.filter((o) => o.role !== 'change').reduce((s, o) => s + o.value, 0n)\n const conv = conventionalFee(inputSizes(tx), tx.outputs.map((o) => outputSize(o.script)))\n if (fee < conv) warnings.add('fee-below-conventional')\n if (amount > 0n && fee * 10n > amount) warnings.add('fee-over-10pct-of-amount')\n if (!outputs.some((o) => o.role === 'change')) warnings.add('no-change')\n if (tx.expiryHeight === 0) warnings.add('no-expiry')\n const signed = tx.inputs.length > 0 && tx.inputs.every((i) => i.scriptSig.length > 0)\n const desc: ZcashTxDescription = {\n kind: 'zcash-transfer', version: 5, consensusBranchId: tx.consensusBranchId, inputs, outputs, amount, fee, conventionalFee: conv,\n size: serializeTx(tx).length, lockTime: tx.lockTime, expiryHeight: tx.expiryHeight, warnings: [...warnings],\n }\n if (signed) desc.txid = txidOf(tx)\n return desc\n}\n\n/**\n * Hard checks run before signing and before broadcasting. Throws UnsafeTransactionError;\n * never mutates. With `intended`, exactly one output must be the requested\n * recipient/amount and every other output must be our change.\n */\nexport function assertSafe(desc: ZcashTxDescription, ctx: DescribeContext): void {\n const maxFee = ctx.maxFee ?? DEFAULT_MAX_FEE\n if (desc.fee < 0n) throw new UnsafeTransactionError('outputs-exceed-inputs', 'Outputs exceed inputs.')\n if (desc.fee > maxFee) throw new UnsafeTransactionError('fee-too-high', `Fee ${desc.fee} zatoshis exceeds the ${maxFee} zatoshi ceiling (maxFee).`)\n for (const o of desc.outputs) {\n if (o.role === 'change' && o.address !== ctx.ownAddress) throw new UnsafeTransactionError('change-not-ours', `Change output pays ${o.address ?? '<no address>'}, not ${ctx.ownAddress}.`)\n }\n if (ctx.intended) {\n const recipients = desc.outputs.filter((o) => o.role === 'recipient')\n if (recipients.length !== 1) throw new UnsafeTransactionError('recipient-mismatch', `Expected one output of ${ctx.intended.value} zatoshis to ${ctx.intended.to}, found ${recipients.length}.`)\n const unknown = desc.outputs.filter((o) => o.role === 'unknown')\n if (unknown.length) throw new UnsafeTransactionError('unexpected-output', `Transaction carries ${unknown.length} output(s) that are neither the recipient nor our change.`)\n }\n}\n","/**\n * Zcash Blockbook REST transport — the same `/api/v2` surface as Bitcoin's\n * (NOWNodes `https://zec-blockbook.nownodes.io` with an `api-key` header, any\n * self-hosted Blockbook built for Zcash). Serves testnet too.\n */\nimport { NetworkError } from '@anywalletkit/core'\nimport { hexToBytes } from './encoding.js'\nimport { DEFAULT_TIMEOUT_MS, fetchWithTimeout, isInt, isIntString, isRecord, refusal, refusedStatus } from './http.js'\nimport type { SpentOutput, Utxo, ZcashClient, ZcashTxInfo } from './types.js'\n\nexport interface BlockbookVin { txid?: string; vout?: number; n?: number; isAddress?: boolean; addresses?: string[]; value?: string }\nexport interface BlockbookVout { n: number; isAddress?: boolean; addresses?: string[]; value?: string; hex?: string }\nexport interface BlockbookTxDetails {\n txid: string\n blockHeight: number\n confirmations: number\n blockTime?: number\n fees?: string\n hex?: string\n vin?: BlockbookVin[]\n vout?: BlockbookVout[]\n}\n\nexport class ZcashBlockbookClient implements ZcashClient {\n private readonly base: string\n private readonly headers: Record<string, string>\n private readonly fetchFn: typeof fetch\n private readonly timeoutMs: number\n\n constructor(config: { url: string; headers?: Record<string, string> }, fetchFn: typeof fetch = globalThis.fetch, timeoutMs = DEFAULT_TIMEOUT_MS) {\n this.base = config.url.replace(/\\/+$/, '').replace(/\\/api$/, '')\n this.headers = { accept: 'application/json', ...(config.headers ?? {}) }\n this.fetchFn = fetchFn\n this.timeoutMs = timeoutMs\n }\n\n async connect(): Promise<void> {}\n async close(): Promise<void> {}\n\n private async get<T>(path: string, check: (v: unknown) => v is T): Promise<T> {\n const url = `${this.base}/api${path}`\n const res = await fetchWithTimeout(this.fetchFn, url, { headers: this.headers }, this.timeoutMs, this.base)\n if (!res.ok) {\n // A 4xx (not 408) is the server refusing: nothing was taken. A 5xx may have been forwarded (round 3, M12).\n const reason = refusedStatus(res.status) ? (await res.text().catch(() => '')).slice(0, 200) : ''\n const err = new NetworkError(`Blockbook request failed: ${res.status} ${res.statusText} (${url})${reason ? `: ${reason}` : ''}`, { provider: this.base })\n throw refusedStatus(res.status) ? refusal(err) : err\n }\n let body: unknown\n try { body = await res.json() } catch (e) { throw new NetworkError(`Blockbook returned non-JSON for ${url}`, { provider: this.base, cause: e }) }\n if (!check(body)) throw new NetworkError(`Blockbook returned an unexpected shape for ${url}`, { provider: this.base })\n return body\n }\n\n async getBalance(address: string) {\n const data = await this.get(`/v2/address/${address}?details=basic`, (v): v is { balance: string; unconfirmedBalance: string } => isRecord(v) && isIntString(v.balance) && isIntString(v.unconfirmedBalance))\n return { confirmed: BigInt(data.balance), unconfirmed: BigInt(data.unconfirmedBalance) }\n }\n\n async listUnspent(address: string): Promise<Utxo[]> {\n const data = await this.get(`/v2/utxo/${address}`, (v): v is Array<{ txid: string; vout: number; value: string; height?: number }> =>\n Array.isArray(v) && v.every((u) => isRecord(u) && typeof u.txid === 'string' && isInt(u.vout) && isIntString(u.value)))\n return data.map((u) => ({ txid: u.txid, vout: u.vout, value: BigInt(u.value), height: u.height && u.height > 0 ? u.height : -1 }))\n }\n\n private static isTx(v: unknown): v is BlockbookTxDetails {\n return isRecord(v) && typeof v.txid === 'string' && isInt(v.blockHeight) && isInt(v.confirmations)\n }\n\n async getTransactionDetails(txid: string): Promise<BlockbookTxDetails | undefined> {\n try { return await this.get(`/v2/tx/${txid}`, ZcashBlockbookClient.isTx) } catch (e) {\n if (e instanceof NetworkError && /\\b(400|404)\\b/.test(e.message)) return undefined\n throw e\n }\n }\n\n async getTransaction(txid: string): Promise<string> {\n const tx = await this.get(`/v2/tx/${txid}`, ZcashBlockbookClient.isTx)\n if (typeof tx.hex !== 'string' || !tx.hex) throw new NetworkError(`Transaction ${txid} has no hex data`, { provider: this.base })\n return tx.hex\n }\n\n async getOutput(txid: string, vout: number): Promise<SpentOutput | undefined> {\n const tx = await this.getTransactionDetails(txid)\n const o = tx?.vout?.find((x) => x.n === vout)\n if (!o || !isIntString(o.value) || typeof o.hex !== 'string') return undefined\n return { value: BigInt(o.value), script: hexToBytes(o.hex) }\n }\n\n async getTransactionInfo(txid: string): Promise<ZcashTxInfo | undefined> {\n const tx = await this.getTransactionDetails(txid)\n if (!tx) return undefined\n const info: ZcashTxInfo = { txid: tx.txid, blockHeight: tx.blockHeight > 0 ? tx.blockHeight : -1, confirmations: tx.confirmations }\n if (isIntString(tx.fees)) info.fee = BigInt(tx.fees)\n if (typeof tx.blockTime === 'number') info.blockTime = tx.blockTime\n return info\n }\n\n async broadcast(rawTx: string): Promise<string> {\n const data = await this.get(`/v2/sendtx/${rawTx}`, (v): v is { result?: string; error?: { message?: string } | string } => isRecord(v))\n if (data.error) throw refusal(new Error(`Broadcast rejected: ${typeof data.error === 'string' ? data.error : data.error.message ?? 'broadcast failed'}`))\n if (!data.result) throw new NetworkError('Blockbook returned no txid', { provider: this.base })\n return data.result\n }\n\n async getBlockHeight(): Promise<number> {\n const data = await this.get('/v2', (v): v is { blockbook?: { bestHeight?: number } } => isRecord(v))\n const h = data.blockbook?.bestHeight\n if (typeof h !== 'number' || h <= 0) throw new NetworkError('Blockbook did not report a block height', { provider: this.base })\n return h\n }\n}\n","import { NetworkError } from '@anywalletkit/core'\nimport { BlockchairClient } from './blockchair.js'\nimport { ZcashBlockbookClient } from './blockbook.js'\nimport { DEFAULT_TIMEOUT_MS, isAnsweredRefusal } from './http.js'\nimport type { ZcashClient, ZcashClientConfig, ZcashConfig } from './types.js'\n\nconst isClient = (c: unknown): c is ZcashClient => typeof c === 'object' && c !== null && typeof (c as ZcashClient).listUnspent === 'function'\n\nfunction toClient(c: ZcashClientConfig | ZcashClient, fetchFn: typeof fetch | undefined, timeoutMs: number): ZcashClient {\n if (isClient(c)) return c\n switch (c.type) {\n case 'blockchair': return new BlockchairClient(c.clientConfig ?? {}, fetchFn, timeoutMs)\n case 'blockbook-http': return new ZcashBlockbookClient(c.clientConfig, fetchFn, timeoutMs)\n default: throw new Error(`Unknown Zcash client type: ${String((c as { type: string }).type)}`)\n }\n}\n\nconst METHODS = ['connect', 'close', 'getBalance', 'listUnspent', 'getTransaction', 'getOutput', 'getTransactionInfo', 'broadcast', 'getBlockHeight'] as const\n\n/**\n * One client, or a failover client over the list: each call walks the list in\n * order, `retries` extra rounds. A node's refusal of a broadcast is final when\n * no endpoint before it went silent; after a silent one the transaction may be\n * out, so the result is \"maybe sent\" (round 3, M12). Transport failures move on.\n */\nexport function createClient(config: ZcashConfig): ZcashClient | undefined {\n if (config.client === undefined) return undefined\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const list = (Array.isArray(config.client) ? config.client : [config.client]).map((c) => toClient(c, config.fetch, timeoutMs))\n if (list.length === 0) return undefined\n if (list.length === 1) return list[0]!\n const attempts = list.length + (config.retries ?? 3)\n const call = (method: (typeof METHODS)[number]) => async (...args: unknown[]) => {\n let last: unknown\n let silent = false\n for (let i = 0; i < attempts; i++) {\n const c = list[i % list.length]! as unknown as Record<string, (...a: unknown[]) => Promise<unknown>>\n try { return await c[method]!.apply(c, args) } catch (e) {\n if (method === 'broadcast') {\n if (isAnsweredRefusal(e)) {\n if (!silent) throw e\n throw new NetworkError('A Zcash client refused the broadcast after another never answered: it may be out', { cause: e })\n }\n silent = true\n }\n last = e\n }\n }\n throw new NetworkError(`All Zcash clients failed for ${method}`, { cause: last })\n }\n const out = {} as Record<(typeof METHODS)[number], (...args: unknown[]) => Promise<unknown>>\n for (const m of METHODS) out[m] = call(m)\n return out as unknown as ZcashClient\n}\n","/**\n * The transaction was handed to the network but no definitive answer came back (no response, a\n * timeout, a 5xx, an unreadable body): it MAY be in the mempool. Do not spend the same coins again —\n * watch `hash`, the txid computed before sending (round 3, M12).\n */\nexport class BroadcastUnknownError extends Error {\n /** Always true: the transaction may be on its way. */\n readonly maybeSent = true\n /** The transaction id (hex). */\n readonly hash: string\n constructor(hash: string, cause: unknown) {\n super(`Broadcast outcome unknown for ${hash}: ${cause instanceof Error ? cause.message.slice(0, 200) : String(cause).slice(0, 200)}`, { cause })\n this.name = 'BroadcastUnknownError'\n this.hash = hash\n }\n}\n","/**\n * Zcash signed messages (zcashd `signmessage` / `verifymessage`): the Bitcoin\n * scheme with the `Zcash Signed Message:\\n` magic. hash = sha256d(varint(prefix)\n * ‖ prefix ‖ varint(len) ‖ message); header byte = 27 + recovery + 4\n * (compressed key); output base64 of header ‖ r ‖ s. RFC-6979 deterministic, low-S.\n */\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { base64 } from '@scure/base'\nimport type { Signer } from '@anywalletkit/core'\nimport { compactSize, utf8ToBytes } from './encoding.js'\n\nconst MAGIC = 'Zcash Signed Message:\\n'\nconst PREFIX = utf8ToBytes(MAGIC)\n\n/** Hash of a signed message (`Zcash Signed Message:` prefix, double SHA-256). */\nexport function magicHash(message: string | Uint8Array): Uint8Array {\n const msg = typeof message === 'string' ? utf8ToBytes(message) : message\n const p = compactSize(PREFIX.length), l = compactSize(msg.length)\n const buf = new Uint8Array(p.length + PREFIX.length + l.length + msg.length)\n let o = 0\n for (const part of [p, PREFIX, l, msg]) { buf.set(part, o); o += part.length }\n return sha256(sha256(buf))\n}\n\n/** Encode `r‖s` + recovery id as a base64 signature (compressed-key header 31 + recovery). */\nexport function encodeMessageSignature(rs: Uint8Array, recovery: number): string {\n if (rs.length !== 64 || recovery > 3) throw new Error('Expected a 64-byte r‖s signature and a recovery id 0..3.')\n const out = new Uint8Array(65)\n out[0] = 27 + 4 + recovery\n out.set(rs, 1)\n return base64.encode(out)\n}\n\n/** Sign through a {@link Signer} (`ecdsa-recoverable`, context `zcash-message`). */\nexport async function signMessageWith(message: string | Uint8Array, signer: Signer): Promise<string> {\n const sig = await signer.sign(magicHash(message), { scheme: 'ecdsa-recoverable', context: 'zcash-message' })\n return encodeMessageSignature(sig.subarray(0, 64), sig[64]!)\n}\n\n/** Recover the compressed public key from a message signature, or undefined when malformed. */\nexport function recoverMessagePublicKey(message: string | Uint8Array, signature: string): Uint8Array | undefined {\n let bytes: Uint8Array\n try { bytes = base64.decode(signature) } catch { return undefined }\n if (bytes.length !== 65) return undefined\n const flag = bytes[0]! - 27\n if (flag < 0 || flag > 15) return undefined\n const recovered = new Uint8Array(65)\n recovered[0] = flag & 3\n recovered.set(bytes.subarray(1), 1)\n try {\n const pub = secp256k1.recoverPublicKey(recovered, magicHash(message), { prehash: false })\n return pub.length === 33 ? pub : secp256k1.Point.fromBytes(pub).toBytes(true)\n } catch { return undefined }\n}\n","import { LocalSigner, SignerError, WalletManager, isSeedSigner, type FeeRates, type Signer } from '@anywalletkit/core'\nimport { WalletAccountZcash } from './account.js'\nimport { MARGINAL_FEE } from './fee.js'\nimport { WalletAccountReadOnlyZcash } from './read-only-account.js'\nimport type { ZcashConfig, ZcashNetwork } from './types.js'\n\n/** SLIP-44 coin type: 133 for mainnet, 1 for testnet. */\nexport const coinType = (network: ZcashNetwork): 133 | 1 => (network === 'mainnet' ? 133 : 1)\n\n/**\n * One seed → Zcash transparent accounts at m/44'/133'/0'/0/i (BIP-44, the path\n * Zashi, YWallet, Ledger and Trezor use for the transparent receiver) — t1… on\n * mainnet, tm… on testnet. Paths may be relative to the purpose/coin prefix\n * (\"0'/0/i\") or given in full.\n *\n * Built with a secp256k1 `Signer` instead of a seed, the manager wraps it:\n * a derivable `SeedSigner` yields `getAccount(i)` children below its path; a\n * leaf or external signer is `getAccount(0)`.\n */\nexport class WalletManagerZcash extends WalletManager<WalletAccountZcash, ZcashConfig> {\n constructor(seedOrSigner: string | Uint8Array | Signer, config: ZcashConfig = {}) {\n super(seedOrSigner, config)\n }\n\n /** `m/44'/133'` on mainnet (coin type 1 on testnet); account `i` is at `basePath/0'/0/i`. */\n get basePath(): string {\n return `m/44'/${coinType(this._config.network ?? 'mainnet')}'`\n }\n\n async getAccount(index = 0): Promise<WalletAccountZcash> {\n return this.getAccountByPath(`${this.basePath}/0'/0/${index}`)\n }\n\n async getAccountByPath(path: string): Promise<WalletAccountZcash> {\n const full = path.startsWith('m/') ? path : `${this.basePath}/${path}`\n const cached = this._accounts.get(full)\n if (cached) return cached\n const external = this.externalSigner()\n if (external) return this.fromSigner(external, full)\n return this.cachedAccount(full, () => {\n const signer = LocalSigner.leafFromSeed(this.seedBytes(), 'secp256k1', full)\n return new WalletAccountZcash(signer, signer.publicKey, full, this._config)\n })\n }\n\n private async fromSigner(signer: Signer, path: string): Promise<WalletAccountZcash> {\n this.requireSigner('secp256k1')\n let rel: string | undefined\n let key = 'external'\n if (isSeedSigner(signer)) {\n if (path === signer.path) key = path\n else if (path.startsWith(`${signer.path}/`)) { rel = path.slice(signer.path.length + 1); key = path }\n else throw new SignerError(`The injected signer sits at ${signer.path}; it cannot provide ${path}.`)\n } else if (path !== `${this.basePath}/0'/0/0` && path !== 'external') {\n throw new SignerError(`An external signer has one account; ${path} is not derivable from it.`)\n }\n return this.signerAccount(key, signer, rel, (leaf, publicKey) => new WalletAccountZcash(leaf, publicKey, key, this._config))\n }\n\n /** A read-only account for any transparent address, with this manager's config. */\n getReadOnlyAccount(address: string): WalletAccountReadOnlyZcash {\n return new WalletAccountReadOnlyZcash(address, this._config)\n }\n\n /** ZIP-317 has no fee market: every tier is the 5000-zatoshi marginal fee per logical action. */\n async getFeeRates(): Promise<FeeRates> {\n return { slow: MARGINAL_FEE, normal: MARGINAL_FEE, fast: MARGINAL_FEE }\n }\n}\n","import { InsufficientFundsError, LocalSigner, NetworkError, SignerError, feeLimit, requireCurve, type IWalletAccount, type IWalletAccountReadOnly, type Signer, type TransferResult, type WriteOptions } from '@anywalletkit/core'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { DUST_LIMIT, addressFromPublicKey } from './address.js'\nimport { UnsafeTransactionError, assertSafe, describeTransaction, type DescribeContext } from './describe.js'\nimport { bytesToHex } from './encoding.js'\nimport { BroadcastUnknownError } from './errors.js'\nimport { isAlreadyKnown, isAnsweredRefusal } from './http.js'\nimport { signMessageWith } from './message.js'\nimport { WalletAccountReadOnlyZcash, type SpendPlan } from './read-only-account.js'\nimport { FINAL_SEQUENCE, branchIdForHeight, p2pkhScriptSig, parseTx, serializeTx, sighashAll, txid as txidOf, type TransparentTxV5 } from './tx.js'\nimport type { SpentOutput, ZcashClient, ZcashConfig, ZcashNetwork, ZcashSpend, ZcashTransaction, ZcashTransferOptions, ZcashTxDescription } from './types.js'\n\nexport { addressFromPublicKey }\n\n/** t-address for a compressed public key. */\nexport function addressFor(publicKey: Uint8Array, network: ZcashNetwork = 'mainnet'): string {\n return addressFromPublicKey(publicKey, network)\n}\n\n/** ZIP-203 default: a transaction expires 40 blocks (~50 min) after it was built. */\nexport const DEFAULT_EXPIRY_DELTA = 40\n\ninterface Built {\n tx: TransparentTxV5\n hex: string\n txid: string\n fee: bigint\n plan: SpendPlan\n desc: ZcashTxDescription\n}\n\n/**\n * Signing Zcash account — BIP-44 P2PKH at m/44'/133'/0'/0/i (t1…). The key never\n * enters this package: every input is one `signer.sign(...)` call over the\n * ZIP-244 signature digest computed here (`ecdsa`, DER-encoded + SIGHASH_ALL\n * into the scriptSig); messages are `ecdsa-recoverable` over the Zcash magic hash.\n *\n * Every spend is resolved to a full description (\"what you sign\") and run through\n * the hard safety checks (fee ceiling, recipient/amount exactness, change\n * ownership) before signing AND before broadcast — also for caller-supplied raw hex.\n */\nexport class WalletAccountZcash extends WalletAccountReadOnlyZcash implements IWalletAccount {\n /** UTXOs and the tip height come from the network before signing. */\n readonly needsNetwork = true\n /** Derivation path, or `external` for an external signer. */\n readonly path: string\n /** Compressed secp256k1 public key. */\n readonly publicKey: Uint8Array\n /** The signer that holds the key. */\n readonly signer: Signer\n private _disposed = false\n private _readOnly: WalletAccountReadOnlyZcash | undefined\n\n /** `publicKey` is the signer's compressed secp256k1 key (33 bytes); it is needed synchronously for the address. */\n constructor(signer: Signer, publicKey: Uint8Array, path: string, config: ZcashConfig = {}) {\n super(addressFromPublicKey(publicKey, config.network ?? 'mainnet'), config)\n this.signer = requireCurve(signer, 'secp256k1')\n if (!this.signer.schemes.includes('ecdsa')) throw new SignerError(`A Zcash account needs a signer with the 'ecdsa' scheme (has: ${this.signer.schemes.join(', ')}).`)\n this.publicKey = publicKey\n this.path = path\n }\n\n /** Back-compat: wrap a raw derived key in a {@link LocalSigner} (the account takes ownership; it cannot derive). */\n static fromPrivateKey(privateKey: Uint8Array, publicKey: Uint8Array, path: string, config: ZcashConfig = {}): WalletAccountZcash {\n return new WalletAccountZcash(LocalSigner.fromPrivateKey('secp256k1', privateKey, publicKey, path), publicKey, path, config)\n }\n\n /** Account index for the standard m/44'/133'/0'/0/i path. */\n get index(): number | undefined {\n const m = /^m\\/44'\\/(133|1)'\\/0'\\/0\\/(\\d+)$/.exec(this.path)\n return m ? Number(m[2]) : undefined\n }\n\n private live(): void {\n if (this._disposed) throw new SignerError('This account has been disposed.')\n }\n\n /** Zcash message signature (zcashd `signmessage` encoding), base64. */\n async sign(message: string | Uint8Array): Promise<string> {\n this.live()\n return signMessageWith(message, this.signer)\n }\n\n private ctx(intended?: { to: string; value: bigint }): DescribeContext {\n return { network: this._network, ownAddress: this.address, intended, maxFee: this.maxFee }\n }\n\n /**\n * Lock time, expiry and branch id for a transaction that lands in the next block (round 3, L7):\n * expiry = tip + 1 + `expiryDelta`, the branch id in force at tip + 1 (mainnet table; off mainnet\n * `consensusBranchId` must be configured — testnet and regtest activate upgrades at other heights).\n * Without a tip nothing is signed when the expiry, anti-fee-sniping or the branch id need it: a\n * transaction signed with expiry 0 never expires.\n */\n private async chainParams(): Promise<{ lockTime: number; expiryHeight: number; consensusBranchId: number }> {\n const delta = this._config.expiryDelta ?? DEFAULT_EXPIRY_DELTA\n const configured = this._config.consensusBranchId\n if (configured === undefined && this._network !== 'mainnet') {\n throw new UnsafeTransactionError('unknown-branch-id', `On ${this._network} the consensus branch id depends on that network's upgrade heights; set consensusBranchId in the config.`)\n }\n const antiSnipe = this._config.antiFeeSniping !== false\n const needTip = delta > 0 || antiSnipe || configured === undefined\n const tip = needTip ? await this.tipHeight() : undefined\n if (needTip && tip === undefined) throw new NetworkError('The Zcash chain tip is unknown, so the expiry height and the branch id cannot be set; nothing was signed.')\n const next = tip === undefined ? undefined : tip + 1\n const consensusBranchId = configured ?? branchIdForHeight(next)\n const lockTime = tip !== undefined && antiSnipe ? tip : 0\n const expiryHeight = next !== undefined && delta > 0 ? next + delta : 0\n return { lockTime, expiryHeight, consensusBranchId }\n }\n\n /** Sign every input through the signer; the scriptSig is `<DER ‖ 0x01> <pubkey>`. */\n private async signInputs(tx: TransparentTxV5, spent: SpentOutput[]): Promise<void> {\n for (let i = 0; i < tx.inputs.length; i++) {\n const digest = sighashAll(tx, i, spent)\n const rs = await this.signer.sign(digest, { scheme: 'ecdsa', context: 'zcash-sighash' })\n const der = secp256k1.Signature.fromBytes(rs, 'compact').toBytes('der')\n tx.inputs[i]!.scriptSig = p2pkhScriptSig(der, this.publicKey)\n }\n }\n\n protected async signSpend(spend: ZcashSpend): Promise<Built> {\n this.live()\n const plan = await this.planSpend(spend)\n const params = await this.chainParams()\n const tx: TransparentTxV5 = {\n ...params,\n inputs: plan.utxos.map((u) => ({ txid: u.txid, vout: u.vout, scriptSig: new Uint8Array(0), sequence: FINAL_SEQUENCE })),\n outputs: [{ value: plan.amount, script: plan.recipient.script }, ...(plan.change > 0n ? [{ value: plan.change, script: this.scriptPubKey }] : [])],\n }\n const spent: SpentOutput[] = plan.utxos.map((u) => ({ value: u.value, script: this.scriptPubKey }))\n const have = plan.utxos.reduce((s, u) => s + u.value, 0n)\n if (have < plan.amount + plan.fee) throw new InsufficientFundsError(plan.amount + plan.fee, have, 'ZEC')\n await this.signInputs(tx, spent)\n const ctx = this.ctx({ to: spend.to, value: plan.amount })\n const desc = describeTransaction(tx, spent, ctx)\n assertSafe(desc, ctx)\n const bytes = serializeTx(tx)\n return { tx, hex: bytesToHex(bytes), txid: txidOf(tx), fee: plan.fee, plan, desc }\n }\n\n private checkMax(fee: bigint, limit: bigint | number | undefined, op: string) {\n if (limit !== undefined && fee > BigInt(limit)) throw new Error(`Exceeded maximum fee cost for ${op} operation.`)\n }\n\n /** The outputs a raw transaction spends, fetched through the client (the wire format carries no values). */\n private async spentOutputs(tx: TransparentTxV5): Promise<SpentOutput[]> {\n const client = this.requireClient('inspect a raw transaction')\n const out: SpentOutput[] = []\n for (const i of tx.inputs) {\n const o = await client.getOutput(i.txid, i.vout)\n if (!o) throw new Error(`Prevout ${i.txid}:${i.vout} not found.`)\n out.push(o)\n }\n return out\n }\n\n /** Describe a raw signed tx (needs the network for prevouts) and run the safety checks. */\n private async describeRaw(rawHex: string): Promise<{ tx: TransparentTxV5; desc: ZcashTxDescription }> {\n const tx = parseTx(rawHex)\n const ctx = this.ctx()\n const desc = describeTransaction(tx, await this.spentOutputs(tx), ctx)\n assertSafe(desc, ctx)\n return { tx, desc }\n }\n\n /** \"What you sign\": the fully resolved spend (signed, NOT broadcast) or a caller's raw hex. */\n async describeTransaction(tx: ZcashTransaction): Promise<ZcashTxDescription> {\n if (typeof tx === 'string') return (await this.describeRaw(tx)).desc\n return (await this.signSpend(tx)).desc\n }\n\n /** Sign without broadcasting. Returns the raw transaction hex. Raw hex input gets the checks `sendTransaction` runs (prevouts through the client) and is returned unchanged, never re-signed. */\n async signTransaction(tx: ZcashTransaction, options: WriteOptions = {}): Promise<string> {\n this.live()\n if (typeof tx === 'string') {\n const { desc } = await this.describeRaw(tx)\n this.checkMax(desc.fee, feeLimit(this._config.transactionMaxFee, options), 'transaction')\n return tx\n }\n const built = await this.signSpend(tx)\n this.checkMax(built.fee, feeLimit(this._config.transactionMaxFee, options), 'transaction')\n return built.hex\n }\n\n override async quoteSendTransaction(tx: ZcashTransaction): Promise<{ fee: bigint }> {\n if (typeof tx === 'string') return { fee: (await this.describeRaw(tx)).desc.fee }\n return super.quoteSendTransaction(tx)\n }\n\n async sendTransaction(tx: ZcashTransaction, options: WriteOptions = {}): Promise<TransferResult> {\n this.live()\n const client = this.requireClient('send transactions')\n let rawHex: string, hash: string, fee: bigint\n if (typeof tx === 'string') {\n const { tx: parsed, desc } = await this.describeRaw(tx)\n rawHex = tx; hash = txidOf(parsed); fee = desc.fee\n } else {\n const built = await this.signSpend(tx)\n rawHex = built.hex; hash = built.txid; fee = built.fee\n }\n this.checkMax(fee, feeLimit(this._config.transactionMaxFee, options), 'transaction')\n return { hash: await this.broadcast(client, rawHex, hash), fee }\n }\n\n /** Native ZEC only (`token` is rejected). Subject to `transferMaxFee`. */\n async transfer(o: ZcashTransferOptions, writeOptions: WriteOptions = {}): Promise<TransferResult> {\n if (o.token) throw new Error('Tokens are not supported on the zcash blockchain.')\n this.live()\n const client = this.requireClient('transfer')\n const built = await this.signSpend({ to: o.recipient, value: o.amount })\n this.checkMax(built.fee, feeLimit(this._config.transferMaxFee, writeOptions), 'transfer')\n return { hash: await this.broadcast(client, built.hex, built.txid), fee: built.fee }\n }\n\n /**\n * Send once through the client. Only a node's refusal means nothing went out; \"already in the\n * mempool / block chain\" means an earlier attempt delivered it; anything else may have landed and\n * is a {@link BroadcastUnknownError} with the txid computed before sending (round 3, M12).\n */\n private async broadcast(client: ZcashClient, rawHex: string, txid: string): Promise<string> {\n try {\n return (await client.broadcast(rawHex)) || txid\n } catch (e) {\n if (isAlreadyKnown(e)) return txid\n if (isAnsweredRefusal(e)) throw e\n throw new BroadcastUnknownError(txid, e)\n }\n }\n\n /** The same address as a {@link WalletAccountReadOnlyZcash}. */\n toReadOnlyAccount(): IWalletAccountReadOnly {\n this._readOnly ??= new WalletAccountReadOnlyZcash(this.address, this._config)\n return this._readOnly\n }\n\n dispose(): void {\n this._disposed = true\n this.signer.dispose()\n }\n}\n\nexport { DUST_LIMIT, UnsafeTransactionError }\n","import { InsufficientFundsError, NetworkError, type IWalletAccountReadOnly } from '@anywalletkit/core'\nimport { DUST_LIMIT, addressFromPublicKey, decodeAddress, outputSize, type DecodedAddress } from './address.js'\nimport { createClient } from './client.js'\nimport { DEFAULT_MAX_FEE } from './describe.js'\nimport { MAX_UTXO_INPUTS, selectAll, selectCoins, type CoinSelection } from './fee.js'\nimport { recoverMessagePublicKey } from './message.js'\nimport { CAIP2, type ZcashClient, type ZcashConfig, type ZcashMaxSpendableResult, type ZcashNetwork, type ZcashReceipt, type ZcashSpend, type ZcashTransferOptions } from './types.js'\n\n/** A coin selection for one spend, with the decoded recipient. */\nexport interface SpendPlan extends CoinSelection {\n /** Zatoshis the recipient gets (the requested value — never reduced). */\n amount: bigint\n recipient: DecodedAddress\n}\n\nconst toBig = (v: bigint | number | string): bigint => (typeof v === 'bigint' ? v : BigInt(typeof v === 'string' ? v.trim() : Math.round(v)))\n\n/** Watch-only Zcash account: balances, quotes, receipts, message verification. No key. */\nexport class WalletAccountReadOnlyZcash implements IWalletAccountReadOnly {\n /** The transparent address. */\n readonly address: string\n readonly chain: string\n /** The address's scriptPubKey. */\n readonly scriptPubKey: Uint8Array\n /** Script type of the address. */\n readonly scriptKind: DecodedAddress['kind']\n protected readonly _config: ZcashConfig\n protected readonly _client: ZcashClient | undefined\n protected readonly _network: ZcashNetwork\n\n constructor(address: string, config: ZcashConfig = {}) {\n this._config = config\n this._network = config.network ?? 'mainnet'\n const decoded = decodeAddress(address, this._network)\n this.address = address.trim()\n this.scriptPubKey = decoded.script\n this.scriptKind = decoded.kind\n this.chain = CAIP2[this._network]\n this._client = createClient(config)\n }\n\n protected requireClient(what: string): ZcashClient {\n if (!this._client) throw new NetworkError(`The wallet must be connected to a client to ${what}.`)\n return this._client\n }\n\n /** Fee ceiling in zatoshis: `ZcashConfig.maxFee` or the default. */\n get maxFee(): bigint {\n return this._config.maxFee !== undefined ? toBig(this._config.maxFee) : DEFAULT_MAX_FEE\n }\n\n /** The transparent address. */\n async getAddress(): Promise<string> { return this.address }\n\n /** Confirmed plus incoming mempool value (the transports do not expose pending spends of our own outputs). */\n async getBalance(): Promise<bigint> {\n const { confirmed, unconfirmed } = await this.requireClient('read balances').getBalance(this.address)\n return confirmed + unconfirmed\n }\n\n /** Always throws: Zcash has no tokens. */\n async getTokenBalance(_token: string): Promise<bigint> {\n throw new Error(\"The 'getTokenBalance' method is not supported on the zcash blockchain.\")\n }\n\n /** Coin selection for a spend (ZIP-317 fee). Validates the recipient and the dust floor first. */\n protected async planSpend(spend: ZcashSpend): Promise<SpendPlan> {\n if (this.scriptKind !== 'p2pkh') throw new Error(`Cannot build spends from a ${this.scriptKind} address; only P2PKH (t1…) accounts spend.`)\n const amount = toBig(spend.value)\n const recipient = decodeAddress(spend.to, this._network)\n if (amount < DUST_LIMIT) throw new Error(`The amount must be at least the dust limit (${DUST_LIMIT} zatoshis).`)\n const utxos = await this.requireClient('plan a spend').listUnspent(this.address)\n if (utxos.length === 0) throw new InsufficientFundsError(amount, 0n, 'ZEC')\n const selection = selectCoins({\n utxos,\n target: amount,\n recipientOutputSize: outputSize(recipient.script),\n changeOutputSize: outputSize(this.scriptPubKey),\n maxInputs: this._config.maxInputs ?? MAX_UTXO_INPUTS,\n ...(spend.fee !== undefined ? { fee: toBig(spend.fee) } : {}),\n })\n return { ...selection, amount, recipient }\n }\n\n /** ZIP-317 fee of a spend in zatoshis. */\n async quoteSendTransaction(tx: ZcashSpend): Promise<{ fee: bigint }> {\n const { fee } = await this.planSpend(tx)\n return { fee }\n }\n\n /** ZIP-317 fee of a transfer in zatoshis. */\n async quoteTransfer(o: ZcashTransferOptions): Promise<{ fee: bigint }> {\n if (o.token) throw new Error('Tokens are not supported on the zcash blockchain.')\n return this.quoteSendTransaction({ to: o.recipient, value: o.amount })\n }\n\n /** Everything spendable in ONE transaction to a single output, no change. */\n async getMaxSpendable(opts: { to?: string; fee?: bigint | number } = {}): Promise<ZcashMaxSpendableResult> {\n const utxos = await this.requireClient('plan a spend').listUnspent(this.address)\n const outScript = opts.to ? decodeAddress(opts.to, this._network).script : this.scriptPubKey\n const sweep = selectAll({ utxos, outputSize: outputSize(outScript), maxInputs: this._config.maxInputs ?? MAX_UTXO_INPUTS, ...(opts.fee !== undefined ? { fee: toBig(opts.fee) } : {}) })\n const amount = sweep.amount >= DUST_LIMIT ? sweep.amount : 0n\n return { amount, fee: amount > 0n ? sweep.fee : 0n, changeValue: 0n, inputs: amount > 0n ? sweep.utxos.length : 0 }\n }\n\n /** Undefined until the transaction is mined. */\n async getTransactionReceipt(hash: string): Promise<ZcashReceipt | undefined> {\n if (!/^[0-9a-fA-F]{64}$/.test(hash)) throw new Error(\"The 'getTransactionReceipt(hash)' method requires a valid transaction hash.\")\n const info = await this.requireClient('fetch transaction receipts').getTransactionInfo(hash)\n if (!info || info.blockHeight <= 0) return undefined\n return { hash, status: 1, blockNumber: BigInt(info.blockHeight), confirmations: info.confirmations, ...(info.fee !== undefined ? { fee: info.fee } : {}) }\n }\n\n /** Recover the key from a Zcash message signature and compare its P2PKH address with ours. */\n async verify(message: string | Uint8Array, signature: string): Promise<boolean> {\n const pub = recoverMessagePublicKey(message, signature)\n if (!pub) return false\n try { return addressFromPublicKey(pub, this._network) === this.address } catch { return false }\n }\n\n /** Chain tip for lock time / expiry; undefined when the transport cannot tell. */\n protected async tipHeight(): Promise<number | undefined> {\n if (!this._client) return undefined\n try { return await this._client.getBlockHeight() } catch { return undefined }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,SAAS,cAAc;AACvB,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAG5B,IAAM,MAAM,YAAY,MAAM;AAc9B,IAAM,SAA8E;AAAA,EAClF,SAAS,EAAE,OAAO,CAAC,IAAM,GAAI,GAAG,MAAM,CAAC,IAAM,GAAI,EAAE;AAAA,EACnD,SAAS,EAAE,OAAO,CAAC,IAAM,EAAI,GAAG,MAAM,CAAC,IAAM,GAAI,EAAE;AACrD;AAGO,SAAS,cAAc,SAAuB,MAA6C;AAChG,SAAO,OAAO,OAAO,EAAE,IAAI;AAC7B;AAGO,SAAS,QAAQ,MAA8B;AACpD,SAAO,UAAU,OAAO,IAAI,CAAC;AAC/B;AAGO,SAAS,UAAU,MAAkB,MAA8B;AACxE,MAAI,KAAK,WAAW,GAAI,OAAM,IAAI,MAAM,2CAA2C;AACnF,MAAI,SAAS,QAAS,QAAO,WAAW,GAAG,KAAM,KAAM,IAAM,GAAG,MAAM,KAAM,GAAI;AAChF,SAAO,WAAW,GAAG,KAAM,IAAM,GAAG,MAAM,GAAI;AAChD;AAGO,SAAS,WAAW,QAA4C;AACrE,MAAI,OAAO,WAAW,MAAM,OAAO,CAAC,MAAM,OAAQ,OAAO,CAAC,MAAM,OAAQ,OAAO,CAAC,MAAM,MAAQ,OAAO,EAAE,MAAM,OAAQ,OAAO,EAAE,MAAM,IAAM,QAAO;AACjJ,MAAI,OAAO,WAAW,MAAM,OAAO,CAAC,MAAM,OAAQ,OAAO,CAAC,MAAM,MAAQ,OAAO,EAAE,MAAM,IAAM,QAAO;AACpG,SAAO;AACT;AAGO,SAAS,cAAc,MAAkB,MAAkB,SAA+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QAAI,MAAM;AACV,QAAI,aAAa,MAAM,GAAG;AACxB,UAAI,SAAS,OAAO,KAAM,OAAM;AAAA,eACvB,KAAK,WAAW,GAAG,OAAO,IAAI,GAAG,GAAG;AAAE,cAAM,KAAK,MAAM,OAAO,KAAK,SAAS,CAAC;AAAG,cAAM;AAAA,MAAK,MAC/F,OAAM,IAAIC,aAAY,+BAA+B,OAAO,IAAI,uBAAuB,IAAI,GAAG;AAAA,IACrG,WAAW,SAAS,GAAG,KAAK,QAAQ,aAAa,SAAS,YAAY;AACpE,YAAM,IAAIA,aAAY,uCAAuC,IAAI,4BAA4B;AAAA,IAC/F;AACA,WAAO,KAAK,cAAc,KAAK,QAAQ,KAAK,CAAC,MAAM,cAAc,IAAI,mBAAmB,MAAM,WAAW,KAAK,KAAK,OAAO,CAAC;AAAA,EAC7H;AAAA;AAAA,EAGA,mBAAmB,SAA6C;AAC9D,WAAO,IAAI,2BAA2B,SAAS,KAAK,OAAO;AAAA,EAC7D;AAAA;AAAA,EAGA,MAAM,cAAiC;AACrC,WAAO,EAAE,MAAM,cAAc,QAAQ,cAAc,MAAM,aAAa;AAAA,EACxE;AACF;","names":["inputSizes","txid","txid","h","NetworkError","NetworkError","sha256","PREFIX","sha256","LocalSigner","SignerError","InsufficientFundsError","NetworkError","secp256k1","InsufficientFundsError","NetworkError","NetworkError","InsufficientFundsError","NetworkError","secp256k1","InsufficientFundsError","txid","LocalSigner","SignerError"]}
1
+ {"version":3,"sources":["../src/address.ts","../src/fee.ts","../src/tx.ts","../src/describe.ts","../src/blockbook.ts","../src/client.ts","../src/errors.ts","../src/message.ts","../src/manager.ts","../src/account.ts","../src/read-only-account.ts"],"sourcesContent":["/**\n * Zcash transparent addresses: Base58Check with a two-byte version prefix.\n * mainnet t1… P2PKH 0x1CB8 t3… P2SH 0x1CBD\n * testnet tm… P2PKH 0x1D25 t2… P2SH 0x1CBA\n * Shielded (zs…, u1…) and Sprout (zc…) addresses are recognised and refused\n * with a message — this package sends transparent value only.\n */\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { ripemd160 } from '@noble/hashes/legacy.js'\nimport { base58check } from '@scure/base'\nimport type { ZcashNetwork } from './types.js'\n\nconst b58 = base58check(sha256)\n\n/** Transparent address type: pay-to-pubkey-hash (`t1…`) or pay-to-script-hash (`t3…`). */\nexport type ScriptKind = 'p2pkh' | 'p2sh'\n\n/** A transparent address decoded to its type and 20-byte hash. */\nexport interface DecodedAddress {\n kind: ScriptKind\n /** 20-byte hash (pubkey hash or script hash). */\n hash: Uint8Array\n /** The scriptPubKey. */\n script: Uint8Array\n}\n\nconst PREFIX: Record<ZcashNetwork, Record<ScriptKind, readonly [number, number]>> = {\n mainnet: { p2pkh: [0x1c, 0xb8], p2sh: [0x1c, 0xbd] },\n testnet: { p2pkh: [0x1d, 0x25], p2sh: [0x1c, 0xba] },\n}\n\n/** Base58Check version prefix for a transparent address kind on a network (exported for tests / tooling). */\nexport function addressPrefix(network: ZcashNetwork, kind: ScriptKind): readonly [number, number] {\n return PREFIX[network][kind]\n}\n\n/** RIPEMD-160 of SHA-256, the hash inside a transparent address. */\nexport function hash160(data: Uint8Array): Uint8Array {\n return ripemd160(sha256(data))\n}\n\n/** OP_DUP OP_HASH160 <20> OP_EQUALVERIFY OP_CHECKSIG, or OP_HASH160 <20> OP_EQUAL. */\nexport function scriptFor(kind: ScriptKind, hash: Uint8Array): Uint8Array {\n if (hash.length !== 20) throw new Error('A transparent script needs a 20-byte hash')\n if (kind === 'p2pkh') return Uint8Array.of(0x76, 0xa9, 0x14, ...hash, 0x88, 0xac)\n return Uint8Array.of(0xa9, 0x14, ...hash, 0x87)\n}\n\n/** Type of an output script; `unknown` for anything but p2pkh and p2sh. */\nexport function scriptKind(script: Uint8Array): ScriptKind | 'unknown' {\n if (script.length === 25 && script[0] === 0x76 && script[1] === 0xa9 && script[2] === 0x14 && script[23] === 0x88 && script[24] === 0xac) return 'p2pkh'\n if (script.length === 23 && script[0] === 0xa9 && script[1] === 0x14 && script[22] === 0x87) return 'p2sh'\n return 'unknown'\n}\n\n/** Transparent address of a 20-byte hash. */\nexport function encodeAddress(kind: ScriptKind, hash: Uint8Array, network: ZcashNetwork): string {\n if (hash.length !== 20) throw new Error('A transparent address needs a 20-byte hash')\n const [a, b] = PREFIX[network][kind]\n return b58.encode(Uint8Array.of(a, b, ...hash))\n}\n\n/** Decode and validate a transparent address for `network`; throws a message that names the problem. */\nexport function decodeAddress(address: string, network: ZcashNetwork): DecodedAddress {\n const a = address.trim()\n if (/^u1|^utest/i.test(a)) throw new Error(`Unified address (${a.slice(0, 6)}…) — shielded receivers are not supported; use a transparent t-address.`)\n if (/^zs1|^ztestsapling/i.test(a)) throw new Error('Sapling shielded address (zs1…) — this wallet sends to transparent t-addresses only.')\n if (/^zc/i.test(a) && a.length > 90) throw new Error('Sprout address (zc…) — the Sprout pool is deprecated; use a transparent t-address.')\n let payload: Uint8Array\n try { payload = b58.decode(a) } catch (e) {\n throw new Error(`Invalid Zcash address: ${a}`, { cause: e })\n }\n if (payload.length !== 22) throw new Error(`Invalid Zcash address: ${a}`)\n const p0 = payload[0]!, p1 = payload[1]!\n for (const net of ['mainnet', 'testnet'] as const) {\n for (const kind of ['p2pkh', 'p2sh'] as const) {\n const [a0, a1] = PREFIX[net][kind]\n if (p0 === a0 && p1 === a1) {\n if (net !== network) throw new Error(`${a} is a Zcash ${net} address; this wallet is on ${network}.`)\n const hash = payload.slice(2)\n return { kind, hash, script: scriptFor(kind, hash) }\n }\n }\n }\n throw new Error(`Invalid Zcash address: ${a} (unknown version prefix)`)\n}\n\n/** Address for an output script, or undefined when the script has no address form. */\nexport function addressFromScript(script: Uint8Array, network: ZcashNetwork): string | undefined {\n const kind = scriptKind(script)\n if (kind === 'unknown') return undefined\n return encodeAddress(kind, kind === 'p2pkh' ? script.slice(3, 23) : script.slice(2, 22), network)\n}\n\n/** P2PKH address of a compressed secp256k1 public key (what `m/44'/133'/0'/0/i` yields). */\nexport function addressFromPublicKey(publicKey: Uint8Array, network: ZcashNetwork = 'mainnet'): string {\n if (publicKey.length !== 33) throw new Error('Expected a 33-byte compressed public key')\n return encodeAddress('p2pkh', hash160(publicKey), network)\n}\n\n/** Output size in bytes: 8 (value) + CompactSize + script. */\nexport function outputSize(script: Uint8Array): number {\n return 8 + (script.length < 0xfd ? 1 : 3) + script.length\n}\n\n/** Below this an output is uneconomic to spend (Bitcoin Core's P2PKH dust floor; zatoshis). */\nexport const DUST_LIMIT = 546n\n","/**\n * ZIP-317 fees and coin selection.\n *\n * conventional_fee = marginal_fee · max(grace_actions, logical_actions)\n * marginal_fee = 5000 zatoshis, grace_actions = 2,\n * transparent logical actions = max(ceil(Σ tx_in bytes / 150), ceil(Σ tx_out bytes / 34)).\n *\n * The fee depends on the number of inputs and outputs, not on a market rate,\n * so selection is simple: largest-first accumulation until the inputs cover\n * amount + fee, change kept when it clears the dust floor.\n */\nimport { InsufficientFundsError } from '@anywalletkit/core'\nimport { DUST_LIMIT } from './address.js'\nimport type { Utxo } from './types.js'\n\nexport const MARGINAL_FEE = 5_000n\nexport const GRACE_ACTIONS = 2\nexport const P2PKH_STANDARD_INPUT_SIZE = 150\nexport const P2PKH_STANDARD_OUTPUT_SIZE = 34\n/** Serialized size of one signed P2PKH input: prevout 36 + CompactSize 1 + scriptSig (1+73+1+33) + sequence 4. */\nexport const P2PKH_INPUT_SIZE = 149\n/** Most inputs one spend may use. */\nexport const MAX_UTXO_INPUTS = 200\n\nexport function logicalActions(inputSizes: readonly number[], outputSizes: readonly number[]): number {\n const inBytes = inputSizes.reduce((s, n) => s + n, 0)\n const outBytes = outputSizes.reduce((s, n) => s + n, 0)\n return Math.max(Math.ceil(inBytes / P2PKH_STANDARD_INPUT_SIZE), Math.ceil(outBytes / P2PKH_STANDARD_OUTPUT_SIZE))\n}\n\n/** The fee a transaction of this shape should pay (zatoshis). */\nexport function conventionalFee(inputSizes: readonly number[], outputSizes: readonly number[]): bigint {\n return MARGINAL_FEE * BigInt(Math.max(GRACE_ACTIONS, logicalActions(inputSizes, outputSizes)))\n}\n\n/** Transaction size estimate: v5 header 20 + counts 2 + inputs + outputs + 3 empty bundle counts. */\nexport function estimateSize(inputs: number, outputSizes: readonly number[]): number {\n const cs = (n: number) => (n < 0xfd ? 1 : 3)\n return 20 + cs(inputs) + inputs * P2PKH_INPUT_SIZE + cs(outputSizes.length) + outputSizes.reduce((s, n) => s + n, 0) + 3\n}\n\n/** A spend would need more inputs than allowed; consolidate the UTXOs first. */\nexport class TooManyInputsError extends Error {\n readonly maxInputs: number\n constructor(maxInputs: number) {\n super(`The spend needs more than ${maxInputs} inputs; consolidate the UTXOs first or raise maxInputs.`)\n this.name = 'TooManyInputsError'\n this.maxInputs = maxInputs\n }\n}\n\n/** Input to {@link selectCoins}. */\nexport interface CoinSelectOptions {\n utxos: Utxo[]\n /** Zatoshis the recipient gets. */\n target: bigint\n /** Serialized size of the recipient output. */\n recipientOutputSize: number\n /** Serialized size of a change output to our own address. */\n changeOutputSize: number\n changeDust?: bigint\n maxInputs?: number\n /** Caller-chosen fee (replaces the conventional fee; still has to be covered by the inputs). */\n fee?: bigint\n}\n\n/** UTXOs chosen for a spend, the ZIP-317 fee and the change. */\nexport interface CoinSelection {\n utxos: Utxo[]\n fee: bigint\n /** The ZIP-317 fee for the chosen shape (equals `fee` unless the caller overrode it or change was folded in). */\n conventionalFee: bigint\n /** Change back to us; 0n when folded into the fee. */\n change: bigint\n /** True when change existed but fell below dust and became fee. */\n changeFolded: boolean\n size: number\n}\n\nconst cmpUtxo = (a: Utxo, b: Utxo): number =>\n a.value > b.value ? -1 : a.value < b.value ? 1 : a.txid < b.txid ? -1 : a.txid > b.txid ? 1 : a.vout - b.vout\n\n/** UTXOs worth spending (each adds at most one logical action = 5000 zatoshis), largest first. */\nexport function spendableUtxos(utxos: Utxo[]): Utxo[] {\n return utxos.filter((u) => u.value > MARGINAL_FEE).sort(cmpUtxo)\n}\n\n/**\n * Pick UTXOs to fund `target` at the ZIP-317 fee; change below dust joins the fee.\n *\n * @throws `InsufficientFundsError` (core) when the UTXOs cannot cover target plus fee,\n * `TooManyInputsError` above `maxInputs`.\n */\nexport function selectCoins(o: CoinSelectOptions): CoinSelection {\n const maxInputs = o.maxInputs ?? MAX_UTXO_INPUTS\n const dust = o.changeDust ?? DUST_LIMIT\n const candidates = spendableUtxos(o.utxos)\n const available = o.utxos.reduce((s, u) => s + u.value, 0n)\n const inputs = (n: number) => Array.from({ length: n }, () => P2PKH_INPUT_SIZE)\n const selected: Utxo[] = []\n let sum = 0n\n for (const u of candidates) {\n if (selected.length >= maxInputs) throw new TooManyInputsError(maxInputs)\n selected.push(u)\n sum += u.value\n const n = selected.length\n const convNoChange = conventionalFee(inputs(n), [o.recipientOutputSize])\n const feeNoChange = o.fee ?? convNoChange\n if (sum < o.target + feeNoChange) continue\n const convWithChange = conventionalFee(inputs(n), [o.recipientOutputSize, o.changeOutputSize])\n const feeWithChange = o.fee ?? convWithChange\n const change = sum - o.target - feeWithChange\n if (change >= dust) {\n return { utxos: selected, fee: feeWithChange, conventionalFee: convWithChange, change, changeFolded: false, size: estimateSize(n, [o.recipientOutputSize, o.changeOutputSize]) }\n }\n return { utxos: selected, fee: sum - o.target, conventionalFee: convNoChange, change: 0n, changeFolded: sum - o.target > feeNoChange, size: estimateSize(n, [o.recipientOutputSize]) }\n }\n const need = o.target + (o.fee ?? conventionalFee(inputs(Math.max(selected.length, 1)), [o.recipientOutputSize]))\n throw new InsufficientFundsError(need, available, 'ZEC')\n}\n\n/** Sweep: every spendable input (largest first, capped), one output, no change. */\nexport function selectAll(o: { utxos: Utxo[]; outputSize: number; maxInputs?: number; fee?: bigint }): { utxos: Utxo[]; fee: bigint; amount: bigint; size: number } {\n const maxInputs = o.maxInputs ?? MAX_UTXO_INPUTS\n const utxos = spendableUtxos(o.utxos).slice(0, maxInputs)\n if (utxos.length === 0) return { utxos, fee: 0n, amount: 0n, size: 0 }\n const fee = o.fee ?? conventionalFee(Array.from({ length: utxos.length }, () => P2PKH_INPUT_SIZE), [o.outputSize])\n const amount = utxos.reduce((s, u) => s + u.value, 0n) - fee\n return { utxos, fee, amount: amount > 0n ? amount : 0n, size: estimateSize(utxos.length, [o.outputSize]) }\n}\n","/**\n * Zcash v5 transactions (ZIP-225 format) carrying transparent inputs and\n * outputs only — the shielded bundles are serialized empty. Transaction ids and\n * signature hashes follow ZIP-244 (BLAKE2b-256 digest tree); the consensus\n * branch id is part of both, so a transaction signed for one network upgrade\n * is invalid under the next.\n */\nimport { blake2b } from '@noble/hashes/blake2.js'\nimport { Reader, Writer, bytesToHex, compactSize, hexToBytes, i64le, reverseBytes, u32le, utf8ToBytes } from './encoding.js'\nimport type { SpentOutput } from './types.js'\n\nexport const TX_VERSION_V5 = 0x80000005 // fOverwintered | 5\nexport const VERSION_GROUP_ID_V5 = 0x26a7270a\nexport const SIGHASH_ALL = 0x01\n\n/** Mainnet network upgrades and their consensus branch ids (ZIP-200 table), oldest first. */\nexport const MAINNET_UPGRADES: ReadonlyArray<{ name: string; height: number; branchId: number }> = Object.freeze([\n { name: 'NU5', height: 1_687_104, branchId: 0xc2d6d0b4 },\n { name: 'NU6', height: 2_726_400, branchId: 0xc8e71055 },\n { name: 'NU6.1', height: 3_146_400, branchId: 0x4dec4df0 },\n { name: 'NU6.3', height: 3_428_143, branchId: 0x37a5165b },\n])\n\n/** The branch id the current mainnet tip signs under (NU6.3 \"Ironwood\", active since block 3 428 143, 2026-07-28). */\nexport const CURRENT_BRANCH_ID = MAINNET_UPGRADES[MAINNET_UPGRADES.length - 1]!.branchId\n\n/** Branch id in force at `height` on mainnet (the newest upgrade when the height is unknown or ahead of the table). */\nexport function branchIdForHeight(height: number | undefined): number {\n if (height === undefined || !Number.isFinite(height)) return CURRENT_BRANCH_ID\n let id = MAINNET_UPGRADES[0]!.branchId\n for (const u of MAINNET_UPGRADES) if (height >= u.height) id = u.branchId\n return id\n}\n\nexport interface TxInput {\n /** Display-order hex (as explorers show it). */\n txid: string\n vout: number\n scriptSig: Uint8Array\n sequence: number\n}\n\nexport interface TxOutput {\n value: bigint\n script: Uint8Array\n}\n\n/**\n * A v5 (NU5) transaction with transparent inputs and outputs only, as signed and serialized here.\n */\nexport interface TransparentTxV5 {\n consensusBranchId: number\n lockTime: number\n expiryHeight: number\n inputs: TxInput[]\n outputs: TxOutput[]\n}\n\nexport const FINAL_SEQUENCE = 0xfffffffe\nexport const MAX_SEQUENCE = 0xffffffff\n\nconst assertTxid = (txid: string) => { if (!/^[0-9a-fA-F]{64}$/.test(txid)) throw new Error(`Invalid txid: ${txid}`) }\n\nfunction writeTransparent(w: Writer, tx: TransparentTxV5): void {\n w.compact(tx.inputs.length)\n for (const i of tx.inputs) {\n assertTxid(i.txid)\n w.bytes(reverseBytes(hexToBytes(i.txid))).u32(i.vout).varBytes(i.scriptSig).u32(i.sequence)\n }\n w.compact(tx.outputs.length)\n for (const o of tx.outputs) {\n if (o.value < 0n) throw new Error('Negative output value')\n w.i64(o.value).varBytes(o.script)\n }\n}\n\n/** ZIP-225 wire format with empty Sapling and Orchard bundles. */\nexport function serializeTx(tx: TransparentTxV5): Uint8Array {\n const w = new Writer()\n w.u32(TX_VERSION_V5).u32(VERSION_GROUP_ID_V5).u32(tx.consensusBranchId >>> 0).u32(tx.lockTime).u32(tx.expiryHeight)\n writeTransparent(w, tx)\n w.compact(0) // nSpendsSapling\n w.compact(0) // nOutputsSapling (no valueBalanceSapling / anchor / proofs when both are zero)\n w.compact(0) // nActionsOrchard\n return w.finish()\n}\n\n/** Parse raw hex / bytes. Accepts v5 transactions whose shielded bundles are empty; anything else is refused by name. */\nexport function parseTx(raw: string | Uint8Array): TransparentTxV5 {\n const r = new Reader(typeof raw === 'string' ? hexToBytes(raw) : raw)\n const header = r.u32()\n const overwintered = (header & 0x80000000) !== 0\n const version = header & 0x7fffffff\n if (!overwintered || version !== 5) throw new Error(`Only v5 Zcash transactions are supported here (got version ${version}${overwintered ? '' : ', not overwintered'}).`)\n const vgid = r.u32()\n if (vgid !== VERSION_GROUP_ID_V5) throw new Error(`Unexpected version group id 0x${vgid.toString(16)} for a v5 transaction.`)\n const consensusBranchId = r.u32()\n const lockTime = r.u32()\n const expiryHeight = r.u32()\n const nIn = r.compact()\n const inputs: TxInput[] = []\n for (let i = 0; i < nIn; i++) {\n const txid = bytesToHex(reverseBytes(r.bytes(32)))\n const vout = r.u32()\n const scriptSig = r.varBytes()\n const sequence = r.u32()\n inputs.push({ txid, vout, scriptSig, sequence })\n }\n const nOut = r.compact()\n const outputs: TxOutput[] = []\n for (let i = 0; i < nOut; i++) outputs.push({ value: r.i64(), script: r.varBytes() })\n const nSpends = r.compact()\n const nOutputs = r.compact()\n if (nSpends !== 0 || nOutputs !== 0) throw new Error('This transaction carries a Sapling bundle; shielded transactions are not supported.')\n const nActions = r.compact()\n if (nActions !== 0) throw new Error('This transaction carries an Orchard bundle; shielded transactions are not supported.')\n if (r.remaining !== 0) throw new Error(`Trailing bytes after the transaction (${r.remaining}).`)\n return { consensusBranchId, lockTime, expiryHeight, inputs, outputs }\n}\n\n// ── ZIP-244 digests ──────────────────────────────────────────────────────────\n\nfunction personal(tag: string): Uint8Array {\n const p = utf8ToBytes(tag)\n if (p.length !== 16) throw new Error(`BLAKE2b personalization must be 16 bytes: ${tag}`)\n return p\n}\n\nfunction h(tag: string | Uint8Array, data: Uint8Array): Uint8Array {\n return blake2b(data, { dkLen: 32, personalization: typeof tag === 'string' ? personal(tag) : tag })\n}\n\nconst EMPTY = new Uint8Array(0)\n\n/** `ZcashTxHash_` ‖ consensus branch id (LE) — the personalization of both the txid and the signature digest. */\nexport function txHashPersonalization(consensusBranchId: number): Uint8Array {\n const p = new Uint8Array(16)\n p.set(utf8ToBytes('ZcashTxHash_'), 0)\n p.set(u32le(consensusBranchId >>> 0), 12)\n return p\n}\n\nexport function headerDigest(tx: TransparentTxV5): Uint8Array {\n const w = new Writer().u32(TX_VERSION_V5).u32(VERSION_GROUP_ID_V5).u32(tx.consensusBranchId >>> 0).u32(tx.lockTime).u32(tx.expiryHeight)\n return h('ZTxIdHeadersHash', w.finish())\n}\n\nexport function prevoutsDigest(tx: TransparentTxV5): Uint8Array {\n const w = new Writer()\n for (const i of tx.inputs) { assertTxid(i.txid); w.bytes(reverseBytes(hexToBytes(i.txid))).u32(i.vout) }\n return h('ZTxIdPrevoutHash', w.finish())\n}\n\nexport function sequenceDigest(tx: TransparentTxV5): Uint8Array {\n const w = new Writer()\n for (const i of tx.inputs) w.u32(i.sequence)\n return h('ZTxIdSequencHash', w.finish())\n}\n\nexport function outputsDigest(tx: TransparentTxV5): Uint8Array {\n const w = new Writer()\n for (const o of tx.outputs) w.i64(o.value).varBytes(o.script)\n return h('ZTxIdOutputsHash', w.finish())\n}\n\n/** T.2: hash of the three transparent digests; the hash of the empty string when there are no inputs AND no outputs. */\nexport function transparentDigest(tx: TransparentTxV5): Uint8Array {\n if (tx.inputs.length === 0 && tx.outputs.length === 0) return h('ZTxIdTranspaHash', EMPTY)\n const w = new Writer().bytes(prevoutsDigest(tx)).bytes(sequenceDigest(tx)).bytes(outputsDigest(tx))\n return h('ZTxIdTranspaHash', w.finish())\n}\n\nexport const saplingDigestEmpty = (): Uint8Array => h('ZTxIdSaplingHash', EMPTY)\nexport const orchardDigestEmpty = (): Uint8Array => h('ZTxIdOrchardHash', EMPTY)\n\n/** Non-malleable transaction id (ZIP-244 T.1 … T.4), internal byte order. */\nexport function txidDigest(tx: TransparentTxV5): Uint8Array {\n const w = new Writer().bytes(headerDigest(tx)).bytes(transparentDigest(tx)).bytes(saplingDigestEmpty()).bytes(orchardDigestEmpty())\n return h(txHashPersonalization(tx.consensusBranchId), w.finish())\n}\n\n/** Transaction id as explorers display it (byte-reversed hex). */\nexport function txid(tx: TransparentTxV5): string {\n return bytesToHex(reverseBytes(txidDigest(tx)))\n}\n\n/**\n * ZIP-244 S.2 transparent signature digest + S.1 … S.4 wrapper for SIGHASH_ALL\n * over input `index`. `spent[i]` is the output input `i` spends (value and\n * scriptPubKey are both committed to, so a lying transport cannot make us sign\n * for a different amount).\n */\nexport function sighashAll(tx: TransparentTxV5, index: number, spent: SpentOutput[]): Uint8Array {\n if (spent.length !== tx.inputs.length) throw new Error(`sighash: ${tx.inputs.length} inputs but ${spent.length} spent outputs`)\n const input = tx.inputs[index]\n const coin = spent[index]\n if (!input || !coin) throw new Error(`sighash: input ${index} does not exist`)\n const amounts = new Writer()\n const scripts = new Writer()\n for (const s of spent) { amounts.i64(s.value); scripts.varBytes(s.script) }\n const txin = new Writer().bytes(reverseBytes(hexToBytes(input.txid))).u32(input.vout).i64(coin.value).varBytes(coin.script).u32(input.sequence)\n const t = new Writer()\n .u8(SIGHASH_ALL)\n .bytes(prevoutsDigest(tx))\n .bytes(h('ZTxTrAmountsHash', amounts.finish()))\n .bytes(h('ZTxTrScriptsHash', scripts.finish()))\n .bytes(sequenceDigest(tx))\n .bytes(outputsDigest(tx))\n .bytes(h('Zcash___TxInHash', txin.finish()))\n const transparentSig = h('ZTxIdTranspaHash', t.finish())\n const w = new Writer().bytes(headerDigest(tx)).bytes(transparentSig).bytes(saplingDigestEmpty()).bytes(orchardDigestEmpty())\n return h(txHashPersonalization(tx.consensusBranchId), w.finish())\n}\n\n/** `<sig ‖ 0x01> <pubkey>` — the scriptSig of a P2PKH spend. */\nexport function p2pkhScriptSig(derSignature: Uint8Array, publicKey: Uint8Array): Uint8Array {\n const sig = new Uint8Array(derSignature.length + 1)\n sig.set(derSignature, 0)\n sig[derSignature.length] = SIGHASH_ALL\n return new Writer().bytes(compactSize(sig.length)).bytes(sig).bytes(compactSize(publicKey.length)).bytes(publicKey).finish()\n}\n\n/** Split a P2PKH scriptSig back into DER signature (hash type stripped) and public key; undefined when it is not one. */\nexport function parseP2pkhScriptSig(scriptSig: Uint8Array): { signature: Uint8Array; hashType: number; publicKey: Uint8Array } | undefined {\n try {\n const r = new Reader(scriptSig)\n const sig = r.varBytes()\n const pub = r.varBytes()\n if (r.remaining !== 0 || sig.length < 9 || (pub.length !== 33 && pub.length !== 65)) return undefined\n return { signature: sig.slice(0, -1), hashType: sig[sig.length - 1]!, publicKey: pub }\n } catch { return undefined }\n}\n\nexport { i64le }\n","import { DUST_LIMIT, addressFromScript, decodeAddress, outputSize, scriptKind } from './address.js'\nimport { bytesToHex } from './encoding.js'\nimport { conventionalFee } from './fee.js'\nimport { serializeTx, txid as txidOf, type TransparentTxV5 } from './tx.js'\nimport type { SpentOutput, ZcashNetwork, ZcashTxDescription, ZcashTxOutputDescription, ZcashWarning } from './types.js'\n\n/** Default hard fee ceiling: 0.01 ZEC. */\nexport const DEFAULT_MAX_FEE = 1_000_000n\n\n/** Why a spend was refused before signing. */\nexport type UnsafeTransactionCode =\n /** Fee above `maxFee`. */\n | 'fee-too-high'\n /** Outputs exceed inputs. */\n | 'outputs-exceed-inputs'\n /** An output that is neither the requested recipient/amount nor our change. */\n | 'unexpected-output'\n /** The recipient output is missing or carries a different amount. */\n | 'recipient-mismatch'\n /** A change output pays an address that is not ours. */\n | 'change-not-ours'\n /** Off mainnet without a configured `consensusBranchId`: the branch id cannot be known. */\n | 'unknown-branch-id'\n\n/** A transaction failed a hard safety check and was not signed / broadcast. */\nexport class UnsafeTransactionError extends Error {\n readonly code: UnsafeTransactionCode\n constructor(code: UnsafeTransactionCode, message: string) {\n super(message)\n this.name = 'UnsafeTransactionError'\n this.code = code\n }\n}\n\n/** What a description needs to tell recipient, change and unknown outputs apart. */\nexport interface DescribeContext {\n network: ZcashNetwork\n /** Our own address: outputs paying it are tagged `change`. */\n ownAddress: string\n /** The spend the caller asked for. Outputs matching it are `recipient`; anything else is `unknown`. */\n intended?: { to: string; value: bigint } | undefined\n maxFee?: bigint | undefined\n}\n\n/** Byte size of a serialized input (what ZIP-317 counts). */\nfunction inputSizes(tx: TransparentTxV5): number[] {\n return tx.inputs.map((i) => 32 + 4 + (i.scriptSig.length < 0xfd ? 1 : 3) + i.scriptSig.length + 4)\n}\n\n/** Describe a (signed or unsigned) transaction given the output every input spends. Pure: no network, no signing. */\nexport function describeTransaction(tx: TransparentTxV5, spent: SpentOutput[], ctx: DescribeContext): ZcashTxDescription {\n if (spent.length !== tx.inputs.length) throw new Error(`describeTransaction: ${tx.inputs.length} inputs but ${spent.length} spent outputs`)\n const inputs = tx.inputs.map((i, k) => ({ txid: i.txid, vout: i.vout, value: spent[k]!.value, address: addressFromScript(spent[k]!.script, ctx.network) }))\n const outputs: ZcashTxOutputDescription[] = []\n const warnings = new Set<ZcashWarning>()\n // Outputs are matched by script, the recipient first: a transfer to oneself pays our own script\n // twice, recipient and change (round 3, L9).\n const scriptOf = (address: string): string | undefined => { try { return bytesToHex(decodeAddress(address, ctx.network).script) } catch { return undefined } }\n const ownScript = scriptOf(ctx.ownAddress)\n const intendedScript = ctx.intended ? scriptOf(ctx.intended.to) : undefined\n let recipientSeen = false\n for (const o of tx.outputs) {\n const address = addressFromScript(o.script, ctx.network)\n const script = bytesToHex(o.script)\n const mine = script === ownScript\n let role: ZcashTxOutputDescription['role']\n if (ctx.intended === undefined) role = mine ? 'change' : 'recipient'\n else if (!recipientSeen && script === intendedScript && o.value === ctx.intended.value) { role = 'recipient'; recipientSeen = true }\n else role = mine ? 'change' : 'unknown'\n if (scriptKind(o.script) !== 'unknown' && o.value < DUST_LIMIT) warnings.add('dust-output')\n outputs.push({ address, value: o.value, role })\n }\n const inputSum = spent.reduce((s, c) => s + c.value, 0n)\n const outputSum = tx.outputs.reduce((s, o) => s + o.value, 0n)\n const fee = inputSum - outputSum\n const amount = outputs.filter((o) => o.role !== 'change').reduce((s, o) => s + o.value, 0n)\n const conv = conventionalFee(inputSizes(tx), tx.outputs.map((o) => outputSize(o.script)))\n if (fee < conv) warnings.add('fee-below-conventional')\n if (amount > 0n && fee * 10n > amount) warnings.add('fee-over-10pct-of-amount')\n if (!outputs.some((o) => o.role === 'change')) warnings.add('no-change')\n if (tx.expiryHeight === 0) warnings.add('no-expiry')\n const signed = tx.inputs.length > 0 && tx.inputs.every((i) => i.scriptSig.length > 0)\n const desc: ZcashTxDescription = {\n kind: 'zcash-transfer', version: 5, consensusBranchId: tx.consensusBranchId, inputs, outputs, amount, fee, conventionalFee: conv,\n size: serializeTx(tx).length, lockTime: tx.lockTime, expiryHeight: tx.expiryHeight, warnings: [...warnings],\n }\n if (signed) desc.txid = txidOf(tx)\n return desc\n}\n\n/**\n * Hard checks run before signing and before broadcasting. Throws UnsafeTransactionError;\n * never mutates. With `intended`, exactly one output must be the requested\n * recipient/amount and every other output must be our change.\n */\nexport function assertSafe(desc: ZcashTxDescription, ctx: DescribeContext): void {\n const maxFee = ctx.maxFee ?? DEFAULT_MAX_FEE\n if (desc.fee < 0n) throw new UnsafeTransactionError('outputs-exceed-inputs', 'Outputs exceed inputs.')\n if (desc.fee > maxFee) throw new UnsafeTransactionError('fee-too-high', `Fee ${desc.fee} zatoshis exceeds the ${maxFee} zatoshi ceiling (maxFee).`)\n for (const o of desc.outputs) {\n if (o.role === 'change' && o.address !== ctx.ownAddress) throw new UnsafeTransactionError('change-not-ours', `Change output pays ${o.address ?? '<no address>'}, not ${ctx.ownAddress}.`)\n }\n if (ctx.intended) {\n const recipients = desc.outputs.filter((o) => o.role === 'recipient')\n if (recipients.length !== 1) throw new UnsafeTransactionError('recipient-mismatch', `Expected one output of ${ctx.intended.value} zatoshis to ${ctx.intended.to}, found ${recipients.length}.`)\n const unknown = desc.outputs.filter((o) => o.role === 'unknown')\n if (unknown.length) throw new UnsafeTransactionError('unexpected-output', `Transaction carries ${unknown.length} output(s) that are neither the recipient nor our change.`)\n }\n}\n","/**\n * Zcash Blockbook REST transport — the same `/api/v2` surface as Bitcoin's\n * (NOWNodes `https://zec-blockbook.nownodes.io` with an `api-key` header, any\n * self-hosted Blockbook built for Zcash). Serves testnet too.\n */\nimport { NetworkError } from '@anywalletkit/core'\nimport { hexToBytes } from './encoding.js'\nimport { DEFAULT_TIMEOUT_MS, fetchWithTimeout, isInt, isIntString, isRecord, refusal, refusedStatus } from './http.js'\nimport type { SpentOutput, Utxo, ZcashClient, ZcashTxInfo } from './types.js'\n\nexport interface BlockbookVin { txid?: string; vout?: number; n?: number; isAddress?: boolean; addresses?: string[]; value?: string }\nexport interface BlockbookVout { n: number; isAddress?: boolean; addresses?: string[]; value?: string; hex?: string }\nexport interface BlockbookTxDetails {\n txid: string\n blockHeight: number\n confirmations: number\n blockTime?: number\n fees?: string\n hex?: string\n vin?: BlockbookVin[]\n vout?: BlockbookVout[]\n}\n\nexport class ZcashBlockbookClient implements ZcashClient {\n private readonly base: string\n private readonly headers: Record<string, string>\n private readonly fetchFn: typeof fetch\n private readonly timeoutMs: number\n\n constructor(config: { url: string; headers?: Record<string, string> }, fetchFn: typeof fetch = globalThis.fetch, timeoutMs = DEFAULT_TIMEOUT_MS) {\n this.base = config.url.replace(/\\/+$/, '').replace(/\\/api$/, '')\n this.headers = { accept: 'application/json', ...(config.headers ?? {}) }\n this.fetchFn = fetchFn\n this.timeoutMs = timeoutMs\n }\n\n async connect(): Promise<void> {}\n async close(): Promise<void> {}\n\n private async get<T>(path: string, check: (v: unknown) => v is T): Promise<T> {\n const url = `${this.base}/api${path}`\n const res = await fetchWithTimeout(this.fetchFn, url, { headers: this.headers }, this.timeoutMs, this.base)\n if (!res.ok) {\n // A 4xx (not 408) is the server refusing: nothing was taken. A 5xx may have been forwarded (round 3, M12).\n const reason = refusedStatus(res.status) ? (await res.text().catch(() => '')).slice(0, 200) : ''\n const err = new NetworkError(`Blockbook request failed: ${res.status} ${res.statusText} (${url})${reason ? `: ${reason}` : ''}`, { provider: this.base })\n throw refusedStatus(res.status) ? refusal(err) : err\n }\n let body: unknown\n try { body = await res.json() } catch (e) { throw new NetworkError(`Blockbook returned non-JSON for ${url}`, { provider: this.base, cause: e }) }\n if (!check(body)) throw new NetworkError(`Blockbook returned an unexpected shape for ${url}`, { provider: this.base })\n return body\n }\n\n async getBalance(address: string) {\n const data = await this.get(`/v2/address/${address}?details=basic`, (v): v is { balance: string; unconfirmedBalance: string } => isRecord(v) && isIntString(v.balance) && isIntString(v.unconfirmedBalance))\n return { confirmed: BigInt(data.balance), unconfirmed: BigInt(data.unconfirmedBalance) }\n }\n\n async listUnspent(address: string): Promise<Utxo[]> {\n const data = await this.get(`/v2/utxo/${address}`, (v): v is Array<{ txid: string; vout: number; value: string; height?: number }> =>\n Array.isArray(v) && v.every((u) => isRecord(u) && typeof u.txid === 'string' && isInt(u.vout) && isIntString(u.value)))\n return data.map((u) => ({ txid: u.txid, vout: u.vout, value: BigInt(u.value), height: u.height && u.height > 0 ? u.height : -1 }))\n }\n\n private static isTx(v: unknown): v is BlockbookTxDetails {\n return isRecord(v) && typeof v.txid === 'string' && isInt(v.blockHeight) && isInt(v.confirmations)\n }\n\n async getTransactionDetails(txid: string): Promise<BlockbookTxDetails | undefined> {\n try { return await this.get(`/v2/tx/${txid}`, ZcashBlockbookClient.isTx) } catch (e) {\n if (e instanceof NetworkError && /\\b(400|404)\\b/.test(e.message)) return undefined\n throw e\n }\n }\n\n async getTransaction(txid: string): Promise<string> {\n const tx = await this.get(`/v2/tx/${txid}`, ZcashBlockbookClient.isTx)\n if (typeof tx.hex !== 'string' || !tx.hex) throw new NetworkError(`Transaction ${txid} has no hex data`, { provider: this.base })\n return tx.hex\n }\n\n async getOutput(txid: string, vout: number): Promise<SpentOutput | undefined> {\n const tx = await this.getTransactionDetails(txid)\n const o = tx?.vout?.find((x) => x.n === vout)\n if (!o || !isIntString(o.value) || typeof o.hex !== 'string') return undefined\n return { value: BigInt(o.value), script: hexToBytes(o.hex) }\n }\n\n async getTransactionInfo(txid: string): Promise<ZcashTxInfo | undefined> {\n const tx = await this.getTransactionDetails(txid)\n if (!tx) return undefined\n const info: ZcashTxInfo = { txid: tx.txid, blockHeight: tx.blockHeight > 0 ? tx.blockHeight : -1, confirmations: tx.confirmations }\n if (isIntString(tx.fees)) info.fee = BigInt(tx.fees)\n if (typeof tx.blockTime === 'number') info.blockTime = tx.blockTime\n return info\n }\n\n async broadcast(rawTx: string): Promise<string> {\n const data = await this.get(`/v2/sendtx/${rawTx}`, (v): v is { result?: string; error?: { message?: string } | string } => isRecord(v))\n if (data.error) throw refusal(new Error(`Broadcast rejected: ${typeof data.error === 'string' ? data.error : data.error.message ?? 'broadcast failed'}`))\n if (!data.result) throw new NetworkError('Blockbook returned no txid', { provider: this.base })\n return data.result\n }\n\n async getBlockHeight(): Promise<number> {\n const data = await this.get('/v2', (v): v is { blockbook?: { bestHeight?: number } } => isRecord(v))\n const h = data.blockbook?.bestHeight\n if (typeof h !== 'number' || h <= 0) throw new NetworkError('Blockbook did not report a block height', { provider: this.base })\n return h\n }\n}\n","import { NetworkError } from '@anywalletkit/core'\nimport { BlockchairClient } from './blockchair.js'\nimport { ZcashBlockbookClient } from './blockbook.js'\nimport { DEFAULT_TIMEOUT_MS, isAnsweredRefusal } from './http.js'\nimport type { ZcashClient, ZcashClientConfig, ZcashConfig } from './types.js'\n\nconst isClient = (c: unknown): c is ZcashClient => typeof c === 'object' && c !== null && typeof (c as ZcashClient).listUnspent === 'function'\n\nfunction toClient(c: ZcashClientConfig | ZcashClient, fetchFn: typeof fetch | undefined, timeoutMs: number): ZcashClient {\n if (isClient(c)) return c\n switch (c.type) {\n case 'blockchair': return new BlockchairClient(c.clientConfig ?? {}, fetchFn, timeoutMs)\n case 'blockbook-http': return new ZcashBlockbookClient(c.clientConfig, fetchFn, timeoutMs)\n default: throw new Error(`Unknown Zcash client type: ${String((c as { type: string }).type)}`)\n }\n}\n\nconst METHODS = ['connect', 'close', 'getBalance', 'listUnspent', 'getTransaction', 'getOutput', 'getTransactionInfo', 'broadcast', 'getBlockHeight'] as const\n\n/**\n * One client, or a failover client over the list: each call walks the list in\n * order, `retries` extra rounds. A node's refusal of a broadcast is final when\n * no endpoint before it went silent; after a silent one the transaction may be\n * out, so the result is \"maybe sent\" (round 3, M12). Transport failures move on.\n */\nexport function createClient(config: ZcashConfig): ZcashClient | undefined {\n if (config.client === undefined) return undefined\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const list = (Array.isArray(config.client) ? config.client : [config.client]).map((c) => toClient(c, config.fetch, timeoutMs))\n if (list.length === 0) return undefined\n if (list.length === 1) return list[0]!\n const attempts = list.length + (config.retries ?? 3)\n const call = (method: (typeof METHODS)[number]) => async (...args: unknown[]) => {\n let last: unknown\n let silent = false\n for (let i = 0; i < attempts; i++) {\n const c = list[i % list.length]! as unknown as Record<string, (...a: unknown[]) => Promise<unknown>>\n try { return await c[method]!.apply(c, args) } catch (e) {\n if (method === 'broadcast') {\n if (isAnsweredRefusal(e)) {\n if (!silent) throw e\n throw new NetworkError('A Zcash client refused the broadcast after another never answered: it may be out', { cause: e })\n }\n silent = true\n }\n last = e\n }\n }\n throw new NetworkError(`All Zcash clients failed for ${method}`, { cause: last })\n }\n const out = {} as Record<(typeof METHODS)[number], (...args: unknown[]) => Promise<unknown>>\n for (const m of METHODS) out[m] = call(m)\n return out as unknown as ZcashClient\n}\n","/**\n * The transaction was handed to the network but no definitive answer came back (no response, a\n * timeout, a 5xx, an unreadable body): it MAY be in the mempool. Do not spend the same coins again —\n * watch `hash`, the txid computed before sending (round 3, M12).\n */\nexport class BroadcastUnknownError extends Error {\n /** Always true: the transaction may be on its way. */\n readonly maybeSent = true\n /** The transaction id (hex). */\n readonly hash: string\n constructor(hash: string, cause: unknown) {\n super(`Broadcast outcome unknown for ${hash}: ${cause instanceof Error ? cause.message.slice(0, 200) : String(cause).slice(0, 200)}`, { cause })\n this.name = 'BroadcastUnknownError'\n this.hash = hash\n }\n}\n","/**\n * Zcash signed messages (zcashd `signmessage` / `verifymessage`): the Bitcoin\n * scheme with the `Zcash Signed Message:\\n` magic. hash = sha256d(varint(prefix)\n * ‖ prefix ‖ varint(len) ‖ message); header byte = 27 + recovery + 4\n * (compressed key); output base64 of header ‖ r ‖ s. RFC-6979 deterministic, low-S.\n */\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { base64 } from '@scure/base'\nimport type { Signer } from '@anywalletkit/core'\nimport { compactSize, utf8ToBytes } from './encoding.js'\n\nconst MAGIC = 'Zcash Signed Message:\\n'\nconst PREFIX = utf8ToBytes(MAGIC)\n\n/** Hash of a signed message (`Zcash Signed Message:` prefix, double SHA-256). */\nexport function magicHash(message: string | Uint8Array): Uint8Array {\n const msg = typeof message === 'string' ? utf8ToBytes(message) : message\n const p = compactSize(PREFIX.length), l = compactSize(msg.length)\n const buf = new Uint8Array(p.length + PREFIX.length + l.length + msg.length)\n let o = 0\n for (const part of [p, PREFIX, l, msg]) { buf.set(part, o); o += part.length }\n return sha256(sha256(buf))\n}\n\n/** Encode `r‖s` + recovery id as a base64 signature (compressed-key header 31 + recovery). */\nexport function encodeMessageSignature(rs: Uint8Array, recovery: number): string {\n if (rs.length !== 64 || recovery > 3) throw new Error('Expected a 64-byte r‖s signature and a recovery id 0..3.')\n const out = new Uint8Array(65)\n out[0] = 27 + 4 + recovery\n out.set(rs, 1)\n return base64.encode(out)\n}\n\n/** Sign through a {@link Signer} (`ecdsa-recoverable`, context `zcash-message`). */\nexport async function signMessageWith(message: string | Uint8Array, signer: Signer): Promise<string> {\n const sig = await signer.sign(magicHash(message), { scheme: 'ecdsa-recoverable', context: 'zcash-message' })\n return encodeMessageSignature(sig.subarray(0, 64), sig[64]!)\n}\n\n/** Recover the compressed public key from a message signature, or undefined when malformed. */\nexport function recoverMessagePublicKey(message: string | Uint8Array, signature: string): Uint8Array | undefined {\n let bytes: Uint8Array\n try { bytes = base64.decode(signature) } catch { return undefined }\n if (bytes.length !== 65) return undefined\n const flag = bytes[0]! - 27\n if (flag < 0 || flag > 15) return undefined\n const recovered = new Uint8Array(65)\n recovered[0] = flag & 3\n recovered.set(bytes.subarray(1), 1)\n try {\n const pub = secp256k1.recoverPublicKey(recovered, magicHash(message), { prehash: false })\n return pub.length === 33 ? pub : secp256k1.Point.fromBytes(pub).toBytes(true)\n } catch { return undefined }\n}\n","import { LocalSigner, SignerError, WalletManager, isSeedSigner, type FeeRates, type Signer } from '@anywalletkit/core'\nimport { WalletAccountZcash } from './account.js'\nimport { MARGINAL_FEE } from './fee.js'\nimport { WalletAccountReadOnlyZcash } from './read-only-account.js'\nimport type { ZcashConfig, ZcashNetwork } from './types.js'\n\n/** SLIP-44 coin type: 133 for mainnet, 1 for testnet. */\nexport const coinType = (network: ZcashNetwork): 133 | 1 => (network === 'mainnet' ? 133 : 1)\n\n/**\n * One seed → Zcash transparent accounts at m/44'/133'/0'/0/i (BIP-44, the path\n * Zashi, YWallet, Ledger and Trezor use for the transparent receiver) — t1… on\n * mainnet, tm… on testnet. Paths may be relative to the purpose/coin prefix\n * (\"0'/0/i\") or given in full.\n *\n * Built with a secp256k1 `Signer` instead of a seed, the manager wraps it:\n * a derivable `SeedSigner` yields `getAccount(i)` children below its path; a\n * leaf or external signer is `getAccount(0)`.\n */\nexport class WalletManagerZcash extends WalletManager<WalletAccountZcash, ZcashConfig> {\n constructor(seedOrSigner: string | Uint8Array | Signer, config: ZcashConfig = {}) {\n super(seedOrSigner, config)\n }\n\n /** `m/44'/133'` on mainnet (coin type 1 on testnet); account `i` is at `basePath/0'/0/i`. */\n get basePath(): string {\n return `m/44'/${coinType(this._config.network ?? 'mainnet')}'`\n }\n\n async getAccount(index = 0): Promise<WalletAccountZcash> {\n return this.getAccountByPath(`${this.basePath}/0'/0/${index}`)\n }\n\n async getAccountByPath(path: string): Promise<WalletAccountZcash> {\n const full = path.startsWith('m/') ? path : `${this.basePath}/${path}`\n const cached = this._accounts.get(full)\n if (cached) return cached\n const external = this.externalSigner()\n if (external) return this.fromSigner(external, full)\n return this.cachedAccount(full, () => {\n const signer = LocalSigner.leafFromSeed(this.seedBytes(), 'secp256k1', full)\n return new WalletAccountZcash(signer, signer.publicKey, full, this._config)\n })\n }\n\n private async fromSigner(signer: Signer, path: string): Promise<WalletAccountZcash> {\n this.requireSigner('secp256k1')\n let rel: string | undefined\n let key = 'external'\n if (isSeedSigner(signer)) {\n if (path === signer.path) key = path\n else if (path.startsWith(`${signer.path}/`)) { rel = path.slice(signer.path.length + 1); key = path }\n else throw new SignerError(`The injected signer sits at ${signer.path}; it cannot provide ${path}.`)\n } else if (path !== `${this.basePath}/0'/0/0` && path !== 'external') {\n throw new SignerError(`An external signer has one account; ${path} is not derivable from it.`)\n }\n return this.signerAccount(key, signer, rel, (leaf, publicKey) => new WalletAccountZcash(leaf, publicKey, key, this._config))\n }\n\n /** A read-only account for any transparent address, with this manager's config. */\n getReadOnlyAccount(address: string): WalletAccountReadOnlyZcash {\n return new WalletAccountReadOnlyZcash(address, this._config)\n }\n\n /** ZIP-317 has no fee market: every tier is the 5000-zatoshi marginal fee per logical action. */\n async getFeeRates(): Promise<FeeRates> {\n return { slow: MARGINAL_FEE, normal: MARGINAL_FEE, fast: MARGINAL_FEE }\n }\n}\n","import { InsufficientFundsError, LocalSigner, NetworkError, SignerError, feeLimit, requireCurve, type IWalletAccount, type IWalletAccountReadOnly, type Signer, type TransferResult, type WriteOptions } from '@anywalletkit/core'\nimport { secp256k1 } from '@noble/curves/secp256k1.js'\nimport { DUST_LIMIT, addressFromPublicKey } from './address.js'\nimport { UnsafeTransactionError, assertSafe, describeTransaction, type DescribeContext } from './describe.js'\nimport { bytesToHex } from './encoding.js'\nimport { BroadcastUnknownError } from './errors.js'\nimport { isAlreadyKnown, isAnsweredRefusal } from './http.js'\nimport { signMessageWith } from './message.js'\nimport { WalletAccountReadOnlyZcash, type SpendPlan } from './read-only-account.js'\nimport { FINAL_SEQUENCE, branchIdForHeight, p2pkhScriptSig, parseTx, serializeTx, sighashAll, txid as txidOf, type TransparentTxV5 } from './tx.js'\nimport type { SpentOutput, ZcashClient, ZcashConfig, ZcashNetwork, ZcashSpend, ZcashTransaction, ZcashTransferOptions, ZcashTxDescription } from './types.js'\n\nexport { addressFromPublicKey }\n\n/** t-address for a compressed public key. */\nexport function addressFor(publicKey: Uint8Array, network: ZcashNetwork = 'mainnet'): string {\n return addressFromPublicKey(publicKey, network)\n}\n\n/** ZIP-203 default: a transaction expires 40 blocks (~50 min) after it was built. */\nexport const DEFAULT_EXPIRY_DELTA = 40\n\nexport interface Built {\n tx: TransparentTxV5\n hex: string\n txid: string\n fee: bigint\n plan: SpendPlan\n desc: ZcashTxDescription\n}\n\n/**\n * Signing Zcash account — BIP-44 P2PKH at m/44'/133'/0'/0/i (t1…). The key never\n * enters this package: every input is one `signer.sign(...)` call over the\n * ZIP-244 signature digest computed here (`ecdsa`, DER-encoded + SIGHASH_ALL\n * into the scriptSig); messages are `ecdsa-recoverable` over the Zcash magic hash.\n *\n * Every spend is resolved to a full description (\"what you sign\") and run through\n * the hard safety checks (fee ceiling, recipient/amount exactness, change\n * ownership) before signing AND before broadcast — also for caller-supplied raw hex.\n */\nexport class WalletAccountZcash extends WalletAccountReadOnlyZcash implements IWalletAccount {\n /** UTXOs and the tip height come from the network before signing. */\n readonly needsNetwork = true\n /** Derivation path, or `external` for an external signer. */\n readonly path: string\n /** Compressed secp256k1 public key. */\n readonly publicKey: Uint8Array\n /** The signer that holds the key. */\n readonly signer: Signer\n private _disposed = false\n private _readOnly: WalletAccountReadOnlyZcash | undefined\n\n /** `publicKey` is the signer's compressed secp256k1 key (33 bytes); it is needed synchronously for the address. */\n constructor(signer: Signer, publicKey: Uint8Array, path: string, config: ZcashConfig = {}) {\n super(addressFromPublicKey(publicKey, config.network ?? 'mainnet'), config)\n this.signer = requireCurve(signer, 'secp256k1')\n if (!this.signer.schemes.includes('ecdsa')) throw new SignerError(`A Zcash account needs a signer with the 'ecdsa' scheme (has: ${this.signer.schemes.join(', ')}).`)\n this.publicKey = publicKey\n this.path = path\n }\n\n /** Back-compat: wrap a raw derived key in a {@link LocalSigner} (the account takes ownership; it cannot derive). */\n static fromPrivateKey(privateKey: Uint8Array, publicKey: Uint8Array, path: string, config: ZcashConfig = {}): WalletAccountZcash {\n return new WalletAccountZcash(LocalSigner.fromPrivateKey('secp256k1', privateKey, publicKey, path), publicKey, path, config)\n }\n\n /** Account index for the standard m/44'/133'/0'/0/i path. */\n get index(): number | undefined {\n const m = /^m\\/44'\\/(133|1)'\\/0'\\/0\\/(\\d+)$/.exec(this.path)\n return m ? Number(m[2]) : undefined\n }\n\n private live(): void {\n if (this._disposed) throw new SignerError('This account has been disposed.')\n }\n\n /** Zcash message signature (zcashd `signmessage` encoding), base64. */\n async sign(message: string | Uint8Array): Promise<string> {\n this.live()\n return signMessageWith(message, this.signer)\n }\n\n private ctx(intended?: { to: string; value: bigint }): DescribeContext {\n return { network: this._network, ownAddress: this.address, intended, maxFee: this.maxFee }\n }\n\n /**\n * Lock time, expiry and branch id for a transaction that lands in the next block (round 3, L7):\n * expiry = tip + 1 + `expiryDelta`, the branch id in force at tip + 1 (mainnet table; off mainnet\n * `consensusBranchId` must be configured — testnet and regtest activate upgrades at other heights).\n * Without a tip nothing is signed when the expiry, anti-fee-sniping or the branch id need it: a\n * transaction signed with expiry 0 never expires.\n */\n private async chainParams(): Promise<{ lockTime: number; expiryHeight: number; consensusBranchId: number }> {\n const delta = this._config.expiryDelta ?? DEFAULT_EXPIRY_DELTA\n const configured = this._config.consensusBranchId\n if (configured === undefined && this._network !== 'mainnet') {\n throw new UnsafeTransactionError('unknown-branch-id', `On ${this._network} the consensus branch id depends on that network's upgrade heights; set consensusBranchId in the config.`)\n }\n const antiSnipe = this._config.antiFeeSniping !== false\n const needTip = delta > 0 || antiSnipe || configured === undefined\n const tip = needTip ? await this.tipHeight() : undefined\n if (needTip && tip === undefined) throw new NetworkError('The Zcash chain tip is unknown, so the expiry height and the branch id cannot be set; nothing was signed.')\n const next = tip === undefined ? undefined : tip + 1\n const consensusBranchId = configured ?? branchIdForHeight(next)\n const lockTime = tip !== undefined && antiSnipe ? tip : 0\n const expiryHeight = next !== undefined && delta > 0 ? next + delta : 0\n return { lockTime, expiryHeight, consensusBranchId }\n }\n\n /** Sign every input through the signer; the scriptSig is `<DER ‖ 0x01> <pubkey>`. */\n private async signInputs(tx: TransparentTxV5, spent: SpentOutput[]): Promise<void> {\n for (let i = 0; i < tx.inputs.length; i++) {\n const digest = sighashAll(tx, i, spent)\n const rs = await this.signer.sign(digest, { scheme: 'ecdsa', context: 'zcash-sighash' })\n const der = secp256k1.Signature.fromBytes(rs, 'compact').toBytes('der')\n tx.inputs[i]!.scriptSig = p2pkhScriptSig(der, this.publicKey)\n }\n }\n\n protected async signSpend(spend: ZcashSpend): Promise<Built> {\n this.live()\n const plan = await this.planSpend(spend)\n const params = await this.chainParams()\n const tx: TransparentTxV5 = {\n ...params,\n inputs: plan.utxos.map((u) => ({ txid: u.txid, vout: u.vout, scriptSig: new Uint8Array(0), sequence: FINAL_SEQUENCE })),\n outputs: [{ value: plan.amount, script: plan.recipient.script }, ...(plan.change > 0n ? [{ value: plan.change, script: this.scriptPubKey }] : [])],\n }\n const spent: SpentOutput[] = plan.utxos.map((u) => ({ value: u.value, script: this.scriptPubKey }))\n const have = plan.utxos.reduce((s, u) => s + u.value, 0n)\n if (have < plan.amount + plan.fee) throw new InsufficientFundsError(plan.amount + plan.fee, have, 'ZEC')\n await this.signInputs(tx, spent)\n const ctx = this.ctx({ to: spend.to, value: plan.amount })\n const desc = describeTransaction(tx, spent, ctx)\n assertSafe(desc, ctx)\n const bytes = serializeTx(tx)\n return { tx, hex: bytesToHex(bytes), txid: txidOf(tx), fee: plan.fee, plan, desc }\n }\n\n private checkMax(fee: bigint, limit: bigint | number | undefined, op: string) {\n if (limit !== undefined && fee > BigInt(limit)) throw new Error(`Exceeded maximum fee cost for ${op} operation.`)\n }\n\n /** The outputs a raw transaction spends, fetched through the client (the wire format carries no values). */\n private async spentOutputs(tx: TransparentTxV5): Promise<SpentOutput[]> {\n const client = this.requireClient('inspect a raw transaction')\n const out: SpentOutput[] = []\n for (const i of tx.inputs) {\n const o = await client.getOutput(i.txid, i.vout)\n if (!o) throw new Error(`Prevout ${i.txid}:${i.vout} not found.`)\n out.push(o)\n }\n return out\n }\n\n /** Describe a raw signed tx (needs the network for prevouts) and run the safety checks. */\n private async describeRaw(rawHex: string): Promise<{ tx: TransparentTxV5; desc: ZcashTxDescription }> {\n const tx = parseTx(rawHex)\n const ctx = this.ctx()\n const desc = describeTransaction(tx, await this.spentOutputs(tx), ctx)\n assertSafe(desc, ctx)\n return { tx, desc }\n }\n\n /** \"What you sign\": the fully resolved spend (signed, NOT broadcast) or a caller's raw hex. */\n async describeTransaction(tx: ZcashTransaction): Promise<ZcashTxDescription> {\n if (typeof tx === 'string') return (await this.describeRaw(tx)).desc\n return (await this.signSpend(tx)).desc\n }\n\n /** Sign without broadcasting. Returns the raw transaction hex. Raw hex input gets the checks `sendTransaction` runs (prevouts through the client) and is returned unchanged, never re-signed. */\n async signTransaction(tx: ZcashTransaction, options: WriteOptions = {}): Promise<string> {\n this.live()\n if (typeof tx === 'string') {\n const { desc } = await this.describeRaw(tx)\n this.checkMax(desc.fee, feeLimit(this._config.transactionMaxFee, options), 'transaction')\n return tx\n }\n const built = await this.signSpend(tx)\n this.checkMax(built.fee, feeLimit(this._config.transactionMaxFee, options), 'transaction')\n return built.hex\n }\n\n override async quoteSendTransaction(tx: ZcashTransaction): Promise<{ fee: bigint }> {\n if (typeof tx === 'string') return { fee: (await this.describeRaw(tx)).desc.fee }\n return super.quoteSendTransaction(tx)\n }\n\n async sendTransaction(tx: ZcashTransaction, options: WriteOptions = {}): Promise<TransferResult> {\n this.live()\n const client = this.requireClient('send transactions')\n let rawHex: string, hash: string, fee: bigint\n if (typeof tx === 'string') {\n const { tx: parsed, desc } = await this.describeRaw(tx)\n rawHex = tx; hash = txidOf(parsed); fee = desc.fee\n } else {\n const built = await this.signSpend(tx)\n rawHex = built.hex; hash = built.txid; fee = built.fee\n }\n this.checkMax(fee, feeLimit(this._config.transactionMaxFee, options), 'transaction')\n return { hash: await this.broadcast(client, rawHex, hash), fee }\n }\n\n /** Native ZEC only (`token` is rejected). Subject to `transferMaxFee`. */\n async transfer(o: ZcashTransferOptions, writeOptions: WriteOptions = {}): Promise<TransferResult> {\n if (o.token) throw new Error('Tokens are not supported on the zcash blockchain.')\n this.live()\n const client = this.requireClient('transfer')\n const built = await this.signSpend({ to: o.recipient, value: o.amount })\n this.checkMax(built.fee, feeLimit(this._config.transferMaxFee, writeOptions), 'transfer')\n return { hash: await this.broadcast(client, built.hex, built.txid), fee: built.fee }\n }\n\n /**\n * Send once through the client. Only a node's refusal means nothing went out; \"already in the\n * mempool / block chain\" means an earlier attempt delivered it; anything else may have landed and\n * is a {@link BroadcastUnknownError} with the txid computed before sending (round 3, M12).\n */\n private async broadcast(client: ZcashClient, rawHex: string, txid: string): Promise<string> {\n try {\n return (await client.broadcast(rawHex)) || txid\n } catch (e) {\n if (isAlreadyKnown(e)) return txid\n if (isAnsweredRefusal(e)) throw e\n throw new BroadcastUnknownError(txid, e)\n }\n }\n\n /** The same address as a {@link WalletAccountReadOnlyZcash}. */\n toReadOnlyAccount(): IWalletAccountReadOnly {\n this._readOnly ??= new WalletAccountReadOnlyZcash(this.address, this._config)\n return this._readOnly\n }\n\n dispose(): void {\n this._disposed = true\n this.signer.dispose()\n }\n}\n\nexport { DUST_LIMIT, UnsafeTransactionError }\n","import { InsufficientFundsError, NetworkError, type IWalletAccountReadOnly } from '@anywalletkit/core'\nimport { DUST_LIMIT, addressFromPublicKey, decodeAddress, outputSize, type DecodedAddress } from './address.js'\nimport { createClient } from './client.js'\nimport { DEFAULT_MAX_FEE } from './describe.js'\nimport { MAX_UTXO_INPUTS, selectAll, selectCoins, type CoinSelection } from './fee.js'\nimport { recoverMessagePublicKey } from './message.js'\nimport { CAIP2, type ZcashClient, type ZcashConfig, type ZcashMaxSpendableResult, type ZcashNetwork, type ZcashReceipt, type ZcashSpend, type ZcashTransferOptions } from './types.js'\n\n/** A coin selection for one spend, with the decoded recipient. */\nexport interface SpendPlan extends CoinSelection {\n /** Zatoshis the recipient gets (the requested value — never reduced). */\n amount: bigint\n recipient: DecodedAddress\n}\n\nconst toBig = (v: bigint | number | string): bigint => (typeof v === 'bigint' ? v : BigInt(typeof v === 'string' ? v.trim() : Math.round(v)))\n\n/** Watch-only Zcash account: balances, quotes, receipts, message verification. No key. */\nexport class WalletAccountReadOnlyZcash implements IWalletAccountReadOnly {\n /** The transparent address. */\n readonly address: string\n readonly chain: string\n /** The address's scriptPubKey. */\n readonly scriptPubKey: Uint8Array\n /** Script type of the address. */\n readonly scriptKind: DecodedAddress['kind']\n protected readonly _config: ZcashConfig\n protected readonly _client: ZcashClient | undefined\n protected readonly _network: ZcashNetwork\n\n constructor(address: string, config: ZcashConfig = {}) {\n this._config = config\n this._network = config.network ?? 'mainnet'\n const decoded = decodeAddress(address, this._network)\n this.address = address.trim()\n this.scriptPubKey = decoded.script\n this.scriptKind = decoded.kind\n this.chain = CAIP2[this._network]\n this._client = createClient(config)\n }\n\n protected requireClient(what: string): ZcashClient {\n if (!this._client) throw new NetworkError(`The wallet must be connected to a client to ${what}.`)\n return this._client\n }\n\n /** Fee ceiling in zatoshis: `ZcashConfig.maxFee` or the default. */\n get maxFee(): bigint {\n return this._config.maxFee !== undefined ? toBig(this._config.maxFee) : DEFAULT_MAX_FEE\n }\n\n /** The transparent address. */\n async getAddress(): Promise<string> { return this.address }\n\n /** Confirmed plus incoming mempool value (the transports do not expose pending spends of our own outputs). */\n async getBalance(): Promise<bigint> {\n const { confirmed, unconfirmed } = await this.requireClient('read balances').getBalance(this.address)\n return confirmed + unconfirmed\n }\n\n /** Always throws: Zcash has no tokens. */\n async getTokenBalance(_token: string): Promise<bigint> {\n throw new Error(\"The 'getTokenBalance' method is not supported on the zcash blockchain.\")\n }\n\n /** Coin selection for a spend (ZIP-317 fee). Validates the recipient and the dust floor first. */\n protected async planSpend(spend: ZcashSpend): Promise<SpendPlan> {\n if (this.scriptKind !== 'p2pkh') throw new Error(`Cannot build spends from a ${this.scriptKind} address; only P2PKH (t1…) accounts spend.`)\n const amount = toBig(spend.value)\n const recipient = decodeAddress(spend.to, this._network)\n if (amount < DUST_LIMIT) throw new Error(`The amount must be at least the dust limit (${DUST_LIMIT} zatoshis).`)\n const utxos = await this.requireClient('plan a spend').listUnspent(this.address)\n if (utxos.length === 0) throw new InsufficientFundsError(amount, 0n, 'ZEC')\n const selection = selectCoins({\n utxos,\n target: amount,\n recipientOutputSize: outputSize(recipient.script),\n changeOutputSize: outputSize(this.scriptPubKey),\n maxInputs: this._config.maxInputs ?? MAX_UTXO_INPUTS,\n ...(spend.fee !== undefined ? { fee: toBig(spend.fee) } : {}),\n })\n return { ...selection, amount, recipient }\n }\n\n /** ZIP-317 fee of a spend in zatoshis. */\n async quoteSendTransaction(tx: ZcashSpend): Promise<{ fee: bigint }> {\n const { fee } = await this.planSpend(tx)\n return { fee }\n }\n\n /** ZIP-317 fee of a transfer in zatoshis. */\n async quoteTransfer(o: ZcashTransferOptions): Promise<{ fee: bigint }> {\n if (o.token) throw new Error('Tokens are not supported on the zcash blockchain.')\n return this.quoteSendTransaction({ to: o.recipient, value: o.amount })\n }\n\n /** Everything spendable in ONE transaction to a single output, no change. */\n async getMaxSpendable(opts: { to?: string; fee?: bigint | number } = {}): Promise<ZcashMaxSpendableResult> {\n const utxos = await this.requireClient('plan a spend').listUnspent(this.address)\n const outScript = opts.to ? decodeAddress(opts.to, this._network).script : this.scriptPubKey\n const sweep = selectAll({ utxos, outputSize: outputSize(outScript), maxInputs: this._config.maxInputs ?? MAX_UTXO_INPUTS, ...(opts.fee !== undefined ? { fee: toBig(opts.fee) } : {}) })\n const amount = sweep.amount >= DUST_LIMIT ? sweep.amount : 0n\n return { amount, fee: amount > 0n ? sweep.fee : 0n, changeValue: 0n, inputs: amount > 0n ? sweep.utxos.length : 0 }\n }\n\n /** Undefined until the transaction is mined. */\n async getTransactionReceipt(hash: string): Promise<ZcashReceipt | undefined> {\n if (!/^[0-9a-fA-F]{64}$/.test(hash)) throw new Error(\"The 'getTransactionReceipt(hash)' method requires a valid transaction hash.\")\n const info = await this.requireClient('fetch transaction receipts').getTransactionInfo(hash)\n if (!info || info.blockHeight <= 0) return undefined\n return { hash, status: 1, blockNumber: BigInt(info.blockHeight), confirmations: info.confirmations, ...(info.fee !== undefined ? { fee: info.fee } : {}) }\n }\n\n /** Recover the key from a Zcash message signature and compare its P2PKH address with ours. */\n async verify(message: string | Uint8Array, signature: string): Promise<boolean> {\n const pub = recoverMessagePublicKey(message, signature)\n if (!pub) return false\n try { return addressFromPublicKey(pub, this._network) === this.address } catch { return false }\n }\n\n /** Chain tip for lock time / expiry; undefined when the transport cannot tell. */\n protected async tipHeight(): Promise<number | undefined> {\n if (!this._client) return undefined\n try { return await this._client.getBlockHeight() } catch { return undefined }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,SAAS,cAAc;AACvB,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAG5B,IAAM,MAAM,YAAY,MAAM;AAc9B,IAAM,SAA8E;AAAA,EAClF,SAAS,EAAE,OAAO,CAAC,IAAM,GAAI,GAAG,MAAM,CAAC,IAAM,GAAI,EAAE;AAAA,EACnD,SAAS,EAAE,OAAO,CAAC,IAAM,EAAI,GAAG,MAAM,CAAC,IAAM,GAAI,EAAE;AACrD;AAGO,SAAS,cAAc,SAAuB,MAA6C;AAChG,SAAO,OAAO,OAAO,EAAE,IAAI;AAC7B;AAGO,SAAS,QAAQ,MAA8B;AACpD,SAAO,UAAU,OAAO,IAAI,CAAC;AAC/B;AAGO,SAAS,UAAU,MAAkB,MAA8B;AACxE,MAAI,KAAK,WAAW,GAAI,OAAM,IAAI,MAAM,2CAA2C;AACnF,MAAI,SAAS,QAAS,QAAO,WAAW,GAAG,KAAM,KAAM,IAAM,GAAG,MAAM,KAAM,GAAI;AAChF,SAAO,WAAW,GAAG,KAAM,IAAM,GAAG,MAAM,GAAI;AAChD;AAGO,SAAS,WAAW,QAA4C;AACrE,MAAI,OAAO,WAAW,MAAM,OAAO,CAAC,MAAM,OAAQ,OAAO,CAAC,MAAM,OAAQ,OAAO,CAAC,MAAM,MAAQ,OAAO,EAAE,MAAM,OAAQ,OAAO,EAAE,MAAM,IAA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C3E,aAAO,IAAI,mBAAmB,QAAQ,OAAO,WAAW,MAAM,KAAK,OAAO;AAAA,IAC5E,CAAC;AAAA,EACH;AAAA,EAEA,MAAc,WAAW,QAAgB,MAA2C;AAClF,SAAK,cAAc,WAAW;AAC9B,QAAI;AACJ,QAAI,MAAM;AACV,QAAI,aAAa,MAAM,GAAG;AACxB,UAAI,SAAS,OAAO,KAAM,OAAM;AAAA,eACvB,KAAK,WAAW,GAAG,OAAO,IAAI,GAAG,GAAG;AAAE,cAAM,KAAK,MAAM,OAAO,KAAK,SAAS,CAAC;AAAG,cAAM;AAAA,MAAK,MAC/F,OAAM,IAAIC,aAAY,+BAA+B,OAAO,IAAI,uBAAuB,IAAI,GAAG;AAAA,IACrG,WAAW,SAAS,GAAG,KAAK,QAAQ,aAAa,SAAS,YAAY;AACpE,YAAM,IAAIA,aAAY,uCAAuC,IAAI,4BAA4B;AAAA,IAC/F;AACA,WAAO,KAAK,cAAc,KAAK,QAAQ,KAAK,CAAC,MAAM,cAAc,IAAI,mBAAmB,MAAM,WAAW,KAAK,KAAK,OAAO,CAAC;AAAA,EAC7H;AAAA;AAAA,EAGA,mBAAmB,SAA6C;AAC9D,WAAO,IAAI,2BAA2B,SAAS,KAAK,OAAO;AAAA,EAC7D;AAAA;AAAA,EAGA,MAAM,cAAiC;AACrC,WAAO,EAAE,MAAM,cAAc,QAAQ,cAAc,MAAM,aAAa;AAAA,EACxE;AACF;","names":["inputSizes","txid","txid","h","NetworkError","NetworkError","sha256","PREFIX","sha256","LocalSigner","SignerError","InsufficientFundsError","NetworkError","secp256k1","InsufficientFundsError","NetworkError","NetworkError","InsufficientFundsError","NetworkError","secp256k1","InsufficientFundsError","txid","LocalSigner","SignerError"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anywalletkit/wallet-zcash",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Zcash wallet for Any Wallet Kit: transparent t-addresses (BIP-44 coin 133), v5 transactions with ZIP-244 signature hashing, ZIP-317 fees, Blockchair / Blockbook transports. Shielded pools are out of scope.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://docs.anywallet.tech",
@@ -45,18 +45,19 @@
45
45
  "zip-244",
46
46
  "zip-317",
47
47
  "blockchair",
48
- "blockbook"
48
+ "blockbook",
49
+ "anywalletkit"
49
50
  ],
50
51
  "dependencies": {
51
52
  "@noble/curves": "^2.4.0",
52
53
  "@noble/hashes": "^2.4.0",
53
54
  "@scure/base": "^2.4.0",
54
- "@anywalletkit/core": "0.6.0"
55
+ "@anywalletkit/core": "0.6.1"
55
56
  },
56
57
  "devDependencies": {
57
58
  "viem": "^2.44.4",
58
59
  "vitest": "^5.0.3",
59
- "@anywalletkit/conformance": "0.4.3"
60
+ "@anywalletkit/conformance": "0.4.4"
60
61
  },
61
62
  "publishConfig": {
62
63
  "access": "public",