@babylonlabs-io/ts-sdk 0.17.1 → 0.19.0
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/errors-DVNYib5y.cjs +2 -0
- package/dist/errors-DVNYib5y.cjs.map +1 -0
- package/dist/errors-aMocmFr-.js +1225 -0
- package/dist/errors-aMocmFr-.js.map +1 -0
- package/dist/index-BX-V3C9t.js +995 -0
- package/dist/index-BX-V3C9t.js.map +1 -0
- package/dist/index-BgnxXV5G.cjs +2 -0
- package/dist/index-BgnxXV5G.cjs.map +1 -0
- package/dist/index-BvFLf3vm.js +1513 -0
- package/dist/index-BvFLf3vm.js.map +1 -0
- package/dist/index-DpKhuCta.cjs +2 -0
- package/dist/index-DpKhuCta.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +84 -74
- package/dist/tbv/core/clients/eth/__tests__/protocol-params-reader.test.d.ts +2 -0
- package/dist/tbv/core/clients/eth/__tests__/protocol-params-reader.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/__tests__/signer-set-reader.test.d.ts +2 -0
- package/dist/tbv/core/clients/eth/__tests__/signer-set-reader.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/contract-address-resolver.d.ts +18 -0
- package/dist/tbv/core/clients/eth/contract-address-resolver.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/index.d.ts +4 -1
- package/dist/tbv/core/clients/eth/index.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts +27 -0
- package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/signer-set-reader.d.ts +37 -0
- package/dist/tbv/core/clients/eth/signer-set-reader.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/types.d.ts +80 -0
- package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +25 -21
- package/dist/tbv/core/contracts/abis/ApplicationRegistry.abi.d.ts +74 -0
- package/dist/tbv/core/contracts/abis/ApplicationRegistry.abi.d.ts.map +1 -0
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +74 -0
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
- package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts +233 -0
- package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts.map +1 -0
- package/dist/tbv/core/contracts/index.d.ts +2 -0
- package/dist/tbv/core/contracts/index.d.ts.map +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +86 -76
- package/dist/tbv/core/services/htlc/__tests__/htlc.test.d.ts +2 -0
- package/dist/tbv/core/services/htlc/__tests__/htlc.test.d.ts.map +1 -0
- package/dist/tbv/core/services/htlc/index.d.ts +25 -0
- package/dist/tbv/core/services/htlc/index.d.ts.map +1 -0
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.d.ts +1 -0
- package/dist/tbv/core/services/index.d.ts.map +1 -1
- package/dist/tbv/core/services/index.js +6 -4
- package/dist/tbv/core/wots/__tests__/blockDerivation.test.d.ts +2 -0
- package/dist/tbv/core/wots/__tests__/blockDerivation.test.d.ts.map +1 -0
- package/dist/tbv/core/wots/blockDerivation.d.ts +36 -0
- package/dist/tbv/core/wots/blockDerivation.d.ts.map +1 -0
- package/dist/tbv/core/wots/index.d.ts +1 -0
- package/dist/tbv/core/wots/index.d.ts.map +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +86 -76
- package/dist/tbv/integrations/aave/clients/abis/AaveSpoke.abi.json.d.ts +140 -0
- package/dist/tbv/integrations/aave/clients/index.d.ts +1 -1
- package/dist/tbv/integrations/aave/clients/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/clients/query.d.ts +12 -1
- package/dist/tbv/integrations/aave/clients/query.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.cjs +1 -1
- package/dist/tbv/integrations/aave/index.cjs.map +1 -1
- package/dist/tbv/integrations/aave/index.d.ts +2 -2
- package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.js +141 -129
- package/dist/tbv/integrations/aave/index.js.map +1 -1
- package/dist/tbv/integrations/aave/types.d.ts +10 -0
- package/dist/tbv/integrations/aave/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/errors-DKLboMnq.cjs +0 -2
- package/dist/errors-DKLboMnq.cjs.map +0 -1
- package/dist/errors-KY63mgWT.js +0 -1510
- package/dist/errors-KY63mgWT.js.map +0 -1
- package/dist/index-D3z3SZAj.cjs +0 -2
- package/dist/index-D3z3SZAj.cjs.map +0 -1
- package/dist/index-Dw7FAwne.js +0 -913
- package/dist/index-Dw7FAwne.js.map +0 -1
- package/dist/signAndSubmitPayouts-CAOEAQp9.js +0 -490
- package/dist/signAndSubmitPayouts-CAOEAQp9.js.map +0 -1
- package/dist/signAndSubmitPayouts-CSJmcPQN.cjs +0 -2
- package/dist/signAndSubmitPayouts-CSJmcPQN.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors-KY63mgWT.js","sources":["../src/tbv/core/contracts/errors.ts","../src/tbv/core/managers/PeginManager.ts","../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/utils.js","../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/hmac.js","../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/_md.js","../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/legacy.js","../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/_u64.js","../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/sha2.js","../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/sha3.js","../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/pbkdf2.js","../../../node_modules/.pnpm/@scure+bip39@2.0.1/node_modules/@scure/bip39/index.js","../src/tbv/core/wots/derivation.ts","../src/tbv/core/wots/deriveWotsPkHash.ts","../src/tbv/core/wots/errors.ts"],"sourcesContent":["/**\n * Contract Error Handling Utilities\n *\n * Provides utilities for extracting and handling contract revert errors.\n * Maps known error selectors to user-friendly messages.\n *\n * @module contracts/errors\n */\n\n/**\n * Known contract error signatures mapped to user-friendly messages.\n *\n * Error selectors are the first 4 bytes of keccak256(error signature).\n * Example: keccak256(\"VaultAlreadyExists()\") = 0x04aabf33...\n */\nexport const CONTRACT_ERRORS: Record<string, string> = {\n // VaultAlreadyExists()\n \"0x04aabf33\":\n \"Vault already exists: This Bitcoin transaction has already been registered. \" +\n \"Please select different UTXOs or use a different amount to create a unique transaction.\",\n // ScriptPubKeyMismatch() - taproot output doesn't match expected script\n \"0x4fec082d\":\n \"Script mismatch: The Bitcoin transaction's taproot output does not match the expected vault script. \" +\n \"This may be caused by incorrect vault participants or key configuration.\",\n // InvalidBTCProofOfPossession()\n \"0x6cc363a5\":\n \"Invalid BTC proof of possession: The signature could not be verified. \" +\n \"Please ensure you're signing with the correct Bitcoin wallet.\",\n // InvalidBTCPublicKey()\n \"0x6c3f2bf6\":\n \"Invalid BTC public key: The Bitcoin public key format is invalid.\",\n // InvalidAmount()\n \"0x2c5211c6\":\n \"Invalid amount: The deposit amount is invalid or below the minimum required.\",\n // ApplicationNotRegistered()\n \"0x0405f772\":\n \"Application not registered: The application controller is not registered in the system.\",\n // InvalidProviderStatus()\n \"0x24e165cc\":\n \"Invalid provider status: The vault provider is not in a valid state to accept deposits.\",\n // ZeroAddress()\n \"0xd92e233d\":\n \"Zero address: One of the required addresses is the zero address.\",\n // BtcKeyMismatch()\n \"0x65aa7007\":\n \"BTC key mismatch: The Bitcoin public key does not match the expected key.\",\n // Unauthorized()\n \"0x82b42900\":\n \"Unauthorized: You must be the depositor or vault provider to submit this transaction.\",\n // InvalidSignature() - common signature verification error\n \"0x8baa579f\":\n \"Invalid signature: The BTC proof of possession signature could not be verified.\",\n // InvalidBtcTransaction()\n \"0x2f9d01e9\":\n \"Invalid BTC transaction: The Bitcoin transaction format is invalid.\",\n // VaultProviderNotRegistered()\n \"0x5a3c6b3e\":\n \"Vault provider not registered: The selected vault provider is not registered.\",\n // InvalidPeginFee(uint256,uint256)\n \"0x979f4518\":\n \"Invalid pegin fee: The ETH fee sent does not match the required amount. \" +\n \"This may indicate a fee rate change during the transaction.\",\n};\n\n/**\n * Extract error data from various error formats.\n *\n * Viem and wallet providers wrap errors in multiple levels. This function\n * searches through the error chain to find the revert data.\n *\n * @param error - The error object to extract data from\n * @returns The error data (e.g., \"0x04aabf33\") or undefined\n */\nexport function extractErrorData(error: unknown): string | undefined {\n if (!error || typeof error !== \"object\") return undefined;\n\n const err = error as Record<string, unknown>;\n\n // Check direct properties first\n if (typeof err.data === \"string\" && err.data.startsWith(\"0x\")) {\n return err.data;\n }\n if (typeof err.details === \"string\" && err.details.startsWith(\"0x\")) {\n return err.details;\n }\n\n // Walk the cause chain (viem wraps errors multiple levels deep)\n let current: unknown = err.cause;\n let depth = 0;\n const maxDepth = 5;\n\n while (current && typeof current === \"object\" && depth < maxDepth) {\n const cause = current as Record<string, unknown>;\n if (typeof cause.data === \"string\" && cause.data.startsWith(\"0x\")) {\n return cause.data;\n }\n current = cause.cause;\n depth++;\n }\n\n // Check error message for embedded hex error selector\n const message = typeof err.message === \"string\" ? err.message : \"\";\n const hexMatch = message.match(/\\b(0x[a-fA-F0-9]{8})\\b/);\n if (hexMatch) {\n return hexMatch[1];\n }\n\n return undefined;\n}\n\n/**\n * Get a user-friendly error message for a contract error.\n *\n * @param error - The error object from a contract call\n * @returns A user-friendly error message, or undefined if error is not recognized\n */\nexport function getContractErrorMessage(error: unknown): string | undefined {\n const errorData = extractErrorData(error);\n if (errorData) {\n // Check exact match first, then match by 4-byte selector prefix.\n // Parametric errors (e.g. InvalidPeginFee(uint256,uint256)) return\n // the selector + ABI-encoded args, so the full string won't match.\n const selector = errorData.substring(0, 10); // \"0x\" + 4 bytes\n return CONTRACT_ERRORS[errorData] ?? CONTRACT_ERRORS[selector];\n }\n return undefined;\n}\n\n/**\n * Check if an error is a known contract error.\n *\n * @param error - The error object to check\n * @returns True if the error is a known contract error\n */\nexport function isKnownContractError(error: unknown): boolean {\n const errorData = extractErrorData(error);\n if (errorData === undefined) return false;\n const selector = errorData.substring(0, 10);\n return errorData in CONTRACT_ERRORS || selector in CONTRACT_ERRORS;\n}\n\n/**\n * Handle a contract error by throwing a user-friendly error.\n *\n * This function extracts error data, maps it to a user-friendly message,\n * and throws an appropriate error. Use this in catch blocks after contract calls.\n *\n * @param error - The error from a contract call\n * @throws Always throws an error with a descriptive message\n */\nexport function handleContractError(error: unknown): never {\n // Log full error for debugging\n console.error(\"[Contract Error] Raw error:\", error);\n\n // Extract error data from the error chain\n const errorData = extractErrorData(error);\n console.error(\"[Contract Error] Extracted error data:\", errorData);\n\n // Check for known contract error signatures (exact match or 4-byte selector prefix)\n if (errorData) {\n const selector = errorData.substring(0, 10);\n const knownError = CONTRACT_ERRORS[errorData] ?? CONTRACT_ERRORS[selector];\n if (knownError) {\n console.error(\"[Contract Error] Known error:\", knownError);\n throw new Error(knownError);\n }\n }\n\n // Check for gas estimation errors or internal JSON-RPC errors\n const errorMsg = (error as Error)?.message || \"\";\n if (\n errorMsg.includes(\"gas limit too high\") ||\n errorMsg.includes(\"21000000\") ||\n errorMsg.includes(\"Internal JSON-RPC error\")\n ) {\n // If we found error data but it's not in our known list, include it\n const errorHint = errorData ? ` (error code: ${errorData})` : \"\";\n console.error(\n \"[Contract Error] Transaction rejected. Error code:\",\n errorData,\n \"Message:\",\n errorMsg,\n );\n throw new Error(\n `Transaction failed: The contract rejected this transaction${errorHint}. ` +\n \"Possible causes: (1) Vault already exists for this transaction, \" +\n \"(2) Invalid signature, (3) Unauthorized caller. \" +\n \"Please check your transaction parameters and try again.\",\n );\n }\n\n // Default: re-throw original error with better context\n if (error instanceof Error) {\n console.error(\"[Contract Error] Unhandled error:\", error.message);\n throw error;\n }\n throw new Error(`Contract call failed: ${String(error)}`);\n}\n","/**\n * Peg-in Manager - Wallet Orchestration for Peg-in Operations\n *\n * This module provides the PeginManager class that orchestrates the complete\n * peg-in flow using SDK primitives, utilities, and wallet interfaces.\n *\n * @remarks\n * PeginManager handles the peg-in flow:\n * 1. **preparePegin()** - Build Pre-PegIn HTLC, fund it, sign PegIn input\n * 2. **registerPeginOnChain()** - Submit to Ethereum contract with PoP\n * 3. *(Use {@link PayoutManager} for payout authorization signing)*\n * 4. **signAndBroadcast()** - Sign and broadcast Pre-PegIn tx to Bitcoin network\n *\n * @see {@link PayoutManager} - For Step 3: sign payout transactions\n * @see {@link buildPrePeginPsbt} - Lower-level primitive used internally\n *\n * @module managers/PeginManager\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport {\n createPublicClient,\n encodeFunctionData,\n http,\n zeroAddress,\n type Address,\n type Chain,\n type Hex,\n type WalletClient,\n} from \"viem\";\n\nimport type { BitcoinWallet, Hash, SignPsbtOptions } from \"../../../shared/wallets\";\nimport { createTaprootScriptPathSignOptions } from \"../utils/signing\";\nimport { type UtxoInfo, getUtxoInfo, pushTx } from \"../clients/mempool\";\nimport { BTCVaultRegistryABI, handleContractError } from \"../contracts\";\nimport {\n buildPrePeginPsbt,\n buildPeginTxFromFundedPrePegin,\n buildPeginInputPsbt,\n extractPeginInputSignature,\n finalizePeginInputPsbt,\n deriveVaultId,\n type PrePeginParams,\n type Network,\n} from \"../primitives\";\nimport {\n ensureHexPrefix,\n isAddressFromPublicKey,\n stripHexPrefix,\n} from \"../primitives/utils/bitcoin\";\nimport {\n calculateBtcTxHash,\n fundPeginTransaction,\n getNetwork,\n getPsbtInputFields,\n peginOutputCount,\n selectUtxosForPegin,\n type UTXO,\n} from \"../utils\";\n\n/** Referral code sent with pegin registration — 0 means no referral. */\nconst NO_REFERRAL_CODE = 0;\n\n/**\n * Configuration for the PeginManager.\n */\nexport interface PeginManagerConfig {\n /**\n * Bitcoin network to use for transactions.\n */\n btcNetwork: Network;\n\n /**\n * Bitcoin wallet for signing peg-in transactions.\n */\n btcWallet: BitcoinWallet;\n\n /**\n * Ethereum wallet for registering peg-in on-chain.\n * Uses viem's WalletClient directly for proper gas estimation.\n */\n ethWallet: WalletClient;\n\n /**\n * Ethereum chain configuration.\n * Required for proper gas estimation in contract calls.\n */\n ethChain: Chain;\n\n /**\n * Vault contract addresses.\n */\n vaultContracts: {\n /**\n * BTCVaultRegistry contract address on Ethereum.\n */\n btcVaultRegistry: Address;\n };\n\n /**\n * Mempool API URL for fetching UTXO data and broadcasting transactions.\n * Use MEMPOOL_API_URLS constant for standard mempool.space URLs, or provide\n * a custom URL if running your own mempool instance.\n */\n mempoolApiUrl: string;\n}\n\n/**\n * Parameters for the pegin flow (pre-pegin + pegin transactions).\n */\nexport interface PreparePeginParams {\n /**\n * Amounts to peg in per HTLC (in satoshis).\n * Must have the same length as `hashlocks`.\n * For single deposits, pass a single-element array.\n */\n amounts: readonly bigint[];\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex).\n * Can be provided with or without \"0x\" prefix (will be stripped automatically).\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex).\n * Can be provided with or without \"0x\" prefix (will be stripped automatically).\n */\n vaultKeeperBtcPubkeys: readonly string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex).\n * Can be provided with or without \"0x\" prefix (will be stripped automatically).\n */\n universalChallengerBtcPubkeys: readonly string[];\n\n /**\n * CSV timelock in blocks for the PegIn vault output.\n */\n timelockPegin: number;\n\n /**\n * CSV timelock in blocks for the Pre-PegIn HTLC refund path.\n */\n timelockRefund: number;\n\n /**\n * SHA256 hash commitment(s) for the HTLC (64 hex chars = 32 bytes each).\n * Generated by the depositor as H = SHA256(secret).\n * For single deposits, pass a single-element array.\n */\n hashlocks: readonly string[];\n\n /**\n * Protocol fee rate in sat/vB from the contract offchain params.\n * Used by WASM for computing depositorClaimValue and min pegin fee.\n */\n protocolFeeRate: bigint;\n\n /**\n * Mempool fee rate in sat/vB for funding the Pre-PegIn transaction.\n * Used for UTXO selection and change calculation.\n */\n mempoolFeeRate: number;\n\n /**\n * M in M-of-N council multisig (from contract params).\n */\n councilQuorum: number;\n\n /**\n * N in M-of-N council multisig (from contract params).\n */\n councilSize: number;\n\n /**\n * Available UTXOs from the depositor's wallet for funding the Pre-PegIn transaction.\n */\n availableUTXOs: readonly UTXO[];\n\n /**\n * Bitcoin address for receiving change from the Pre-PegIn transaction.\n */\n changeAddress: string;\n}\n\n/**\n * Result of preparing a pegin.\n */\n/** Per-vault PegIn data derived from a shared Pre-PegIn transaction */\nexport interface PerVaultPeginData {\n /** Index of the HTLC output in the Pre-PegIn transaction (0, 1, 2, ...) */\n htlcVout: number;\n /** HTLC output value in satoshis */\n htlcValue: bigint;\n /** Depositor-signed PegIn transaction hex (for contract registration) */\n peginTxHex: string;\n /** PegIn transaction ID */\n peginTxid: string;\n /** Depositor's Schnorr signature over PegIn input (HTLC leaf 0) */\n peginInputSignature: string;\n /** Vault output scriptPubKey hex */\n vaultScriptPubKey: string;\n}\n\nexport interface PreparePeginResult {\n /** Funded but unsigned Pre-PegIn transaction hex */\n fundedPrePeginTxHex: string;\n /** Funded Pre-PegIn transaction ID */\n prePeginTxid: string;\n /** Unfunded Pre-PegIn transaction hex (for contract DA submission) */\n unsignedPrePeginTxHex: string;\n /** Per-vault PegIn data — one entry per hashlock/amount */\n perVault: PerVaultPeginData[];\n /** UTXOs selected to fund the Pre-PegIn transaction */\n selectedUTXOs: UTXO[];\n /** Transaction fee in satoshis */\n fee: bigint;\n /** Change amount in satoshis (if any) */\n changeAmount: bigint;\n}\n\n\n/**\n * Parameters for signing and broadcasting a transaction.\n */\nexport interface SignAndBroadcastParams {\n /**\n * Funded Pre-PegIn transaction hex from preparePegin().\n */\n fundedPrePeginTxHex: string;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex).\n * Can be provided with or without \"0x\" prefix.\n * Required for Taproot signing.\n */\n depositorBtcPubkey: string;\n\n /**\n * Optional pre-fetched prevout data for inputs not yet in the mempool.\n * Key format: \"txid:vout\" (e.g. \"abc123...def:0\").\n * When provided, matching inputs skip the mempool API fetch.\n * Useful for split transactions where outputs are unconfirmed.\n */\n localPrevouts?: Record<string, { scriptPubKey: string; value: number }>;\n}\n\n/**\n * Parameters for registering a peg-in on Ethereum.\n */\nexport interface RegisterPeginParams {\n /**\n * Depositor's BTC public key (x-only, 64-char hex).\n * Can be provided with or without \"0x\" prefix.\n */\n depositorBtcPubkey: string;\n\n /**\n * Unsigned Pre-PegIn transaction hex (submitted to contract for data availability).\n */\n unsignedPrePeginTx: string;\n\n /**\n * Depositor-signed PegIn transaction hex (submitted to contract; vault ID derived from this).\n */\n depositorSignedPeginTx: string;\n\n /**\n * Vault provider's Ethereum address.\n */\n vaultProvider: Address;\n\n /**\n * SHA256 hashlock for HTLC activation (bytes32 hex with 0x prefix).\n */\n hashlock: Hex;\n\n /**\n * Optional callback invoked after PoP signing completes but before ETH transaction.\n */\n onPopSigned?: () => void | Promise<void>;\n\n /**\n * Depositor's BTC payout address (e.g. bc1p..., bc1q...).\n * Converted to scriptPubKey internally via bitcoinjs-lib.\n *\n * If omitted, defaults to the connected BTC wallet's address\n * via `btcWallet.getAddress()`.\n */\n depositorPayoutBtcAddress?: string;\n\n /** Keccak256 hash of the depositor's WOTS public key (bytes32) */\n depositorWotsPkHash: Hex;\n\n /**\n * Pre-signed BTC PoP signature (hex with 0x prefix).\n * When provided, the BTC wallet signing step is skipped and this signature is used directly.\n * Useful for multi-vault deposits where PoP only needs to be signed once.\n */\n preSignedBtcPopSignature?: Hex;\n\n /**\n * Zero-based index of the HTLC output in the Pre-PegIn transaction that\n * this PegIn spends. In a batch Pre-PegIn with N HTLC outputs, each vault\n * registration references a different htlcVout (0..N-1).\n */\n htlcVout: number;\n}\n\n/**\n * Result of registering a peg-in on Ethereum.\n */\nexport interface RegisterPeginResult {\n /**\n * Ethereum transaction hash for the peg-in registration.\n */\n ethTxHash: Hash;\n\n /**\n * Derived vault ID: keccak256(abi.encode(peginTxHash, depositor)).\n * Used for contract reads/writes and indexer queries.\n */\n vaultId: Hex;\n\n /**\n * Raw Bitcoin pegin transaction hash (double-SHA256 of the signed pegin tx).\n * Used for VP RPC operations which key on the BTC transaction ID.\n */\n peginTxHash: Hex;\n\n /**\n * The BTC PoP signature used for this registration (hex with 0x prefix).\n * Returned so callers can reuse it for subsequent pegins without re-signing.\n */\n btcPopSignature: Hex;\n}\n\n/**\n * Single request in a batch pegin registration.\n * All requests in a batch share the same vault provider and depositor.\n */\nexport interface BatchPeginRequestItem {\n /** Depositor's BTC public key (x-only, 64-char hex or with 0x prefix) */\n depositorBtcPubkey: string;\n /** Unsigned Pre-PegIn tx hex (same for all vaults in batch) */\n unsignedPrePeginTx: string;\n /** Signed PegIn tx hex for this vault */\n depositorSignedPeginTx: string;\n /** SHA256 hashlock for HTLC activation (bytes32 hex) */\n hashlock: Hex;\n /** Zero-based HTLC output index in the Pre-PegIn tx */\n htlcVout: number;\n /** Depositor's BTC payout address (required — funds are sent here on payout) */\n depositorPayoutBtcAddress: string;\n /** Keccak256 hash of the depositor's WOTS public key (bytes32) */\n depositorWotsPkHash: Hex;\n}\n\n/**\n * Parameters for registerPeginBatchOnChain.\n */\nexport interface RegisterPeginBatchParams {\n /** Vault provider address (shared across all vaults in batch) */\n vaultProvider: Address;\n /** Individual pegin requests (one per vault) */\n requests: BatchPeginRequestItem[];\n /** Pre-signed BTC PoP signature (signed once, reused for all vaults) */\n preSignedBtcPopSignature?: Hex;\n /** Called after PoP is signed (before ETH tx) */\n onPopSigned?: () => void | Promise<void>;\n}\n\n/**\n * Per-vault result from a batch pegin registration.\n */\nexport interface BatchPeginResultItem {\n /** Derived vault ID: keccak256(abi.encode(peginTxHash, depositor)) */\n vaultId: Hex;\n /** Raw BTC pegin transaction hash */\n peginTxHash: Hex;\n}\n\n/**\n * Result of registering a batch of pegins on Ethereum in a single transaction.\n */\nexport interface RegisterPeginBatchResult {\n /** Ethereum transaction hash */\n ethTxHash: Hex;\n /** Per-vault results (same order as input requests) */\n vaults: BatchPeginResultItem[];\n /** The BTC PoP signature used (for reference) */\n btcPopSignature: Hex;\n}\n\n/**\n * Resolve prevout data for a transaction input.\n * Checks localPrevouts first; falls back to mempool API.\n */\nfunction resolveUtxoInfo(\n txid: string,\n vout: number,\n localPrevouts: Record<string, { scriptPubKey: string; value: number }> | undefined,\n apiUrl: string,\n): Promise<UtxoInfo> {\n const local = localPrevouts?.[`${txid}:${vout}`];\n if (local) {\n return Promise.resolve({\n txid,\n vout,\n value: local.value,\n scriptPubKey: local.scriptPubKey,\n });\n }\n return getUtxoInfo(txid, vout, apiUrl);\n}\n\n/**\n * Manager for orchestrating peg-in operations.\n *\n * This manager provides a high-level API for creating peg-in transactions\n * by coordinating between SDK primitives, utilities, and wallet interfaces.\n *\n * @remarks\n * The complete peg-in flow consists of 4 steps:\n *\n * | Step | Method | Description |\n * |------|--------|-------------|\n * | 1 | {@link preparePegin} | Build Pre-PegIn HTLC, fund it, sign PegIn input |\n * | 2 | {@link registerPeginOnChain} | Submit to Ethereum contract with PoP |\n * | 3 | {@link PayoutManager} | Sign BOTH payout authorizations |\n * | 4 | {@link signAndBroadcast} | Sign and broadcast Pre-PegIn tx to Bitcoin network |\n *\n * **Important:** Step 3 uses {@link PayoutManager}, not this class. After step 2,\n * the vault provider prepares 3 transactions per claimer:\n * - `claim_tx` - Claim transaction\n * - `assert_tx` - Assert transaction\n * - `payout_tx` - Payout transaction\n *\n * You must sign the Payout transaction for each claimer:\n * - {@link PayoutManager.signPayoutTransaction} - uses assert_tx as input reference\n *\n * Submit all signatures to the vault provider before proceeding to step 4.\n *\n * @see {@link PayoutManager} - Required for Step 3 (payout authorization)\n * @see {@link buildPrePeginPsbt} - Lower-level primitive for custom implementations\n * @see {@link https://github.com/babylonlabs-io/babylon-toolkit/blob/main/packages/babylon-ts-sdk/docs/quickstart/managers.md | Managers Quickstart}\n */\n/**\n * Maximum time (ms) to wait for a transaction receipt before timing out.\n * Matches the prior vault-service polling timeout so users see a clear error\n * instead of an indefinite hang when a transaction is dropped from the mempool.\n */\nconst RECEIPT_TIMEOUT_MS = 120_000;\n\nexport class PeginManager {\n private readonly config: PeginManagerConfig;\n\n /**\n * Creates a new PeginManager instance.\n *\n * @param config - Manager configuration including wallets and contract addresses\n */\n constructor(config: PeginManagerConfig) {\n this.config = config;\n }\n\n /**\n * Prepares a peg-in by building the Pre-PegIn HTLC transaction,\n * funding it, constructing the PegIn transaction, and signing the PegIn input.\n *\n * This method orchestrates the following steps:\n * 1. Get depositor BTC public key from wallet\n * 2. Build unfunded Pre-PegIn transaction (HTLC output) using primitives\n * 3. Select UTXOs to cover the HTLC value\n * 4. Fund the Pre-PegIn transaction\n * 5. Derive the PegIn transaction from the funded Pre-PegIn txid\n * 6. Build PSBT for signing the PegIn input (HTLC leaf 0)\n * 7. Sign via BTC wallet and extract depositor signature\n *\n * The returned `fundedPrePeginTxHex` is funded but unsigned (inputs unsigned).\n * Use `signAndBroadcast()` AFTER registering on Ethereum to broadcast it.\n *\n * @param params - Pegin parameters including amount, HTLC params, UTXOs\n * @returns Pegin result with funded Pre-PegIn tx, signed PegIn input, and signatures\n * @throws Error if wallet operations fail or insufficient funds\n */\n async preparePegin(\n params: PreparePeginParams,\n ): Promise<PreparePeginResult> {\n // Step 1: Get depositor BTC public key from wallet\n const depositorBtcPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n // Convert 33-byte compressed (66 chars) to 32-byte x-only (64 chars) if needed\n const depositorBtcPubkey =\n depositorBtcPubkeyRaw.length === 66\n ? depositorBtcPubkeyRaw.slice(2)\n : depositorBtcPubkeyRaw;\n\n const vaultProviderBtcPubkey = stripHexPrefix(params.vaultProviderBtcPubkey);\n const vaultKeeperBtcPubkeys = params.vaultKeeperBtcPubkeys.map(stripHexPrefix);\n const universalChallengerBtcPubkeys =\n params.universalChallengerBtcPubkeys.map(stripHexPrefix);\n\n if (params.hashlocks.length !== params.amounts.length) {\n throw new Error(\n `hashlocks.length (${params.hashlocks.length}) must equal amounts.length (${params.amounts.length})`,\n );\n }\n if (params.hashlocks.length === 0) {\n throw new Error(\"hashlocks must contain at least one entry\");\n }\n\n const numLocalChallengers = vaultKeeperBtcPubkeys.length;\n\n const prePeginParams: PrePeginParams = {\n depositorPubkey: depositorBtcPubkey,\n vaultProviderPubkey: vaultProviderBtcPubkey,\n vaultKeeperPubkeys: vaultKeeperBtcPubkeys,\n universalChallengerPubkeys: universalChallengerBtcPubkeys,\n hashlocks: params.hashlocks,\n timelockRefund: params.timelockRefund,\n pegInAmounts: params.amounts,\n feeRate: params.protocolFeeRate,\n numLocalChallengers,\n councilQuorum: params.councilQuorum,\n councilSize: params.councilSize,\n network: this.config.btcNetwork,\n };\n\n // Step 2: Build unfunded Pre-PegIn transaction (N HTLC outputs, no inputs)\n const prePeginResult = await buildPrePeginPsbt(prePeginParams);\n\n // Step 3: Select UTXOs to cover ALL unfunded tx outputs (HTLCs + CPFP anchor)\n const utxoSelection = selectUtxosForPegin(\n [...params.availableUTXOs],\n prePeginResult.totalOutputValue,\n params.mempoolFeeRate,\n peginOutputCount(prePeginResult.htlcValues.length),\n );\n\n // Step 4: Fund the Pre-PegIn transaction with selected UTXOs\n const network = getNetwork(this.config.btcNetwork);\n const fundedPrePeginTxHex = fundPeginTransaction({\n unfundedTxHex: prePeginResult.psbtHex,\n selectedUTXOs: utxoSelection.selectedUTXOs,\n changeAddress: params.changeAddress,\n changeAmount: utxoSelection.changeAmount,\n network,\n });\n\n const prePeginTxid = stripHexPrefix(calculateBtcTxHash(fundedPrePeginTxHex));\n\n // Step 5: For each HTLC output, derive PegIn tx and build PSBT (no signing yet)\n const peginTxResults: Array<{\n txHex: string;\n txid: string;\n vaultScriptPubKey: string;\n }> = [];\n const psbtsToSign: string[] = [];\n const signOptions: SignPsbtOptions[] = [];\n\n for (let i = 0; i < params.hashlocks.length; i++) {\n const peginTxResult = await buildPeginTxFromFundedPrePegin({\n prePeginParams,\n timelockPegin: params.timelockPegin,\n fundedPrePeginTxHex,\n htlcVout: i,\n });\n\n const peginInputPsbtResult = await buildPeginInputPsbt({\n peginTxHex: peginTxResult.txHex,\n fundedPrePeginTxHex,\n depositorPubkey: depositorBtcPubkey,\n vaultProviderPubkey: vaultProviderBtcPubkey,\n vaultKeeperPubkeys: vaultKeeperBtcPubkeys,\n universalChallengerPubkeys: universalChallengerBtcPubkeys,\n hashlock: params.hashlocks[i],\n timelockRefund: params.timelockRefund,\n network: this.config.btcNetwork,\n });\n\n peginTxResults.push(peginTxResult);\n psbtsToSign.push(peginInputPsbtResult.psbtHex);\n signOptions.push(\n createTaprootScriptPathSignOptions(depositorBtcPubkeyRaw, 1),\n );\n }\n\n // Step 6: Batch sign all PegIn input PSBTs (single signPsbts call where supported)\n const signedPsbts = await this.signPsbtsWithFallback(\n psbtsToSign,\n signOptions,\n );\n\n // Step 7: Extract signatures and finalize\n const perVault: PerVaultPeginData[] = [];\n for (let i = 0; i < signedPsbts.length; i++) {\n const peginInputSignature = extractPeginInputSignature(\n signedPsbts[i],\n depositorBtcPubkey,\n );\n\n const depositorSignedPeginTxHex = finalizePeginInputPsbt(signedPsbts[i]);\n\n perVault.push({\n htlcVout: i,\n htlcValue: prePeginResult.htlcValues[i],\n peginTxHex: depositorSignedPeginTxHex,\n peginTxid: peginTxResults[i].txid,\n peginInputSignature,\n vaultScriptPubKey: peginTxResults[i].vaultScriptPubKey,\n });\n }\n\n return {\n fundedPrePeginTxHex,\n prePeginTxid,\n unsignedPrePeginTxHex: prePeginResult.psbtHex,\n perVault,\n selectedUTXOs: utxoSelection.selectedUTXOs,\n fee: utxoSelection.fee,\n changeAmount: utxoSelection.changeAmount,\n };\n }\n\n /**\n * Signs multiple PSBTs using batch signing if available, falling back to sequential signing.\n *\n * Wallets that support native batch signing (e.g. UniSat) will sign all PSBTs\n * in a single interaction. Others (e.g. Ledger, AppKit) implement signPsbts\n * by looping signPsbt internally, so the UX depends on the wallet adapter.\n */\n private async signPsbtsWithFallback(\n psbtsHexes: string[],\n options: SignPsbtOptions[],\n ): Promise<string[]> {\n if (typeof this.config.btcWallet.signPsbts === \"function\") {\n const signedPsbts = await this.config.btcWallet.signPsbts(\n psbtsHexes,\n options,\n );\n if (signedPsbts.length !== psbtsHexes.length) {\n throw new Error(\n `Expected ${psbtsHexes.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n return signedPsbts;\n }\n\n // Fallback: sign sequentially\n const signedPsbts: string[] = [];\n for (let i = 0; i < psbtsHexes.length; i++) {\n const signed = await this.config.btcWallet.signPsbt(\n psbtsHexes[i],\n options[i],\n );\n signedPsbts.push(signed);\n }\n return signedPsbts;\n }\n\n /**\n * Signs and broadcasts a funded peg-in transaction to the Bitcoin network.\n *\n * This method:\n * 1. Parses the funded transaction hex\n * 2. Fetches UTXO data from mempool for each input\n * 3. Creates a PSBT with proper witnessUtxo/tapInternalKey\n * 4. Signs via btcWallet.signPsbt()\n * 5. Finalizes and extracts the transaction\n * 6. Broadcasts via mempool API\n *\n * @param params - Transaction hex and depositor public key\n * @returns The broadcasted Bitcoin transaction ID\n * @throws Error if signing or broadcasting fails\n */\n async signAndBroadcast(params: SignAndBroadcastParams): Promise<string> {\n const { fundedPrePeginTxHex, depositorBtcPubkey } = params;\n\n // Step 1: Parse the funded transaction\n const cleanHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const tx = Transaction.fromHex(cleanHex);\n\n if (tx.ins.length === 0) {\n throw new Error(\"Transaction has no inputs\");\n }\n\n // Step 2: Create PSBT and add inputs with UTXO data from mempool\n const psbt = new Psbt();\n psbt.setVersion(tx.version);\n psbt.setLocktime(tx.locktime);\n\n // Strip 0x prefix if present before converting to Buffer\n const cleanPubkey = depositorBtcPubkey.startsWith(\"0x\")\n ? depositorBtcPubkey.slice(2)\n : depositorBtcPubkey;\n // Validate x-only pubkey length and format (32 bytes = 64 hex chars)\n if (cleanPubkey.length !== 64 || !/^[0-9a-fA-F]+$/.test(cleanPubkey)) {\n throw new Error(\n \"Invalid depositorBtcPubkey: expected 64 hex characters (x-only pubkey)\",\n );\n }\n const publicKeyNoCoord = Buffer.from(cleanPubkey, \"hex\");\n if (publicKeyNoCoord.length !== 32) {\n throw new Error(\n `Invalid depositorBtcPubkey length: expected 32 bytes, got ${publicKeyNoCoord.length}`,\n );\n }\n const apiUrl = this.config.mempoolApiUrl;\n\n // Resolve prevout data for each input (local cache or mempool API)\n const utxoDataPromises = tx.ins.map((input) => {\n const txid = Buffer.from(input.hash).reverse().toString(\"hex\");\n const vout = input.index;\n return resolveUtxoInfo(txid, vout, params.localPrevouts, apiUrl).then(\n (utxoData) => ({ input, utxoData, txid, vout }),\n );\n });\n\n const inputsWithUtxoData = await Promise.all(utxoDataPromises);\n\n // Cross-validate: total input value must cover total output value.\n // A mismatch indicates the mempool API returned manipulated UTXO data,\n // which could lead to fee-siphoning or invalid signatures.\n const totalInputValue = inputsWithUtxoData.reduce(\n (sum, i) => sum + BigInt(i.utxoData.value),\n 0n,\n );\n const totalOutputValue = tx.outs.reduce(\n (sum, out) => sum + BigInt(out.value),\n 0n,\n );\n if (totalInputValue < totalOutputValue) {\n throw new Error(\n `UTXO value mismatch: total input value (${totalInputValue} sat) is less than ` +\n `total output value (${totalOutputValue} sat). ` +\n `This may indicate the mempool API returned manipulated UTXO data.`,\n );\n }\n\n // Add inputs with proper PSBT fields based on script type\n for (const { input, utxoData, txid, vout } of inputsWithUtxoData) {\n const psbtInputFields = getPsbtInputFields(\n {\n txid,\n vout,\n value: utxoData.value,\n scriptPubKey: utxoData.scriptPubKey,\n },\n publicKeyNoCoord,\n );\n\n psbt.addInput({\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n ...psbtInputFields,\n });\n }\n\n // Step 3: Add outputs\n for (const output of tx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n // Step 4: Sign PSBT via wallet\n const signedPsbtHex = await this.config.btcWallet.signPsbt(psbt.toHex());\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n\n // Step 5: Finalize and extract transaction\n try {\n signedPsbt.finalizeAllInputs();\n } catch (e) {\n // Some wallets (e.g. UniSat, OKX) auto-finalize PSBTs before returning them.\n // Attempting to finalize again throws, which is expected and safe to skip —\n // but verify the wallet actually finalized all inputs.\n const allFinalized = signedPsbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n const signedTxHex = signedPsbt.extractTransaction().toHex();\n\n // Step 6: Broadcast to Bitcoin network\n const btcTxid = await pushTx(signedTxHex, apiUrl);\n\n return btcTxid;\n }\n\n /**\n * Registers a peg-in on Ethereum by calling the BTCVaultRegistry contract.\n *\n * This method:\n * 1. Gets depositor ETH address from wallet\n * 2. Creates proof of possession (BTC signature of ETH address)\n * 3. Checks if vault already exists (pre-flight check)\n * 4. Encodes the contract call using viem\n * 5. Estimates gas (catches contract errors early with proper revert reasons)\n * 6. Sends transaction with pre-estimated gas via ethWallet.sendTransaction()\n *\n * @param params - Registration parameters including BTC pubkey and unsigned tx\n * @returns Result containing Ethereum transaction hash and vault ID\n * @throws Error if signing or transaction fails\n * @throws Error if vault already exists\n * @throws Error if contract simulation fails (e.g., invalid signature, unauthorized)\n */\n async registerPeginOnChain(\n params: RegisterPeginParams,\n ): Promise<RegisterPeginResult> {\n const {\n depositorBtcPubkey,\n unsignedPrePeginTx,\n depositorSignedPeginTx,\n vaultProvider,\n hashlock,\n htlcVout,\n onPopSigned,\n depositorPayoutBtcAddress,\n depositorWotsPkHash,\n preSignedBtcPopSignature,\n } = params;\n\n // Step 1: Get depositor ETH address (from wallet account)\n if (!this.config.ethWallet.account) {\n throw new Error(\"Ethereum wallet account not found\");\n }\n const depositorEthAddress = this.config.ethWallet.account.address;\n\n // Step 2: Create proof of possession (or reuse pre-signed one)\n const btcPopSignature = await this.resolvePopSignature(\n depositorEthAddress,\n preSignedBtcPopSignature,\n );\n\n if (onPopSigned) {\n await onPopSigned();\n }\n\n // Step 3: Format parameters for contract call\n const depositorBtcPubkeyHex = ensureHexPrefix(depositorBtcPubkey);\n const unsignedPrePeginTxHex = ensureHexPrefix(unsignedPrePeginTx);\n const depositorSignedPeginTxHex = ensureHexPrefix(depositorSignedPeginTx);\n\n const payoutScriptPubKey = await this.resolvePayoutScriptPubKey(\n depositorPayoutBtcAddress,\n );\n\n // Step 4: Calculate pegin tx hash and derive vault ID, then check if it already exists\n const peginTxHash = calculateBtcTxHash(depositorSignedPeginTxHex);\n const derivedVaultIdHex = await deriveVaultId(\n stripHexPrefix(peginTxHash),\n stripHexPrefix(depositorEthAddress),\n );\n const vaultId = ensureHexPrefix(derivedVaultIdHex) as Hex;\n const exists = await this.checkVaultExists(vaultId);\n\n if (exists) {\n throw new Error(\n `Vault already exists (ID: ${vaultId}, peginTxHash: ${peginTxHash}). ` +\n `Vault IDs are derived from the pegin transaction hash and depositor address. ` +\n `To create a new vault, use different UTXOs or a different amount to generate a unique transaction.`,\n );\n }\n\n // Step 5: Query required pegin fee from the contract\n const publicClient = createPublicClient({\n chain: this.config.ethChain,\n transport: http(),\n });\n\n let peginFee: bigint;\n try {\n peginFee = (await publicClient.readContract({\n address: this.config.vaultContracts.btcVaultRegistry,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n } catch {\n throw new Error(\n \"Failed to query pegin fee from the contract. \" +\n \"Please check your network connection and that the contract address is correct.\",\n );\n }\n\n // Step 6: Encode the contract call data\n const callData = encodeFunctionData({\n abi: BTCVaultRegistryABI,\n functionName: \"submitPeginRequest\",\n args: [\n depositorEthAddress,\n depositorBtcPubkeyHex,\n btcPopSignature,\n unsignedPrePeginTxHex,\n depositorSignedPeginTxHex,\n vaultProvider,\n hashlock,\n htlcVout,\n payoutScriptPubKey,\n depositorWotsPkHash,\n ],\n });\n\n // Step 7: Estimate gas first to catch contract errors before showing wallet popup\n // This ensures users see actual contract revert reasons instead of gas errors\n // The gas estimate is then passed to sendTransaction to avoid double estimation\n let gasEstimate: bigint;\n try {\n gasEstimate = await publicClient.estimateGas({\n to: this.config.vaultContracts.btcVaultRegistry,\n data: callData,\n value: peginFee,\n account: this.config.ethWallet.account.address,\n });\n } catch (error) {\n // Estimation failed - handle contract error with actual revert reason\n handleContractError(error); // always throws (return type: never)\n }\n\n // Step 8: Submit peg-in request to contract (estimation passed)\n let ethTxHash: Hex;\n try {\n // Send transaction with pre-estimated gas to skip internal estimation\n // Note: viem's sendTransaction uses `gas`, not `gasLimit`\n ethTxHash = await this.config.ethWallet.sendTransaction({\n to: this.config.vaultContracts.btcVaultRegistry,\n data: callData,\n value: peginFee,\n account: this.config.ethWallet.account,\n chain: this.config.ethChain,\n gas: gasEstimate,\n });\n } catch (error) {\n // Use proper error handler for better error messages\n handleContractError(error); // always throws (return type: never)\n }\n\n // Step 9: Wait for transaction receipt and verify it was not reverted\n const receipt = await publicClient.waitForTransactionReceipt({\n hash: ethTxHash,\n timeout: RECEIPT_TIMEOUT_MS,\n });\n if (receipt.status === \"reverted\") {\n handleContractError(\n new Error(\n `Transaction reverted. Hash: ${ethTxHash}. ` +\n `Check the transaction on block explorer for details.`,\n ),\n );\n }\n\n return {\n ethTxHash: receipt.transactionHash,\n vaultId,\n peginTxHash,\n btcPopSignature,\n };\n }\n\n /**\n * Register multiple pegins on Ethereum in a single transaction.\n *\n * Uses the contract's submitPeginRequestBatch() to submit all vault\n * registrations atomically. All vaults must share the same vault provider.\n * The PoP signature is signed once and included in each request.\n *\n * @param params - Batch registration parameters\n * @returns Batch result with per-vault IDs and single ETH tx hash\n */\n async registerPeginBatchOnChain(\n params: RegisterPeginBatchParams,\n ): Promise<RegisterPeginBatchResult> {\n const { vaultProvider, requests, preSignedBtcPopSignature, onPopSigned } =\n params;\n\n if (requests.length === 0) {\n throw new Error(\"Batch pegin requires at least one request\");\n }\n\n // Step 1: Get depositor ETH address\n if (!this.config.ethWallet.account) {\n throw new Error(\"Ethereum wallet account not found\");\n }\n const depositorEthAddress = this.config.ethWallet.account.address;\n\n // Step 2: Create proof of possession (or reuse pre-signed one)\n const btcPopSignature = await this.resolvePopSignature(\n depositorEthAddress,\n preSignedBtcPopSignature,\n );\n\n if (onPopSigned) {\n await onPopSigned();\n }\n\n // Step 3: Resolve per-request payout scriptPubKey.\n const resolvedPayoutScripts: Hex[] = [];\n for (const req of requests) {\n resolvedPayoutScripts.push(\n await this.resolvePayoutScriptPubKey(req.depositorPayoutBtcAddress),\n );\n }\n\n // Step 4: Pre-compute vault IDs and check for duplicates\n const vaultResults: BatchPeginResultItem[] = [];\n for (const req of requests) {\n const depositorSignedPeginTxHex = ensureHexPrefix(\n req.depositorSignedPeginTx,\n );\n const peginTxHash = calculateBtcTxHash(depositorSignedPeginTxHex);\n const derivedVaultIdHex = await deriveVaultId(\n stripHexPrefix(peginTxHash),\n stripHexPrefix(depositorEthAddress),\n );\n const vaultId = ensureHexPrefix(derivedVaultIdHex) as Hex;\n const exists = await this.checkVaultExists(vaultId);\n if (exists) {\n throw new Error(\n `Vault already exists (ID: ${vaultId}, peginTxHash: ${peginTxHash}). ` +\n `To create a new vault, use different UTXOs or a different amount.`,\n );\n }\n vaultResults.push({ vaultId, peginTxHash });\n }\n\n // Step 5: Query pegin fee and compute total\n const publicClient = createPublicClient({\n chain: this.config.ethChain,\n transport: http(),\n });\n\n let peginFee: bigint;\n try {\n peginFee = (await publicClient.readContract({\n address: this.config.vaultContracts.btcVaultRegistry,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n } catch {\n throw new Error(\n \"Failed to query pegin fee from the contract. \" +\n \"Please check your network connection and that the contract address is correct.\",\n );\n }\n const totalFee = peginFee * BigInt(requests.length);\n\n // Step 6: Build BatchPeginRequest[] tuple array\n const batchRequests = requests.map((req, i) => ({\n depositorBtcPubKey: ensureHexPrefix(req.depositorBtcPubkey) as Hex,\n btcPopSignature: btcPopSignature as Hex,\n unsignedPrePeginTx: ensureHexPrefix(req.unsignedPrePeginTx) as Hex,\n depositorSignedPeginTx: ensureHexPrefix(\n req.depositorSignedPeginTx,\n ) as Hex,\n hashlock: req.hashlock,\n htlcVout: req.htlcVout,\n referralCode: NO_REFERRAL_CODE,\n depositorPayoutBtcAddress: resolvedPayoutScripts[i],\n depositorWotsPkHash: req.depositorWotsPkHash,\n }));\n\n // Step 7: Encode batch call data\n const callData = encodeFunctionData({\n abi: BTCVaultRegistryABI,\n functionName: \"submitPeginRequestBatch\",\n args: [depositorEthAddress, vaultProvider, batchRequests],\n });\n\n // Step 8: Estimate gas\n let gasEstimate: bigint;\n try {\n gasEstimate = await publicClient.estimateGas({\n to: this.config.vaultContracts.btcVaultRegistry,\n data: callData,\n value: totalFee,\n account: this.config.ethWallet.account.address,\n });\n } catch (error) {\n handleContractError(error); // always throws (return type: never)\n }\n\n // Step 9: Submit batch transaction\n let ethTxHash: Hex;\n try {\n ethTxHash = await this.config.ethWallet.sendTransaction({\n to: this.config.vaultContracts.btcVaultRegistry,\n data: callData,\n value: totalFee,\n account: this.config.ethWallet.account,\n chain: this.config.ethChain,\n gas: gasEstimate,\n });\n } catch (error) {\n handleContractError(error); // always throws (return type: never)\n }\n\n // Step 10: Wait for receipt\n const receipt = await publicClient.waitForTransactionReceipt({\n hash: ethTxHash,\n timeout: RECEIPT_TIMEOUT_MS,\n });\n if (receipt.status === \"reverted\") {\n handleContractError(\n new Error(\n `Batch transaction reverted. Hash: ${ethTxHash}. ` +\n `Check the transaction on block explorer for details.`,\n ),\n );\n }\n\n return {\n ethTxHash: receipt.transactionHash,\n vaults: vaultResults,\n btcPopSignature,\n };\n }\n\n /**\n * Check if a vault already exists for a given vault ID.\n *\n * @param vaultId - The Bitcoin transaction hash (vault ID)\n * @returns True if vault exists, false otherwise\n */\n private async checkVaultExists(vaultId: Hex): Promise<boolean> {\n try {\n // Create a public client to read from the contract\n const publicClient = createPublicClient({\n chain: this.config.ethChain,\n transport: http(),\n });\n\n const result = (await publicClient.readContract({\n address: this.config.vaultContracts.btcVaultRegistry,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as readonly [Address, ...unknown[]];\n\n // First element is depositor; if not zero address, vault exists\n return result[0] !== zeroAddress;\n } catch {\n // If reading fails, assume vault doesn't exist and let contract handle it\n return false;\n }\n }\n\n /**\n * Resolve the BTC payout address to a scriptPubKey hex for the contract.\n *\n * If a payout address is provided, converts it directly.\n * If omitted, uses the wallet's address and validates it against the\n * wallet's public key to guard against a compromised wallet provider.\n */\n private async resolvePayoutScriptPubKey(\n depositorPayoutBtcAddress?: string,\n ): Promise<Hex> {\n let address: string;\n\n if (depositorPayoutBtcAddress) {\n address = depositorPayoutBtcAddress;\n } else {\n address = await this.config.btcWallet.getAddress();\n const walletPubkey = await this.config.btcWallet.getPublicKeyHex();\n if (\n !isAddressFromPublicKey(\n address,\n walletPubkey,\n this.config.btcNetwork,\n )\n ) {\n throw new Error(\n \"The BTC address from your wallet does not match the wallet's public key. \" +\n \"Please ensure your wallet is using a supported address type (Taproot or Native SegWit).\",\n );\n }\n }\n\n const network = getNetwork(this.config.btcNetwork);\n try {\n return `0x${bitcoin.address.toOutputScript(address, network).toString(\"hex\")}` as Hex;\n } catch {\n throw new Error(\n `Invalid BTC payout address: \"${address}\". ` +\n `Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`,\n );\n }\n }\n\n /**\n * Resolve or create a BTC Proof-of-Possession signature.\n *\n * Reuses a pre-signed signature when provided (e.g. multi-vault deposits),\n * otherwise signs a BIP-322 message with the BTC wallet.\n */\n private async resolvePopSignature(\n depositorEthAddress: Address,\n preSignedBtcPopSignature?: Hex,\n ): Promise<Hex> {\n if (preSignedBtcPopSignature) {\n return preSignedBtcPopSignature;\n }\n\n // Message format matches BTCProofOfPossession.sol buildMessage()\n const verifyingContract = this.config.vaultContracts.btcVaultRegistry;\n const popMessage = `${depositorEthAddress.toLowerCase()}:${this.config.ethChain.id}:pegin:${verifyingContract.toLowerCase()}`;\n const btcPopSignatureRaw = await this.config.btcWallet.signMessage(\n popMessage,\n \"bip322-simple\",\n );\n\n // BTC wallets return base64, Ethereum contracts expect hex\n if (btcPopSignatureRaw.startsWith(\"0x\")) {\n return btcPopSignatureRaw as Hex;\n }\n const signatureBytes = Buffer.from(btcPopSignatureRaw, \"base64\");\n return `0x${signatureBytes.toString(\"hex\")}` as Hex;\n }\n\n /**\n * Gets the configured Bitcoin network.\n *\n * @returns The Bitcoin network (mainnet, testnet, signet, regtest)\n */\n getNetwork(): Network {\n return this.config.btcNetwork;\n }\n\n /**\n * Gets the configured BTCVaultRegistry contract address.\n *\n * @returns The Ethereum address of the BTCVaultRegistry contract\n */\n getVaultContractAddress(): Address {\n return this.config.vaultContracts.btcVaultRegistry;\n }\n}\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n, title = '') {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(value, length, title = '') {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/** Merges default options and passed options. */\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher(hashCons, info = {}) {\n const hashC = (msg, opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix) => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n//# sourceMappingURL=utils.js.map","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean } from \"./utils.js\";\n/** Internal class for HMAC. */\nexport class _HMAC {\n oHash;\n iHash;\n blockLen;\n outputLen;\n finished = false;\n destroyed = false;\n constructor(hash, key) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen, 'output');\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new _HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView } from \"./utils.js\";\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD {\n blockLen;\n outputLen;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to ||= new this.constructor();\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from \"./_md.js\";\nimport { clean, createHasher, rotl } from \"./utils.js\";\n/** Initial SHA1 state */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Reusable temporary buffer\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD {\n A = SHA1_IV[0] | 0;\n B = SHA1_IV[1] | 0;\n C = SHA1_IV[2] | 0;\n D = SHA1_IV[3] | 0;\n E = SHA1_IV[4] | 0;\n constructor() {\n super(64, 20, 8, false);\n }\n get() {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n set(A, B, C, D, E) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n }\n else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n }\n else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n }\n else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n roundClean() {\n clean(SHA1_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */\nexport const sha1 = /* @__PURE__ */ createHasher(() => new _SHA1());\n/** Per-round constants */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));\n/** md5 initial state: same as sha1, but 4 u32 instead of 5. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n// Reusable temporary buffer\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD {\n A = MD5_IV[0] | 0;\n B = MD5_IV[1] | 0;\n C = MD5_IV[2] | 0;\n D = MD5_IV[3] | 0;\n constructor() {\n super(64, 16, 8, true);\n }\n get() {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n set(A, B, C, D) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\n }\n else if (i < 32) {\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n s = [5, 9, 14, 20];\n }\n else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n }\n else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n this.set(A, B, C, D);\n }\n roundClean() {\n clean(MD5_W);\n }\n destroy() {\n this.set(0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n */\nexport const md5 = /* @__PURE__ */ createHasher(() => new _MD5());\n// RIPEMD-160\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++)\n for (let j of res)\n j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction ripemd_f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n if (group === 1)\n return (x & y) | (~x & z);\n if (group === 2)\n return (x | ~y) ^ z;\n if (group === 3)\n return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable temporary buffer\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\nexport class _RIPEMD160 extends HashMD {\n h0 = 0x67452301 | 0;\n h1 = 0xefcdab89 | 0;\n h2 = 0x98badcfe | 0;\n h3 = 0x10325476 | 0;\n h4 = 0xc3d2e1f0 | 0;\n constructor() {\n super(64, 20, 8, true);\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n clean(BUF_160);\n }\n destroy() {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\n */\nexport const ripemd160 = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n//# sourceMappingURL=legacy.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal 32-byte base SHA2 hash class. */\nclass SHA2_32B extends HashMD {\n constructor(outputLen) {\n super(64, outputLen, 8, false);\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA2-256 hash class. */\nexport class _SHA256 extends SHA2_32B {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n/** Internal SHA2-224 hash class. */\nexport class _SHA224 extends SHA2_32B {\n A = SHA224_IV[0] | 0;\n B = SHA224_IV[1] | 0;\n C = SHA224_IV[2] | 0;\n D = SHA224_IV[3] | 0;\n E = SHA224_IV[4] | 0;\n F = SHA224_IV[5] | 0;\n G = SHA224_IV[6] | 0;\n H = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal 64-byte base SHA2 hash class. */\nclass SHA2_64B extends HashMD {\n constructor(outputLen) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA2-512 hash class. */\nexport class _SHA512 extends SHA2_64B {\n Ah = SHA512_IV[0] | 0;\n Al = SHA512_IV[1] | 0;\n Bh = SHA512_IV[2] | 0;\n Bl = SHA512_IV[3] | 0;\n Ch = SHA512_IV[4] | 0;\n Cl = SHA512_IV[5] | 0;\n Dh = SHA512_IV[6] | 0;\n Dl = SHA512_IV[7] | 0;\n Eh = SHA512_IV[8] | 0;\n El = SHA512_IV[9] | 0;\n Fh = SHA512_IV[10] | 0;\n Fl = SHA512_IV[11] | 0;\n Gh = SHA512_IV[12] | 0;\n Gl = SHA512_IV[13] | 0;\n Hh = SHA512_IV[14] | 0;\n Hl = SHA512_IV[15] | 0;\n constructor() {\n super(64);\n }\n}\n/** Internal SHA2-384 hash class. */\nexport class _SHA384 extends SHA2_64B {\n Ah = SHA384_IV[0] | 0;\n Al = SHA384_IV[1] | 0;\n Bh = SHA384_IV[2] | 0;\n Bl = SHA384_IV[3] | 0;\n Ch = SHA384_IV[4] | 0;\n Cl = SHA384_IV[5] | 0;\n Dh = SHA384_IV[6] | 0;\n Dl = SHA384_IV[7] | 0;\n Eh = SHA384_IV[8] | 0;\n El = SHA384_IV[9] | 0;\n Fh = SHA384_IV[10] | 0;\n Fl = SHA384_IV[11] | 0;\n Gh = SHA384_IV[12] | 0;\n Gl = SHA384_IV[13] | 0;\n Hh = SHA384_IV[14] | 0;\n Hl = SHA384_IV[15] | 0;\n constructor() {\n super(48);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA2-512/224 hash class. */\nexport class _SHA512_224 extends SHA2_64B {\n Ah = T224_IV[0] | 0;\n Al = T224_IV[1] | 0;\n Bh = T224_IV[2] | 0;\n Bl = T224_IV[3] | 0;\n Ch = T224_IV[4] | 0;\n Cl = T224_IV[5] | 0;\n Dh = T224_IV[6] | 0;\n Dl = T224_IV[7] | 0;\n Eh = T224_IV[8] | 0;\n El = T224_IV[9] | 0;\n Fh = T224_IV[10] | 0;\n Fl = T224_IV[11] | 0;\n Gh = T224_IV[12] | 0;\n Gl = T224_IV[13] | 0;\n Hh = T224_IV[14] | 0;\n Hl = T224_IV[15] | 0;\n constructor() {\n super(28);\n }\n}\n/** Internal SHA2-512/256 hash class. */\nexport class _SHA512_256 extends SHA2_64B {\n Ah = T256_IV[0] | 0;\n Al = T256_IV[1] | 0;\n Bh = T256_IV[2] | 0;\n Bl = T256_IV[3] | 0;\n Ch = T256_IV[4] | 0;\n Cl = T256_IV[5] | 0;\n Dh = T256_IV[6] | 0;\n Dl = T256_IV[7] | 0;\n Eh = T256_IV[8] | 0;\n El = T256_IV[9] | 0;\n Fh = T256_IV[10] | 0;\n Fl = T256_IV[11] | 0;\n Gh = T256_IV[12] | 0;\n Gl = T256_IV[13] | 0;\n Hh = T256_IV[14] | 0;\n Hl = T256_IV[15] | 0;\n constructor() {\n super(32);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n//# sourceMappingURL=sha2.js.map","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from \"./_u64.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput, clean, createHasher, oidNist, swap32IfBE, u32 } from \"./utils.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = []; // no pure annotation: var is always used\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n/** Keccak sponge function. */\nexport class Keccak {\n state;\n pos = 0;\n posOut = 0;\n finished = false;\n state32;\n destroyed = false;\n blockLen;\n suffix;\n outputLen;\n enableXOF = false;\n rounds;\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen, 'outputLen');\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);\n/** SHA3-224 hash function. */\nexport const sha3_224 = /* @__PURE__ */ genKeccak(0x06, 144, 28, \n/* @__PURE__ */ oidNist(0x07));\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256 = /* @__PURE__ */ genKeccak(0x06, 136, 32, \n/* @__PURE__ */ oidNist(0x08));\n/** SHA3-384 hash function. */\nexport const sha3_384 = /* @__PURE__ */ genKeccak(0x06, 104, 48, \n/* @__PURE__ */ oidNist(0x09));\n/** SHA3-512 hash function. */\nexport const sha3_512 = /* @__PURE__ */ genKeccak(0x06, 72, 64, \n/* @__PURE__ */ oidNist(0x0a));\n/** keccak-224 hash function. */\nexport const keccak_224 = /* @__PURE__ */ genKeccak(0x01, 144, 28);\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256 = /* @__PURE__ */ genKeccak(0x01, 136, 32);\n/** keccak-384 hash function. */\nexport const keccak_384 = /* @__PURE__ */ genKeccak(0x01, 104, 48);\n/** keccak-512 hash function. */\nexport const keccak_512 = /* @__PURE__ */ genKeccak(0x01, 72, 64);\nconst genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true), info);\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));\n/** SHAKE128 XOF with 256-bit output (NIST version). */\nexport const shake128_32 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b));\n/** SHAKE256 XOF with 512-bit output (NIST version). */\nexport const shake256_64 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));\n//# sourceMappingURL=sha3.js.map","/**\n * PBKDF (RFC 2898). Can be used to create a key from password and salt.\n * @module\n */\nimport { hmac } from \"./hmac.js\";\n// prettier-ignore\nimport { ahash, anumber, asyncLoop, checkOpts, clean, createView, kdfInputToBytes } from \"./utils.js\";\n// Common start and end for sync/async functions\nfunction pbkdf2Init(hash, _password, _salt, _opts) {\n ahash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n anumber(c, 'c');\n anumber(dkLen, 'dkLen');\n anumber(asyncTick, 'asyncTick');\n if (c < 1)\n throw new Error('iterations (c) must be >= 1');\n const password = kdfInputToBytes(_password, 'password');\n const salt = kdfInputToBytes(_salt, 'salt');\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\nfunction pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW)\n prfW.destroy();\n clean(u);\n return DK;\n}\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n * @example\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });\n */\nexport function pbkdf2(hash, password, salt, opts) {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function. Async version.\n * @example\n * await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n */\nexport async function pbkdf2Async(hash, password, salt, opts) {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n//# sourceMappingURL=pbkdf2.js.map","/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, anumber, randomBytes } from '@noble/hashes/utils.js';\nimport { pbkdf2 as pbkdf2web, sha512 as sha512web } from '@noble/hashes/webcrypto.js';\nimport { utils as baseUtils } from '@scure/base';\n// Japanese wordlist\nconst isJapanese = (wordlist) => wordlist[0] === '\\u3042\\u3044\\u3053\\u304f\\u3057\\u3093';\n// Normalization replaces equivalent sequences of characters\n// so that any two texts that are equivalent will be reduced\n// to the same sequence of code points, called the normal form of the original text.\n// https://tonsky.me/blog/unicode/#why-is-a----\nfunction nfkd(str) {\n if (typeof str !== 'string')\n throw new TypeError('invalid mnemonic type: ' + typeof str);\n return str.normalize('NFKD');\n}\nfunction normalize(str) {\n const norm = nfkd(str);\n const words = norm.split(' ');\n if (![12, 15, 18, 21, 24].includes(words.length))\n throw new Error('Invalid mnemonic');\n return { nfkd: norm, words };\n}\nfunction aentropy(ent) {\n abytes(ent);\n if (![16, 20, 24, 28, 32].includes(ent.length))\n throw new Error('invalid entropy length');\n}\n/**\n * Generate x random words. Uses Cryptographically-Secure Random Number Generator.\n * @param wordlist imported wordlist for specific language\n * @param strength mnemonic strength 128-256 bits\n * @example\n * generateMnemonic(wordlist, 128)\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nexport function generateMnemonic(wordlist, strength = 128) {\n anumber(strength);\n if (strength % 32 !== 0 || strength > 256)\n throw new TypeError('Invalid entropy');\n return entropyToMnemonic(randomBytes(strength / 8), wordlist);\n}\nconst calcChecksum = (entropy) => {\n // Checksum is ent.length/4 bits long\n const bitsLeft = 8 - entropy.length / 4;\n // Zero rightmost \"bitsLeft\" bits in byte\n // For example: bitsLeft=4 val=10111101 -> 10110000\n return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]);\n};\nfunction getCoder(wordlist) {\n if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')\n throw new Error('Wordlist: expected array of 2048 strings');\n wordlist.forEach((i) => {\n if (typeof i !== 'string')\n throw new Error('wordlist: non-string element: ' + i);\n });\n return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist));\n}\n/**\n * Reversible: Converts mnemonic string to raw entropy in form of byte array.\n * @param mnemonic 12-24 words\n * @param wordlist imported wordlist for specific language\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToEntropy(mnem, wordlist)\n * // Produces\n * new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ])\n */\nexport function mnemonicToEntropy(mnemonic, wordlist) {\n const { words } = normalize(mnemonic);\n const entropy = getCoder(wordlist).decode(words);\n aentropy(entropy);\n return entropy;\n}\n/**\n * Reversible: Converts raw entropy in form of byte array to mnemonic string.\n * @param entropy byte array\n * @param wordlist imported wordlist for specific language\n * @returns 12-24 words\n * @example\n * const ent = new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ]);\n * entropyToMnemonic(ent, wordlist);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nexport function entropyToMnemonic(entropy, wordlist) {\n aentropy(entropy);\n const words = getCoder(wordlist).encode(entropy);\n return words.join(isJapanese(wordlist) ? '\\u3000' : ' ');\n}\n/**\n * Validates mnemonic for being 12-24 words contained in `wordlist`.\n */\nexport function validateMnemonic(mnemonic, wordlist) {\n try {\n mnemonicToEntropy(mnemonic, wordlist);\n }\n catch (e) {\n return false;\n }\n return true;\n}\nconst psalt = (passphrase) => nfkd('mnemonic' + passphrase);\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * await mnemonicToSeed(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeed(mnemonic, passphrase = '') {\n return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToSeedSync(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeedSync(mnemonic, passphrase = '') {\n return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n/**\n * Uses native, built-in functionality, provided by globalThis.crypto.\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToSeedWebcrypto(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nexport function mnemonicToSeedWebcrypto(mnemonic, passphrase = '') {\n return pbkdf2web(sha512web, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n","/**\n * @module wots/derivation\n *\n * Deterministic WOTS one-time-signature key derivation for Babylon vault\n * deposits. Pure crypto functions extracted from the vault frontend into the\n * shared SDK.\n *\n * See the vault frontend's `wotsService.ts` for the full derivation\n * documentation.\n */\nimport { hmac } from \"@noble/hashes/hmac.js\";\nimport { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { sha256, sha512 } from \"@noble/hashes/sha2.js\";\nimport { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport { mnemonicToSeedSync } from \"@scure/bip39\";\n\nimport { stripHexPrefix } from \"../primitives/utils/bitcoin\";\n\nimport type { WotsKeypair, WotsPublicKey } from \"./types\";\n\n/**\n * Number of bit positions in the WOTS keypair. Corresponds to the number\n * of garbled-circuit labels used in the BitVM-style protocol (PI_1 circuit).\n */\nconst PI_1_BITS = 508;\n\n/**\n * Size in bytes of each WOTS preimage (garbled-circuit label size).\n * Preimages are truncated from HMAC-SHA-512 output to this length.\n */\nconst GC_LABEL_SIZE = 16;\n\n/** Size in bytes of the parent key or derived key (first half of a 64-byte seed/HMAC). */\nconst KEY_SIZE = 32;\n\n/** Size in bytes of the full BIP-39 seed / HMAC-SHA-512 output. */\nconst SEED_SIZE = 64;\n\n/** Size of the index buffer used in per-bit derivation (1 byte flag + 4 byte big-endian index). */\nconst INDEX_BUFFER_SIZE = 5;\n\n/** Size of the big-endian length prefix prepended to variable-length fields. */\nconst LENGTH_PREFIX_SIZE = 4;\n\n// ---------------------------------------------------------------------------\n// Internal byte-manipulation utilities\n// ---------------------------------------------------------------------------\n\n/** Concatenate multiple `Uint8Array` buffers into a single array. */\nfunction concatBytes(...arrays: Uint8Array[]): Uint8Array {\n const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const arr of arrays) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n}\n\n/** Encode a UTF-8 string as bytes. */\nfunction stringToBytes(str: string): Uint8Array {\n return new TextEncoder().encode(str);\n}\n\n/**\n * Prepend a 4-byte big-endian length prefix to `data`.\n * Used to unambiguously concatenate variable-length fields in the vault\n * derivation path.\n */\nfunction lengthPrefixed(data: Uint8Array): Uint8Array {\n const len = new Uint8Array(LENGTH_PREFIX_SIZE);\n new DataView(len.buffer).setUint32(0, data.length, false);\n return concatBytes(len, data);\n}\n\n// ---------------------------------------------------------------------------\n// Internal cryptographic primitives (@noble/hashes wrappers)\n// ---------------------------------------------------------------------------\n\n/**\n * Compute HMAC-SHA-512.\n *\n * Uses `@noble/hashes/hmac` which accepts `Uint8Array` directly,\n * avoiding the unsafe `Uint8Array.buffer as ArrayBuffer` cast that\n * the Web Crypto API would require.\n *\n * @param key - HMAC key bytes.\n * @param data - Message bytes.\n * @returns 64-byte HMAC digest.\n */\nfunction hmacSha512(key: Uint8Array, data: Uint8Array): Uint8Array {\n return hmac(sha512, key, data);\n}\n\n/**\n * Compute Hash160: `RIPEMD-160(SHA-256(data))`.\n *\n * This is the same hash function used in Bitcoin for address derivation.\n *\n * @param data - Input bytes.\n * @returns 20-byte hash.\n */\nfunction hash160(data: Uint8Array): Uint8Array {\n return ripemd160(sha256(data));\n}\n\n/** Convert a byte array to a lowercase hex string. */\nconst toHex = (bytes: Uint8Array) =>\n Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n\n// ---------------------------------------------------------------------------\n// Seed and keypair derivation\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a BIP-39 mnemonic into a 64-byte seed.\n *\n * Internally uses PBKDF2 with 2048 rounds of HMAC-SHA-512 and the passphrase\n * `\"mnemonic\"` (no user password), per the BIP-39 specification.\n *\n * @param mnemonic - A valid 12-word BIP-39 mnemonic.\n * @returns 64-byte seed suitable for {@link deriveWotsKeypair}.\n */\nexport function mnemonicToWotsSeed(mnemonic: string): Uint8Array {\n const seed = mnemonicToSeedSync(mnemonic);\n const copy = new Uint8Array(seed);\n seed.fill(0);\n return copy;\n}\n\n/**\n * Derive a deterministic WOTS keypair for a specific vault.\n *\n * ### Derivation steps\n *\n * 1. **Split the seed** — bytes `[0..32)` = parent key, `[32..64)` = chain code.\n *\n * 2. **Child key derivation** —\n * ```\n * vaultData = lenPrefix(vaultId) || lenPrefix(depositorPk) || lenPrefix(appContractAddress)\n * hmac = HMAC-SHA-512(chainCode, parentKey || vaultData)\n * derivedKey = hmac[0..32)\n * derivedChainCode = hmac[32..64)\n * ```\n *\n * 3. **Bit-level key expansion** — For each bit index `i` in `[0, 508)`:\n * ```\n * falseHmac = HMAC-SHA-512(derivedChainCode, derivedKey || 0x00 || bigEndian32(i))\n * trueHmac = HMAC-SHA-512(derivedChainCode, derivedKey || 0x01 || bigEndian32(i))\n *\n * falsePreimage = falseHmac[0..16) // 16 bytes = GC_LABEL_SIZE\n * truePreimage = trueHmac[0..16)\n *\n * falseHash = Hash160(falsePreimage) // 20 bytes\n * trueHash = Hash160(truePreimage)\n * ```\n *\n * 4. **Cleanup** — All intermediate key material is zeroed.\n *\n * The same (mnemonic, vaultId, depositorPk, appContractAddress) tuple always\n * produces the same keypair, enabling recovery from the mnemonic alone.\n *\n * @param seed - 64-byte seed from {@link mnemonicToWotsSeed}.\n * @param vaultId - Unique identifier of the vault (e.g. pegin tx hash).\n * @param depositorPk - Depositor's public key (hex string).\n * @param appContractAddress - Ethereum address of the application contract.\n * @returns A {@link WotsKeypair} with 508 preimage/hash pairs per branch.\n */\nexport async function deriveWotsKeypair(\n seed: Uint8Array,\n vaultId: string,\n depositorPk: string,\n appContractAddress: string,\n): Promise<WotsKeypair> {\n if (seed.length !== SEED_SIZE) {\n throw new Error(\n `WOTS seed must be ${SEED_SIZE} bytes, got ${seed.length}`,\n );\n }\n\n // Normalize BTC-style inputs by stripping 0x prefixes.\n // appContractAddress is NOT stripped — Ethereum addresses include the 0x\n // prefix in their canonical form, and existing on-chain commitments were\n // computed with it included. Changing this would break hash determinism.\n vaultId = stripHexPrefix(vaultId);\n depositorPk = stripHexPrefix(depositorPk);\n\n const chainCode = seed.slice(KEY_SIZE, SEED_SIZE);\n const parentKey = seed.slice(0, KEY_SIZE);\n\n // Track all intermediate buffers containing key material for cleanup.\n const sensitiveBuffers: Uint8Array[] = [chainCode, parentKey];\n\n try {\n const vaultData = concatBytes(\n lengthPrefixed(stringToBytes(vaultId)),\n lengthPrefixed(stringToBytes(depositorPk)),\n lengthPrefixed(stringToBytes(appContractAddress)),\n );\n\n const hmacInput = concatBytes(parentKey, vaultData);\n sensitiveBuffers.push(hmacInput);\n\n const hmacResult = hmacSha512(chainCode, hmacInput);\n sensitiveBuffers.push(hmacResult);\n\n const derivedKey = hmacResult.slice(0, KEY_SIZE);\n const derivedChainCode = hmacResult.slice(KEY_SIZE, SEED_SIZE);\n sensitiveBuffers.push(derivedKey, derivedChainCode);\n\n const falsePreimages: Uint8Array[] = [];\n const truePreimages: Uint8Array[] = [];\n const falseHashes: Uint8Array[] = [];\n const trueHashes: Uint8Array[] = [];\n\n let succeeded = false;\n try {\n for (let bit = 0; bit < PI_1_BITS; bit++) {\n const falseIndex = new Uint8Array(INDEX_BUFFER_SIZE);\n falseIndex[0] = 0;\n new DataView(falseIndex.buffer).setUint32(1, bit, false);\n\n const trueIndex = new Uint8Array(INDEX_BUFFER_SIZE);\n trueIndex[0] = 1;\n new DataView(trueIndex.buffer).setUint32(1, bit, false);\n\n const falseInput = concatBytes(derivedKey, falseIndex);\n const trueInput = concatBytes(derivedKey, trueIndex);\n const falseHmac = hmacSha512(derivedChainCode, falseInput);\n const trueHmac = hmacSha512(derivedChainCode, trueInput);\n\n try {\n const falsePreimage = falseHmac.slice(0, GC_LABEL_SIZE);\n const truePreimage = trueHmac.slice(0, GC_LABEL_SIZE);\n\n falsePreimages.push(falsePreimage);\n truePreimages.push(truePreimage);\n falseHashes.push(hash160(falsePreimage));\n trueHashes.push(hash160(truePreimage));\n } finally {\n falseInput.fill(0);\n trueInput.fill(0);\n falseHmac.fill(0);\n trueHmac.fill(0);\n }\n }\n\n succeeded = true;\n return { falsePreimages, truePreimages, falseHashes, trueHashes };\n } finally {\n if (!succeeded) {\n for (const p of falsePreimages) p.fill(0);\n for (const p of truePreimages) p.fill(0);\n }\n }\n } finally {\n for (const buf of sensitiveBuffers) {\n buf.fill(0);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Serialization\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the public key from a WOTS keypair.\n *\n * The public key consists of the Hash160 digests (hex-encoded) for both\n * the `false` and `true` branch of each bit position. This is the value\n * submitted on-chain and to the vault provider for later signature\n * verification.\n *\n * @param keypair - A derived {@link WotsKeypair}.\n * @returns The {@link WotsPublicKey} with `false_list` and `true_list`,\n * each containing 508 hex strings of 40 characters (20 bytes).\n */\nexport function keypairToPublicKey(keypair: WotsKeypair): WotsPublicKey {\n return {\n false_list: keypair.falseHashes.map(toHex),\n true_list: keypair.trueHashes.map(toHex),\n };\n}\n\n/**\n * Compute the keccak256 hash of a WOTS keypair's public key.\n *\n * Matches the Rust `InputLabelHashes::keccak256_hash()` implementation:\n * `keccak256(falseHashes[0] || falseHashes[1] || ... || trueHashes[0] || trueHashes[1] || ...)`\n *\n * Each hash is 20 bytes (Hash160). Total input: `PI_1_BITS * 20 * 2` bytes.\n * The result is committed on-chain as `depositorWotsPkHash` so the vault\n * provider can later verify submitted WOTS public keys.\n *\n * @param keypair - A derived {@link WotsKeypair}.\n * @returns 32-byte keccak256 digest as a `0x`-prefixed hex string.\n */\nexport function computeWotsPkHash(keypair: WotsKeypair): `0x${string}` {\n if (keypair.falseHashes.length === 0 || keypair.trueHashes.length === 0) {\n throw new Error(\n \"computeWotsPkHash: keypair hash arrays must not be empty\",\n );\n }\n const hashSize = keypair.falseHashes[0].length;\n const totalBytes =\n (keypair.falseHashes.length + keypair.trueHashes.length) * hashSize;\n const buffer = new Uint8Array(totalBytes);\n\n let offset = 0;\n for (const h of keypair.falseHashes) {\n buffer.set(h, offset);\n offset += hashSize;\n }\n for (const h of keypair.trueHashes) {\n buffer.set(h, offset);\n offset += hashSize;\n }\n\n const digest = keccak_256(buffer);\n return `0x${toHex(digest)}`;\n}\n","import { computeWotsPkHash, deriveWotsKeypair, mnemonicToWotsSeed } from \"./derivation\";\n\n/**\n * Convenience wrapper: derive a WOTS keypair from a mnemonic and return\n * the keccak256 hash of its public key. Handles seed creation and cleanup.\n *\n * Used before the ETH transaction to produce the `depositorWotsPkHash`\n * that gets committed on-chain.\n */\nexport async function deriveWotsPkHash(\n mnemonic: string,\n peginTxid: string,\n depositorBtcPubkey: string,\n appContractAddress: string,\n): Promise<`0x${string}`> {\n const seed = mnemonicToWotsSeed(mnemonic);\n try {\n const keypair = await deriveWotsKeypair(\n seed,\n peginTxid,\n depositorBtcPubkey,\n appContractAddress,\n );\n try {\n return computeWotsPkHash(keypair);\n } finally {\n for (const p of keypair.falsePreimages) p.fill(0);\n for (const p of keypair.truePreimages) p.fill(0);\n }\n } finally {\n seed.fill(0);\n }\n}\n","/**\n * Check whether an error from the vault provider indicates that the\n * submitted WOTS public key hash does not match the on-chain\n * commitment. This signals that the wrong mnemonic was used.\n */\nexport function isWotsMismatchError(error: unknown): boolean {\n const msg = (\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"\"\n ).toLowerCase();\n\n return (\n msg.includes(\"wots\") &&\n msg.includes(\"hash\") &&\n msg.includes(\"does not match\")\n );\n}\n"],"names":["CONTRACT_ERRORS","extractErrorData","error","err","current","depth","maxDepth","cause","hexMatch","getContractErrorMessage","errorData","selector","isKnownContractError","handleContractError","knownError","errorMsg","errorHint","NO_REFERRAL_CODE","resolveUtxoInfo","txid","vout","localPrevouts","apiUrl","local","getUtxoInfo","RECEIPT_TIMEOUT_MS","PeginManager","config","__publicField","params","depositorBtcPubkeyRaw","depositorBtcPubkey","vaultProviderBtcPubkey","stripHexPrefix","vaultKeeperBtcPubkeys","universalChallengerBtcPubkeys","numLocalChallengers","prePeginParams","prePeginResult","buildPrePeginPsbt","utxoSelection","selectUtxosForPegin","peginOutputCount","network","getNetwork","fundedPrePeginTxHex","fundPeginTransaction","prePeginTxid","calculateBtcTxHash","peginTxResults","psbtsToSign","signOptions","i","peginTxResult","buildPeginTxFromFundedPrePegin","peginInputPsbtResult","buildPeginInputPsbt","createTaprootScriptPathSignOptions","signedPsbts","perVault","peginInputSignature","extractPeginInputSignature","depositorSignedPeginTxHex","finalizePeginInputPsbt","psbtsHexes","options","signed","cleanHex","tx","Transaction","psbt","Psbt","cleanPubkey","publicKeyNoCoord","Buffer","utxoDataPromises","input","utxoData","inputsWithUtxoData","totalInputValue","sum","totalOutputValue","out","psbtInputFields","getPsbtInputFields","output","signedPsbtHex","signedPsbt","e","inp","signedTxHex","pushTx","unsignedPrePeginTx","depositorSignedPeginTx","vaultProvider","hashlock","htlcVout","onPopSigned","depositorPayoutBtcAddress","depositorWotsPkHash","preSignedBtcPopSignature","depositorEthAddress","btcPopSignature","depositorBtcPubkeyHex","ensureHexPrefix","unsignedPrePeginTxHex","payoutScriptPubKey","peginTxHash","derivedVaultIdHex","deriveVaultId","vaultId","publicClient","createPublicClient","http","peginFee","BTCVaultRegistryABI","callData","encodeFunctionData","gasEstimate","ethTxHash","receipt","requests","resolvedPayoutScripts","req","vaultResults","totalFee","batchRequests","zeroAddress","address","walletPubkey","isAddressFromPublicKey","bitcoin","verifyingContract","popMessage","btcPopSignatureRaw","isBytes","a","anumber","n","title","prefix","abytes","value","length","bytes","len","needsLen","ofLen","got","ahash","h","aexists","instance","checkFinished","aoutput","min","u32","arr","clean","arrays","createView","rotr","word","shift","rotl","isLE","byteSwap","byteSwap32","swap32IfBE","u","utf8ToBytes","str","kdfInputToBytes","data","errorTitle","checkOpts","defaults","opts","createHasher","hashCons","info","hashC","msg","tmp","oidNist","suffix","_HMAC","hash","key","blockLen","pad","buf","to","oHash","iHash","finished","destroyed","outputLen","hmac","message","Chi","b","c","Maj","HashMD","padOffset","view","buffer","pos","take","dataView","oview","outLen","state","res","SHA256_IV","SHA512_IV","Rho160","Id160","_","Pi160","idxLR","j","k","idxL","idxR","shifts160","shiftsL160","idx","shiftsR160","Kl160","Kr160","ripemd_f","group","x","y","z","BUF_160","_RIPEMD160","h0","h1","h2","h3","h4","offset","al","ar","bl","br","cl","cr","dl","dr","el","er","rGroup","hbl","hbr","rl","rr","sl","sr","tl","tr","ripemd160","U32_MASK64","_32n","fromBig","le","split","lst","Ah","Al","l","shrSH","_l","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","rotlSH","rotlSL","rotlBH","rotlBL","add","Bh","Bl","add3L","Cl","add3H","low","Ch","add4L","Dl","add4H","Dh","add5L","El","add5H","Eh","SHA256_K","SHA256_W","SHA2_32B","A","B","C","D","E","F","G","H","W15","W2","s0","s1","sigma1","T1","T2","_SHA256","K512","u64.split","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","SHA2_64B","Fh","Fl","Gh","Gl","Hh","Hl","W15h","W15l","s0h","u64.rotrSH","u64.shrSH","s0l","u64.rotrSL","u64.shrSL","W2h","W2l","s1h","u64.rotrBH","s1l","u64.rotrBL","SUMl","u64.add4L","SUMh","u64.add4H","sigma1h","sigma1l","CHIh","CHIl","T1ll","u64.add5L","T1h","u64.add5H","T1l","sigma0h","sigma0l","MAJh","MAJl","u64.add","All","u64.add3L","u64.add3H","_SHA512","sha256","sha512","_0n","_1n","_2n","_7n","_256n","_0x71n","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","round","R","t","IOTAS","SHA3_IOTA_H","SHA3_IOTA_L","rotlH","rotlL","keccakP","s","rounds","idx1","idx0","B0","B1","Th","Tl","curH","curL","PI","Keccak","enableXOF","bufferOut","genKeccak","keccak_256","pbkdf2Init","_password","_salt","_opts","dkLen","asyncTick","password","salt","DK","PRF","PRFSalt","pbkdf2Output","prfW","pbkdf2","ti","Ti","ui","nfkd","normalize","norm","words","psalt","passphrase","mnemonicToSeedSync","mnemonic","PI_1_BITS","GC_LABEL_SIZE","KEY_SIZE","SEED_SIZE","INDEX_BUFFER_SIZE","LENGTH_PREFIX_SIZE","concatBytes","totalLength","result","stringToBytes","lengthPrefixed","hmacSha512","hash160","toHex","mnemonicToWotsSeed","seed","copy","deriveWotsKeypair","depositorPk","appContractAddress","chainCode","parentKey","sensitiveBuffers","vaultData","hmacInput","hmacResult","derivedKey","derivedChainCode","falsePreimages","truePreimages","falseHashes","trueHashes","succeeded","bit","falseIndex","trueIndex","falseInput","trueInput","falseHmac","trueHmac","falsePreimage","truePreimage","p","keypairToPublicKey","keypair","computeWotsPkHash","hashSize","totalBytes","digest","deriveWotsPkHash","peginTxid","isWotsMismatchError"],"mappings":";;;;;;;;;;;;;;AAeO,MAAMA,IAA0C;AAAA;AAAA,EAErD,cACE;AAAA;AAAA,EAGF,cACE;AAAA;AAAA,EAGF,cACE;AAAA;AAAA,EAGF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAAA;AAAA,EAEF,cACE;AAEJ;AAWO,SAASC,GAAiBC,GAAoC;AACnE,MAAI,CAACA,KAAS,OAAOA,KAAU,SAAU;AAEzC,QAAMC,IAAMD;AAGZ,MAAI,OAAOC,EAAI,QAAS,YAAYA,EAAI,KAAK,WAAW,IAAI;AAC1D,WAAOA,EAAI;AAEb,MAAI,OAAOA,EAAI,WAAY,YAAYA,EAAI,QAAQ,WAAW,IAAI;AAChE,WAAOA,EAAI;AAIb,MAAIC,IAAmBD,EAAI,OACvBE,IAAQ;AACZ,QAAMC,IAAW;AAEjB,SAAOF,KAAW,OAAOA,KAAY,YAAYC,IAAQC,KAAU;AACjE,UAAMC,IAAQH;AACd,QAAI,OAAOG,EAAM,QAAS,YAAYA,EAAM,KAAK,WAAW,IAAI;AAC9D,aAAOA,EAAM;AAEf,IAAAH,IAAUG,EAAM,OAChBF;AAAA,EACF;AAIA,QAAMG,KADU,OAAOL,EAAI,WAAY,WAAWA,EAAI,UAAU,IACvC,MAAM,wBAAwB;AACvD,MAAIK;AACF,WAAOA,EAAS,CAAC;AAIrB;AAQO,SAASC,GAAwBP,GAAoC;AAC1E,QAAMQ,IAAYT,GAAiBC,CAAK;AACxC,MAAIQ,GAAW;AAIb,UAAMC,IAAWD,EAAU,UAAU,GAAG,EAAE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M6C,IAAU,MAAM3B;AAAA,MACpBF;AAAA,MACAmC;AAAA,MACAjc;AAAA,MACAka;AAAA,IAAA;AAEF,QAAI;AACF,aAAO0B,GAAkBD,CAAO;AAAA,IAClC,UAAA;AACE,iBAAWF,KAAKE,EAAQ,eAAgB,CAAAF,EAAE,KAAK,CAAC;AAChD,iBAAWA,KAAKE,EAAQ,cAAe,CAAAF,EAAE,KAAK,CAAC;AAAA,IACjD;AAAA,EACF,UAAA;AACE,IAAA3B,EAAK,KAAK,CAAC;AAAA,EACb;AACF;AC3BO,SAASoC,GAAoB/d,GAAyB;AAC3D,QAAMoL,KACJpL,aAAiB,QACbA,EAAM,UACN,OAAOA,KAAU,WACfA,IACA,IACN,YAAA;AAEF,SACEoL,EAAI,SAAS,MAAM,KACnBA,EAAI,SAAS,MAAM,KACnBA,EAAI,SAAS,gBAAgB;AAEjC;","x_google_ignoreList":[2,3,4,5,6,7,8,9,10]}
|
package/dist/index-D3z3SZAj.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var S=Object.defineProperty;var F=(n,t,e)=>t in n?S(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var g=(n,t,e)=>F(n,typeof t!="symbol"?t+"":t,e);const w=require("./types-DEWiqXYp.cjs"),k=21e6*1e8,m=3e4;async function d(n,t){const e=new AbortController,r=setTimeout(()=>e.abort(),m),o=[e.signal,t==null?void 0:t.signal].filter(Boolean);try{return await fetch(n,{...t,signal:AbortSignal.any(o)})}catch(s){throw clearTimeout(r),s!=null&&typeof s=="object"&&"name"in s&&s.name==="AbortError"?new Error(`Mempool API request timed out after ${m}ms: ${n}`):s}}const P=1e4;function T(n){return Number.isInteger(n)&&n>0&&n<=k}function j(n){return Number.isInteger(n)&&n>0&&n<=P}function v(n,t){return!Number.isInteger(n)||n<0?!1:t===void 0||n<t}const x={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function c(n,t){try{const e=await d(n,t);if(!e.ok){const o=await e.text();throw new Error(`Mempool API error (${e.status}): ${o||e.statusText}`)}const r=e.headers.get("content-type");return r!=null&&r.includes("application/json")?await e.json():await e.text()}catch(e){throw e instanceof Error?new Error(`Failed to fetch from mempool API: ${e.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function B(n,t){try{const e=await d(`${t}/tx`,{method:"POST",body:n,headers:{"Content-Type":"text/plain"}});if(!e.ok){const o=await e.text();let s;try{s=JSON.parse(o).message}catch{s=o}throw new Error(s||`Failed to broadcast transaction: ${e.statusText}`)}return await e.text()}catch(e){throw e instanceof Error?new Error(`Failed to broadcast BTC transaction: ${e.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function $(n,t){return c(`${t}/tx/${n}`)}async function R(n,t){try{const e=await d(`${t}/tx/${n}/hex`);if(!e.ok){const r=await e.text();throw new Error(`Mempool API error (${e.status}): ${r||e.statusText}`)}return await e.text()}catch(e){throw e instanceof Error?new Error(`Failed to get transaction hex for ${n}: ${e.message}`):new Error(`Failed to get transaction hex for ${n}: Unknown error`)}}async function C(n,t,e){const r=await $(n,e);if(!v(t,r.vout.length))throw new Error(`Invalid vout ${t} for transaction ${n} (has ${r.vout.length} outputs)`);const o=r.vout[t];if(!T(o.value))throw new Error(`Invalid UTXO value ${o.value} for ${n}:${t}`);return{txid:n,vout:t,value:o.value,scriptPubKey:o.scriptpubkey}}async function M(n,t){try{const e=await c(`${t}/address/${n}/utxo`),r=await c(`${t}/v1/validate-address/${n}`);if(!r.isvalid)throw new Error(`Invalid Bitcoin address: ${n}. Mempool API validation failed.`);for(const s of e){if(!v(s.vout))throw new Error(`Invalid vout ${s.vout} for ${s.txid}`);if(!T(s.value))throw new Error(`Invalid UTXO value ${s.value} for ${s.txid}:${s.vout}`)}return e.sort((s,f)=>f.value-s.value).map(s=>({txid:s.txid,vout:s.vout,value:s.value,scriptPubKey:r.scriptPubKey,confirmed:s.status.confirmed}))}catch(e){throw e instanceof Error?new Error(`Failed to get UTXOs for address ${n}: ${e.message}`):new Error(`Failed to get UTXOs for address ${n}: Unknown error`)}}function O(n){return x[n]}async function D(n,t){return c(`${t}/address/${n}/txs`)}async function U(n){const t=await d(`${n}/v1/fees/recommended`);if(!t.ok)throw new Error(`Failed to fetch network fees: ${t.status} ${t.statusText}`);const e=await t.json(),r=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const o of r)if(!j(e[o]))throw new Error(`Invalid fee rate ${o}=${e[o]} from mempool API: expected a positive number ≤ ${P}`);if(e.minimumFee>e.economyFee||e.economyFee>e.hourFee||e.hourFee>e.halfHourFee||e.halfHourFee>e.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${e.minimumFee}) <= economyFee (${e.economyFee}) <= hourFee (${e.hourFee}) <= halfHourFee (${e.halfHourFee}) <= fastestFee (${e.fastestFee}).`);return e}const V=[{type:"function",name:"submitPeginRequest",inputs:[{name:"depositor",type:"address",internalType:"address"},{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"btcPopSignature",type:"bytes",internalType:"bytes"},{name:"unsignedPrePeginTx",type:"bytes",internalType:"bytes"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"depositorPayoutBtcAddress",type:"bytes",internalType:"bytes"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"payable"},{type:"function",name:"submitPeginRequest",inputs:[{name:"depositor",type:"address",internalType:"address"},{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"btcPopSignature",type:"bytes",internalType:"bytes"},{name:"unsignedPrePeginTx",type:"bytes",internalType:"bytes"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"referralCode",type:"uint32",internalType:"uint32"},{name:"depositorPayoutBtcAddress",type:"bytes",internalType:"bytes"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"payable"},{type:"function",name:"submitPeginRequestBatch",inputs:[{name:"depositor",type:"address",internalType:"address"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"requests",type:"tuple[]",internalType:"struct IBTCVaultRegistry.BatchPeginRequest[]",components:[{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"btcPopSignature",type:"bytes",internalType:"bytes"},{name:"unsignedPrePeginTx",type:"bytes",internalType:"bytes"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"referralCode",type:"uint32",internalType:"uint32"},{name:"depositorPayoutBtcAddress",type:"bytes",internalType:"bytes"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"}]}],outputs:[{name:"vaultIds",type:"bytes32[]",internalType:"bytes32[]"}],stateMutability:"payable"},{type:"function",name:"activateVaultWithSecret",inputs:[{name:"vaultId",type:"bytes32",internalType:"bytes32"},{name:"s",type:"bytes32",internalType:"bytes32"},{name:"activationMetadata",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"getPegInFee",inputs:[{name:"vaultProvider",type:"address",internalType:"address"}],outputs:[{name:"totalFee",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getBtcVaultBasicInfo",inputs:[{name:"vaultId",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"depositor",type:"address",internalType:"address"},{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"amount",type:"uint256",internalType:"uint256"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"status",type:"uint8",internalType:"enum IBTCVaultRegistry.BTCVaultStatus"},{name:"applicationEntryPoint",type:"address",internalType:"address"},{name:"createdAt",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"error",name:"InvalidPeginFee",inputs:[{name:"provided",type:"uint256",internalType:"uint256"},{name:"required",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidSecret",inputs:[]},{type:"error",name:"ActivationDeadlineExpired",inputs:[]},{type:"error",name:"InvalidHashlock",inputs:[]},{type:"error",name:"DuplicateHashlock",inputs:[]},{type:"error",name:"CapExceeded",inputs:[]},{type:"error",name:"InvalidOutputIndex",inputs:[]},{type:"error",name:"PeginSignaturesIncomplete",inputs:[]}],h=new Set(Object.values(w.DaemonStatus)),H=200;function i(n){var t;return((t=JSON.stringify(n))==null?void 0:t.slice(0,H))??"undefined"}const N="The vault provider returned an unexpected response. Please try again or contact support.";class a extends Error{constructor(e){super(N);g(this,"detail");this.name="VpResponseValidationError",this.detail=e}}const q=/^[0-9a-fA-F]+$/,b=64,_=66,y=64;function p(n){return typeof n=="string"&&n.length>0&&q.test(n)}function E(n){return typeof n=="string"&&n.length>0}function A(n,t){if(!p(n))throw new a(`VP response validation failed: "${t}" must be a non-empty hex string, got ${i(n)}`)}function u(n,t){if(!E(n))throw new a(`VP response validation failed: "${t}" must be a non-empty string, got ${i(n)}`)}function I(n,t){if(!p(n)||n.length!==b&&n.length!==_)throw new a(`VP response validation failed: "${t}" must be a ${b} or ${_}-char hex string (BTC pubkey), got ${i(n)}`)}function L(n){const t=n.presigning;if(t==null)return;if(typeof t!="object"||Array.isArray(t))throw new a('VP response validation failed: "progress.presigning" must be an object if present');const e=t;if(e.depositor_graph_created!==void 0&&typeof e.depositor_graph_created!="boolean")throw new a(`VP response validation failed: "progress.presigning.depositor_graph_created" must be a boolean if present, got ${i(e.depositor_graph_created)}`);if(e.vk_challenger_presigning_completed!==void 0&&typeof e.vk_challenger_presigning_completed!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_completed" must be a number if present, got ${i(e.vk_challenger_presigning_completed)}`);if(e.vk_challenger_presigning_total!==void 0&&typeof e.vk_challenger_presigning_total!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_total" must be a number if present, got ${i(e.vk_challenger_presigning_total)}`)}function X(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: getPeginStatus response is not an object");const t=n;if(!p(t.pegin_txid)||t.pegin_txid.length!==y)throw new a(`VP response validation failed: "pegin_txid" must be a ${y}-char hex string (txid), got ${i(t.pegin_txid)}`);if(typeof t.status!="string")throw new a('VP response validation failed: "status" must be a string');if(!h.has(t.status))throw new a(`VP response validation failed: unrecognized status "${t.status}". Expected one of: ${[...h].join(", ")}`);if(t.progress===null||typeof t.progress!="object"||Array.isArray(t.progress))throw new a('VP response validation failed: "progress" must be an object');if(L(t.progress),typeof t.health_info!="string")throw new a('VP response validation failed: "health_info" must be a string');if(t.last_error!==void 0&&typeof t.last_error!="string")throw new a(`VP response validation failed: "last_error" must be a string if present, got ${i(t.last_error)}`)}function K(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: requestDepositorPresignTransactions response is not an object");const t=n;if(!Array.isArray(t.txs))throw new a('VP response validation failed: "txs" must be an array');for(let e=0;e<t.txs.length;e++)W(t.txs[e],`txs[${e}]`);if(t.depositor_graph===null||typeof t.depositor_graph!="object")throw new a('VP response validation failed: "depositor_graph" must be an object');Q(t.depositor_graph)}function l(n,t){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${t}" must be an object`);A(n.tx_hex,`${t}.tx_hex`)}function W(n,t){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${t}" must be an object`);const e=n;I(e.claimer_pubkey,`${t}.claimer_pubkey`),l(e.claim_tx,`${t}.claim_tx`),l(e.assert_tx,`${t}.assert_tx`),l(e.payout_tx,`${t}.payout_tx`),u(e.payout_psbt,`${t}.payout_psbt`)}function G(n,t){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${t}" must be an object`);const e=n;u(e.wots_pks_json,`${t}.wots_pks_json`),u(e.gc_wots_keys_json,`${t}.gc_wots_keys_json`)}function J(n,t){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${t}" must be an object`);const e=n;if(I(e.challenger_pubkey,`${t}.challenger_pubkey`),l(e.challenge_assert_x_tx,`${t}.challenge_assert_x_tx`),l(e.challenge_assert_y_tx,`${t}.challenge_assert_y_tx`),l(e.nopayout_tx,`${t}.nopayout_tx`),u(e.nopayout_psbt,`${t}.nopayout_psbt`),!Array.isArray(e.challenge_assert_connectors))throw new a(`VP response validation failed: "${t}.challenge_assert_connectors" must be an array`);for(let r=0;r<e.challenge_assert_connectors.length;r++)G(e.challenge_assert_connectors[r],`${t}.challenge_assert_connectors[${r}]`);if(!Array.isArray(e.output_label_hashes))throw new a(`VP response validation failed: "${t}.output_label_hashes" must be an array`);for(let r=0;r<e.output_label_hashes.length;r++)A(e.output_label_hashes[r],`${t}.output_label_hashes[${r}]`)}function Y(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const t=n;if(!E(t.tx_graph_json))throw new a(`VP response validation failed: "tx_graph_json" must be a non-empty string, got ${i(t.tx_graph_json)}`);if(!p(t.verifying_key_hex))throw new a(`VP response validation failed: "verifying_key_hex" must be a non-empty hex string, got ${i(t.verifying_key_hex)}`);if(t.babe_sessions===null||typeof t.babe_sessions!="object")throw new a('VP response validation failed: "babe_sessions" must be an object');for(const[e,r]of Object.entries(t.babe_sessions)){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "babe_sessions.${e}" must be an object`);const o=r;if(!p(o.decryptor_artifacts_hex))throw new a(`VP response validation failed: "babe_sessions.${e}.decryptor_artifacts_hex" must be a non-empty hex string, got ${i(o.decryptor_artifacts_hex)}`)}}function z(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: getPegoutStatus response is not an object");const t=n;if(!p(t.pegin_txid)||t.pegin_txid.length!==y)throw new a(`VP response validation failed: "pegin_txid" must be a ${y}-char hex string (txid), got ${i(t.pegin_txid)}`);if(typeof t.found!="boolean")throw new a(`VP response validation failed: "found" must be a boolean, got ${i(t.found)}`);if(t.claimer!==void 0){if(t.claimer===null||typeof t.claimer!="object")throw new a('VP response validation failed: "claimer" must be an object if present');const e=t.claimer;if(typeof e.status!="string")throw new a(`VP response validation failed: "claimer.status" must be a string, got ${i(e.status)}`);if(typeof e.failed!="boolean")throw new a(`VP response validation failed: "claimer.failed" must be a boolean, got ${i(e.failed)}`)}if(t.challenger!==void 0){if(t.challenger===null||typeof t.challenger!="object")throw new a('VP response validation failed: "challenger" must be an object if present');const e=t.challenger;if(typeof e.status!="string")throw new a(`VP response validation failed: "challenger.status" must be a string, got ${i(e.status)}`)}}function Q(n){if(l(n.claim_tx,"depositor_graph.claim_tx"),l(n.assert_tx,"depositor_graph.assert_tx"),l(n.payout_tx,"depositor_graph.payout_tx"),u(n.payout_psbt,"depositor_graph.payout_psbt"),!Array.isArray(n.challenger_presign_data))throw new a('VP response validation failed: "depositor_graph.challenger_presign_data" must be an array');for(let t=0;t<n.challenger_presign_data.length;t++)J(n.challenger_presign_data[t],`depositor_graph.challenger_presign_data[${t}]`);if(typeof n.offchain_params_version!="number")throw new a('VP response validation failed: "depositor_graph.offchain_params_version" must be a number')}const Z=6e4;class ee{constructor(t,e){g(this,"client");const r={baseUrl:t,timeout:(e==null?void 0:e.timeout)??Z,retries:e==null?void 0:e.retries,retryDelay:e==null?void 0:e.retryDelay,retryableFor:e==null?void 0:e.retryableFor,headers:e==null?void 0:e.headers};this.client=new w.JsonRpcClient(r)}async requestDepositorPresignTransactions(t,e){const r=await this.client.call("vaultProvider_requestDepositorPresignTransactions",t,e);return K(r),r}async submitDepositorPresignatures(t,e){return this.client.call("vaultProvider_submitDepositorPresignatures",t,e)}async submitDepositorWotsKey(t,e){return this.client.call("vaultProvider_submitDepositorWotsKey",t,e)}async requestDepositorClaimerArtifacts(t,e){const r=await this.client.call("vaultProvider_requestDepositorClaimerArtifacts",t,e);return Y(r),r}async getPeginStatus(t,e){const r=await this.client.call("vaultProvider_getPeginStatus",t,e);return X(r),r}async getPegoutStatus(t,e){const r=await this.client.call("vaultProvider_getPegoutStatus",t,e);return z(r),r}}const te=[{type:"function",name:"getBtcVaultProtocolInfo",inputs:[{name:"vaultId",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"universalChallengersVersion",type:"uint32",internalType:"uint32"},{name:"appVaultKeepersVersion",type:"uint32",internalType:"uint32"},{name:"offchainParamsVersion",type:"uint32",internalType:"uint32"},{name:"verifiedAt",type:"uint256",internalType:"uint256"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"depositorPopSignature",type:"bytes",internalType:"bytes"},{name:"prePeginTxHash",type:"bytes32",internalType:"bytes32"},{name:"vaultProviderCommissionBps",type:"uint16",internalType:"uint16"}],stateMutability:"view"}];class ne{constructor(t,e){this.publicClient=t,this.contractAddress=e}async getVaultBasicInfo(t){const e=await this.publicClient.readContract({address:this.contractAddress,abi:V,functionName:"getBtcVaultBasicInfo",args:[t]});return{depositor:e[0],depositorBtcPubKey:e[1],amount:e[2],vaultProvider:e[3],status:e[4],applicationEntryPoint:e[5],createdAt:e[6]}}async getVaultProtocolInfo(t){const e=await this.publicClient.readContract({address:this.contractAddress,abi:te,functionName:"getBtcVaultProtocolInfo",args:[t]});return{depositorSignedPeginTx:e[0],universalChallengersVersion:e[1],appVaultKeepersVersion:e[2],offchainParamsVersion:e[3],verifiedAt:e[4],depositorWotsPkHash:e[5],hashlock:e[6],htlcVout:e[7],depositorPopSignature:e[8],prePeginTxHash:e[9],vaultProviderCommissionBps:e[10]}}async getVaultData(t){const[e,r]=await Promise.all([this.getVaultBasicInfo(t),this.getVaultProtocolInfo(t)]);if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${t} not found on-chain or has no pegin transaction`);return{basic:e,protocol:r}}}exports.BTCVaultRegistryABI=V;exports.MEMPOOL_API_URLS=x;exports.VaultProviderRpcClient=ee;exports.ViemVaultRegistryReader=ne;exports.VpResponseValidationError=a;exports.getAddressTxs=D;exports.getAddressUtxos=M;exports.getMempoolApiUrl=O;exports.getNetworkFees=U;exports.getTxHex=R;exports.getTxInfo=$;exports.getUtxoInfo=C;exports.pushTx=B;
|
|
2
|
-
//# sourceMappingURL=index-D3z3SZAj.cjs.map
|