@babylonlabs-io/ts-sdk 2.0.1 → 3.0.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/{PayoutManager-CpfQjtL0.cjs → PayoutManager-B6GFbG3X.cjs} +2 -2
- package/dist/{PayoutManager-CpfQjtL0.cjs.map → PayoutManager-B6GFbG3X.cjs.map} +1 -1
- package/dist/{PayoutManager-CHTOwj0E.js → PayoutManager-BSwbUQeF.js} +2 -2
- package/dist/{PayoutManager-CHTOwj0E.js.map → PayoutManager-BSwbUQeF.js.map} +1 -1
- package/dist/{PeginManager-DEldv_Ro.js → PeginManager-CKf7Bjmj.js} +6 -6
- package/dist/PeginManager-CKf7Bjmj.js.map +1 -0
- package/dist/{PeginManager-6tjlGd0t.cjs → PeginManager-Dt2Z5ljw.cjs} +2 -2
- package/dist/PeginManager-Dt2Z5ljw.cjs.map +1 -0
- package/dist/{bip322Verify-DSco3Yhl.js → bip322Verify-BXYrHBh8.js} +2 -2
- package/dist/{bip322Verify-DSco3Yhl.js.map → bip322Verify-BXYrHBh8.js.map} +1 -1
- package/dist/{bip322Verify-B7_gIhRk.cjs → bip322Verify-DLxJR9CQ.cjs} +2 -2
- package/dist/{bip322Verify-B7_gIhRk.cjs.map → bip322Verify-DLxJR9CQ.cjs.map} +1 -1
- package/dist/buildAndBroadcastReclaim-BDc-SK9i.cjs +2 -0
- package/dist/buildAndBroadcastReclaim-BDc-SK9i.cjs.map +1 -0
- package/dist/{buildAndBroadcastReclaim-CqO2DoP8.js → buildAndBroadcastReclaim-T5ZFPUpM.js} +943 -732
- package/dist/buildAndBroadcastReclaim-T5ZFPUpM.js.map +1 -0
- package/dist/{deriveVaultRoot-BwbXmN0x.js → deriveVaultRoot-BcvmER1E.js} +2 -2
- package/dist/{deriveVaultRoot-BwbXmN0x.js.map → deriveVaultRoot-BcvmER1E.js.map} +1 -1
- package/dist/{deriveVaultRoot-DvhkHzNb.cjs → deriveVaultRoot-C3uqnJto.cjs} +2 -2
- package/dist/{deriveVaultRoot-DvhkHzNb.cjs.map → deriveVaultRoot-C3uqnJto.cjs.map} +1 -1
- package/dist/{index-DQ5bfoT3.js → index-B6w5MM-8.js} +147 -124
- package/dist/index-B6w5MM-8.js.map +1 -0
- package/dist/index-EHLYplSd.cjs +2 -0
- package/dist/index-EHLYplSd.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +163 -158
- package/dist/{onChainBtcPubkey-BXry_CM4.cjs → onChainBtcPubkey-BlzxYImF.cjs} +2 -2
- package/dist/{onChainBtcPubkey-BXry_CM4.cjs.map → onChainBtcPubkey-BlzxYImF.cjs.map} +1 -1
- package/dist/{onChainBtcPubkey-C1WqyxPM.js → onChainBtcPubkey-CCTdl53s.js} +2 -2
- package/dist/{onChainBtcPubkey-C1WqyxPM.js.map → onChainBtcPubkey-CCTdl53s.js.map} +1 -1
- package/dist/{pegin-registration-client-BNV44jzw.cjs → pegin-registration-client-BdJ6c7si.cjs} +2 -2
- package/dist/{pegin-registration-client-BNV44jzw.cjs.map → pegin-registration-client-BdJ6c7si.cjs.map} +1 -1
- package/dist/{pegin-registration-client-1sZ-74UC.js → pegin-registration-client-C5Hktrja.js} +3 -3
- package/dist/{pegin-registration-client-1sZ-74UC.js.map → pegin-registration-client-C5Hktrja.js.map} +1 -1
- package/dist/peginState-BU2ONFXF.js +68 -0
- package/dist/{peginState-CxDiaKuk.js.map → peginState-BU2ONFXF.js.map} +1 -1
- package/dist/peginState-DUv10EJR.cjs +2 -0
- package/dist/{peginState-eaQ4IO_R.cjs.map → peginState-DUv10EJR.cjs.map} +1 -1
- package/dist/{primeVpAuth-DdfHSC53.js → primeVpAuth-Bdy_B_Sq.js} +5 -5
- package/dist/{primeVpAuth-DdfHSC53.js.map → primeVpAuth-Bdy_B_Sq.js.map} +1 -1
- package/dist/primeVpAuth-CQRsu6VB.cjs +2 -0
- package/dist/{primeVpAuth-BOGKniTl.cjs.map → primeVpAuth-CQRsu6VB.cjs.map} +1 -1
- package/dist/{reservation-Cj9F0rP9.js → reservation-DOAHVT3B.js} +2 -2
- package/dist/{reservation-Cj9F0rP9.js.map → reservation-DOAHVT3B.js.map} +1 -1
- package/dist/{reservation-Dr2HLCxx.cjs → reservation-ECxjZi5t.cjs} +2 -2
- package/dist/{reservation-Dr2HLCxx.cjs.map → reservation-ECxjZi5t.cjs.map} +1 -1
- package/dist/sha2-Ce6KewYx.cjs +2 -0
- package/dist/{sha2-DI0-0SHr.cjs.map → sha2-Ce6KewYx.cjs.map} +1 -1
- package/dist/{sha2-CLpQd0Rd.js → sha2-YqVHJiFj.js} +91 -77
- package/dist/{sha2-CLpQd0Rd.js.map → sha2-YqVHJiFj.js.map} +1 -1
- package/dist/state-DMFlvLL3.cjs +2 -0
- package/dist/state-DMFlvLL3.cjs.map +1 -0
- package/dist/{json-rpc-client-DuUARJvV.js → state-mE-QfITd.js} +91 -69
- package/dist/state-mE-QfITd.js.map +1 -0
- package/dist/tbv/core/clients/eth/index.cjs +1 -1
- package/dist/tbv/core/clients/eth/index.js +3 -3
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +27 -26
- package/dist/tbv/core/clients/vault-provider/api.d.ts +2 -1
- package/dist/tbv/core/clients/vault-provider/api.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/index.d.ts +1 -1
- package/dist/tbv/core/clients/vault-provider/index.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.cjs +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.d.ts +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.js +10 -9
- package/dist/tbv/core/clients/vault-provider/types.d.ts +7 -3
- package/dist/tbv/core/clients/vault-provider/types.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/validators.d.ts +8 -0
- package/dist/tbv/core/clients/vault-provider/validators.d.ts.map +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +163 -158
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +2 -2
- package/dist/tbv/core/services/deposit/__tests__/graphFingerprint.test.d.ts +2 -0
- package/dist/tbv/core/services/deposit/__tests__/graphFingerprint.test.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/graphFingerprint.d.ts +115 -0
- package/dist/tbv/core/services/deposit/graphFingerprint.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/index.d.ts +2 -1
- package/dist/tbv/core/services/deposit/index.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/peginState.d.ts +23 -0
- package/dist/tbv/core/services/deposit/peginState.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts +11 -0
- package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +52 -47
- package/dist/tbv/core/services/index.js.map +1 -1
- package/dist/tbv/core/services/pegout/state.d.ts +8 -3
- package/dist/tbv/core/services/pegout/state.d.ts.map +1 -1
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +1 -1
- package/dist/tbv/core/vault-secrets/index.cjs +1 -1
- package/dist/tbv/core/vault-secrets/index.js +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +163 -158
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/{toRefundInputs-BaN9XluU.cjs → toRefundInputs-B_GlIXjk.cjs} +2 -2
- package/dist/{toRefundInputs-BaN9XluU.cjs.map → toRefundInputs-B_GlIXjk.cjs.map} +1 -1
- package/dist/{toRefundInputs-mtuuYezp.js → toRefundInputs-DIIdhjvu.js} +5 -5
- package/dist/{toRefundInputs-mtuuYezp.js.map → toRefundInputs-DIIdhjvu.js.map} +1 -1
- package/dist/{types-BuxreSq4.cjs → types-DJxOEU3P.cjs} +2 -2
- package/dist/{types-BuxreSq4.cjs.map → types-DJxOEU3P.cjs.map} +1 -1
- package/dist/{types-BdCEoANP.js → types-Dz1kVqn6.js} +2 -2
- package/dist/{types-BdCEoANP.js.map → types-Dz1kVqn6.js.map} +1 -1
- package/package.json +1 -1
- package/dist/PeginManager-6tjlGd0t.cjs.map +0 -1
- package/dist/PeginManager-DEldv_Ro.js.map +0 -1
- package/dist/buildAndBroadcastReclaim-BwT6Jxp5.cjs +0 -2
- package/dist/buildAndBroadcastReclaim-BwT6Jxp5.cjs.map +0 -1
- package/dist/buildAndBroadcastReclaim-CqO2DoP8.js.map +0 -1
- package/dist/index-CK1Xvq4K.cjs +0 -2
- package/dist/index-CK1Xvq4K.cjs.map +0 -1
- package/dist/index-DQ5bfoT3.js.map +0 -1
- package/dist/json-rpc-client-BiAmg_ho.cjs +0 -2
- package/dist/json-rpc-client-BiAmg_ho.cjs.map +0 -1
- package/dist/json-rpc-client-DuUARJvV.js.map +0 -1
- package/dist/peginState-CxDiaKuk.js +0 -63
- package/dist/peginState-eaQ4IO_R.cjs +0 -2
- package/dist/primeVpAuth-BOGKniTl.cjs +0 -2
- package/dist/sha2-DI0-0SHr.cjs +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"onChainBtcPubkey-C1WqyxPM.js","sources":["../src/tbv/core/clients/eth/pegin-transaction.ts","../src/tbv/core/clients/eth/onChainBtcPubkey.ts"],"sourcesContent":["/**\n * Dependency-free Bitcoin txid and vault-ID helpers for Ethereum-only clients.\n * Transaction hex and vault-ID inputs accept an optional `0x` prefix.\n * Depositor addresses use strict EIP-55 validation.\n * Txids use a `0x` prefix. Vault IDs use no prefix. Both use lowercase hex.\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport {\n encodeAbiParameters,\n isAddress,\n keccak256,\n type Address,\n type Hex,\n} from \"viem\";\n\n/** Decode an optional-prefixed, even-length hex string. */\nfunction decodeHex(value: string, label: string): Uint8Array {\n const clean = value.startsWith(\"0x\") ? value.slice(2) : value;\n if (clean.length === 0 || clean.length % 2 !== 0) {\n throw new Error(`${label} must be non-empty, even-length hex`);\n }\n if (!/^[0-9a-fA-F]+$/.test(clean)) {\n throw new Error(`${label} contains non-hex characters`);\n }\n\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/** Encode bytes as lowercase hex without a prefix. */\nfunction encodeHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n}\n\n/** Concatenate byte chunks without a buffer dependency. */\nfunction concatBytes(chunks: readonly Uint8Array[]): Uint8Array {\n const result = new Uint8Array(\n chunks.reduce((length, chunk) => length + chunk.length, 0),\n );\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n}\n\n/**\n * Parse enough of Bitcoin's consensus transaction encoding to serialize the\n * no-witness form used for txid calculation. Every length is bounds-checked;\n * malformed/trailing data is rejected rather than hashed as an opaque blob.\n */\nfunction serializeWithoutWitness(transaction: Uint8Array): Uint8Array {\n let offset = 0;\n\n const take = (length: number, label: string): Uint8Array => {\n if (!Number.isSafeInteger(length) || length < 0) {\n throw new Error(`Invalid ${label} length ${length}`);\n }\n if (offset + length > transaction.length) {\n throw new Error(`Truncated Bitcoin transaction while reading ${label}`);\n }\n const value = transaction.slice(offset, offset + length);\n offset += length;\n return value;\n };\n\n const readLittleEndian = (length: number, label: string): bigint => {\n const bytes = take(length, label);\n let value = 0n;\n for (let i = bytes.length - 1; i >= 0; i--) {\n value = (value << 8n) | BigInt(bytes[i]);\n }\n return value;\n };\n\n const readCompactSize = (\n label: string,\n ): { encoded: Uint8Array; value: number } => {\n const start = offset;\n const prefix = take(1, label)[0];\n let value: bigint;\n if (prefix < 0xfd) {\n value = BigInt(prefix);\n } else if (prefix === 0xfd) {\n value = readLittleEndian(2, label);\n if (value < 0xfdn) throw new Error(`Non-canonical ${label}`);\n } else if (prefix === 0xfe) {\n value = readLittleEndian(4, label);\n if (value <= 0xffffn) throw new Error(`Non-canonical ${label}`);\n } else {\n value = readLittleEndian(8, label);\n if (value <= 0xffffffffn) throw new Error(`Non-canonical ${label}`);\n }\n if (value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new Error(`${label} exceeds JavaScript's safe integer range`);\n }\n return {\n encoded: transaction.slice(start, offset),\n value: Number(value),\n };\n };\n\n const version = take(4, \"version\");\n const hasWitness =\n transaction[offset] === 0x00 && transaction[offset + 1] === 0x01;\n if (hasWitness) offset += 2;\n\n const inputCount = readCompactSize(\"input count\");\n const inputs: Uint8Array[] = [];\n for (let i = 0; i < inputCount.value; i++) {\n const start = offset;\n take(32, `input ${i} previous transaction hash`);\n take(4, `input ${i} previous output index`);\n const scriptLength = readCompactSize(`input ${i} script length`);\n take(scriptLength.value, `input ${i} script`);\n take(4, `input ${i} sequence`);\n inputs.push(transaction.slice(start, offset));\n }\n\n const outputCount = readCompactSize(\"output count\");\n const outputs: Uint8Array[] = [];\n for (let i = 0; i < outputCount.value; i++) {\n const start = offset;\n take(8, `output ${i} value`);\n const scriptLength = readCompactSize(`output ${i} script length`);\n take(scriptLength.value, `output ${i} script`);\n outputs.push(transaction.slice(start, offset));\n }\n\n if (hasWitness) {\n let hasWitnessData = false;\n for (let i = 0; i < inputCount.value; i++) {\n const itemCount = readCompactSize(`input ${i} witness item count`);\n hasWitnessData ||= itemCount.value > 0;\n for (let j = 0; j < itemCount.value; j++) {\n const itemLength = readCompactSize(\n `input ${i} witness item ${j} length`,\n );\n take(itemLength.value, `input ${i} witness item ${j}`);\n }\n }\n if (!hasWitnessData) {\n throw new Error(\"Bitcoin transaction has superfluous witness marker\");\n }\n }\n\n const locktime = take(4, \"locktime\");\n if (offset !== transaction.length) {\n throw new Error(\n `Bitcoin transaction has ${transaction.length - offset} trailing byte(s)`,\n );\n }\n\n return concatBytes([\n version,\n inputCount.encoded,\n ...inputs,\n outputCount.encoded,\n ...outputs,\n locktime,\n ]);\n}\n\n/** Calculate a Bitcoin txid without importing bitcoinjs-lib. */\nexport function calculateBtcTxHash(transactionHex: string): Hex {\n const serialized = serializeWithoutWitness(\n decodeHex(transactionHex, \"transactionHex\"),\n );\n const digest = sha256(sha256(serialized));\n digest.reverse();\n return `0x${encodeHex(digest)}`;\n}\n\n/**\n * Derive the Solidity vault ID without loading the Rust/WASM package.\n *\n * Inputs accept an optional `0x` prefix to match the current PeginManager\n * call sites. Address validation stays strict: lowercase and valid EIP-55\n * addresses pass, while uppercase and incorrectly checksummed mixed-case\n * addresses fail. The synchronous result is lowercase hex without a prefix,\n * matching the WASM helper that this function replaces.\n */\nexport function derivePeginVaultId(\n peginTxHash: string,\n depositor: string,\n): string {\n const normalizedPeginTxHash = peginTxHash.startsWith(\"0x\")\n ? peginTxHash\n : `0x${peginTxHash}`;\n if (!/^0x[0-9a-fA-F]{64}$/.test(normalizedPeginTxHash)) {\n throw new Error(\"peginTxHash must be a 32-byte hex value\");\n }\n const normalizedDepositor = depositor.startsWith(\"0x\")\n ? depositor\n : `0x${depositor}`;\n if (!isAddress(normalizedDepositor, { strict: true })) {\n throw new Error(`Invalid depositor Ethereum address: ${depositor}`);\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"address\" }],\n [normalizedPeginTxHash as Hex, normalizedDepositor as Address],\n ),\n ).slice(2);\n}\n","/**\n * The single validator that mints {@link OnChainBtcPubkey}.\n *\n * Extracted from `ViemVaultRegistryReader.getVaultProviderGenesisBtcPubKey` so that\n * RFC-006 operation-key resolution can produce branded keys through exactly\n * the same checks, rather than casting past the brand. Every producer of an\n * `OnChainBtcPubkey` must go through here.\n */\n\nimport type { Hex } from \"viem\";\n\nimport type { OnChainBtcPubkey } from \"./types\";\n\n/** secp256k1's base-field prime, `2^256 - 2^32 - 977`. */\nconst SECP256K1_FIELD_PRIME =\n 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn;\n\n/** secp256k1's curve coefficient `b`, from `y^2 = x^3 + b`. */\nconst SECP256K1_CURVE_B = 7n;\n\n/** Modular exponentiation without a crypto-library dependency. */\nfunction modPow(base: bigint, exponent: bigint, modulus: bigint): bigint {\n let result = 1n;\n let factor = base % modulus;\n let remaining = exponent;\n\n while (remaining > 0n) {\n if ((remaining & 1n) === 1n) {\n result = (result * factor) % modulus;\n }\n factor = (factor * factor) % modulus;\n remaining >>= 1n;\n }\n\n return result;\n}\n\n/**\n * secp256k1's field prime is congruent to 3 mod 4, so an x-coordinate is on\n * the curve iff `(x^3 + 7)^((p + 1) / 4)` squares back to `x^3 + 7` modulo\n * p. This is the same curve-membership condition used by x-only key parsers;\n * it deliberately does not merely validate length/range.\n * `x^3 + 7` cannot be zero because `-7` is not a cubic residue in this field,\n * so the zero square-root edge case is unreachable.\n */\nfunction isSecp256k1XCoordinate(value: string): boolean {\n const x = BigInt(`0x${value}`);\n if (x >= SECP256K1_FIELD_PRIME) return false;\n\n const xCubed =\n (((x * x) % SECP256K1_FIELD_PRIME) * x) % SECP256K1_FIELD_PRIME;\n const curveValue = (xCubed + SECP256K1_CURVE_B) % SECP256K1_FIELD_PRIME;\n const y = modPow(\n curveValue,\n (SECP256K1_FIELD_PRIME + 1n) >> 2n,\n SECP256K1_FIELD_PRIME,\n );\n\n return (y * y) % SECP256K1_FIELD_PRIME === curveValue;\n}\n\n/**\n * Validate a registry-returned `bytes32` as an x-only BTC pubkey and mint the\n * brand. Checks length, hex form, and secp256k1 curve membership. Returns\n * 64-char lowercase hex without the `0x` prefix.\n *\n * `label` identifies the read site in error messages (e.g.\n * `getOperationBtcKeyAtEpoch (vp=0x…, epoch=0)`), so a failure names which\n * participant and which getter produced it.\n *\n * A zero hash fails the curve check, so an unregistered operator or an epoch\n * with no bonded key surfaces as an error rather than a silent all-zero key.\n */\nexport function assertOnChainBtcPubkey(\n value: Hex,\n label: string,\n): OnChainBtcPubkey {\n const lowered = value.toLowerCase();\n if (!/^0x[0-9a-f]{64}$/.test(lowered)) {\n throw new Error(\n `${label} returned an unexpected value (length ${lowered.length}, prefix \"${lowered.slice(0, 2)}\")`,\n );\n }\n const stripped = lowered.slice(2);\n if (!isSecp256k1XCoordinate(stripped)) {\n throw new Error(\n `${label} returned a value that is not on the secp256k1 curve`,\n );\n }\n return stripped as OnChainBtcPubkey;\n}\n"],"names":["decodeHex","value","label","clean","bytes","i","encodeHex","byte","concatBytes","chunks","result","length","chunk","offset","serializeWithoutWitness","transaction","take","readLittleEndian","readCompactSize","start","prefix","version","hasWitness","inputCount","inputs","scriptLength","outputCount","outputs","hasWitnessData","itemCount","j","itemLength","locktime","calculateBtcTxHash","transactionHex","serialized","digest","sha256","derivePeginVaultId","peginTxHash","depositor","normalizedPeginTxHash","normalizedDepositor","isAddress","keccak256","encodeAbiParameters","SECP256K1_FIELD_PRIME","SECP256K1_CURVE_B","modPow","base","exponent","modulus","factor","remaining","isSecp256k1XCoordinate","x","curveValue","y","assertOnChainBtcPubkey","lowered","stripped"],"mappings":";;AAiBA,SAASA,EAAUC,GAAeC,GAA2B;AAC3D,QAAMC,IAAQF,EAAM,WAAW,IAAI,IAAIA,EAAM,MAAM,CAAC,IAAIA;AACxD,MAAIE,EAAM,WAAW,KAAKA,EAAM,SAAS,MAAM;AAC7C,UAAM,IAAI,MAAM,GAAGD,CAAK,qCAAqC;AAE/D,MAAI,CAAC,iBAAiB,KAAKC,CAAK;AAC9B,UAAM,IAAI,MAAM,GAAGD,CAAK,8BAA8B;AAGxD,QAAME,IAAQ,IAAI,WAAWD,EAAM,SAAS,CAAC;AAC7C,WAASE,IAAI,GAAGA,IAAID,EAAM,QAAQC;AAChC,IAAAD,EAAMC,CAAC,IAAI,OAAO,SAASF,EAAM,MAAME,IAAI,GAAGA,IAAI,IAAI,CAAC,GAAG,EAAE;AAE9D,SAAOD;AACT;AAGA,SAASE,EAAUF,GAA2B;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UAAM,IAAI;AAAA,MACR,GAAG1D,CAAK;AAAA,IAAA;AAGZ,SAAO0D;AACT;"}
|
|
1
|
+
{"version":3,"file":"onChainBtcPubkey-CCTdl53s.js","sources":["../src/tbv/core/clients/eth/pegin-transaction.ts","../src/tbv/core/clients/eth/onChainBtcPubkey.ts"],"sourcesContent":["/**\n * Dependency-free Bitcoin txid and vault-ID helpers for Ethereum-only clients.\n * Transaction hex and vault-ID inputs accept an optional `0x` prefix.\n * Depositor addresses use strict EIP-55 validation.\n * Txids use a `0x` prefix. Vault IDs use no prefix. Both use lowercase hex.\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport {\n encodeAbiParameters,\n isAddress,\n keccak256,\n type Address,\n type Hex,\n} from \"viem\";\n\n/** Decode an optional-prefixed, even-length hex string. */\nfunction decodeHex(value: string, label: string): Uint8Array {\n const clean = value.startsWith(\"0x\") ? value.slice(2) : value;\n if (clean.length === 0 || clean.length % 2 !== 0) {\n throw new Error(`${label} must be non-empty, even-length hex`);\n }\n if (!/^[0-9a-fA-F]+$/.test(clean)) {\n throw new Error(`${label} contains non-hex characters`);\n }\n\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/** Encode bytes as lowercase hex without a prefix. */\nfunction encodeHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n}\n\n/** Concatenate byte chunks without a buffer dependency. */\nfunction concatBytes(chunks: readonly Uint8Array[]): Uint8Array {\n const result = new Uint8Array(\n chunks.reduce((length, chunk) => length + chunk.length, 0),\n );\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n}\n\n/**\n * Parse enough of Bitcoin's consensus transaction encoding to serialize the\n * no-witness form used for txid calculation. Every length is bounds-checked;\n * malformed/trailing data is rejected rather than hashed as an opaque blob.\n */\nfunction serializeWithoutWitness(transaction: Uint8Array): Uint8Array {\n let offset = 0;\n\n const take = (length: number, label: string): Uint8Array => {\n if (!Number.isSafeInteger(length) || length < 0) {\n throw new Error(`Invalid ${label} length ${length}`);\n }\n if (offset + length > transaction.length) {\n throw new Error(`Truncated Bitcoin transaction while reading ${label}`);\n }\n const value = transaction.slice(offset, offset + length);\n offset += length;\n return value;\n };\n\n const readLittleEndian = (length: number, label: string): bigint => {\n const bytes = take(length, label);\n let value = 0n;\n for (let i = bytes.length - 1; i >= 0; i--) {\n value = (value << 8n) | BigInt(bytes[i]);\n }\n return value;\n };\n\n const readCompactSize = (\n label: string,\n ): { encoded: Uint8Array; value: number } => {\n const start = offset;\n const prefix = take(1, label)[0];\n let value: bigint;\n if (prefix < 0xfd) {\n value = BigInt(prefix);\n } else if (prefix === 0xfd) {\n value = readLittleEndian(2, label);\n if (value < 0xfdn) throw new Error(`Non-canonical ${label}`);\n } else if (prefix === 0xfe) {\n value = readLittleEndian(4, label);\n if (value <= 0xffffn) throw new Error(`Non-canonical ${label}`);\n } else {\n value = readLittleEndian(8, label);\n if (value <= 0xffffffffn) throw new Error(`Non-canonical ${label}`);\n }\n if (value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new Error(`${label} exceeds JavaScript's safe integer range`);\n }\n return {\n encoded: transaction.slice(start, offset),\n value: Number(value),\n };\n };\n\n const version = take(4, \"version\");\n const hasWitness =\n transaction[offset] === 0x00 && transaction[offset + 1] === 0x01;\n if (hasWitness) offset += 2;\n\n const inputCount = readCompactSize(\"input count\");\n const inputs: Uint8Array[] = [];\n for (let i = 0; i < inputCount.value; i++) {\n const start = offset;\n take(32, `input ${i} previous transaction hash`);\n take(4, `input ${i} previous output index`);\n const scriptLength = readCompactSize(`input ${i} script length`);\n take(scriptLength.value, `input ${i} script`);\n take(4, `input ${i} sequence`);\n inputs.push(transaction.slice(start, offset));\n }\n\n const outputCount = readCompactSize(\"output count\");\n const outputs: Uint8Array[] = [];\n for (let i = 0; i < outputCount.value; i++) {\n const start = offset;\n take(8, `output ${i} value`);\n const scriptLength = readCompactSize(`output ${i} script length`);\n take(scriptLength.value, `output ${i} script`);\n outputs.push(transaction.slice(start, offset));\n }\n\n if (hasWitness) {\n let hasWitnessData = false;\n for (let i = 0; i < inputCount.value; i++) {\n const itemCount = readCompactSize(`input ${i} witness item count`);\n hasWitnessData ||= itemCount.value > 0;\n for (let j = 0; j < itemCount.value; j++) {\n const itemLength = readCompactSize(\n `input ${i} witness item ${j} length`,\n );\n take(itemLength.value, `input ${i} witness item ${j}`);\n }\n }\n if (!hasWitnessData) {\n throw new Error(\"Bitcoin transaction has superfluous witness marker\");\n }\n }\n\n const locktime = take(4, \"locktime\");\n if (offset !== transaction.length) {\n throw new Error(\n `Bitcoin transaction has ${transaction.length - offset} trailing byte(s)`,\n );\n }\n\n return concatBytes([\n version,\n inputCount.encoded,\n ...inputs,\n outputCount.encoded,\n ...outputs,\n locktime,\n ]);\n}\n\n/** Calculate a Bitcoin txid without importing bitcoinjs-lib. */\nexport function calculateBtcTxHash(transactionHex: string): Hex {\n const serialized = serializeWithoutWitness(\n decodeHex(transactionHex, \"transactionHex\"),\n );\n const digest = sha256(sha256(serialized));\n digest.reverse();\n return `0x${encodeHex(digest)}`;\n}\n\n/**\n * Derive the Solidity vault ID without loading the Rust/WASM package.\n *\n * Inputs accept an optional `0x` prefix to match the current PeginManager\n * call sites. Address validation stays strict: lowercase and valid EIP-55\n * addresses pass, while uppercase and incorrectly checksummed mixed-case\n * addresses fail. The synchronous result is lowercase hex without a prefix,\n * matching the WASM helper that this function replaces.\n */\nexport function derivePeginVaultId(\n peginTxHash: string,\n depositor: string,\n): string {\n const normalizedPeginTxHash = peginTxHash.startsWith(\"0x\")\n ? peginTxHash\n : `0x${peginTxHash}`;\n if (!/^0x[0-9a-fA-F]{64}$/.test(normalizedPeginTxHash)) {\n throw new Error(\"peginTxHash must be a 32-byte hex value\");\n }\n const normalizedDepositor = depositor.startsWith(\"0x\")\n ? depositor\n : `0x${depositor}`;\n if (!isAddress(normalizedDepositor, { strict: true })) {\n throw new Error(`Invalid depositor Ethereum address: ${depositor}`);\n }\n return keccak256(\n encodeAbiParameters(\n [{ type: \"bytes32\" }, { type: \"address\" }],\n [normalizedPeginTxHash as Hex, normalizedDepositor as Address],\n ),\n ).slice(2);\n}\n","/**\n * The single validator that mints {@link OnChainBtcPubkey}.\n *\n * Extracted from `ViemVaultRegistryReader.getVaultProviderGenesisBtcPubKey` so that\n * RFC-006 operation-key resolution can produce branded keys through exactly\n * the same checks, rather than casting past the brand. Every producer of an\n * `OnChainBtcPubkey` must go through here.\n */\n\nimport type { Hex } from \"viem\";\n\nimport type { OnChainBtcPubkey } from \"./types\";\n\n/** secp256k1's base-field prime, `2^256 - 2^32 - 977`. */\nconst SECP256K1_FIELD_PRIME =\n 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn;\n\n/** secp256k1's curve coefficient `b`, from `y^2 = x^3 + b`. */\nconst SECP256K1_CURVE_B = 7n;\n\n/** Modular exponentiation without a crypto-library dependency. */\nfunction modPow(base: bigint, exponent: bigint, modulus: bigint): bigint {\n let result = 1n;\n let factor = base % modulus;\n let remaining = exponent;\n\n while (remaining > 0n) {\n if ((remaining & 1n) === 1n) {\n result = (result * factor) % modulus;\n }\n factor = (factor * factor) % modulus;\n remaining >>= 1n;\n }\n\n return result;\n}\n\n/**\n * secp256k1's field prime is congruent to 3 mod 4, so an x-coordinate is on\n * the curve iff `(x^3 + 7)^((p + 1) / 4)` squares back to `x^3 + 7` modulo\n * p. This is the same curve-membership condition used by x-only key parsers;\n * it deliberately does not merely validate length/range.\n * `x^3 + 7` cannot be zero because `-7` is not a cubic residue in this field,\n * so the zero square-root edge case is unreachable.\n */\nfunction isSecp256k1XCoordinate(value: string): boolean {\n const x = BigInt(`0x${value}`);\n if (x >= SECP256K1_FIELD_PRIME) return false;\n\n const xCubed =\n (((x * x) % SECP256K1_FIELD_PRIME) * x) % SECP256K1_FIELD_PRIME;\n const curveValue = (xCubed + SECP256K1_CURVE_B) % SECP256K1_FIELD_PRIME;\n const y = modPow(\n curveValue,\n (SECP256K1_FIELD_PRIME + 1n) >> 2n,\n SECP256K1_FIELD_PRIME,\n );\n\n return (y * y) % SECP256K1_FIELD_PRIME === curveValue;\n}\n\n/**\n * Validate a registry-returned `bytes32` as an x-only BTC pubkey and mint the\n * brand. Checks length, hex form, and secp256k1 curve membership. Returns\n * 64-char lowercase hex without the `0x` prefix.\n *\n * `label` identifies the read site in error messages (e.g.\n * `getOperationBtcKeyAtEpoch (vp=0x…, epoch=0)`), so a failure names which\n * participant and which getter produced it.\n *\n * A zero hash fails the curve check, so an unregistered operator or an epoch\n * with no bonded key surfaces as an error rather than a silent all-zero key.\n */\nexport function assertOnChainBtcPubkey(\n value: Hex,\n label: string,\n): OnChainBtcPubkey {\n const lowered = value.toLowerCase();\n if (!/^0x[0-9a-f]{64}$/.test(lowered)) {\n throw new Error(\n `${label} returned an unexpected value (length ${lowered.length}, prefix \"${lowered.slice(0, 2)}\")`,\n );\n }\n const stripped = lowered.slice(2);\n if (!isSecp256k1XCoordinate(stripped)) {\n throw new Error(\n `${label} returned a value that is not on the secp256k1 curve`,\n );\n }\n return stripped as OnChainBtcPubkey;\n}\n"],"names":["decodeHex","value","label","clean","bytes","i","encodeHex","byte","concatBytes","chunks","result","length","chunk","offset","serializeWithoutWitness","transaction","take","readLittleEndian","readCompactSize","start","prefix","version","hasWitness","inputCount","inputs","scriptLength","outputCount","outputs","hasWitnessData","itemCount","j","itemLength","locktime","calculateBtcTxHash","transactionHex","serialized","digest","sha256","derivePeginVaultId","peginTxHash","depositor","normalizedPeginTxHash","normalizedDepositor","isAddress","keccak256","encodeAbiParameters","SECP256K1_FIELD_PRIME","SECP256K1_CURVE_B","modPow","base","exponent","modulus","factor","remaining","isSecp256k1XCoordinate","x","curveValue","y","assertOnChainBtcPubkey","lowered","stripped"],"mappings":";;AAiBA,SAAS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B,MAAIsD,KAAKT,EAAuB,QAAO;AAIvC,QAAMU,KADDD,IAAIA,IAAKT,IAAyBS,IAAKT,IACfC,KAAqBD,GAC5CW,IAAIT;AAAA,IACRQ;AAAA,IACCV,IAAwB,MAAO;AAAA,IAChCA;AAAA,EAAA;AAGF,SAAQW,IAAIA,IAAKX,MAA0BU;AAC7C;AAcO,SAASE,EACdzD,GACAC,GACkB;AAClB,QAAMyD,IAAU1D,EAAM,YAAA;AACtB,MAAI,CAAC,mBAAmB,KAAK0D,CAAO;AAClC,UAAM,IAAI;AAAA,MACR,GAAGzD,CAAK,yCAAyCyD,EAAQ,MAAM,aAAaA,EAAQ,MAAM,GAAG,CAAC,CAAC;AAAA,IAAA;AAGnG,QAAMC,IAAWD,EAAQ,MAAM,CAAC;AAChC,MAAI,CAACL,EAAuBM,CAAQ;AAClC,UAAM,IAAI;AAAA,MACR,GAAG1D,CAAK;AAAA,IAAA;AAGZ,SAAO0D;AACT;"}
|
package/dist/{pegin-registration-client-BNV44jzw.cjs → pegin-registration-client-BdJ6c7si.cjs}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var lt=Object.defineProperty;var gt=(t,e,o)=>e in t?lt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o;var b=(t,e,o)=>gt(t,typeof e!="symbol"?e+"":e,o);const E=require("viem"),h=require("./BTCVaultRegistry.abi-BQ5tFNSu.cjs"),I=require("./BTCVaultRegistryKeyEpochs.abi-DCJnzKer.cjs"),V=require("./constants-BTZdyOuk.cjs"),dt=require("./tbv/core/utils/eth/index.cjs"),C=require("./onChainBtcPubkey-BXry_CM4.cjs"),P=require("./secp256k1-DDHQ1_za.cjs"),l=require("./sha2-DI0-0SHr.cjs"),A=25,X=9999;function $(t){if(!Number.isInteger(t)||t<0||t>=V.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`Quoted commissionBps must be an integer in [0, ${V.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${t}`);return Math.min(t+A,X)}const pt=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),z=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),ft=z.map(t=>(9*t+5)%16),G=(()=>{const o=[[z],[ft]];for(let n=0;n<4;n++)for(let i of o)i.push(i[n].map(s=>pt[s]));return o})(),Q=G[0],Y=G[1],j=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),Pt=Q.map((t,e)=>t.map(o=>j[e][o])),mt=Y.map((t,e)=>t.map(o=>j[e][o])),bt=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),yt=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function M(t,e,o,n){return t===0?e^o^n:t===1?e&o|~e&n:t===2?(e|~o)^n:t===3?e&n|o&~n:e^(o|~n)}const T=new Uint32Array(16);class Ct extends l.HashMD{constructor(){super(64,20,8,!0);b(this,"h0",1732584193);b(this,"h1",-271733879);b(this,"h2",-1732584194);b(this,"h3",271733878);b(this,"h4",-1009589776)}get(){const{h0:o,h1:n,h2:i,h3:s,h4:r}=this;return[o,n,i,s,r]}set(o,n,i,s,r){this.h0=o|0,this.h1=n|0,this.h2=i|0,this.h3=s|0,this.h4=r|0}process(o,n){for(let a=0;a<16;a++,n+=4)T[a]=o.getUint32(n,!0);let i=this.h0|0,s=i,r=this.h1|0,c=r,u=this.h2|0,g=u,f=this.h3|0,B=f,m=this.h4|0,w=m;for(let a=0;a<5;a++){const d=4-a,st=bt[a],rt=yt[a],at=Q[a],ct=Y[a],ut=Pt[a],ht=mt[a];for(let p=0;p<16;p++){const S=l.rotl(i+M(a,r,u,f)+T[at[p]]+st,ut[p])+m|0;i=m,m=f,f=l.rotl(u,10)|0,u=r,r=S}for(let p=0;p<16;p++){const S=l.rotl(s+M(d,c,g,B)+T[ct[p]]+rt,ht[p])+w|0;s=w,w=B,B=l.rotl(g,10)|0,g=c,c=S}}this.set(this.h1+u+B|0,this.h2+f+w|0,this.h3+m+s|0,this.h4+i+c|0,this.h0+r+g|0)}roundClean(){l.clean(T)}destroy(){this.destroyed=!0,l.clean(this.buffer),this.set(0,0,0,0,0)}}const Z=l.createHasher(()=>new Ct),Bt="5120",_="0014",Et=20,K=33,wt=65,It=2,Tt=3,Vt=4;function J(t,e){const o=t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t;if(!/^(?:[0-9a-fA-F]{2})+$/.test(o))throw new Error(`${e} must be non-empty, even-length hex`);return`0x${o.toLowerCase()}`}function At(t){const e=l.hexToBytes(t),o=P.schnorr.utils.lift_x(BigInt(`0x${t}`)),n=P.schnorr.utils.bytesToNumberBE(P.schnorr.utils.taggedHash("TapTweak",e));if(n>=P.secp256k1.CURVE.n)throw new Error("Proof of possession BTC pubkey has an invalid TapTweak");const i=n===0n?o:o.add(P.schnorr.Point.BASE.multiply(n));return`0x${Bt}${l.bytesToHex(P.schnorr.utils.pointToBytes(i))}`}function xt(t){const e=J(t,"depositorBtcPubkeyRaw"),o=l.hexToBytes(e.slice(2));if(o.length===32)return{xOnlyPubkey:C.assertOnChainBtcPubkey(e,"Payout BTC pubkey")};const n=o.length===K&&(o[0]===It||o[0]===Tt),i=o.length===wt&&o[0]===Vt;if(!n&&!i)throw new Error("depositorBtcPubkeyRaw must be x-only, compressed, or uncompressed");try{P.secp256k1.Point.fromBytes(o)}catch{throw new Error("depositorBtcPubkeyRaw is not a valid BTC pubkey")}return{xOnlyPubkey:l.bytesToHex(o.subarray(1,K)),compressedPubkey:n?o:void 0}}function St(t){return`0x${_}${l.bytesToHex(Z(l.sha256(t)))}`}function Rt(t,e,o){const n=J(t,"depositorPayoutScriptPubKey");if((n.length-2)/2>V.MAX_PAYOUT_SCRIPT_LEN)throw new Error(`depositorPayoutScriptPubKey exceeds ${V.MAX_PAYOUT_SCRIPT_LEN} bytes`);const i=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e,s=C.assertOnChainBtcPubkey(`0x${i}`,"Proof of possession BTC pubkey"),r=xt(o);if(r.xOnlyPubkey!==s)throw new Error("depositorBtcPubkeyRaw does not match the proof of possession BTC pubkey");if(n===At(s))return n;if(n.startsWith(`0x${_}`)&&n.length===2+_.length+Et*2){if(!r.compressedPubkey)throw new Error("A P2WPKH payout requires a compressed BTC pubkey");if(n===St(r.compressedPubkey))return n}throw new Error("depositorPayoutScriptPubKey does not match the proof of possession BTC pubkey")}const R=65535,H=1e4,x=4294967295,F=255;function tt(t){if(!Number.isInteger(t)||t<0||t>x)throw new Error(`Invalid offchainParamsVersion from contract: must be a uint32, got ${t}`)}function et(t){const e=[];if(t.timelockAssert<=0n&&e.push(`timelockAssert must be positive, got ${t.timelockAssert}`),t.timelockAssert>BigInt(R)&&e.push(`timelockAssert ${t.timelockAssert} exceeds uint16 max (${R})`),t.timelockChallengeAssert<=0n&&e.push(`timelockChallengeAssert must be positive, got ${t.timelockChallengeAssert}`),t.tRefund<=0&&e.push(`tRefund must be positive, got ${t.tRefund}`),t.tStale<=0&&e.push(`tStale must be positive, got ${t.tStale}`),t.securityCouncilKeys.length===0&&e.push("securityCouncilKeys must not be empty"),t.councilQuorum<=0&&e.push(`councilQuorum must be positive, got ${t.councilQuorum}`),t.councilQuorum>t.securityCouncilKeys.length&&e.push(`councilQuorum (${t.councilQuorum}) exceeds securityCouncilKeys count (${t.securityCouncilKeys.length})`),t.feeRate<=0n&&e.push(`feeRate must be positive, got ${t.feeRate}`),t.minPeginFeeRate<=0n&&e.push(`minPeginFeeRate must be positive, got ${t.minPeginFeeRate}`),(!Number.isInteger(t.proverCircuitVersion)||t.proverCircuitVersion<0||t.proverCircuitVersion>R)&&e.push(`proverCircuitVersion must be a uint16, got ${t.proverCircuitVersion}`),(!Number.isInteger(t.minPrepeginDepth)||t.minPrepeginDepth<=0||t.minPrepeginDepth>x)&&e.push(`minPrepeginDepth must be a uint32 in [1, ${x}], got ${t.minPrepeginDepth}`),t.babeTotalInstances<=0&&e.push(`babeTotalInstances must be positive, got ${t.babeTotalInstances}`),t.babeInstancesToFinalize<=0&&e.push(`babeInstancesToFinalize must be positive, got ${t.babeInstancesToFinalize}`),t.babeInstancesToFinalize>t.babeTotalInstances&&e.push(`babeInstancesToFinalize (${t.babeInstancesToFinalize}) exceeds babeTotalInstances (${t.babeTotalInstances})`),(t.minVpCommissionBps<0||t.minVpCommissionBps>H)&&e.push(`minVpCommissionBps must be in [0, ${H}], got ${t.minVpCommissionBps}`),e.length>0)throw new Error(`Invalid offchain protocol parameters: ${e.join("; ")}`)}function ot(t){const e=[];if(t.minimumPegInAmount<=0n&&e.push(`minimumPegInAmount must be positive, got ${t.minimumPegInAmount}`),t.maxPegInAmount<t.minimumPegInAmount&&e.push(`maxPegInAmount (${t.maxPegInAmount}) must be >= minimumPegInAmount (${t.minimumPegInAmount})`),t.pegInAckTimeout<=0n&&e.push(`pegInAckTimeout must be positive, got ${t.pegInAckTimeout}`),t.pegInActivationTimeout<=0n&&e.push(`pegInActivationTimeout must be positive, got ${t.pegInActivationTimeout}`),(!Number.isInteger(t.maxHtlcOutputCount)||t.maxHtlcOutputCount<=0||t.maxHtlcOutputCount>F)&&e.push(`maxHtlcOutputCount must be an integer in [1, ${F}], got ${t.maxHtlcOutputCount}`),(typeof t.expiredPegInGraceBlocks!="bigint"||t.expiredPegInGraceBlocks<=0n)&&e.push(`expiredPegInGraceBlocks must be a positive bigint, got ${t.expiredPegInGraceBlocks}`),e.length>0)throw new Error(`Invalid TBV protocol parameters: ${e.join("; ")}`)}function vt(t){if(ot(t),et(t.offchainParams),!Number.isInteger(t.offchainParamsVersion)||t.offchainParamsVersion<0||t.offchainParamsVersion>x)throw new Error(`Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${t.offchainParamsVersion}`);P.assertValidVaultCoreVersion(t.activeVaultCoreVersion,"ProtocolParams.activeVaultCoreVersion()")}const nt="RegistrationLogsUnavailableError";class N extends Error{constructor(o){super(`The Ethereum node returned no registration logs for block ${o}, which holds a vault registration; the node may not have indexed that block yet. Try again.`);b(this,"blockNumber");this.name=nt,this.blockNumber=o}}function kt(t){return t instanceof N?!0:typeof t!="object"||t===null?!1:t.name===nt}const q=9999;function U(t){return{depositor:t.depositor,depositorBtcPubKey:t.depositorBtcPubKey,amount:t.amount,vaultProvider:t.vaultProvider,status:t.status,applicationEntryPoint:t.applicationEntryPoint,createdAt:t.createdAt}}function v(t){const e=Number(t.offchainParamsVersion);return tt(e),{depositorSignedPeginTx:t.depositorSignedPeginTx,universalChallengersVersion:t.universalChallengersVersion,appVaultKeepersVersion:t.appVaultKeepersVersion,offchainParamsVersion:e,verifiedAt:t.verifiedAt,depositorWotsPkHash:t.depositorWotsPkHash,hashlock:t.hashlock,htlcVout:t.htlcVout,depositorPopSignature:t.depositorPopSignature,prePeginTxHash:t.prePeginTxHash,vaultProviderCommissionBps:t.vaultProviderCommissionBps,vaultCoreVersion:t.vaultCoreVersion}}const $t=1n<<64n,D=0n,_t=[E.getAbiItem({abi:h.BTCVaultRegistryABI,name:"PegInSubmitted"}),E.getAbiItem({abi:h.BTCVaultRegistryABI,name:"PegInSubmittedV2"})];function k(t,e,o){if(t<0n||t>=$t)throw new Error(`getBtcVaultProtocolInfo returned ${e}=${t} for vault ${o}, outside the uint64 range — the registry may predate RFC-006`);return t}function L(t,e){return{vpKeyEpoch:k(t.vpKeyEpoch,"vpKeyEpoch",e),appKeeperKeyEpoch:k(t.appKeeperKeyEpoch,"appKeeperKeyEpoch",e),ucKeyEpoch:k(t.ucKeyEpoch,"ucKeyEpoch",e)}}class it{constructor(e,o){this.publicClient=e,this.contractAddress=o}async getVaultProviderGenesisBtcPubKey(e,o){const n=await this.publicClient.readContract({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getOperationBtcKeyAtEpoch",args:[e,D],blockNumber:o});return C.assertOnChainBtcPubkey(n,`getOperationBtcKeyAtEpoch (vp=${e}, epoch=${D})`)}async getVaultProviderApplication(e,o){return await this.publicClient.readContract({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getVaultProviderApplication",args:[e],blockNumber:o})}async getCurrentVaultProviderOperationBtcKey(e){const o=await this.publicClient.readContract({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getCurrentOperationBtcKey",args:[e]});return C.assertOnChainBtcPubkey(o,`getCurrentOperationBtcKey (vp=${e})`)}async getVaultKeyEpochs(e){const o=await this.publicClient.readContract({address:this.contractAddress,abi:I.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return L(o,e)}async getVaultKeyEpochsBatch(e){return e.length===0?[]:(await this.publicClient.multicall({contracts:e.map(n=>({address:this.contractAddress,abi:I.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[n]})),allowFailure:!1})).map((n,i)=>L(n,e[i]))}async getVaultBasicInfo(e){const o=await this.publicClient.readContract({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]});return U(o)}async getVaultProtocolInfo(e){const o=await this.publicClient.readContract({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return v(o)}async getProtocolInfoBatch(e){return e.length===0?[]:(await this.publicClient.multicall({contracts:e.map(n=>({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[n]})),allowFailure:!1})).map((n,i)=>{const s=n;if(!s.depositorSignedPeginTx||s.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e[i]} not found on-chain or has no pegin transaction`);return v(s)})}async getPegInFee(e){return await this.publicClient.readContract({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getPegInFee",args:[e]})}async getVaultProviderCommission(e){const o=await this.publicClient.readContract({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getVaultProviderCommission",args:[e]});if(!Number.isInteger(o)||o<0||o>q)throw new Error(`getVaultProviderCommission returned ${o} bps for ${e}, outside the protocol range [0, ${q}]`);return o}async getVaultData(e){const[o,n]=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]},{address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]}],allowFailure:!1}),i=U(o),s=v(n);if(!s.depositorSignedPeginTx||s.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e} not found on-chain or has no pegin transaction`);return{basic:i,protocol:s}}async getMaxAcceptableCommissionBpsBatch(e,o){if(e.length===0)return[];const n=await this.publicClient.getLogs({address:this.contractAddress,events:_t,fromBlock:o,toBlock:o,strict:!0});if(n.length===0)throw new N(o);return e.map(i=>{const s=i.toLowerCase();let r=!1;const c=[];for(const u of n)u.args.vaultId.toLowerCase()===s&&(r=!0,u.eventName==="PegInSubmittedV2"&&c.push(u.args.maxAcceptableCommissionBps));if(c.length===1)return c[0];throw c.length>1?new Error(`Expected one PegInSubmittedV2 log for vault ${i} at block ${o}, found ${c.length} PegInSubmittedV2 logs`):r?new Error(`Vault ${i} was registered before the registry emitted the depositor's commission ceiling (no PegInSubmittedV2 log at block ${o}), so the ceiling cannot be recovered on-chain`):new Error(`Vault ${i} has no registration log at its on-chain registration block ${o}`)})}}const Ot=0,Nt=255,Mt=12e4;function y(t,e){const o=t.startsWith("0x")?t:t.startsWith("0X")?`0x${t.slice(2)}`:`0x${t}`;if(!/^0x(?:[0-9a-fA-F]{2})+$/.test(o))throw new Error(`${e} must be non-empty, even-length hex`);return o}function O(t,e){if(!/^0x[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be a 32-byte hex value`)}const Kt="0x0000000000000000000000000000000000000000000000000000000000000000";function W(t){if(O(t,"expectedFingerprint"),t.toLowerCase()===Kt)throw new Error("expectedFingerprint must not be zero: the registry cannot resolve a zero fingerprint, so this submission would always revert")}function Ht(t){if(!Number.isInteger(t)||t<0||t>Nt)throw new Error(`htlcVout must be a uint8, got ${t}`)}class Ft{constructor(e){this.config=e}async registerPeginOnChain(e){const o={...e,popSignature:{...e.popSignature}};this.assertQuotedCommissionPresentWhenRequired(o.quotedCommissionBps),W(o.expectedFingerprint);const n=this.assertPopMatchesEthAccount(o.popSignature),i=this.normalizeBtcPubkey(o.popSignature),s=y(o.popSignature.btcPopSignature,"btcPopSignature"),r=this.normalizeRequest(o,n,i);await this.assertVaultDoesNotExist(r.vaultId,r.peginTxHash);const c=await this.readPeginFee(o.vaultProvider),u=await this.resolveMaxAcceptableCommissionBps(o.vaultProvider,o.quotedCommissionBps),g=E.encodeFunctionData({abi:h.BTCVaultRegistryABI,functionName:"submitPeginRequest",args:[n,i,s,r.unsignedPrePeginTx,r.depositorSignedPeginTx,o.vaultProvider,u,o.hashlock,o.htlcVout,r.payoutScript,o.depositorWotsPkHash,o.expectedFingerprint]});return{ethTxHash:await this.sendAndWait(g,c,!1,n),vaultId:r.vaultId,peginTxHash:r.peginTxHash}}async registerPeginBatchOnChain(e){const o={...e,popSignature:{...e.popSignature},requests:e.requests.map(a=>({...a}))};if(o.requests.length===0)throw new Error("Batch pegin requires at least one request");this.assertQuotedCommissionPresentWhenRequired(o.quotedCommissionBps),W(o.expectedFingerprint);const n=this.assertPopMatchesEthAccount(o.popSignature),i=y(o.unsignedPrePeginTx,"unsignedPrePeginTx"),s=this.normalizeBtcPubkey(o.popSignature),r=y(o.popSignature.btcPopSignature,"btcPopSignature"),c=[],u=[],g=new Set;for(const a of o.requests){const d=this.normalizeRequest({...a,unsignedPrePeginTx:o.unsignedPrePeginTx,vaultProvider:o.vaultProvider,depositorBtcPubkeyRaw:o.depositorBtcPubkeyRaw},n,s);if(g.has(d.vaultId))throw new Error(`Duplicate vault in batch: ${d.vaultId}`);g.add(d.vaultId),c.push({vaultId:d.vaultId,peginTxHash:d.peginTxHash}),u.push({depositorBtcPubKey:s,btcPopSignature:r,unsignedPrePeginTx:i,depositorSignedPeginTx:d.depositorSignedPeginTx,hashlock:a.hashlock,htlcVout:a.htlcVout,referralCode:Ot,depositorPayoutBtcAddress:d.payoutScript,depositorWotsPkHash:a.depositorWotsPkHash})}for(const a of c)await this.assertVaultDoesNotExist(a.vaultId,a.peginTxHash);const f=await this.readPeginFee(o.vaultProvider),B=await this.resolveMaxAcceptableCommissionBps(o.vaultProvider,o.quotedCommissionBps),m=E.encodeFunctionData({abi:h.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[n,o.vaultProvider,B,o.expectedFingerprint,u]});return{ethTxHash:await this.sendAndWait(m,f*BigInt(o.requests.length),!0,n),vaults:c}}assertQuotedCommissionPresentWhenRequired(e){if(e===void 0&&this.config.requireQuotedCommissionBps)throw new Error("quotedCommissionBps is required when the wallet approved deposit terms: the registration ceiling must anchor to the approved quote.")}assertPopMatchesEthAccount(e){return this.assertEthAccount(e.depositorEthAddress)}assertEthAccount(e){const o=this.config.ethWallet.account;if(!o)throw new Error("Ethereum wallet account not found");if(!E.isAddressEqual(e,o.address))throw new Error(`Proof of possession was signed for ${e} but the Ethereum wallet is currently connected to ${o.address}. Reconnect the original account or sign a new proof of possession.`);return o.address}normalizeBtcPubkey(e){return`0x${C.assertOnChainBtcPubkey(y(e.depositorBtcPubkey,"Proof of possession BTC pubkey"),"Proof of possession BTC pubkey")}`}normalizeRequest(e,o,n){O(e.hashlock,"hashlock"),O(e.depositorWotsPkHash,"depositorWotsPkHash"),Ht(e.htlcVout);const i=y(e.unsignedPrePeginTx,"unsignedPrePeginTx"),s=y(e.depositorSignedPeginTx,"depositorSignedPeginTx"),r=C.calculateBtcTxHash(s);return{unsignedPrePeginTx:i,depositorSignedPeginTx:s,payoutScript:Rt(e.depositorPayoutScriptPubKey,n,e.depositorBtcPubkeyRaw),peginTxHash:r,vaultId:y(C.derivePeginVaultId(r,o),"vaultId")}}async assertVaultDoesNotExist(e,o){if((await this.config.publicClient.readContract({address:this.config.btcVaultRegistry,abi:h.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]})).depositor!==E.zeroAddress)throw new Error(`Vault already exists (ID: ${e}, peginTxHash: ${o}). Vault IDs are derived from the pegin transaction hash and depositor address. To create a new vault, use different UTXOs or a different amount to generate a unique transaction.`)}async readPeginFee(e){try{return await this.config.publicClient.readContract({address:this.config.btcVaultRegistry,abi:h.BTCVaultRegistryABI,functionName:"getPegInFee",args:[e]})}catch(o){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and contract address.",{cause:o})}}async resolveMaxAcceptableCommissionBps(e,o){let n;try{n=await new it(this.config.publicClient,this.config.btcVaultRegistry).getVaultProviderCommission(e)}catch(i){throw new Error("Failed to query vault provider commission from the contract. Please check your network connection and contract address.",{cause:i})}if(o!==void 0){if(n>o+A)throw new Error(`Vault provider commission changed since quote: quoted ${o} bps, chain currently reports ${n} bps (allowed drift ${A} bps). Please refresh and try again.`);return $(o)}return $(n)}async sendAndWait(e,o,n,i){let s=this.assertEthAccount(i),r;try{r=await this.config.publicClient.estimateGas({to:this.config.btcVaultRegistry,data:e,value:o,account:s})}catch(g){I.handleContractError(g)}s=this.assertEthAccount(i);let c;try{c=await this.config.ethWallet.sendTransaction({to:this.config.btcVaultRegistry,data:e,value:o,gas:r,account:s,chain:this.config.ethChain})}catch(g){I.handleContractError(g)}const u=await dt.waitForTransactionReceiptSmartAware({publicClient:this.config.publicClient,walletAddress:i,hash:c,timeout:this.config.receiptTimeoutMs??Mt});return u.status==="reverted"&&I.handleContractError(new Error(`${n?"Batch transaction":"Transaction"} reverted. Hash: ${u.transactionHash}. Check a block explorer for details.`)),u.transactionHash}}exports.COMMISSION_BPS_HEADROOM=A;exports.MAX_ACCEPTABLE_COMMISSION_BPS_CAP=X;exports.RegistrationLogsUnavailableError=N;exports.ViemPeginRegistrationClient=Ft;exports.ViemVaultRegistryReader=it;exports.assertValidOffchainParamsVersion=tt;exports.capMaxAcceptableCommissionBps=$;exports.isRegistrationLogsUnavailableError=kt;exports.ripemd160=Z;exports.validateOffchainParams=et;exports.validatePegInConfiguration=vt;exports.validateTBVProtocolParams=ot;
|
|
2
|
-
//# sourceMappingURL=pegin-registration-client-
|
|
1
|
+
"use strict";var lt=Object.defineProperty;var gt=(t,e,o)=>e in t?lt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o;var b=(t,e,o)=>gt(t,typeof e!="symbol"?e+"":e,o);const E=require("viem"),h=require("./BTCVaultRegistry.abi-BQ5tFNSu.cjs"),I=require("./BTCVaultRegistryKeyEpochs.abi-DCJnzKer.cjs"),V=require("./constants-BTZdyOuk.cjs"),dt=require("./tbv/core/utils/eth/index.cjs"),C=require("./onChainBtcPubkey-BlzxYImF.cjs"),P=require("./secp256k1-DDHQ1_za.cjs"),l=require("./sha2-Ce6KewYx.cjs"),A=25,X=9999;function $(t){if(!Number.isInteger(t)||t<0||t>=V.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`Quoted commissionBps must be an integer in [0, ${V.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${t}`);return Math.min(t+A,X)}const pt=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),z=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),ft=z.map(t=>(9*t+5)%16),G=(()=>{const o=[[z],[ft]];for(let n=0;n<4;n++)for(let i of o)i.push(i[n].map(s=>pt[s]));return o})(),Q=G[0],Y=G[1],j=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),Pt=Q.map((t,e)=>t.map(o=>j[e][o])),mt=Y.map((t,e)=>t.map(o=>j[e][o])),bt=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),yt=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function M(t,e,o,n){return t===0?e^o^n:t===1?e&o|~e&n:t===2?(e|~o)^n:t===3?e&n|o&~n:e^(o|~n)}const T=new Uint32Array(16);class Ct extends l.HashMD{constructor(){super(64,20,8,!0);b(this,"h0",1732584193);b(this,"h1",-271733879);b(this,"h2",-1732584194);b(this,"h3",271733878);b(this,"h4",-1009589776)}get(){const{h0:o,h1:n,h2:i,h3:s,h4:r}=this;return[o,n,i,s,r]}set(o,n,i,s,r){this.h0=o|0,this.h1=n|0,this.h2=i|0,this.h3=s|0,this.h4=r|0}process(o,n){for(let a=0;a<16;a++,n+=4)T[a]=o.getUint32(n,!0);let i=this.h0|0,s=i,r=this.h1|0,c=r,u=this.h2|0,g=u,f=this.h3|0,B=f,m=this.h4|0,w=m;for(let a=0;a<5;a++){const d=4-a,st=bt[a],rt=yt[a],at=Q[a],ct=Y[a],ut=Pt[a],ht=mt[a];for(let p=0;p<16;p++){const S=l.rotl(i+M(a,r,u,f)+T[at[p]]+st,ut[p])+m|0;i=m,m=f,f=l.rotl(u,10)|0,u=r,r=S}for(let p=0;p<16;p++){const S=l.rotl(s+M(d,c,g,B)+T[ct[p]]+rt,ht[p])+w|0;s=w,w=B,B=l.rotl(g,10)|0,g=c,c=S}}this.set(this.h1+u+B|0,this.h2+f+w|0,this.h3+m+s|0,this.h4+i+c|0,this.h0+r+g|0)}roundClean(){l.clean(T)}destroy(){this.destroyed=!0,l.clean(this.buffer),this.set(0,0,0,0,0)}}const Z=l.createHasher(()=>new Ct),Bt="5120",_="0014",Et=20,K=33,wt=65,It=2,Tt=3,Vt=4;function J(t,e){const o=t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t;if(!/^(?:[0-9a-fA-F]{2})+$/.test(o))throw new Error(`${e} must be non-empty, even-length hex`);return`0x${o.toLowerCase()}`}function At(t){const e=l.hexToBytes(t),o=P.schnorr.utils.lift_x(BigInt(`0x${t}`)),n=P.schnorr.utils.bytesToNumberBE(P.schnorr.utils.taggedHash("TapTweak",e));if(n>=P.secp256k1.CURVE.n)throw new Error("Proof of possession BTC pubkey has an invalid TapTweak");const i=n===0n?o:o.add(P.schnorr.Point.BASE.multiply(n));return`0x${Bt}${l.bytesToHex(P.schnorr.utils.pointToBytes(i))}`}function xt(t){const e=J(t,"depositorBtcPubkeyRaw"),o=l.hexToBytes(e.slice(2));if(o.length===32)return{xOnlyPubkey:C.assertOnChainBtcPubkey(e,"Payout BTC pubkey")};const n=o.length===K&&(o[0]===It||o[0]===Tt),i=o.length===wt&&o[0]===Vt;if(!n&&!i)throw new Error("depositorBtcPubkeyRaw must be x-only, compressed, or uncompressed");try{P.secp256k1.Point.fromBytes(o)}catch{throw new Error("depositorBtcPubkeyRaw is not a valid BTC pubkey")}return{xOnlyPubkey:l.bytesToHex(o.subarray(1,K)),compressedPubkey:n?o:void 0}}function St(t){return`0x${_}${l.bytesToHex(Z(l.sha256(t)))}`}function Rt(t,e,o){const n=J(t,"depositorPayoutScriptPubKey");if((n.length-2)/2>V.MAX_PAYOUT_SCRIPT_LEN)throw new Error(`depositorPayoutScriptPubKey exceeds ${V.MAX_PAYOUT_SCRIPT_LEN} bytes`);const i=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e,s=C.assertOnChainBtcPubkey(`0x${i}`,"Proof of possession BTC pubkey"),r=xt(o);if(r.xOnlyPubkey!==s)throw new Error("depositorBtcPubkeyRaw does not match the proof of possession BTC pubkey");if(n===At(s))return n;if(n.startsWith(`0x${_}`)&&n.length===2+_.length+Et*2){if(!r.compressedPubkey)throw new Error("A P2WPKH payout requires a compressed BTC pubkey");if(n===St(r.compressedPubkey))return n}throw new Error("depositorPayoutScriptPubKey does not match the proof of possession BTC pubkey")}const R=65535,H=1e4,x=4294967295,F=255;function tt(t){if(!Number.isInteger(t)||t<0||t>x)throw new Error(`Invalid offchainParamsVersion from contract: must be a uint32, got ${t}`)}function et(t){const e=[];if(t.timelockAssert<=0n&&e.push(`timelockAssert must be positive, got ${t.timelockAssert}`),t.timelockAssert>BigInt(R)&&e.push(`timelockAssert ${t.timelockAssert} exceeds uint16 max (${R})`),t.timelockChallengeAssert<=0n&&e.push(`timelockChallengeAssert must be positive, got ${t.timelockChallengeAssert}`),t.tRefund<=0&&e.push(`tRefund must be positive, got ${t.tRefund}`),t.tStale<=0&&e.push(`tStale must be positive, got ${t.tStale}`),t.securityCouncilKeys.length===0&&e.push("securityCouncilKeys must not be empty"),t.councilQuorum<=0&&e.push(`councilQuorum must be positive, got ${t.councilQuorum}`),t.councilQuorum>t.securityCouncilKeys.length&&e.push(`councilQuorum (${t.councilQuorum}) exceeds securityCouncilKeys count (${t.securityCouncilKeys.length})`),t.feeRate<=0n&&e.push(`feeRate must be positive, got ${t.feeRate}`),t.minPeginFeeRate<=0n&&e.push(`minPeginFeeRate must be positive, got ${t.minPeginFeeRate}`),(!Number.isInteger(t.proverCircuitVersion)||t.proverCircuitVersion<0||t.proverCircuitVersion>R)&&e.push(`proverCircuitVersion must be a uint16, got ${t.proverCircuitVersion}`),(!Number.isInteger(t.minPrepeginDepth)||t.minPrepeginDepth<=0||t.minPrepeginDepth>x)&&e.push(`minPrepeginDepth must be a uint32 in [1, ${x}], got ${t.minPrepeginDepth}`),t.babeTotalInstances<=0&&e.push(`babeTotalInstances must be positive, got ${t.babeTotalInstances}`),t.babeInstancesToFinalize<=0&&e.push(`babeInstancesToFinalize must be positive, got ${t.babeInstancesToFinalize}`),t.babeInstancesToFinalize>t.babeTotalInstances&&e.push(`babeInstancesToFinalize (${t.babeInstancesToFinalize}) exceeds babeTotalInstances (${t.babeTotalInstances})`),(t.minVpCommissionBps<0||t.minVpCommissionBps>H)&&e.push(`minVpCommissionBps must be in [0, ${H}], got ${t.minVpCommissionBps}`),e.length>0)throw new Error(`Invalid offchain protocol parameters: ${e.join("; ")}`)}function ot(t){const e=[];if(t.minimumPegInAmount<=0n&&e.push(`minimumPegInAmount must be positive, got ${t.minimumPegInAmount}`),t.maxPegInAmount<t.minimumPegInAmount&&e.push(`maxPegInAmount (${t.maxPegInAmount}) must be >= minimumPegInAmount (${t.minimumPegInAmount})`),t.pegInAckTimeout<=0n&&e.push(`pegInAckTimeout must be positive, got ${t.pegInAckTimeout}`),t.pegInActivationTimeout<=0n&&e.push(`pegInActivationTimeout must be positive, got ${t.pegInActivationTimeout}`),(!Number.isInteger(t.maxHtlcOutputCount)||t.maxHtlcOutputCount<=0||t.maxHtlcOutputCount>F)&&e.push(`maxHtlcOutputCount must be an integer in [1, ${F}], got ${t.maxHtlcOutputCount}`),(typeof t.expiredPegInGraceBlocks!="bigint"||t.expiredPegInGraceBlocks<=0n)&&e.push(`expiredPegInGraceBlocks must be a positive bigint, got ${t.expiredPegInGraceBlocks}`),e.length>0)throw new Error(`Invalid TBV protocol parameters: ${e.join("; ")}`)}function vt(t){if(ot(t),et(t.offchainParams),!Number.isInteger(t.offchainParamsVersion)||t.offchainParamsVersion<0||t.offchainParamsVersion>x)throw new Error(`Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${t.offchainParamsVersion}`);P.assertValidVaultCoreVersion(t.activeVaultCoreVersion,"ProtocolParams.activeVaultCoreVersion()")}const nt="RegistrationLogsUnavailableError";class N extends Error{constructor(o){super(`The Ethereum node returned no registration logs for block ${o}, which holds a vault registration; the node may not have indexed that block yet. Try again.`);b(this,"blockNumber");this.name=nt,this.blockNumber=o}}function kt(t){return t instanceof N?!0:typeof t!="object"||t===null?!1:t.name===nt}const q=9999;function U(t){return{depositor:t.depositor,depositorBtcPubKey:t.depositorBtcPubKey,amount:t.amount,vaultProvider:t.vaultProvider,status:t.status,applicationEntryPoint:t.applicationEntryPoint,createdAt:t.createdAt}}function v(t){const e=Number(t.offchainParamsVersion);return tt(e),{depositorSignedPeginTx:t.depositorSignedPeginTx,universalChallengersVersion:t.universalChallengersVersion,appVaultKeepersVersion:t.appVaultKeepersVersion,offchainParamsVersion:e,verifiedAt:t.verifiedAt,depositorWotsPkHash:t.depositorWotsPkHash,hashlock:t.hashlock,htlcVout:t.htlcVout,depositorPopSignature:t.depositorPopSignature,prePeginTxHash:t.prePeginTxHash,vaultProviderCommissionBps:t.vaultProviderCommissionBps,vaultCoreVersion:t.vaultCoreVersion}}const $t=1n<<64n,D=0n,_t=[E.getAbiItem({abi:h.BTCVaultRegistryABI,name:"PegInSubmitted"}),E.getAbiItem({abi:h.BTCVaultRegistryABI,name:"PegInSubmittedV2"})];function k(t,e,o){if(t<0n||t>=$t)throw new Error(`getBtcVaultProtocolInfo returned ${e}=${t} for vault ${o}, outside the uint64 range — the registry may predate RFC-006`);return t}function L(t,e){return{vpKeyEpoch:k(t.vpKeyEpoch,"vpKeyEpoch",e),appKeeperKeyEpoch:k(t.appKeeperKeyEpoch,"appKeeperKeyEpoch",e),ucKeyEpoch:k(t.ucKeyEpoch,"ucKeyEpoch",e)}}class it{constructor(e,o){this.publicClient=e,this.contractAddress=o}async getVaultProviderGenesisBtcPubKey(e,o){const n=await this.publicClient.readContract({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getOperationBtcKeyAtEpoch",args:[e,D],blockNumber:o});return C.assertOnChainBtcPubkey(n,`getOperationBtcKeyAtEpoch (vp=${e}, epoch=${D})`)}async getVaultProviderApplication(e,o){return await this.publicClient.readContract({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getVaultProviderApplication",args:[e],blockNumber:o})}async getCurrentVaultProviderOperationBtcKey(e){const o=await this.publicClient.readContract({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getCurrentOperationBtcKey",args:[e]});return C.assertOnChainBtcPubkey(o,`getCurrentOperationBtcKey (vp=${e})`)}async getVaultKeyEpochs(e){const o=await this.publicClient.readContract({address:this.contractAddress,abi:I.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return L(o,e)}async getVaultKeyEpochsBatch(e){return e.length===0?[]:(await this.publicClient.multicall({contracts:e.map(n=>({address:this.contractAddress,abi:I.BTCVaultRegistryKeyEpochsABI,functionName:"getBtcVaultProtocolInfo",args:[n]})),allowFailure:!1})).map((n,i)=>L(n,e[i]))}async getVaultBasicInfo(e){const o=await this.publicClient.readContract({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]});return U(o)}async getVaultProtocolInfo(e){const o=await this.publicClient.readContract({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return v(o)}async getProtocolInfoBatch(e){return e.length===0?[]:(await this.publicClient.multicall({contracts:e.map(n=>({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[n]})),allowFailure:!1})).map((n,i)=>{const s=n;if(!s.depositorSignedPeginTx||s.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e[i]} not found on-chain or has no pegin transaction`);return v(s)})}async getPegInFee(e){return await this.publicClient.readContract({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getPegInFee",args:[e]})}async getVaultProviderCommission(e){const o=await this.publicClient.readContract({address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getVaultProviderCommission",args:[e]});if(!Number.isInteger(o)||o<0||o>q)throw new Error(`getVaultProviderCommission returned ${o} bps for ${e}, outside the protocol range [0, ${q}]`);return o}async getVaultData(e){const[o,n]=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]},{address:this.contractAddress,abi:h.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]}],allowFailure:!1}),i=U(o),s=v(n);if(!s.depositorSignedPeginTx||s.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e} not found on-chain or has no pegin transaction`);return{basic:i,protocol:s}}async getMaxAcceptableCommissionBpsBatch(e,o){if(e.length===0)return[];const n=await this.publicClient.getLogs({address:this.contractAddress,events:_t,fromBlock:o,toBlock:o,strict:!0});if(n.length===0)throw new N(o);return e.map(i=>{const s=i.toLowerCase();let r=!1;const c=[];for(const u of n)u.args.vaultId.toLowerCase()===s&&(r=!0,u.eventName==="PegInSubmittedV2"&&c.push(u.args.maxAcceptableCommissionBps));if(c.length===1)return c[0];throw c.length>1?new Error(`Expected one PegInSubmittedV2 log for vault ${i} at block ${o}, found ${c.length} PegInSubmittedV2 logs`):r?new Error(`Vault ${i} was registered before the registry emitted the depositor's commission ceiling (no PegInSubmittedV2 log at block ${o}), so the ceiling cannot be recovered on-chain`):new Error(`Vault ${i} has no registration log at its on-chain registration block ${o}`)})}}const Ot=0,Nt=255,Mt=12e4;function y(t,e){const o=t.startsWith("0x")?t:t.startsWith("0X")?`0x${t.slice(2)}`:`0x${t}`;if(!/^0x(?:[0-9a-fA-F]{2})+$/.test(o))throw new Error(`${e} must be non-empty, even-length hex`);return o}function O(t,e){if(!/^0x[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be a 32-byte hex value`)}const Kt="0x0000000000000000000000000000000000000000000000000000000000000000";function W(t){if(O(t,"expectedFingerprint"),t.toLowerCase()===Kt)throw new Error("expectedFingerprint must not be zero: the registry cannot resolve a zero fingerprint, so this submission would always revert")}function Ht(t){if(!Number.isInteger(t)||t<0||t>Nt)throw new Error(`htlcVout must be a uint8, got ${t}`)}class Ft{constructor(e){this.config=e}async registerPeginOnChain(e){const o={...e,popSignature:{...e.popSignature}};this.assertQuotedCommissionPresentWhenRequired(o.quotedCommissionBps),W(o.expectedFingerprint);const n=this.assertPopMatchesEthAccount(o.popSignature),i=this.normalizeBtcPubkey(o.popSignature),s=y(o.popSignature.btcPopSignature,"btcPopSignature"),r=this.normalizeRequest(o,n,i);await this.assertVaultDoesNotExist(r.vaultId,r.peginTxHash);const c=await this.readPeginFee(o.vaultProvider),u=await this.resolveMaxAcceptableCommissionBps(o.vaultProvider,o.quotedCommissionBps),g=E.encodeFunctionData({abi:h.BTCVaultRegistryABI,functionName:"submitPeginRequest",args:[n,i,s,r.unsignedPrePeginTx,r.depositorSignedPeginTx,o.vaultProvider,u,o.hashlock,o.htlcVout,r.payoutScript,o.depositorWotsPkHash,o.expectedFingerprint]});return{ethTxHash:await this.sendAndWait(g,c,!1,n),vaultId:r.vaultId,peginTxHash:r.peginTxHash}}async registerPeginBatchOnChain(e){const o={...e,popSignature:{...e.popSignature},requests:e.requests.map(a=>({...a}))};if(o.requests.length===0)throw new Error("Batch pegin requires at least one request");this.assertQuotedCommissionPresentWhenRequired(o.quotedCommissionBps),W(o.expectedFingerprint);const n=this.assertPopMatchesEthAccount(o.popSignature),i=y(o.unsignedPrePeginTx,"unsignedPrePeginTx"),s=this.normalizeBtcPubkey(o.popSignature),r=y(o.popSignature.btcPopSignature,"btcPopSignature"),c=[],u=[],g=new Set;for(const a of o.requests){const d=this.normalizeRequest({...a,unsignedPrePeginTx:o.unsignedPrePeginTx,vaultProvider:o.vaultProvider,depositorBtcPubkeyRaw:o.depositorBtcPubkeyRaw},n,s);if(g.has(d.vaultId))throw new Error(`Duplicate vault in batch: ${d.vaultId}`);g.add(d.vaultId),c.push({vaultId:d.vaultId,peginTxHash:d.peginTxHash}),u.push({depositorBtcPubKey:s,btcPopSignature:r,unsignedPrePeginTx:i,depositorSignedPeginTx:d.depositorSignedPeginTx,hashlock:a.hashlock,htlcVout:a.htlcVout,referralCode:Ot,depositorPayoutBtcAddress:d.payoutScript,depositorWotsPkHash:a.depositorWotsPkHash})}for(const a of c)await this.assertVaultDoesNotExist(a.vaultId,a.peginTxHash);const f=await this.readPeginFee(o.vaultProvider),B=await this.resolveMaxAcceptableCommissionBps(o.vaultProvider,o.quotedCommissionBps),m=E.encodeFunctionData({abi:h.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[n,o.vaultProvider,B,o.expectedFingerprint,u]});return{ethTxHash:await this.sendAndWait(m,f*BigInt(o.requests.length),!0,n),vaults:c}}assertQuotedCommissionPresentWhenRequired(e){if(e===void 0&&this.config.requireQuotedCommissionBps)throw new Error("quotedCommissionBps is required when the wallet approved deposit terms: the registration ceiling must anchor to the approved quote.")}assertPopMatchesEthAccount(e){return this.assertEthAccount(e.depositorEthAddress)}assertEthAccount(e){const o=this.config.ethWallet.account;if(!o)throw new Error("Ethereum wallet account not found");if(!E.isAddressEqual(e,o.address))throw new Error(`Proof of possession was signed for ${e} but the Ethereum wallet is currently connected to ${o.address}. Reconnect the original account or sign a new proof of possession.`);return o.address}normalizeBtcPubkey(e){return`0x${C.assertOnChainBtcPubkey(y(e.depositorBtcPubkey,"Proof of possession BTC pubkey"),"Proof of possession BTC pubkey")}`}normalizeRequest(e,o,n){O(e.hashlock,"hashlock"),O(e.depositorWotsPkHash,"depositorWotsPkHash"),Ht(e.htlcVout);const i=y(e.unsignedPrePeginTx,"unsignedPrePeginTx"),s=y(e.depositorSignedPeginTx,"depositorSignedPeginTx"),r=C.calculateBtcTxHash(s);return{unsignedPrePeginTx:i,depositorSignedPeginTx:s,payoutScript:Rt(e.depositorPayoutScriptPubKey,n,e.depositorBtcPubkeyRaw),peginTxHash:r,vaultId:y(C.derivePeginVaultId(r,o),"vaultId")}}async assertVaultDoesNotExist(e,o){if((await this.config.publicClient.readContract({address:this.config.btcVaultRegistry,abi:h.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]})).depositor!==E.zeroAddress)throw new Error(`Vault already exists (ID: ${e}, peginTxHash: ${o}). Vault IDs are derived from the pegin transaction hash and depositor address. To create a new vault, use different UTXOs or a different amount to generate a unique transaction.`)}async readPeginFee(e){try{return await this.config.publicClient.readContract({address:this.config.btcVaultRegistry,abi:h.BTCVaultRegistryABI,functionName:"getPegInFee",args:[e]})}catch(o){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and contract address.",{cause:o})}}async resolveMaxAcceptableCommissionBps(e,o){let n;try{n=await new it(this.config.publicClient,this.config.btcVaultRegistry).getVaultProviderCommission(e)}catch(i){throw new Error("Failed to query vault provider commission from the contract. Please check your network connection and contract address.",{cause:i})}if(o!==void 0){if(n>o+A)throw new Error(`Vault provider commission changed since quote: quoted ${o} bps, chain currently reports ${n} bps (allowed drift ${A} bps). Please refresh and try again.`);return $(o)}return $(n)}async sendAndWait(e,o,n,i){let s=this.assertEthAccount(i),r;try{r=await this.config.publicClient.estimateGas({to:this.config.btcVaultRegistry,data:e,value:o,account:s})}catch(g){I.handleContractError(g)}s=this.assertEthAccount(i);let c;try{c=await this.config.ethWallet.sendTransaction({to:this.config.btcVaultRegistry,data:e,value:o,gas:r,account:s,chain:this.config.ethChain})}catch(g){I.handleContractError(g)}const u=await dt.waitForTransactionReceiptSmartAware({publicClient:this.config.publicClient,walletAddress:i,hash:c,timeout:this.config.receiptTimeoutMs??Mt});return u.status==="reverted"&&I.handleContractError(new Error(`${n?"Batch transaction":"Transaction"} reverted. Hash: ${u.transactionHash}. Check a block explorer for details.`)),u.transactionHash}}exports.COMMISSION_BPS_HEADROOM=A;exports.MAX_ACCEPTABLE_COMMISSION_BPS_CAP=X;exports.RegistrationLogsUnavailableError=N;exports.ViemPeginRegistrationClient=Ft;exports.ViemVaultRegistryReader=it;exports.assertValidOffchainParamsVersion=tt;exports.capMaxAcceptableCommissionBps=$;exports.isRegistrationLogsUnavailableError=kt;exports.ripemd160=Z;exports.validateOffchainParams=et;exports.validatePegInConfiguration=vt;exports.validateTBVProtocolParams=ot;
|
|
2
|
+
//# sourceMappingURL=pegin-registration-client-BdJ6c7si.cjs.map
|