@babylonlabs-io/ts-sdk 0.74.0 → 0.75.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/{PeginManager-E-UHA1un.cjs → PeginManager-DEByBX5R.cjs} +2 -2
- package/dist/{PeginManager-E-UHA1un.cjs.map → PeginManager-DEByBX5R.cjs.map} +1 -1
- package/dist/{PeginManager-C9RPOd0L.js → PeginManager-DNimKlmw.js} +11 -11
- package/dist/{PeginManager-C9RPOd0L.js.map → PeginManager-DNimKlmw.js.map} +1 -1
- package/dist/{bip322Verify-D6sBBUHE.js → bip322Verify-DSco3Yhl.js} +2 -2
- package/dist/{bip322Verify-D6sBBUHE.js.map → bip322Verify-DSco3Yhl.js.map} +1 -1
- package/dist/buildAndBroadcastReclaim-Cqc6Jiqk.cjs +2 -0
- package/dist/{buildAndBroadcastReclaim-U-PyFfDg.cjs.map → buildAndBroadcastReclaim-Cqc6Jiqk.cjs.map} +1 -1
- package/dist/{buildAndBroadcastReclaim-BXclIcu_.js → buildAndBroadcastReclaim-DCGcupg7.js} +6 -6
- package/dist/{buildAndBroadcastReclaim-BXclIcu_.js.map → buildAndBroadcastReclaim-DCGcupg7.js.map} +1 -1
- package/dist/constants-BTZdyOuk.cjs +2 -0
- package/dist/constants-BTZdyOuk.cjs.map +1 -0
- package/dist/constants-D5vORbQE.js +29 -0
- package/dist/constants-D5vORbQE.js.map +1 -0
- package/dist/fundPeginTransaction-54-Rwb2k.cjs +2 -0
- package/dist/fundPeginTransaction-54-Rwb2k.cjs.map +1 -0
- package/dist/fundPeginTransaction-CwhRbCQC.js +88 -0
- package/dist/fundPeginTransaction-CwhRbCQC.js.map +1 -0
- package/dist/{index-Cs7_Evtk.cjs → index-CK1Xvq4K.cjs} +2 -2
- package/dist/{index-Cs7_Evtk.cjs.map → index-CK1Xvq4K.cjs.map} +1 -1
- package/dist/{index-LgmJhdEN.js → index-DQ5bfoT3.js} +2 -2
- package/dist/{index-LgmJhdEN.js.map → index-DQ5bfoT3.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +15 -15
- package/dist/noPayout-4RZB2g1e.cjs +2 -0
- package/dist/noPayout-4RZB2g1e.cjs.map +1 -0
- package/dist/noPayout-DiGr4eas.js +361 -0
- package/dist/noPayout-DiGr4eas.js.map +1 -0
- package/dist/{parseFundingOutpoints-B67CoXpF.js → parseFundingOutpoints-BQWvINfm.js} +2 -2
- package/dist/{parseFundingOutpoints-B67CoXpF.js.map → parseFundingOutpoints-BQWvINfm.js.map} +1 -1
- package/dist/pegin-registration-client-CXK3B_D1.js +882 -0
- package/dist/pegin-registration-client-CXK3B_D1.js.map +1 -0
- package/dist/pegin-registration-client-DLsMNm8Z.cjs +2 -0
- package/dist/pegin-registration-client-DLsMNm8Z.cjs.map +1 -0
- package/dist/{primeVpAuth-DBHohVKM.cjs → primeVpAuth-BOGKniTl.cjs} +2 -2
- package/dist/{primeVpAuth-DBHohVKM.cjs.map → primeVpAuth-BOGKniTl.cjs.map} +1 -1
- package/dist/{primeVpAuth-DvaD45q_.js → primeVpAuth-DdfHSC53.js} +4 -4
- package/dist/{primeVpAuth-DvaD45q_.js.map → primeVpAuth-DdfHSC53.js.map} +1 -1
- package/dist/{psbtInputFields-BIxBpPj2.cjs → psbtInputFields-BrV_ZfL_.cjs} +2 -2
- package/dist/{psbtInputFields-BIxBpPj2.cjs.map → psbtInputFields-BrV_ZfL_.cjs.map} +1 -1
- package/dist/{psbtInputFields-B3e05Xe6.js → psbtInputFields-CCVyaQMi.js} +2 -2
- package/dist/{psbtInputFields-B3e05Xe6.js.map → psbtInputFields-CCVyaQMi.js.map} +1 -1
- package/dist/secp256k1-D-H9jmd7.js +1766 -0
- package/dist/secp256k1-D-H9jmd7.js.map +1 -0
- package/dist/secp256k1-DDHQ1_za.cjs +2 -0
- package/dist/secp256k1-DDHQ1_za.cjs.map +1 -0
- package/dist/{sha2-CrlWM5S8.js → sha2-CLpQd0Rd.js} +8 -8
- package/dist/{sha2-CrlWM5S8.js.map → sha2-CLpQd0Rd.js.map} +1 -1
- package/dist/{signPsbtsWithFallback-DMSpIQWH.cjs → signPsbtsWithFallback-DtwzL5AA.cjs} +2 -2
- package/dist/{signPsbtsWithFallback-DMSpIQWH.cjs.map → signPsbtsWithFallback-DtwzL5AA.cjs.map} +1 -1
- package/dist/{signPsbtsWithFallback-0VBALhjS.js → signPsbtsWithFallback-f7QLp0q8.js} +4 -4
- package/dist/{signPsbtsWithFallback-0VBALhjS.js.map → signPsbtsWithFallback-f7QLp0q8.js.map} +1 -1
- 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 +5 -5
- package/dist/tbv/core/clients/vault-provider/status/index.cjs +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.js +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +15 -15
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +2 -2
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.js +4 -4
- package/dist/tbv/core/primitives/psbt/__tests__/assertPeginTxShape.test.d.ts +5 -6
- package/dist/tbv/core/primitives/psbt/__tests__/assertPeginTxShape.test.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/__tests__/assertWasmPeginSizing.test.d.ts +2 -2
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts +36 -14
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/constants.d.ts +39 -0
- package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/peginInput.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/refund.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +2 -2
- package/dist/tbv/core/utils/fee/constants.d.ts +4 -4
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +2 -2
- package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/index.js +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +15 -15
- package/dist/tbv/integrations/aave/constants.d.ts +9 -3
- package/dist/tbv/integrations/aave/constants.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 +1 -1
- package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.js +106 -102
- package/dist/tbv/integrations/aave/index.js.map +1 -1
- package/dist/tbv/integrations/aave/utils/healthFactor.d.ts +10 -7
- package/dist/tbv/integrations/aave/utils/healthFactor.d.ts.map +1 -1
- package/dist/test/setup.browser.d.ts +2 -0
- package/dist/test/setup.browser.d.ts.map +1 -0
- package/dist/testing/index.js +1 -1
- package/dist/{toRefundInputs-C3oIN0aW.js → toRefundInputs-BNSXIymn.js} +7 -7
- package/dist/{toRefundInputs-C3oIN0aW.js.map → toRefundInputs-BNSXIymn.js.map} +1 -1
- package/dist/{toRefundInputs-BwG6T0PP.cjs → toRefundInputs-meTyor7r.cjs} +2 -2
- package/dist/{toRefundInputs-BwG6T0PP.cjs.map → toRefundInputs-meTyor7r.cjs.map} +1 -1
- package/dist/{types-DSlcXtog.cjs → types-BzSOthHH.cjs} +2 -2
- package/dist/{types-DSlcXtog.cjs.map → types-BzSOthHH.cjs.map} +1 -1
- package/dist/{types-CPDLZm3l.js → types-C5DyrC8F.js} +2 -2
- package/dist/{types-CPDLZm3l.js.map → types-C5DyrC8F.js.map} +1 -1
- package/dist/verifyKeyPathSchnorrSignature-BVtNwgK6.js +360 -0
- package/dist/verifyKeyPathSchnorrSignature-BVtNwgK6.js.map +1 -0
- package/dist/verifyKeyPathSchnorrSignature-BjB8Znly.cjs +2 -0
- package/dist/verifyKeyPathSchnorrSignature-BjB8Znly.cjs.map +1 -0
- package/dist/verifyScriptPathSchnorrSignature-D_epga4j.js +1140 -0
- package/dist/verifyScriptPathSchnorrSignature-D_epga4j.js.map +1 -0
- package/dist/verifyScriptPathSchnorrSignature-DaRqvEgW.cjs +2 -0
- package/dist/verifyScriptPathSchnorrSignature-DaRqvEgW.cjs.map +1 -0
- package/package.json +4 -1
- package/dist/buildAndBroadcastReclaim-U-PyFfDg.cjs +0 -2
- package/dist/constants-Bh38W9mq.cjs +0 -2
- package/dist/constants-Bh38W9mq.cjs.map +0 -1
- package/dist/constants-CPzppOdq.js +0 -17
- package/dist/constants-CPzppOdq.js.map +0 -1
- package/dist/fundPeginTransaction-B2wyjqp0.js +0 -83
- package/dist/fundPeginTransaction-B2wyjqp0.js.map +0 -1
- package/dist/fundPeginTransaction-BLD8FRL9.cjs +0 -2
- package/dist/fundPeginTransaction-BLD8FRL9.cjs.map +0 -1
- package/dist/noPayout-DpGRzidi.js +0 -353
- package/dist/noPayout-DpGRzidi.js.map +0 -1
- package/dist/noPayout-zEifyecV.cjs +0 -2
- package/dist/noPayout-zEifyecV.cjs.map +0 -1
- package/dist/pegin-registration-client-6vLk2itL.cjs +0 -2
- package/dist/pegin-registration-client-6vLk2itL.cjs.map +0 -1
- package/dist/pegin-registration-client-BdRiR8br.js +0 -2635
- package/dist/pegin-registration-client-BdRiR8br.js.map +0 -1
- package/dist/vaultCoreVersion-DYfw3qed.cjs +0 -2
- package/dist/vaultCoreVersion-DYfw3qed.cjs.map +0 -1
- package/dist/vaultCoreVersion-D_fP9P3C.js +0 -10
- package/dist/vaultCoreVersion-D_fP9P3C.js.map +0 -1
- package/dist/verifyKeyPathSchnorrSignature-BedSbH2D.cjs +0 -2
- package/dist/verifyKeyPathSchnorrSignature-BedSbH2D.cjs.map +0 -1
- package/dist/verifyKeyPathSchnorrSignature-BrgUJmV0.js +0 -372
- package/dist/verifyKeyPathSchnorrSignature-BrgUJmV0.js.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-BfNUSgA7.cjs +0 -2
- package/dist/verifyScriptPathSchnorrSignature-BfNUSgA7.cjs.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-Ciq_xZhw.js +0 -951
- package/dist/verifyScriptPathSchnorrSignature-Ciq_xZhw.js.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const _="6a20";exports.ASSERT_PAYOUT_OUTPUT_INDEX=0;exports.BPS_DENOMINATOR=1e4;exports.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER=2;exports.DEPOSITOR_PAYOUT_INPUT_COUNT=2;exports.DEPOSITOR_SIGNED_INPUT_COUNT=1;exports.MAX_PAYOUT_SCRIPT_LEN=128;exports.MAX_VP_COMMISSION_BPS_EXCLUSIVE=1e4;exports.NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT=2;exports.PAYOUT_ANCHOR_DUST_SATS=546;exports.PAYOUT_TX_LOCKTIME=0;exports.PAYOUT_TX_VERSION=2;exports.PEGIN_INPUT_SEQUENCE=4294967294;exports.PEGIN_TX_LOCKTIME=0;exports.PEGIN_TX_VERSION_CORE_1=2;exports.PEGIN_TX_VERSION_CORE_2_AND_3=3;exports.PEGIN_VAULT_OUTPUT_INDEX=0;exports.PRE_PEGIN_AUTH_OUTPUT_VALUE_SATS=0;exports.PRE_PEGIN_AUTH_SCRIPT_PREFIX=_;exports.PRE_PEGIN_CPFP_VALUE_SATS=546;exports.PRE_PEGIN_MIN_HTLC_OUTPUT_COUNT=1;exports.PRE_PEGIN_TX_LOCKTIME=0;exports.PRE_PEGIN_TX_VERSION=2;exports.REFUND_TX_LOCKTIME=0;exports.REFUND_TX_VERSION=2;exports.VP_CLAIMER_PAYOUT_OUTPUT_COUNT=3;
|
|
2
|
+
//# sourceMappingURL=constants-BTZdyOuk.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants-BTZdyOuk.cjs","sources":["../src/tbv/core/primitives/psbt/constants.ts"],"sourcesContent":["/**\n * Protocol invariants for depositor graph transactions.\n *\n * These indices and counts encode the on-chain vault protocol layout\n * (which output of PegIn/Assert each child transaction spends, and how\n * many inputs each transaction has). Consumed by the PSBT builders and\n * the depositor graph signing service; a drift between copies of these\n * values would silently change validation behaviour.\n *\n * @module primitives/psbt/constants\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md\n */\n\n/**\n * Depositor Payout transaction input count.\n * Input 0: PegIn:0 (signed). Input 1: Assert:0 (in sighash, not signed).\n */\nexport const DEPOSITOR_PAYOUT_INPUT_COUNT = 2;\n\n/**\n * Inputs the depositor signs per Payout / NoPayout PSBT: input 0 only. The\n * other inputs are in the SIGHASH_DEFAULT sighash but carry no depositor\n * signature — the Ledger host expects exactly this many yields, so a drift\n * here re-arms an input the device never signs.\n */\nexport const DEPOSITOR_SIGNED_INPUT_COUNT = 1;\n\n/** PegIn vault output index spent by the depositor's Payout input 0. */\nexport const PEGIN_VAULT_OUTPUT_INDEX = 0;\n\n/** Assert output index spent by the depositor's Payout input 1 (NOT signed). */\nexport const ASSERT_PAYOUT_OUTPUT_INDEX = 0;\n\n/**\n * Dust amount (sats) for the payout CPFP anchor output. Matches `DUST_AMOUNT`\n * in `btc-vault crates/vault/src/lib.rs`.\n */\nexport const PAYOUT_ANCHOR_DUST_SATS = 546;\n\n/** Minimum number of HTLC outputs in a Pre-PegIn transaction. */\nexport const PRE_PEGIN_MIN_HTLC_OUTPUT_COUNT = 1;\n\n/** Canonical value in sats for the optional Pre-PegIn auth output. */\nexport const PRE_PEGIN_AUTH_OUTPUT_VALUE_SATS = 0;\n\n/**\n * Hex prefix for `OP_RETURN PUSH32`. This matches\n * `ScriptBuf::new_op_return(hash)` in\n * `btc-vault crates/vault/src/transactions/prepegin.rs`.\n */\nexport const PRE_PEGIN_AUTH_SCRIPT_PREFIX = \"6a20\";\n\n/**\n * Value in sats for the Pre-PegIn CPFP anchor output. Matches `DUST_AMOUNT`\n * in `btc-vault crates/vault/src/lib.rs`.\n */\nexport const PRE_PEGIN_CPFP_VALUE_SATS = 546;\n\n/**\n * Canonical Pre-PegIn transaction version. Matches `Version::TWO` in\n * `btc-vault crates/vault/src/transactions/prepegin.rs`.\n */\nexport const PRE_PEGIN_TX_VERSION = 2;\n\n/**\n * Canonical Pre-PegIn transaction locktime. Matches `LockTime::ZERO` in\n * `btc-vault crates/vault/src/transactions/prepegin.rs`.\n */\nexport const PRE_PEGIN_TX_LOCKTIME = 0;\n\n/** Vault Core 1 PegIn nVersion from `PegInTx::expected_tx_version`. */\nexport const PEGIN_TX_VERSION_CORE_1 = 2;\n\n/** Vault Core 2 and 3 PegIn nVersion from `PegInTx::expected_tx_version`. */\nexport const PEGIN_TX_VERSION_CORE_2_AND_3 = 3;\n\n/** PegIn locktime from `PegInTx::new_from_prepegin` (`LockTime::ZERO`). */\nexport const PEGIN_TX_LOCKTIME = 0;\n\n/** PegIn input sequence from `PegInTx::new_from_prepegin`. */\nexport const PEGIN_INPUT_SEQUENCE = 0xfffffffe;\n\n/**\n * Refund version and locktime match `WasmPrePeginTx::build_refund_tx`\n * (`Version::TWO`, `LockTime::ZERO`) in `btc-vault crates/vault/src/wasm/api.rs`.\n */\nexport const REFUND_TX_VERSION = 2;\nexport const REFUND_TX_LOCKTIME = 0;\n\n/**\n * Payout transaction literals btc-vault builds deterministically\n * (`crates/vault/src/transactions/payout.rs`: `Version::TWO`,\n * `LockTime::ZERO`). The depositor's signature commits to both, so a\n * VP-supplied payout that deviates would produce a signature over a\n * transaction the protocol never constructs.\n */\nexport const PAYOUT_TX_VERSION = 2;\nexport const PAYOUT_TX_LOCKTIME = 0;\n\n/** VP-claimer payout output count: [depositor payout, VP commission, CPFP anchor]. */\nexport const VP_CLAIMER_PAYOUT_OUTPUT_COUNT = 3;\n\n/** Depositor/VK-claimer payout output count: [claimer payout, CPFP anchor]. */\nexport const NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT = 2;\n\n/**\n * ChallengeAssert connectors the VP returns per challenger: one for the\n * ChallengeAssertX transaction and one for ChallengeAssertY — two single-input\n * transactions, not a single multi-input one. This is a per-challenger array\n * cardinality, NOT a count of inputs in one transaction.\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md (ChallengeAssertX / ChallengeAssertY)\n */\nexport const CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER = 2;\n\n/**\n * Exclusive upper bound on VP commission (bps). Matches\n * `VPKeyRegistryLogic.sol` (`commissionBps >= 10000` reverts).\n * The minimum is version-locked (`minVpCommissionBps`) and enforced upstream,\n * not here.\n */\nexport const MAX_VP_COMMISSION_BPS_EXCLUSIVE = 10_000;\n\n/**\n * Basis-points denominator for commission math:\n * `floor(value * bps / BPS_DENOMINATOR)`. Numerically equal to\n * {@link MAX_VP_COMMISSION_BPS_EXCLUSIVE} but a distinct concept — tightening\n * the accepted bps range must never change the arithmetic.\n */\nexport const BPS_DENOMINATOR = 10_000;\n\n/**\n * Contract cap on a registered payout/commission scriptPubKey's byte length\n * (`MAX_PAYOUT_ADDRESS_LENGTH`, Constants.sol; empty scripts are rejected at\n * registration, so valid lengths are `[1, 128]`). A measured length outside\n * this range is provably not a registered script.\n */\nexport const MAX_PAYOUT_SCRIPT_LEN = 128;\n"],"names":["PRE_PEGIN_AUTH_SCRIPT_PREFIX"],"mappings":"aAkDO,MAAMA,EAA+B"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const _ = 2, T = 1, E = 0, s = 0, P = 546, N = 1, O = 0, I = "6a20", U = 546, R = 2, A = 0, S = 2, a = 3, o = 0, c = 4294967294, n = 2, t = 0, C = 2, L = 0, X = 3, G = 2, M = 2, V = 1e4, D = 1e4, Y = 128;
|
|
2
|
+
export {
|
|
3
|
+
s as A,
|
|
4
|
+
D as B,
|
|
5
|
+
M as C,
|
|
6
|
+
T as D,
|
|
7
|
+
V as M,
|
|
8
|
+
G as N,
|
|
9
|
+
R as P,
|
|
10
|
+
n as R,
|
|
11
|
+
X as V,
|
|
12
|
+
t as a,
|
|
13
|
+
Y as b,
|
|
14
|
+
A as c,
|
|
15
|
+
N as d,
|
|
16
|
+
O as e,
|
|
17
|
+
I as f,
|
|
18
|
+
U as g,
|
|
19
|
+
S as h,
|
|
20
|
+
a as i,
|
|
21
|
+
o as j,
|
|
22
|
+
c as k,
|
|
23
|
+
_ as l,
|
|
24
|
+
C as m,
|
|
25
|
+
L as n,
|
|
26
|
+
P as o,
|
|
27
|
+
E as p
|
|
28
|
+
};
|
|
29
|
+
//# sourceMappingURL=constants-D5vORbQE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants-D5vORbQE.js","sources":["../src/tbv/core/primitives/psbt/constants.ts"],"sourcesContent":["/**\n * Protocol invariants for depositor graph transactions.\n *\n * These indices and counts encode the on-chain vault protocol layout\n * (which output of PegIn/Assert each child transaction spends, and how\n * many inputs each transaction has). Consumed by the PSBT builders and\n * the depositor graph signing service; a drift between copies of these\n * values would silently change validation behaviour.\n *\n * @module primitives/psbt/constants\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md\n */\n\n/**\n * Depositor Payout transaction input count.\n * Input 0: PegIn:0 (signed). Input 1: Assert:0 (in sighash, not signed).\n */\nexport const DEPOSITOR_PAYOUT_INPUT_COUNT = 2;\n\n/**\n * Inputs the depositor signs per Payout / NoPayout PSBT: input 0 only. The\n * other inputs are in the SIGHASH_DEFAULT sighash but carry no depositor\n * signature — the Ledger host expects exactly this many yields, so a drift\n * here re-arms an input the device never signs.\n */\nexport const DEPOSITOR_SIGNED_INPUT_COUNT = 1;\n\n/** PegIn vault output index spent by the depositor's Payout input 0. */\nexport const PEGIN_VAULT_OUTPUT_INDEX = 0;\n\n/** Assert output index spent by the depositor's Payout input 1 (NOT signed). */\nexport const ASSERT_PAYOUT_OUTPUT_INDEX = 0;\n\n/**\n * Dust amount (sats) for the payout CPFP anchor output. Matches `DUST_AMOUNT`\n * in `btc-vault crates/vault/src/lib.rs`.\n */\nexport const PAYOUT_ANCHOR_DUST_SATS = 546;\n\n/** Minimum number of HTLC outputs in a Pre-PegIn transaction. */\nexport const PRE_PEGIN_MIN_HTLC_OUTPUT_COUNT = 1;\n\n/** Canonical value in sats for the optional Pre-PegIn auth output. */\nexport const PRE_PEGIN_AUTH_OUTPUT_VALUE_SATS = 0;\n\n/**\n * Hex prefix for `OP_RETURN PUSH32`. This matches\n * `ScriptBuf::new_op_return(hash)` in\n * `btc-vault crates/vault/src/transactions/prepegin.rs`.\n */\nexport const PRE_PEGIN_AUTH_SCRIPT_PREFIX = \"6a20\";\n\n/**\n * Value in sats for the Pre-PegIn CPFP anchor output. Matches `DUST_AMOUNT`\n * in `btc-vault crates/vault/src/lib.rs`.\n */\nexport const PRE_PEGIN_CPFP_VALUE_SATS = 546;\n\n/**\n * Canonical Pre-PegIn transaction version. Matches `Version::TWO` in\n * `btc-vault crates/vault/src/transactions/prepegin.rs`.\n */\nexport const PRE_PEGIN_TX_VERSION = 2;\n\n/**\n * Canonical Pre-PegIn transaction locktime. Matches `LockTime::ZERO` in\n * `btc-vault crates/vault/src/transactions/prepegin.rs`.\n */\nexport const PRE_PEGIN_TX_LOCKTIME = 0;\n\n/** Vault Core 1 PegIn nVersion from `PegInTx::expected_tx_version`. */\nexport const PEGIN_TX_VERSION_CORE_1 = 2;\n\n/** Vault Core 2 and 3 PegIn nVersion from `PegInTx::expected_tx_version`. */\nexport const PEGIN_TX_VERSION_CORE_2_AND_3 = 3;\n\n/** PegIn locktime from `PegInTx::new_from_prepegin` (`LockTime::ZERO`). */\nexport const PEGIN_TX_LOCKTIME = 0;\n\n/** PegIn input sequence from `PegInTx::new_from_prepegin`. */\nexport const PEGIN_INPUT_SEQUENCE = 0xfffffffe;\n\n/**\n * Refund version and locktime match `WasmPrePeginTx::build_refund_tx`\n * (`Version::TWO`, `LockTime::ZERO`) in `btc-vault crates/vault/src/wasm/api.rs`.\n */\nexport const REFUND_TX_VERSION = 2;\nexport const REFUND_TX_LOCKTIME = 0;\n\n/**\n * Payout transaction literals btc-vault builds deterministically\n * (`crates/vault/src/transactions/payout.rs`: `Version::TWO`,\n * `LockTime::ZERO`). The depositor's signature commits to both, so a\n * VP-supplied payout that deviates would produce a signature over a\n * transaction the protocol never constructs.\n */\nexport const PAYOUT_TX_VERSION = 2;\nexport const PAYOUT_TX_LOCKTIME = 0;\n\n/** VP-claimer payout output count: [depositor payout, VP commission, CPFP anchor]. */\nexport const VP_CLAIMER_PAYOUT_OUTPUT_COUNT = 3;\n\n/** Depositor/VK-claimer payout output count: [claimer payout, CPFP anchor]. */\nexport const NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT = 2;\n\n/**\n * ChallengeAssert connectors the VP returns per challenger: one for the\n * ChallengeAssertX transaction and one for ChallengeAssertY — two single-input\n * transactions, not a single multi-input one. This is a per-challenger array\n * cardinality, NOT a count of inputs in one transaction.\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md (ChallengeAssertX / ChallengeAssertY)\n */\nexport const CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER = 2;\n\n/**\n * Exclusive upper bound on VP commission (bps). Matches\n * `VPKeyRegistryLogic.sol` (`commissionBps >= 10000` reverts).\n * The minimum is version-locked (`minVpCommissionBps`) and enforced upstream,\n * not here.\n */\nexport const MAX_VP_COMMISSION_BPS_EXCLUSIVE = 10_000;\n\n/**\n * Basis-points denominator for commission math:\n * `floor(value * bps / BPS_DENOMINATOR)`. Numerically equal to\n * {@link MAX_VP_COMMISSION_BPS_EXCLUSIVE} but a distinct concept — tightening\n * the accepted bps range must never change the arithmetic.\n */\nexport const BPS_DENOMINATOR = 10_000;\n\n/**\n * Contract cap on a registered payout/commission scriptPubKey's byte length\n * (`MAX_PAYOUT_ADDRESS_LENGTH`, Constants.sol; empty scripts are rejected at\n * registration, so valid lengths are `[1, 128]`). A measured length outside\n * this range is provably not a registered script.\n */\nexport const MAX_PAYOUT_SCRIPT_LEN = 128;\n"],"names":["DEPOSITOR_PAYOUT_INPUT_COUNT","DEPOSITOR_SIGNED_INPUT_COUNT","PEGIN_VAULT_OUTPUT_INDEX","ASSERT_PAYOUT_OUTPUT_INDEX","PAYOUT_ANCHOR_DUST_SATS","PRE_PEGIN_MIN_HTLC_OUTPUT_COUNT","PRE_PEGIN_AUTH_OUTPUT_VALUE_SATS","PRE_PEGIN_AUTH_SCRIPT_PREFIX","PRE_PEGIN_CPFP_VALUE_SATS","PRE_PEGIN_TX_VERSION","PRE_PEGIN_TX_LOCKTIME","PEGIN_TX_VERSION_CORE_1","PEGIN_TX_VERSION_CORE_2_AND_3","PEGIN_TX_LOCKTIME","PEGIN_INPUT_SEQUENCE","REFUND_TX_VERSION","REFUND_TX_LOCKTIME","PAYOUT_TX_VERSION","PAYOUT_TX_LOCKTIME","VP_CLAIMER_PAYOUT_OUTPUT_COUNT","NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT","CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER","MAX_VP_COMMISSION_BPS_EXCLUSIVE","BPS_DENOMINATOR","MAX_PAYOUT_SCRIPT_LEN"],"mappings":"AAiBO,MAAMA,IAA+B,GAQ/BC,IAA+B,GAG/BC,IAA2B,GAG3BC,IAA6B,GAM7BC,IAA0B,KAG1BC,IAAkC,GAGlCC,IAAmC,GAOnCC,IAA+B,QAM/BC,IAA4B,KAM5BC,IAAuB,GAMvBC,IAAwB,GAGxBC,IAA0B,GAG1BC,IAAgC,GAGhCC,IAAoB,GAGpBC,IAAuB,YAMvBC,IAAoB,GACpBC,IAAqB,GASrBC,IAAoB,GACpBC,IAAqB,GAGrBC,IAAiC,GAGjCC,IAAqC,GASrCC,IAA6C,GAQ7CC,IAAkC,KAQlCC,IAAkB,KAQlBC,IAAwB;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const b=require("bitcoinjs-lib"),u=require("buffer");function l(t){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(s,n,i.get?i:{enumerable:!0,get:()=>t[n]})}}return s.default=t,Object.freeze(s)}const p=l(b),h=58,N=43,B=11,S=546,f=BigInt(S),g=30,O=2;function d(t){return t<=O?g:0}const I=1,U=1;function F(t,s){if(!Number.isInteger(t)||t<1)throw new Error(`peginOutputCount: vaultCount must be a positive integer, got ${t}`);return t+I+(s?U:0)}const D=5,w=100000n;function m(t){const n=t.substring(8,12)==="0001"?12:8,i=parseInt(t.substring(n,n+2),16),o=parseInt(t.substring(n+2,n+4),16);if(i!==0)throw new Error(`Expected 0 inputs from WASM, got ${i}`);if(o===0)throw new Error("Expected at least 1 output from WASM, got 0");const _=u.Buffer.from(t.substring(0,8),"hex").readUInt32LE(0),a=u.Buffer.from(t.substring(t.length-8),"hex").readUInt32LE(0),E=[];let e=n+4;for(let r=0;r<o;r++){const T=t.substring(e,e+16),L=Number(u.Buffer.from(T,"hex").readBigUInt64LE(0));e+=16;const A=parseInt(t.substring(e,e+2),16);e+=2;const R=t.substring(e,e+A*2),P=u.Buffer.from(R,"hex");e+=A*2,E.push({value:L,script:P})}const c=t.length-8;if(e!==c)throw new Error("WASM transaction outputs do not end immediately before locktime");return{version:_,locktime:a,outputs:E}}function C(t){const{unfundedTxHex:s,selectedUTXOs:n,changeAddress:i,changeAmount:o,network:_}=t,{version:a,locktime:E,outputs:e}=m(s),c=new p.Transaction;c.version=a,c.locktime=E;for(const r of n){const T=u.Buffer.from(r.txid,"hex").reverse();c.addInput(T,r.vout)}for(const r of e)c.addOutput(r.script,r.value);if(o<0n)throw new Error(`fundPeginTransaction: changeAmount cannot be negative, got ${o}`);if(o>0n&&o<=f)throw new Error(`fundPeginTransaction: changeAmount must be 0 or strictly above DUST_THRESHOLD (${f}), got ${o}`);if(o>0n){const r=p.address.toOutputScript(i,_);c.addOutput(r,Number(o))}return c.toHex()}exports.BTC_DUST_SAT=S;exports.DUST_THRESHOLD=f;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=g;exports.MAX_NON_LEGACY_OUTPUT_SIZE=N;exports.MAX_REASONABLE_PEGIN_VBYTES=w;exports.P2TR_INPUT_SIZE=h;exports.PEGIN_AUTH_ANCHOR_OUTPUTS=U;exports.PEGIN_FIXED_OUTPUTS=I;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=D;exports.TX_BUFFER_SIZE_OVERHEAD=B;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=O;exports.fundPeginTransaction=C;exports.parseUnfundedWasmTransaction=m;exports.peginOutputCount=F;exports.rateBasedTxBufferFee=d;
|
|
2
|
+
//# sourceMappingURL=fundPeginTransaction-54-Rwb2k.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fundPeginTransaction-54-Rwb2k.cjs","sources":["../src/tbv/core/utils/fee/constants.ts","../src/tbv/core/utils/transaction/fundPeginTransaction.ts"],"sourcesContent":["/**\n * Fee calculation constants for Bitcoin transactions.\n * Based on btc-staking-ts values, adapted for vault peg-in transactions.\n */\n\n// P2TR input size in vbytes (42 vbytes non-witness + 16 vbytes witness)\nexport const P2TR_INPUT_SIZE = 58;\n\n// P2TR output size in bytes (largest non-legacy output type)\nexport const MAX_NON_LEGACY_OUTPUT_SIZE = 43;\n\n// Base transaction overhead (version, input/output counts, locktime, SegWit marker)\nexport const TX_BUFFER_SIZE_OVERHEAD = 11;\n\n// Dust threshold: outputs below this may not be relayed\nexport const BTC_DUST_SAT = 546;\n\n/** Pre-computed BigInt dust threshold to avoid repeated conversions in hot paths */\nexport const DUST_THRESHOLD = BigInt(BTC_DUST_SAT);\n\n// Buffer for low fee rate estimation accuracy (when feeRate <= 2 sat/vbyte)\nexport const LOW_RATE_ESTIMATION_ACCURACY_BUFFER = 30;\n\n// Wallet relay fee rate threshold - different buffer fees are used based on this\nexport const WALLET_RELAY_FEE_RATE_THRESHOLD = 2;\n\n/**\n * Adds a buffer to the transaction fee calculation if the fee rate is low.\n *\n * Some wallets have a relayer fee requirement. If the fee rate is <= 2 sat/vbyte,\n * there's a risk the fee might not be sufficient for transaction relay.\n * We add a buffer to ensure the transaction can be relayed.\n *\n * @param feeRate - Fee rate in satoshis per vbyte\n * @returns Buffer amount in satoshis to add to the transaction fee\n */\nexport function rateBasedTxBufferFee(feeRate: number): number {\n return feeRate <= WALLET_RELAY_FEE_RATE_THRESHOLD\n ? LOW_RATE_ESTIMATION_ACCURACY_BUFFER\n : 0;\n}\n\n/**\n * Number of always-present fixed (non-HTLC) outputs in a Pre-PegIn\n * transaction. Currently this is 1 CPFP anchor output.\n */\nexport const PEGIN_FIXED_OUTPUTS = 1;\n\n/**\n * Size of the auth-anchor `OP_RETURN` output when committed into a\n * Pre-PegIn. The output carries `OP_RETURN <PUSH32 hash>` = 34 script\n * bytes, plus 8 bytes value + 1 byte scriptLen = ~43 bytes total —\n * same as {@link MAX_NON_LEGACY_OUTPUT_SIZE}. Counted as one output\n * toward the fee-estimation output budget.\n */\nexport const PEGIN_AUTH_ANCHOR_OUTPUTS = 1;\n\n/**\n * Compute the total number of outputs (before change) in a Pre-PegIn\n * transaction.\n *\n * A Pre-PegIn tx has: N HTLC outputs (one per vault) + optional\n * auth-anchor OP_RETURN output + fixed outputs (CPFP anchor). The fee model\n * and the Pre-PegIn layout guard share this count. The change\n * output is handled separately by `selectUtxosForPegin` when the change amount\n * exceeds the dust threshold.\n *\n * @param vaultCount - Number of vaults in the batch (≥1).\n * @param hasAuthAnchor - Whether the Pre-PegIn will carry an auth-anchor\n * OP_RETURN output. Pass the same value the\n * caller will hand to `buildPrePeginPsbt`'s\n * `authAnchorHash` (truthy ↔ true) so the fee\n * budget stays in lockstep with the output set.\n * @returns Total output count before change.\n * @throws If `vaultCount` is not a positive integer.\n */\nexport function peginOutputCount(\n vaultCount: number,\n hasAuthAnchor: boolean,\n): number {\n if (!Number.isInteger(vaultCount) || vaultCount < 1) {\n throw new Error(\n `peginOutputCount: vaultCount must be a positive integer, got ${vaultCount}`,\n );\n }\n return (\n vaultCount +\n PEGIN_FIXED_OUTPUTS +\n (hasAuthAnchor ? PEGIN_AUTH_ANCHOR_OUTPUTS : 0)\n );\n}\n\n/**\n * Safety multiplier for split transaction fee validation.\n * The signed PSBT's fee rate and absolute fee must not exceed this multiple\n * of the planned values. 5x accounts for witness estimation variance while\n * catching catastrophic wallet-side overpayment.\n */\nexport const SPLIT_TX_FEE_SAFETY_MULTIPLIER = 5;\n\n/**\n * Binary-independent cap on the implied per-HTLC reserve\n * (`htlcValue - peginAmount - depositorClaimValue`): the exact identity in\n * `assertWasmPeginSizing` is WASM-vs-WASM, so this pure-JS bound is what\n * limits a doctored binary. 100,000 vbytes = Bitcoin Core's relay ceiling\n * (MAX_STANDARD_TX_WEIGHT / 4) — ~19× the protocol-max PegIn (~5,150 vbytes\n * at 99 VKs + 99 UCs), so it can never false-positive.\n */\nexport const MAX_REASONABLE_PEGIN_VBYTES = 100_000n;\n","/**\n * Transaction Funding Utility for Peg-in Transactions\n *\n * This module funds an unfunded transaction template from the SDK by adding\n * UTXO inputs and change outputs, creating a transaction ready for wallet signing.\n *\n * Transaction Flow:\n * 1. SDK buildPrePeginPsbt() → unfunded Pre-PegIn tx (0 inputs, HTLC + CPFP outputs)\n * 2. selectUtxosForPegin() → select UTXOs and calculate fees\n * 3. fundPeginTransaction() → add inputs/change, create funded transaction\n *\n * Technical Note:\n * We manually extract the vault output from SDK hex instead of using bitcoinjs-lib\n * parsing because bitcoinjs-lib cannot parse 0-input transactions (even witness format).\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { DUST_THRESHOLD } from \"../fee/constants\";\nimport type { UTXO } from \"../utxo/selectUtxos\";\n\nexport interface FundPeginTransactionParams {\n /** Unfunded transaction hex from SDK (0 inputs, vault + depositor claim outputs) */\n unfundedTxHex: string;\n /** Selected UTXOs to use as inputs */\n selectedUTXOs: UTXO[];\n /** Change address (from wallet) */\n changeAddress: string;\n /** Change amount in satoshis */\n changeAmount: bigint;\n /** Bitcoin network */\n network: bitcoin.Network;\n}\n\n/** A single parsed output from the unfunded WASM transaction */\nexport interface ParsedOutput {\n value: number;\n script: Buffer;\n}\n\n/** Parsed data from an unfunded WASM transaction */\ninterface ParsedUnfundedTx {\n version: number;\n locktime: number;\n outputs: ParsedOutput[];\n}\n\n/**\n * Parses an unfunded transaction hex from WASM.\n *\n * WASM produces witness-format transactions with 0 inputs, which bitcoinjs-lib cannot parse.\n * This function manually extracts the transaction components.\n *\n * Format: [version:4bytes][marker:0x00][flag:0x01][inputs:1byte=0x00][outputCount:1byte]\n * [output1: value:8bytes + scriptLen:1byte + script:N bytes]\n * [output2: ...]\n * [locktime:4bytes]\n *\n * @param unfundedTxHex - Raw transaction hex from WASM\n * @returns Parsed transaction components\n * @throws Error if transaction structure is invalid\n */\nexport function parseUnfundedWasmTransaction(\n unfundedTxHex: string,\n): ParsedUnfundedTx {\n // Check if witness markers are present (0x00 0x01 after version)\n const hasWitnessMarkers = unfundedTxHex.substring(8, 12) === \"0001\";\n const dataOffset = hasWitnessMarkers ? 12 : 8; // Skip version (8) + optional witness markers (4)\n\n // Parse input/output counts\n const inputCount = parseInt(\n unfundedTxHex.substring(dataOffset, dataOffset + 2),\n 16,\n );\n const outputCount = parseInt(\n unfundedTxHex.substring(dataOffset + 2, dataOffset + 4),\n 16,\n );\n\n if (inputCount !== 0) {\n throw new Error(`Expected 0 inputs from WASM, got ${inputCount}`);\n }\n if (outputCount === 0) {\n throw new Error(\"Expected at least 1 output from WASM, got 0\");\n }\n\n // Parse version (first 4 bytes, little-endian)\n const version = Buffer.from(unfundedTxHex.substring(0, 8), \"hex\").readUInt32LE(0);\n\n // Parse locktime (last 4 bytes, little-endian)\n const locktime = Buffer.from(\n unfundedTxHex.substring(unfundedTxHex.length - 8),\n \"hex\",\n ).readUInt32LE(0);\n\n // Parse all outputs sequentially\n const outputs: ParsedOutput[] = [];\n let pos = dataOffset + 4; // position after input/output counts\n\n for (let i = 0; i < outputCount; i++) {\n const valueHex = unfundedTxHex.substring(pos, pos + 16);\n const value = Number(Buffer.from(valueHex, \"hex\").readBigUInt64LE(0));\n pos += 16;\n\n const scriptLen = parseInt(unfundedTxHex.substring(pos, pos + 2), 16);\n pos += 2;\n\n const scriptHex = unfundedTxHex.substring(pos, pos + scriptLen * 2);\n const script = Buffer.from(scriptHex, \"hex\");\n pos += scriptLen * 2;\n\n outputs.push({ value, script });\n }\n\n const locktimeOffset = unfundedTxHex.length - 8;\n if (pos !== locktimeOffset) {\n throw new Error(\n \"WASM transaction outputs do not end immediately before locktime\",\n );\n }\n\n return { version, locktime, outputs };\n}\n\n/**\n * Funds an unfunded peg-in transaction by adding inputs and change output.\n *\n * Takes an unfunded transaction template (0 inputs, 1 vault output) from the SDK\n * and adds UTXO inputs and a change output to create a funded transaction ready\n * for wallet signing.\n *\n * @param params - Transaction funding parameters\n * @returns Transaction hex string ready for wallet signing\n */\nexport function fundPeginTransaction(\n params: FundPeginTransactionParams,\n): string {\n const { unfundedTxHex, selectedUTXOs, changeAddress, changeAmount, network } =\n params;\n\n // Parse the unfunded transaction from WASM\n const { version, locktime, outputs } =\n parseUnfundedWasmTransaction(unfundedTxHex);\n\n // Create a new transaction with the extracted data\n const tx = new bitcoin.Transaction();\n tx.version = version;\n tx.locktime = locktime;\n\n // Add inputs from selected UTXOs\n for (const utxo of selectedUTXOs) {\n // Bitcoin uses reversed byte order for txid\n const txHash = Buffer.from(utxo.txid, \"hex\").reverse();\n tx.addInput(txHash, utxo.vout);\n }\n\n // Add all WASM outputs (vault output at index 0, depositor claim at index 1, etc.)\n for (const output of outputs) {\n tx.addOutput(output.script, output.value);\n }\n\n // Trust the selector's change decision: `selectUtxosForPegin` runs every\n // candidate set through `applyChangeOutputPolicy` and returns\n // `changeAmount = 0n` whenever the residual would be at-or-below dust\n // after paying the change-output fee. Validate the contract at this\n // boundary — a hand-built or stale `changeAmount` in (0, DUST_THRESHOLD]\n // would produce a non-relayable dust output, and emitting one would also\n // bypass the canonical fee policy that the selector applied.\n if (changeAmount < 0n) {\n throw new Error(\n `fundPeginTransaction: changeAmount cannot be negative, got ${changeAmount}`,\n );\n }\n if (changeAmount > 0n && changeAmount <= DUST_THRESHOLD) {\n throw new Error(\n `fundPeginTransaction: changeAmount must be 0 or strictly above DUST_THRESHOLD (${DUST_THRESHOLD}), got ${changeAmount}`,\n );\n }\n if (changeAmount > 0n) {\n const changeScript = bitcoin.address.toOutputScript(changeAddress, network);\n tx.addOutput(changeScript, Number(changeAmount));\n }\n\n return tx.toHex();\n}\n\n// Re-export getNetwork from the canonical location in primitives\nexport { getNetwork } from \"../../primitives/utils/bitcoin\";\n"],"names":["P2TR_INPUT_SIZE","MAX_NON_LEGACY_OUTPUT_SIZE","TX_BUFFER_SIZE_OVERHEAD","BTC_DUST_SAT","DUST_THRESHOLD","LOW_RATE_ESTIMATION_ACCURACY_BUFFER","WALLET_RELAY_FEE_RATE_THRESHOLD","rateBasedTxBufferFee","feeRate","PEGIN_FIXED_OUTPUTS","PEGIN_AUTH_ANCHOR_OUTPUTS","peginOutputCount","vaultCount","hasAuthAnchor","SPLIT_TX_FEE_SAFETY_MULTIPLIER","MAX_REASONABLE_PEGIN_VBYTES","parseUnfundedWasmTransaction","unfundedTxHex","dataOffset","inputCount","outputCount","version","Buffer","locktime","outputs","pos","i","valueHex","value","scriptLen","scriptHex","script","locktimeOffset","fundPeginTransaction","params","selectedUTXOs","changeAddress","changeAmount","network","tx","bitcoin","utxo","txHash","output","changeScript"],"mappings":"4VAMaA,EAAkB,GAGlBC,EAA6B,GAG7BC,EAA0B,GAG1BC,EAAe,IAGfC,EAAiB,OAAOD,CAAY,EAGpCE,EAAsC,GAGtCC,EAAkC,EAYxC,SAASC,EAAqBC,EAAyB,CAC5D,OAAOA,GAAWF,EACdD,EACA,CACN,CAMO,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|
6
|
+
}
|
|
7
|
+
const U = 1, b = 1;
|
|
8
|
+
function N(t, i) {
|
|
9
|
+
if (!Number.isInteger(t) || t < 1)
|
|
10
|
+
throw new Error(
|
|
11
|
+
`peginOutputCount: vaultCount must be a positive integer, got ${t}`
|
|
12
|
+
);
|
|
13
|
+
return t + U + (i ? b : 0);
|
|
14
|
+
}
|
|
15
|
+
const B = 5, M = 100000n;
|
|
16
|
+
function L(t) {
|
|
17
|
+
const e = t.substring(8, 12) === "0001" ? 12 : 8, a = parseInt(
|
|
18
|
+
t.substring(e, e + 2),
|
|
19
|
+
16
|
|
20
|
+
), o = parseInt(
|
|
21
|
+
t.substring(e + 2, e + 4),
|
|
22
|
+
16
|
|
23
|
+
);
|
|
24
|
+
if (a !== 0)
|
|
25
|
+
throw new Error(`Expected 0 inputs from WASM, got ${a}`);
|
|
26
|
+
if (o === 0)
|
|
27
|
+
throw new Error("Expected at least 1 output from WASM, got 0");
|
|
28
|
+
const E = c.from(t.substring(0, 8), "hex").readUInt32LE(0), p = c.from(
|
|
29
|
+
t.substring(t.length - 8),
|
|
30
|
+
"hex"
|
|
31
|
+
).readUInt32LE(0), u = [];
|
|
32
|
+
let s = e + 4;
|
|
33
|
+
for (let n = 0; n < o; n++) {
|
|
34
|
+
const _ = t.substring(s, s + 16), m = Number(c.from(_, "hex").readBigUInt64LE(0));
|
|
35
|
+
s += 16;
|
|
36
|
+
const f = parseInt(t.substring(s, s + 2), 16);
|
|
37
|
+
s += 2;
|
|
38
|
+
const A = t.substring(s, s + f * 2), S = c.from(A, "hex");
|
|
39
|
+
s += f * 2, u.push({ value: m, script: S });
|
|
40
|
+
}
|
|
41
|
+
const r = t.length - 8;
|
|
42
|
+
if (s !== r)
|
|
43
|
+
throw new Error(
|
|
44
|
+
"WASM transaction outputs do not end immediately before locktime"
|
|
45
|
+
);
|
|
46
|
+
return { version: E, locktime: p, outputs: u };
|
|
47
|
+
}
|
|
48
|
+
function v(t) {
|
|
49
|
+
const { unfundedTxHex: i, selectedUTXOs: e, changeAddress: a, changeAmount: o, network: E } = t, { version: p, locktime: u, outputs: s } = L(i), r = new g.Transaction();
|
|
50
|
+
r.version = p, r.locktime = u;
|
|
51
|
+
for (const n of e) {
|
|
52
|
+
const _ = c.from(n.txid, "hex").reverse();
|
|
53
|
+
r.addInput(_, n.vout);
|
|
54
|
+
}
|
|
55
|
+
for (const n of s)
|
|
56
|
+
r.addOutput(n.script, n.value);
|
|
57
|
+
if (o < 0n)
|
|
58
|
+
throw new Error(
|
|
59
|
+
`fundPeginTransaction: changeAmount cannot be negative, got ${o}`
|
|
60
|
+
);
|
|
61
|
+
if (o > 0n && o <= T)
|
|
62
|
+
throw new Error(
|
|
63
|
+
`fundPeginTransaction: changeAmount must be 0 or strictly above DUST_THRESHOLD (${T}), got ${o}`
|
|
64
|
+
);
|
|
65
|
+
if (o > 0n) {
|
|
66
|
+
const n = g.address.toOutputScript(a, E);
|
|
67
|
+
r.addOutput(n, Number(o));
|
|
68
|
+
}
|
|
69
|
+
return r.toHex();
|
|
70
|
+
}
|
|
71
|
+
export {
|
|
72
|
+
h as B,
|
|
73
|
+
T as D,
|
|
74
|
+
I as L,
|
|
75
|
+
P as M,
|
|
76
|
+
w as P,
|
|
77
|
+
B as S,
|
|
78
|
+
R as T,
|
|
79
|
+
O as W,
|
|
80
|
+
U as a,
|
|
81
|
+
b,
|
|
82
|
+
M as c,
|
|
83
|
+
L as d,
|
|
84
|
+
v as f,
|
|
85
|
+
N as p,
|
|
86
|
+
d as r
|
|
87
|
+
};
|
|
88
|
+
//# sourceMappingURL=fundPeginTransaction-CwhRbCQC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fundPeginTransaction-CwhRbCQC.js","sources":["../src/tbv/core/utils/fee/constants.ts","../src/tbv/core/utils/transaction/fundPeginTransaction.ts"],"sourcesContent":["/**\n * Fee calculation constants for Bitcoin transactions.\n * Based on btc-staking-ts values, adapted for vault peg-in transactions.\n */\n\n// P2TR input size in vbytes (42 vbytes non-witness + 16 vbytes witness)\nexport const P2TR_INPUT_SIZE = 58;\n\n// P2TR output size in bytes (largest non-legacy output type)\nexport const MAX_NON_LEGACY_OUTPUT_SIZE = 43;\n\n// Base transaction overhead (version, input/output counts, locktime, SegWit marker)\nexport const TX_BUFFER_SIZE_OVERHEAD = 11;\n\n// Dust threshold: outputs below this may not be relayed\nexport const BTC_DUST_SAT = 546;\n\n/** Pre-computed BigInt dust threshold to avoid repeated conversions in hot paths */\nexport const DUST_THRESHOLD = BigInt(BTC_DUST_SAT);\n\n// Buffer for low fee rate estimation accuracy (when feeRate <= 2 sat/vbyte)\nexport const LOW_RATE_ESTIMATION_ACCURACY_BUFFER = 30;\n\n// Wallet relay fee rate threshold - different buffer fees are used based on this\nexport const WALLET_RELAY_FEE_RATE_THRESHOLD = 2;\n\n/**\n * Adds a buffer to the transaction fee calculation if the fee rate is low.\n *\n * Some wallets have a relayer fee requirement. If the fee rate is <= 2 sat/vbyte,\n * there's a risk the fee might not be sufficient for transaction relay.\n * We add a buffer to ensure the transaction can be relayed.\n *\n * @param feeRate - Fee rate in satoshis per vbyte\n * @returns Buffer amount in satoshis to add to the transaction fee\n */\nexport function rateBasedTxBufferFee(feeRate: number): number {\n return feeRate <= WALLET_RELAY_FEE_RATE_THRESHOLD\n ? LOW_RATE_ESTIMATION_ACCURACY_BUFFER\n : 0;\n}\n\n/**\n * Number of always-present fixed (non-HTLC) outputs in a Pre-PegIn\n * transaction. Currently this is 1 CPFP anchor output.\n */\nexport const PEGIN_FIXED_OUTPUTS = 1;\n\n/**\n * Size of the auth-anchor `OP_RETURN` output when committed into a\n * Pre-PegIn. The output carries `OP_RETURN <PUSH32 hash>` = 34 script\n * bytes, plus 8 bytes value + 1 byte scriptLen = ~43 bytes total —\n * same as {@link MAX_NON_LEGACY_OUTPUT_SIZE}. Counted as one output\n * toward the fee-estimation output budget.\n */\nexport const PEGIN_AUTH_ANCHOR_OUTPUTS = 1;\n\n/**\n * Compute the total number of outputs (before change) in a Pre-PegIn\n * transaction.\n *\n * A Pre-PegIn tx has: N HTLC outputs (one per vault) + optional\n * auth-anchor OP_RETURN output + fixed outputs (CPFP anchor). The fee model\n * and the Pre-PegIn layout guard share this count. The change\n * output is handled separately by `selectUtxosForPegin` when the change amount\n * exceeds the dust threshold.\n *\n * @param vaultCount - Number of vaults in the batch (≥1).\n * @param hasAuthAnchor - Whether the Pre-PegIn will carry an auth-anchor\n * OP_RETURN output. Pass the same value the\n * caller will hand to `buildPrePeginPsbt`'s\n * `authAnchorHash` (truthy ↔ true) so the fee\n * budget stays in lockstep with the output set.\n * @returns Total output count before change.\n * @throws If `vaultCount` is not a positive integer.\n */\nexport function peginOutputCount(\n vaultCount: number,\n hasAuthAnchor: boolean,\n): number {\n if (!Number.isInteger(vaultCount) || vaultCount < 1) {\n throw new Error(\n `peginOutputCount: vaultCount must be a positive integer, got ${vaultCount}`,\n );\n }\n return (\n vaultCount +\n PEGIN_FIXED_OUTPUTS +\n (hasAuthAnchor ? PEGIN_AUTH_ANCHOR_OUTPUTS : 0)\n );\n}\n\n/**\n * Safety multiplier for split transaction fee validation.\n * The signed PSBT's fee rate and absolute fee must not exceed this multiple\n * of the planned values. 5x accounts for witness estimation variance while\n * catching catastrophic wallet-side overpayment.\n */\nexport const SPLIT_TX_FEE_SAFETY_MULTIPLIER = 5;\n\n/**\n * Binary-independent cap on the implied per-HTLC reserve\n * (`htlcValue - peginAmount - depositorClaimValue`): the exact identity in\n * `assertWasmPeginSizing` is WASM-vs-WASM, so this pure-JS bound is what\n * limits a doctored binary. 100,000 vbytes = Bitcoin Core's relay ceiling\n * (MAX_STANDARD_TX_WEIGHT / 4) — ~19× the protocol-max PegIn (~5,150 vbytes\n * at 99 VKs + 99 UCs), so it can never false-positive.\n */\nexport const MAX_REASONABLE_PEGIN_VBYTES = 100_000n;\n","/**\n * Transaction Funding Utility for Peg-in Transactions\n *\n * This module funds an unfunded transaction template from the SDK by adding\n * UTXO inputs and change outputs, creating a transaction ready for wallet signing.\n *\n * Transaction Flow:\n * 1. SDK buildPrePeginPsbt() → unfunded Pre-PegIn tx (0 inputs, HTLC + CPFP outputs)\n * 2. selectUtxosForPegin() → select UTXOs and calculate fees\n * 3. fundPeginTransaction() → add inputs/change, create funded transaction\n *\n * Technical Note:\n * We manually extract the vault output from SDK hex instead of using bitcoinjs-lib\n * parsing because bitcoinjs-lib cannot parse 0-input transactions (even witness format).\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { DUST_THRESHOLD } from \"../fee/constants\";\nimport type { UTXO } from \"../utxo/selectUtxos\";\n\nexport interface FundPeginTransactionParams {\n /** Unfunded transaction hex from SDK (0 inputs, vault + depositor claim outputs) */\n unfundedTxHex: string;\n /** Selected UTXOs to use as inputs */\n selectedUTXOs: UTXO[];\n /** Change address (from wallet) */\n changeAddress: string;\n /** Change amount in satoshis */\n changeAmount: bigint;\n /** Bitcoin network */\n network: bitcoin.Network;\n}\n\n/** A single parsed output from the unfunded WASM transaction */\nexport interface ParsedOutput {\n value: number;\n script: Buffer;\n}\n\n/** Parsed data from an unfunded WASM transaction */\ninterface ParsedUnfundedTx {\n version: number;\n locktime: number;\n outputs: ParsedOutput[];\n}\n\n/**\n * Parses an unfunded transaction hex from WASM.\n *\n * WASM produces witness-format transactions with 0 inputs, which bitcoinjs-lib cannot parse.\n * This function manually extracts the transaction components.\n *\n * Format: [version:4bytes][marker:0x00][flag:0x01][inputs:1byte=0x00][outputCount:1byte]\n * [output1: value:8bytes + scriptLen:1byte + script:N bytes]\n * [output2: ...]\n * [locktime:4bytes]\n *\n * @param unfundedTxHex - Raw transaction hex from WASM\n * @returns Parsed transaction components\n * @throws Error if transaction structure is invalid\n */\nexport function parseUnfundedWasmTransaction(\n unfundedTxHex: string,\n): ParsedUnfundedTx {\n // Check if witness markers are present (0x00 0x01 after version)\n const hasWitnessMarkers = unfundedTxHex.substring(8, 12) === \"0001\";\n const dataOffset = hasWitnessMarkers ? 12 : 8; // Skip version (8) + optional witness markers (4)\n\n // Parse input/output counts\n const inputCount = parseInt(\n unfundedTxHex.substring(dataOffset, dataOffset + 2),\n 16,\n );\n const outputCount = parseInt(\n unfundedTxHex.substring(dataOffset + 2, dataOffset + 4),\n 16,\n );\n\n if (inputCount !== 0) {\n throw new Error(`Expected 0 inputs from WASM, got ${inputCount}`);\n }\n if (outputCount === 0) {\n throw new Error(\"Expected at least 1 output from WASM, got 0\");\n }\n\n // Parse version (first 4 bytes, little-endian)\n const version = Buffer.from(unfundedTxHex.substring(0, 8), \"hex\").readUInt32LE(0);\n\n // Parse locktime (last 4 bytes, little-endian)\n const locktime = Buffer.from(\n unfundedTxHex.substring(unfundedTxHex.length - 8),\n \"hex\",\n ).readUInt32LE(0);\n\n // Parse all outputs sequentially\n const outputs: ParsedOutput[] = [];\n let pos = dataOffset + 4; // position after input/output counts\n\n for (let i = 0; i < outputCount; i++) {\n const valueHex = unfundedTxHex.substring(pos, pos + 16);\n const value = Number(Buffer.from(valueHex, \"hex\").readBigUInt64LE(0));\n pos += 16;\n\n const scriptLen = parseInt(unfundedTxHex.substring(pos, pos + 2), 16);\n pos += 2;\n\n const scriptHex = unfundedTxHex.substring(pos, pos + scriptLen * 2);\n const script = Buffer.from(scriptHex, \"hex\");\n pos += scriptLen * 2;\n\n outputs.push({ value, script });\n }\n\n const locktimeOffset = unfundedTxHex.length - 8;\n if (pos !== locktimeOffset) {\n throw new Error(\n \"WASM transaction outputs do not end immediately before locktime\",\n );\n }\n\n return { version, locktime, outputs };\n}\n\n/**\n * Funds an unfunded peg-in transaction by adding inputs and change output.\n *\n * Takes an unfunded transaction template (0 inputs, 1 vault output) from the SDK\n * and adds UTXO inputs and a change output to create a funded transaction ready\n * for wallet signing.\n *\n * @param params - Transaction funding parameters\n * @returns Transaction hex string ready for wallet signing\n */\nexport function fundPeginTransaction(\n params: FundPeginTransactionParams,\n): string {\n const { unfundedTxHex, selectedUTXOs, changeAddress, changeAmount, network } =\n params;\n\n // Parse the unfunded transaction from WASM\n const { version, locktime, outputs } =\n parseUnfundedWasmTransaction(unfundedTxHex);\n\n // Create a new transaction with the extracted data\n const tx = new bitcoin.Transaction();\n tx.version = version;\n tx.locktime = locktime;\n\n // Add inputs from selected UTXOs\n for (const utxo of selectedUTXOs) {\n // Bitcoin uses reversed byte order for txid\n const txHash = Buffer.from(utxo.txid, \"hex\").reverse();\n tx.addInput(txHash, utxo.vout);\n }\n\n // Add all WASM outputs (vault output at index 0, depositor claim at index 1, etc.)\n for (const output of outputs) {\n tx.addOutput(output.script, output.value);\n }\n\n // Trust the selector's change decision: `selectUtxosForPegin` runs every\n // candidate set through `applyChangeOutputPolicy` and returns\n // `changeAmount = 0n` whenever the residual would be at-or-below dust\n // after paying the change-output fee. Validate the contract at this\n // boundary — a hand-built or stale `changeAmount` in (0, DUST_THRESHOLD]\n // would produce a non-relayable dust output, and emitting one would also\n // bypass the canonical fee policy that the selector applied.\n if (changeAmount < 0n) {\n throw new Error(\n `fundPeginTransaction: changeAmount cannot be negative, got ${changeAmount}`,\n );\n }\n if (changeAmount > 0n && changeAmount <= DUST_THRESHOLD) {\n throw new Error(\n `fundPeginTransaction: changeAmount must be 0 or strictly above DUST_THRESHOLD (${DUST_THRESHOLD}), got ${changeAmount}`,\n );\n }\n if (changeAmount > 0n) {\n const changeScript = bitcoin.address.toOutputScript(changeAddress, network);\n tx.addOutput(changeScript, Number(changeAmount));\n }\n\n return tx.toHex();\n}\n\n// Re-export getNetwork from the canonical location in primitives\nexport { getNetwork } from \"../../primitives/utils/bitcoin\";\n"],"names":["P2TR_INPUT_SIZE","MAX_NON_LEGACY_OUTPUT_SIZE","TX_BUFFER_SIZE_OVERHEAD","BTC_DUST_SAT","DUST_THRESHOLD","LOW_RATE_ESTIMATION_ACCURACY_BUFFER","WALLET_RELAY_FEE_RATE_THRESHOLD","rateBasedTxBufferFee","feeRate","PEGIN_FIXED_OUTPUTS","PEGIN_AUTH_ANCHOR_OUTPUTS","peginOutputCount","vaultCount","hasAuthAnchor","SPLIT_TX_FEE_SAFETY_MULTIPLIER","MAX_REASONABLE_PEGIN_VBYTES","parseUnfundedWasmTransaction","unfundedTxHex","dataOffset","inputCount","outputCount","version","Buffer","locktime","outputs","pos","i","valueHex","value","scriptLen","scriptHex","script","locktimeOffset","fundPeginTransaction","params","selectedUTXOs","changeAddress","changeAmount","network","tx","bitcoin","utxo","txHash","output","changeScript"],"mappings":";;AAMO,MAAMA,IAAkB,IAGlBC,IAA6B,IAG7BC,IAA0B,IAG1BC,IAAe,KAGfC,IAAiB,OAAOD,CAAY,GAGpCE,IAAsC,IAGtCC,IAAkC;AAYxC,SAASC,EAAqBC,GAAyB;AAC5D,SAAOA,KAAWF,IACdD,IACA;AACN;AAMO,MAAMI,IAAsB,GAStBC,IAA4B;AAqBlC,SAASC,EACdC,GACAC,GACQ;AACR,MAAI,CAAC,OAAO,UAAUD,CAAU,KAAKA,IAAa;AAChD,UAAM,IAAI;AAAA,MACR,gEAAgEA,CAAU;AAAA,IAAA;AAG9E,SACEA,IACAH,KACCI,IAAgBH,IAA4B;AAEjD;AAQO,MAAMI,IAAiC,GAUjCC,IAA8B;AC7CpC,SAASC,EACdC,GACkB;AAGlB,QAAMC,IADoBD,EAAc,UAAU,GAAG,EAAE,MAAM,SACtB,KAAK,GAGtCE,IAAa;AAAA,IACjBF,EAAc,UAAUC,GAAYA,IAAa,CAAC;AAAA,IAClD;AAAA,EAAA,GAEIE,IAAc;AAAA,IAClBH,EAAc,UAAUC,IAAa,GAAGA,IAAa,CAAC;AAAA,IACtD;AAAA,EAAA;AAGF,MAAIC,MAAe;AACjB,UAAM,IAAI,MAAM,oCAAoCA,CAAU,EAAE;AAElE,MAAIC,MAAgB;AAClB,UAAM,IAAI,MAAM,6CAA6C;AAI/D,QAAMC,IAAUC,EAAO,KAAKL,EAAc,UAAU,GAAG,CAAC,GAAG,KAAK,EAAE,aAAa,CAAC,GAG1EM,IAAWD,EAAO;AAAA,I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e,EAAG,UAAUI,EAAO,QAAQA,EAAO,KAAK;AAU1C,MAAIN,IAAe;AACjB,UAAM,IAAI;AAAA,MACR,8DAA8DA,CAAY;AAAA,IAAA;AAG9E,MAAIA,IAAe,MAAMA,KAAgBjC;AACvC,UAAM,IAAI;AAAA,MACR,kFAAkFA,CAAc,UAAUiC,CAAY;AAAA,IAAA;AAG1H,MAAIA,IAAe,IAAI;AACrB,UAAMO,IAAeJ,EAAQ,QAAQ,eAAeJ,GAAeE,CAAO;AAC1E,IAAAC,EAAG,UAAUK,GAAc,OAAOP,CAAY,CAAC;AAAA,EACjD;AAEA,SAAOE,EAAG,MAAA;AACZ;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var G=Object.defineProperty;var O=(s,e,t)=>e in s?G(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var E=(s,e,t)=>O(s,typeof e!="symbol"?e+"":e,t);const j=require("./json-rpc-client-BiAmg_ho.cjs"),C=require("./constants-Bh38W9mq.cjs"),m=require("./validation-C6XTfZak.cjs"),k=new Set(Object.values(j.DaemonStatus)),q=200;function a(s){var e;return((e=JSON.stringify(s))==null?void 0:e.slice(0,q))??"undefined"}const H="The vault provider returned an unexpected response. Please try again or contact support.";class n extends Error{constructor(t){super(H);E(this,"detail");this.name="VpResponseValidationError",this.detail=t}}const b=64;function h(s){return typeof s=="string"&&s.length>0&&m.HEX_RE.test(s)}function D(s){return typeof s=="string"&&s.length>0}function T(s,e){if(!h(s))throw new n(`VP response validation failed: "${e}" must be a non-empty hex string, got ${a(s)}`)}function _(s,e){if(!D(s))throw new n(`VP response validation failed: "${e}" must be a non-empty string, got ${a(s)}`)}function S(s,e){if(!h(s)||s.length!==m.X_ONLY_PUBKEY_HEX_LEN&&s.length!==m.COMPRESSED_PUBKEY_HEX_LEN)throw new n(`VP response validation failed: "${e}" must be a ${m.X_ONLY_PUBKEY_HEX_LEN} or ${m.COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${a(s)}`)}function M(s){const e=s.presigning;if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new n('VP response validation failed: "progress.presigning" must be an object if present');const t=e;if(t.depositor_graph_created!==void 0&&typeof t.depositor_graph_created!="boolean")throw new n(`VP response validation failed: "progress.presigning.depositor_graph_created" must be a boolean if present, got ${a(t.depositor_graph_created)}`);if(t.vk_challenger_presigning_completed!==void 0&&typeof t.vk_challenger_presigning_completed!="number")throw new n(`VP response validation failed: "progress.presigning.vk_challenger_presigning_completed" must be a number if present, got ${a(t.vk_challenger_presigning_completed)}`);if(t.vk_challenger_presigning_total!==void 0&&typeof t.vk_challenger_presigning_total!="number")throw new n(`VP response validation failed: "progress.presigning.vk_challenger_presigning_total" must be a number if present, got ${a(t.vk_challenger_presigning_total)}`)}function L(s){if(s===null||typeof s!="object")throw new n("VP response validation failed: getPeginStatus response is not an object");const e=s;if(!h(e.pegin_txid)||e.pegin_txid.length!==b)throw new n(`VP response validation failed: "pegin_txid" must be a ${b}-char hex string (txid), got ${a(e.pegin_txid)}`);if(typeof e.status!="string")throw new n('VP response validation failed: "status" must be a string');if(!k.has(e.status))throw new n(`VP response validation failed: unrecognized status "${e.status}". Expected one of: ${[...k].join(", ")}`);if(e.progress===null||typeof e.progress!="object"||Array.isArray(e.progress))throw new n('VP response validation failed: "progress" must be an object');if(M(e.progress),typeof e.health_info!="string")throw new n('VP response validation failed: "health_info" must be a string');if(e.last_error!==void 0&&typeof e.last_error!="string")throw new n(`VP response validation failed: "last_error" must be a string if present, got ${a(e.last_error)}`)}function X(s){if(s===null||typeof s!="object")throw new n("VP response validation failed: requestDepositorPresignTransactions response is not an object");const e=s;if(!Array.isArray(e.txs))throw new n('VP response validation failed: "txs" must be an array');for(let t=0;t<e.txs.length;t++)U(e.txs[t],`txs[${t}]`);if(e.depositor_graph===null||typeof e.depositor_graph!="object")throw new n('VP response validation failed: "depositor_graph" must be an object');Z(e.depositor_graph)}function g(s,e){if(s===null||typeof s!="object")throw new n(`VP response validation failed: "${e}" must be an object`);T(s.tx_hex,`${e}.tx_hex`)}function U(s,e){if(s===null||typeof s!="object")throw new n(`VP response validation failed: "${e}" must be an object`);const t=s;S(t.claimer_pubkey,`${e}.claimer_pubkey`),g(t.claim_tx,`${e}.claim_tx`),g(t.assert_tx,`${e}.assert_tx`),g(t.payout_tx,`${e}.payout_tx`),_(t.payout_psbt,`${e}.payout_psbt`)}function I(s,e){if(s===null||typeof s!="object")throw new n(`VP response validation failed: "${e}" must be an object`);const t=s;_(t.wots_pks_json,`${e}.wots_pks_json`),_(t.gc_wots_keys_json,`${e}.gc_wots_keys_json`)}function K(s,e){if(s===null||typeof s!="object")throw new n(`VP response validation failed: "${e}" must be an object`);const t=s;if(S(t.challenger_pubkey,`${e}.challenger_pubkey`),g(t.challenge_assert_x_tx,`${e}.challenge_assert_x_tx`),g(t.challenge_assert_y_tx,`${e}.challenge_assert_y_tx`),g(t.nopayout_tx,`${e}.nopayout_tx`),_(t.nopayout_psbt,`${e}.nopayout_psbt`),!Array.isArray(t.challenge_assert_connectors))throw new n(`VP response validation failed: "${e}.challenge_assert_connectors" must be an array`);if(t.challenge_assert_connectors.length!==C.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER)throw new n(`VP response validation failed: "${e}.challenge_assert_connectors" must have exactly ${C.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER} entries, got ${t.challenge_assert_connectors.length}`);for(let r=0;r<t.challenge_assert_connectors.length;r++)I(t.challenge_assert_connectors[r],`${e}.challenge_assert_connectors[${r}]`);if(!Array.isArray(t.output_label_hashes))throw new n(`VP response validation failed: "${e}.output_label_hashes" must be an array`);for(let r=0;r<t.output_label_hashes.length;r++)T(t.output_label_hashes[r],`${e}.output_label_hashes[${r}]`)}function N(s){if(s===null||typeof s!="object")throw new n("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const e=s;if(!D(e.tx_graph_json))throw new n(`VP response validation failed: "tx_graph_json" must be a non-empty string, got ${a(e.tx_graph_json)}`);if(!h(e.verifying_key_hex))throw new n(`VP response validation failed: "verifying_key_hex" must be a non-empty hex string, got ${a(e.verifying_key_hex)}`);if(e.babe_sessions===null||typeof e.babe_sessions!="object"||Array.isArray(e.babe_sessions))throw new n('VP response validation failed: "babe_sessions" must be an object');const t=Object.entries(e.babe_sessions);if(t.length===0)throw new n('VP response validation failed: "babe_sessions" must contain at least one challenger entry');for(const[r,o]of t){if(S(r,`babe_sessions["${r}"]`),o===null||typeof o!="object")throw new n(`VP response validation failed: "babe_sessions.${r}" must be an object`);const c=o;if(!h(c.decryptor_artifacts_hex))throw new n(`VP response validation failed: "babe_sessions.${r}.decryptor_artifacts_hex" must be a non-empty hex string, got ${a(c.decryptor_artifacts_hex)}`)}}function Y(s){if(s===null||typeof s!="object")throw new n("VP response validation failed: pegout status payload is not an object");const e=s;if(!h(e.pegin_txid)||e.pegin_txid.length!==b)throw new n(`VP response validation failed: "pegin_txid" must be a ${b}-char hex string (txid), got ${a(e.pegin_txid)}`);if(typeof e.found!="boolean")throw new n(`VP response validation failed: "found" must be a boolean, got ${a(e.found)}`);if(e.claimer!==null){if(typeof e.claimer!="object")throw new n(`VP response validation failed: "claimer" must be an object or null, got ${a(e.claimer)}`);z(e.claimer)}if(!Array.isArray(e.challengers))throw new n(`VP response validation failed: "challengers" must be an array, got ${a(e.challengers)}`);for(let t=0;t<e.challengers.length;t++)F(e.challengers[t],t)}function z(s){if(_(s.status,"claimer.status"),typeof s.failed!="boolean")throw new n(`VP response validation failed: "claimer.failed" must be a boolean, got ${a(s.failed)}`);if(_(s.claim_txid,"claimer.claim_txid"),_(s.claimer_pubkey,"claimer.claimer_pubkey"),_(s.assert_txid,"claimer.assert_txid"),typeof s.created_at!="number")throw new n(`VP response validation failed: "claimer.created_at" must be a number, got ${a(s.created_at)}`);if(typeof s.updated_at!="number")throw new n(`VP response validation failed: "claimer.updated_at" must be a number, got ${a(s.updated_at)}`)}function F(s,e){if(s===null||typeof s!="object")throw new n(`VP response validation failed: "challengers[${e}]" must be an object, got ${a(s)}`);const t=s;if(_(t.status,`challengers[${e}].status`),_(t.claim_txid,`challengers[${e}].claim_txid`),_(t.claimer_pubkey,`challengers[${e}].claimer_pubkey`),v(t.assert_txid,`challengers[${e}].assert_txid`),v(t.challenge_assert_x_txid,`challengers[${e}].challenge_assert_x_txid`),v(t.challenge_assert_y_txid,`challengers[${e}].challenge_assert_y_txid`),v(t.nopayout_txid,`challengers[${e}].nopayout_txid`),typeof t.created_at!="number")throw new n(`VP response validation failed: "challengers[${e}].created_at" must be a number, got ${a(t.created_at)}`);if(typeof t.updated_at!="number")throw new n(`VP response validation failed: "challengers[${e}].updated_at" must be a number, got ${a(t.updated_at)}`)}function v(s,e){if(s!==null&&typeof s!="string")throw new n(`VP response validation failed: "${e}" must be a string or null, got ${a(s)}`)}function W(s){B(s,"batchGetPeginStatus",e=>{e.result!==null&&L(e.result)})}function J(s){B(s,"batchGetPegoutStatus",e=>{e.result!==null&&Y(e.result)})}function B(s,e,t){if(s===null||typeof s!="object")throw new n(`VP response validation failed: ${e} response is not an object`);const r=s;if(!Array.isArray(r.results))throw new n(`VP response validation failed: "${e}.results" must be an array, got ${a(r.results)}`);for(let o=0;o<r.results.length;o++){const c=r.results[o];if(c===null||typeof c!="object")throw new n(`VP response validation failed: "${e}.results[${o}]" must be an object, got ${a(c)}`);const i=c;if(!h(i.pegin_txid)||i.pegin_txid.length!==b)throw new n(`VP response validation failed: "${e}.results[${o}].pegin_txid" must be a ${b}-char hex string, got ${a(i.pegin_txid)}`);if(i.error!==null&&typeof i.error!="string")throw new n(`VP response validation failed: "${e}.results[${o}].error" must be a string or null, got ${a(i.error)}`);if(i.result===null&&i.error===null)throw new n(`VP response validation failed: "${e}.results[${o}]" has neither "result" nor "error" populated`);if(i.result!==null&&i.error!==null)throw new n(`VP response validation failed: "${e}.results[${o}]" has both "result" and "error" populated`);t(i,o)}}function Z(s){if(g(s.claim_tx,"depositor_graph.claim_tx"),g(s.assert_tx,"depositor_graph.assert_tx"),g(s.payout_tx,"depositor_graph.payout_tx"),_(s.payout_psbt,"depositor_graph.payout_psbt"),!Array.isArray(s.challenger_presign_data))throw new n('VP response validation failed: "depositor_graph.challenger_presign_data" must be an array');for(let e=0;e<s.challenger_presign_data.length;e++)K(s.challenger_presign_data[e],`depositor_graph.challenger_presign_data[${e}]`);if(typeof s.offchain_params_version!="number")throw new n('VP response validation failed: "depositor_graph.offchain_params_version" must be a number')}const Q=6e4;class ee{constructor(e,t){E(this,"client");const r={baseUrl:e,timeout:(t==null?void 0:t.timeout)??Q,retries:t==null?void 0:t.retries,retryDelay:t==null?void 0:t.retryDelay,retryableFor:t==null?void 0:t.retryableFor,headers:t==null?void 0:t.headers,tokenProvider:t==null?void 0:t.tokenProvider,maxResponseBytes:t==null?void 0:t.maxResponseBytes};this.client=new j.JsonRpcClient(r)}async requestDepositorPresignTransactions(e,t){const r=await this.client.call("vaultProvider_requestDepositorPresignTransactions",e,t);return X(r),r}async submitDepositorPresignatures(e,t){return this.client.call("vaultProvider_submitDepositorPresignatures",e,t)}async submitDepositorWotsKey(e,t){return this.client.call("vaultProvider_submitDepositorWotsKey",e,t)}async requestDepositorClaimerArtifacts(e,t){const r=await this.client.call("vaultProvider_requestDepositorClaimerArtifacts",e,t);return N(r),r}async getPeginStatus(e,t){const r=await this.client.call("vaultProvider_getPeginStatus",e,t);return L(r),r}async batchGetPeginStatus(e,t){const r=await this.client.call("vaultProvider_batchGetPeginStatus",e,t);return W(r),r}async batchGetPegoutStatus(e,t){const r=await this.client.call("vaultProvider_batchGetPegoutStatus",e,t);return J(r),r}}function te(s,e){const t=new Set;for(const p of s)t.add(p.toLowerCase());const r=new Map,o=new Set,c=[],i=[];for(const p of e){const d=p.pegin_txid.toLowerCase();if(!t.has(d)){i.push(d);continue}if(o.has(d)){c.push(d);continue}o.add(d),r.set(d,{result:p.result,error:p.error})}const y=[];for(const p of t)o.has(p)||y.push(p);return{byTxid:r,missing:y,unexpected:i,duplicate:c}}async function se(s){const{items:e,getTxid:t,batchCall:r,onItem:o,onMissing:c,onDuplicate:i,onDuplicateBatch:y,onWholeBatchError:p,onUnexpected:d,batchSize:w=j.VP_BATCH_MAX_SIZE}=s;if(!Number.isInteger(w)||w<=0)throw new Error(`batchPollByProvider: batchSize must be a positive integer, got ${w}`);for(let P=0;P<e.length;P+=w){const A=e.slice(P,P+w),x=new Map,V=[];for(const l of A){const u=t(l).toLowerCase();x.set(u,l),V.push(u)}let f;try{const l=await r(V);f=te(V,l.results)}catch(l){p(A,l);continue}d&&f.unexpected.length>0&&d(f.unexpected);const $=new Set(f.duplicate);for(const l of $){const u=x.get(l);u&&i(u)}y&&$.size>0&&y($.size);for(const l of f.missing){const u=x.get(l);u&&c(u)}for(const[l,u]of f.byTxid){if($.has(l))continue;const R=x.get(l);R&&o(R,{pegin_txid:l,result:u.result,error:u.error})}}}exports.VaultProviderRpcClient=ee;exports.VpResponseValidationError=n;exports.batchPollByProvider=se;exports.validateRequestDepositorClaimerArtifactsResponse=N;
|
|
2
|
-
//# sourceMappingURL=index-
|
|
1
|
+
"use strict";var G=Object.defineProperty;var O=(s,e,t)=>e in s?G(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var E=(s,e,t)=>O(s,typeof e!="symbol"?e+"":e,t);const j=require("./json-rpc-client-BiAmg_ho.cjs"),C=require("./constants-BTZdyOuk.cjs"),m=require("./validation-C6XTfZak.cjs"),k=new Set(Object.values(j.DaemonStatus)),q=200;function a(s){var e;return((e=JSON.stringify(s))==null?void 0:e.slice(0,q))??"undefined"}const H="The vault provider returned an unexpected response. Please try again or contact support.";class n extends Error{constructor(t){super(H);E(this,"detail");this.name="VpResponseValidationError",this.detail=t}}const b=64;function h(s){return typeof s=="string"&&s.length>0&&m.HEX_RE.test(s)}function D(s){return typeof s=="string"&&s.length>0}function T(s,e){if(!h(s))throw new n(`VP response validation failed: "${e}" must be a non-empty hex string, got ${a(s)}`)}function _(s,e){if(!D(s))throw new n(`VP response validation failed: "${e}" must be a non-empty string, got ${a(s)}`)}function S(s,e){if(!h(s)||s.length!==m.X_ONLY_PUBKEY_HEX_LEN&&s.length!==m.COMPRESSED_PUBKEY_HEX_LEN)throw new n(`VP response validation failed: "${e}" must be a ${m.X_ONLY_PUBKEY_HEX_LEN} or ${m.COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${a(s)}`)}function M(s){const e=s.presigning;if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new n('VP response validation failed: "progress.presigning" must be an object if present');const t=e;if(t.depositor_graph_created!==void 0&&typeof t.depositor_graph_created!="boolean")throw new n(`VP response validation failed: "progress.presigning.depositor_graph_created" must be a boolean if present, got ${a(t.depositor_graph_created)}`);if(t.vk_challenger_presigning_completed!==void 0&&typeof t.vk_challenger_presigning_completed!="number")throw new n(`VP response validation failed: "progress.presigning.vk_challenger_presigning_completed" must be a number if present, got ${a(t.vk_challenger_presigning_completed)}`);if(t.vk_challenger_presigning_total!==void 0&&typeof t.vk_challenger_presigning_total!="number")throw new n(`VP response validation failed: "progress.presigning.vk_challenger_presigning_total" must be a number if present, got ${a(t.vk_challenger_presigning_total)}`)}function L(s){if(s===null||typeof s!="object")throw new n("VP response validation failed: getPeginStatus response is not an object");const e=s;if(!h(e.pegin_txid)||e.pegin_txid.length!==b)throw new n(`VP response validation failed: "pegin_txid" must be a ${b}-char hex string (txid), got ${a(e.pegin_txid)}`);if(typeof e.status!="string")throw new n('VP response validation failed: "status" must be a string');if(!k.has(e.status))throw new n(`VP response validation failed: unrecognized status "${e.status}". Expected one of: ${[...k].join(", ")}`);if(e.progress===null||typeof e.progress!="object"||Array.isArray(e.progress))throw new n('VP response validation failed: "progress" must be an object');if(M(e.progress),typeof e.health_info!="string")throw new n('VP response validation failed: "health_info" must be a string');if(e.last_error!==void 0&&typeof e.last_error!="string")throw new n(`VP response validation failed: "last_error" must be a string if present, got ${a(e.last_error)}`)}function X(s){if(s===null||typeof s!="object")throw new n("VP response validation failed: requestDepositorPresignTransactions response is not an object");const e=s;if(!Array.isArray(e.txs))throw new n('VP response validation failed: "txs" must be an array');for(let t=0;t<e.txs.length;t++)U(e.txs[t],`txs[${t}]`);if(e.depositor_graph===null||typeof e.depositor_graph!="object")throw new n('VP response validation failed: "depositor_graph" must be an object');Z(e.depositor_graph)}function g(s,e){if(s===null||typeof s!="object")throw new n(`VP response validation failed: "${e}" must be an object`);T(s.tx_hex,`${e}.tx_hex`)}function U(s,e){if(s===null||typeof s!="object")throw new n(`VP response validation failed: "${e}" must be an object`);const t=s;S(t.claimer_pubkey,`${e}.claimer_pubkey`),g(t.claim_tx,`${e}.claim_tx`),g(t.assert_tx,`${e}.assert_tx`),g(t.payout_tx,`${e}.payout_tx`),_(t.payout_psbt,`${e}.payout_psbt`)}function I(s,e){if(s===null||typeof s!="object")throw new n(`VP response validation failed: "${e}" must be an object`);const t=s;_(t.wots_pks_json,`${e}.wots_pks_json`),_(t.gc_wots_keys_json,`${e}.gc_wots_keys_json`)}function K(s,e){if(s===null||typeof s!="object")throw new n(`VP response validation failed: "${e}" must be an object`);const t=s;if(S(t.challenger_pubkey,`${e}.challenger_pubkey`),g(t.challenge_assert_x_tx,`${e}.challenge_assert_x_tx`),g(t.challenge_assert_y_tx,`${e}.challenge_assert_y_tx`),g(t.nopayout_tx,`${e}.nopayout_tx`),_(t.nopayout_psbt,`${e}.nopayout_psbt`),!Array.isArray(t.challenge_assert_connectors))throw new n(`VP response validation failed: "${e}.challenge_assert_connectors" must be an array`);if(t.challenge_assert_connectors.length!==C.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER)throw new n(`VP response validation failed: "${e}.challenge_assert_connectors" must have exactly ${C.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER} entries, got ${t.challenge_assert_connectors.length}`);for(let r=0;r<t.challenge_assert_connectors.length;r++)I(t.challenge_assert_connectors[r],`${e}.challenge_assert_connectors[${r}]`);if(!Array.isArray(t.output_label_hashes))throw new n(`VP response validation failed: "${e}.output_label_hashes" must be an array`);for(let r=0;r<t.output_label_hashes.length;r++)T(t.output_label_hashes[r],`${e}.output_label_hashes[${r}]`)}function N(s){if(s===null||typeof s!="object")throw new n("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const e=s;if(!D(e.tx_graph_json))throw new n(`VP response validation failed: "tx_graph_json" must be a non-empty string, got ${a(e.tx_graph_json)}`);if(!h(e.verifying_key_hex))throw new n(`VP response validation failed: "verifying_key_hex" must be a non-empty hex string, got ${a(e.verifying_key_hex)}`);if(e.babe_sessions===null||typeof e.babe_sessions!="object"||Array.isArray(e.babe_sessions))throw new n('VP response validation failed: "babe_sessions" must be an object');const t=Object.entries(e.babe_sessions);if(t.length===0)throw new n('VP response validation failed: "babe_sessions" must contain at least one challenger entry');for(const[r,o]of t){if(S(r,`babe_sessions["${r}"]`),o===null||typeof o!="object")throw new n(`VP response validation failed: "babe_sessions.${r}" must be an object`);const c=o;if(!h(c.decryptor_artifacts_hex))throw new n(`VP response validation failed: "babe_sessions.${r}.decryptor_artifacts_hex" must be a non-empty hex string, got ${a(c.decryptor_artifacts_hex)}`)}}function Y(s){if(s===null||typeof s!="object")throw new n("VP response validation failed: pegout status payload is not an object");const e=s;if(!h(e.pegin_txid)||e.pegin_txid.length!==b)throw new n(`VP response validation failed: "pegin_txid" must be a ${b}-char hex string (txid), got ${a(e.pegin_txid)}`);if(typeof e.found!="boolean")throw new n(`VP response validation failed: "found" must be a boolean, got ${a(e.found)}`);if(e.claimer!==null){if(typeof e.claimer!="object")throw new n(`VP response validation failed: "claimer" must be an object or null, got ${a(e.claimer)}`);z(e.claimer)}if(!Array.isArray(e.challengers))throw new n(`VP response validation failed: "challengers" must be an array, got ${a(e.challengers)}`);for(let t=0;t<e.challengers.length;t++)F(e.challengers[t],t)}function z(s){if(_(s.status,"claimer.status"),typeof s.failed!="boolean")throw new n(`VP response validation failed: "claimer.failed" must be a boolean, got ${a(s.failed)}`);if(_(s.claim_txid,"claimer.claim_txid"),_(s.claimer_pubkey,"claimer.claimer_pubkey"),_(s.assert_txid,"claimer.assert_txid"),typeof s.created_at!="number")throw new n(`VP response validation failed: "claimer.created_at" must be a number, got ${a(s.created_at)}`);if(typeof s.updated_at!="number")throw new n(`VP response validation failed: "claimer.updated_at" must be a number, got ${a(s.updated_at)}`)}function F(s,e){if(s===null||typeof s!="object")throw new n(`VP response validation failed: "challengers[${e}]" must be an object, got ${a(s)}`);const t=s;if(_(t.status,`challengers[${e}].status`),_(t.claim_txid,`challengers[${e}].claim_txid`),_(t.claimer_pubkey,`challengers[${e}].claimer_pubkey`),v(t.assert_txid,`challengers[${e}].assert_txid`),v(t.challenge_assert_x_txid,`challengers[${e}].challenge_assert_x_txid`),v(t.challenge_assert_y_txid,`challengers[${e}].challenge_assert_y_txid`),v(t.nopayout_txid,`challengers[${e}].nopayout_txid`),typeof t.created_at!="number")throw new n(`VP response validation failed: "challengers[${e}].created_at" must be a number, got ${a(t.created_at)}`);if(typeof t.updated_at!="number")throw new n(`VP response validation failed: "challengers[${e}].updated_at" must be a number, got ${a(t.updated_at)}`)}function v(s,e){if(s!==null&&typeof s!="string")throw new n(`VP response validation failed: "${e}" must be a string or null, got ${a(s)}`)}function W(s){B(s,"batchGetPeginStatus",e=>{e.result!==null&&L(e.result)})}function J(s){B(s,"batchGetPegoutStatus",e=>{e.result!==null&&Y(e.result)})}function B(s,e,t){if(s===null||typeof s!="object")throw new n(`VP response validation failed: ${e} response is not an object`);const r=s;if(!Array.isArray(r.results))throw new n(`VP response validation failed: "${e}.results" must be an array, got ${a(r.results)}`);for(let o=0;o<r.results.length;o++){const c=r.results[o];if(c===null||typeof c!="object")throw new n(`VP response validation failed: "${e}.results[${o}]" must be an object, got ${a(c)}`);const i=c;if(!h(i.pegin_txid)||i.pegin_txid.length!==b)throw new n(`VP response validation failed: "${e}.results[${o}].pegin_txid" must be a ${b}-char hex string, got ${a(i.pegin_txid)}`);if(i.error!==null&&typeof i.error!="string")throw new n(`VP response validation failed: "${e}.results[${o}].error" must be a string or null, got ${a(i.error)}`);if(i.result===null&&i.error===null)throw new n(`VP response validation failed: "${e}.results[${o}]" has neither "result" nor "error" populated`);if(i.result!==null&&i.error!==null)throw new n(`VP response validation failed: "${e}.results[${o}]" has both "result" and "error" populated`);t(i,o)}}function Z(s){if(g(s.claim_tx,"depositor_graph.claim_tx"),g(s.assert_tx,"depositor_graph.assert_tx"),g(s.payout_tx,"depositor_graph.payout_tx"),_(s.payout_psbt,"depositor_graph.payout_psbt"),!Array.isArray(s.challenger_presign_data))throw new n('VP response validation failed: "depositor_graph.challenger_presign_data" must be an array');for(let e=0;e<s.challenger_presign_data.length;e++)K(s.challenger_presign_data[e],`depositor_graph.challenger_presign_data[${e}]`);if(typeof s.offchain_params_version!="number")throw new n('VP response validation failed: "depositor_graph.offchain_params_version" must be a number')}const Q=6e4;class ee{constructor(e,t){E(this,"client");const r={baseUrl:e,timeout:(t==null?void 0:t.timeout)??Q,retries:t==null?void 0:t.retries,retryDelay:t==null?void 0:t.retryDelay,retryableFor:t==null?void 0:t.retryableFor,headers:t==null?void 0:t.headers,tokenProvider:t==null?void 0:t.tokenProvider,maxResponseBytes:t==null?void 0:t.maxResponseBytes};this.client=new j.JsonRpcClient(r)}async requestDepositorPresignTransactions(e,t){const r=await this.client.call("vaultProvider_requestDepositorPresignTransactions",e,t);return X(r),r}async submitDepositorPresignatures(e,t){return this.client.call("vaultProvider_submitDepositorPresignatures",e,t)}async submitDepositorWotsKey(e,t){return this.client.call("vaultProvider_submitDepositorWotsKey",e,t)}async requestDepositorClaimerArtifacts(e,t){const r=await this.client.call("vaultProvider_requestDepositorClaimerArtifacts",e,t);return N(r),r}async getPeginStatus(e,t){const r=await this.client.call("vaultProvider_getPeginStatus",e,t);return L(r),r}async batchGetPeginStatus(e,t){const r=await this.client.call("vaultProvider_batchGetPeginStatus",e,t);return W(r),r}async batchGetPegoutStatus(e,t){const r=await this.client.call("vaultProvider_batchGetPegoutStatus",e,t);return J(r),r}}function te(s,e){const t=new Set;for(const p of s)t.add(p.toLowerCase());const r=new Map,o=new Set,c=[],i=[];for(const p of e){const d=p.pegin_txid.toLowerCase();if(!t.has(d)){i.push(d);continue}if(o.has(d)){c.push(d);continue}o.add(d),r.set(d,{result:p.result,error:p.error})}const y=[];for(const p of t)o.has(p)||y.push(p);return{byTxid:r,missing:y,unexpected:i,duplicate:c}}async function se(s){const{items:e,getTxid:t,batchCall:r,onItem:o,onMissing:c,onDuplicate:i,onDuplicateBatch:y,onWholeBatchError:p,onUnexpected:d,batchSize:w=j.VP_BATCH_MAX_SIZE}=s;if(!Number.isInteger(w)||w<=0)throw new Error(`batchPollByProvider: batchSize must be a positive integer, got ${w}`);for(let P=0;P<e.length;P+=w){const A=e.slice(P,P+w),x=new Map,V=[];for(const l of A){const u=t(l).toLowerCase();x.set(u,l),V.push(u)}let f;try{const l=await r(V);f=te(V,l.results)}catch(l){p(A,l);continue}d&&f.unexpected.length>0&&d(f.unexpected);const $=new Set(f.duplicate);for(const l of $){const u=x.get(l);u&&i(u)}y&&$.size>0&&y($.size);for(const l of f.missing){const u=x.get(l);u&&c(u)}for(const[l,u]of f.byTxid){if($.has(l))continue;const R=x.get(l);R&&o(R,{pegin_txid:l,result:u.result,error:u.error})}}}exports.VaultProviderRpcClient=ee;exports.VpResponseValidationError=n;exports.batchPollByProvider=se;exports.validateRequestDepositorClaimerArtifactsResponse=N;
|
|
2
|
+
//# sourceMappingURL=index-CK1Xvq4K.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-Cs7_Evtk.cjs","sources":["../src/tbv/core/clients/vault-provider/validators.ts","../src/tbv/core/clients/vault-provider/api.ts","../src/tbv/core/clients/vault-provider/batchAttribution.ts","../src/tbv/core/clients/vault-provider/batchPoll.ts"],"sourcesContent":["/**\n * Runtime validation for vault provider RPC responses.\n *\n * All VP RPC methods return untyped JSON that TypeScript generics cast without\n * inspection. These validators check the critical top-level fields and\n * security-relevant values (status, txids, pubkeys). Optional progress\n * sub-fields (gc_data, ack_collection, claimer_graphs) are NOT validated\n * since they are informational and not used for signing or transaction\n * construction. Only `progress.presigning` sub-fields are checked.\n */\n\nimport { CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER } from \"../../primitives/psbt/constants\";\nimport {\n COMPRESSED_PUBKEY_HEX_LEN,\n HEX_RE,\n X_ONLY_PUBKEY_HEX_LEN,\n} from \"../../utils/validation\";\n\nimport type {\n BatchGetPeginStatusResponse,\n BatchGetPegoutStatusResponse,\n GetPeginStatusResponse,\n GetPegoutStatusResponse,\n RequestDepositorClaimerArtifactsResponse,\n RequestDepositorPresignTransactionsResponse,\n} from \"./types\";\nimport { DaemonStatus } from \"./types\";\n\nconst DAEMON_STATUS_VALUES = new Set<string>(Object.values(DaemonStatus));\n\nconst VP_ERROR_PREVIEW_MAX_LEN = 200;\n\nfunction preview(value: unknown): string {\n return (\n JSON.stringify(value)?.slice(0, VP_ERROR_PREVIEW_MAX_LEN) ?? \"undefined\"\n );\n}\n\nconst VP_VALIDATION_USER_MESSAGE =\n \"The vault provider returned an unexpected response. Please try again or contact support.\";\n\n/**\n * Thrown when a VP RPC response fails runtime validation.\n *\n * `.message` is a user-facing string safe to display in the UI.\n * `.detail` contains the technical reason, suitable for logging.\n */\nexport class VpResponseValidationError extends Error {\n readonly detail: string;\n\n constructor(detail: string) {\n super(VP_VALIDATION_USER_MESSAGE);\n this.name = \"VpResponseValidationError\";\n this.detail = detail;\n }\n}\n\n/** Expected length (in hex chars) of a Bitcoin transaction ID (32 bytes). */\nconst TXID_HEX_LEN = 64;\n\nfunction isNonEmptyHex(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0 && HEX_RE.test(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\nfunction assertNonEmptyHex(value: unknown, field: string): void {\n if (!isNonEmptyHex(value)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a non-empty hex string, got ${preview(value)}`,\n );\n }\n}\n\nfunction assertNonEmptyString(value: unknown, field: string): void {\n if (!isNonEmptyString(value)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a non-empty string, got ${preview(value)}`,\n );\n }\n}\n\n/**\n * Accept both x-only (64-char) and compressed (66-char) pubkeys from VP responses.\n * The signing code normalizes to x-only via processPublicKeyToXOnly().\n */\nfunction assertBtcPubkey(value: unknown, field: string): void {\n if (\n !isNonEmptyHex(value) ||\n (value.length !== X_ONLY_PUBKEY_HEX_LEN &&\n value.length !== COMPRESSED_PUBKEY_HEX_LEN)\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a ${X_ONLY_PUBKEY_HEX_LEN} or ${COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${preview(value)}`,\n );\n }\n}\n\n/**\n * Validate the optional presigning progress fields returned inside PeginProgressDetails.\n */\nfunction validatePresigningProgressFields(\n progress: Record<string, unknown>,\n): void {\n const presigning = progress.presigning;\n if (presigning === undefined || presigning === null) return;\n if (typeof presigning !== \"object\" || Array.isArray(presigning)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning\" must be an object if present`,\n );\n }\n\n const p = presigning as Record<string, unknown>;\n\n if (\n p.depositor_graph_created !== undefined &&\n typeof p.depositor_graph_created !== \"boolean\"\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning.depositor_graph_created\" must be a boolean if present, got ${preview(p.depositor_graph_created)}`,\n );\n }\n\n if (\n p.vk_challenger_presigning_completed !== undefined &&\n typeof p.vk_challenger_presigning_completed !== \"number\"\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning.vk_challenger_presigning_completed\" must be a number if present, got ${preview(p.vk_challenger_presigning_completed)}`,\n );\n }\n\n if (\n p.vk_challenger_presigning_total !== undefined &&\n typeof p.vk_challenger_presigning_total !== \"number\"\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning.vk_challenger_presigning_total\" must be a number if present, got ${preview(p.vk_challenger_presigning_total)}`,\n );\n }\n}\n\n/**\n * Validate a getPeginStatus response.\n *\n * Throws if the status field is not a recognized DaemonStatus value.\n */\nexport function validateGetPeginStatusResponse(\n response: unknown,\n): asserts response is GetPeginStatusResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: getPeginStatus response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!isNonEmptyHex(r.pegin_txid) || r.pegin_txid.length !== TXID_HEX_LEN) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"pegin_txid\" must be a ${TXID_HEX_LEN}-char hex string (txid), got ${preview(r.pegin_txid)}`,\n );\n }\n\n if (typeof r.status !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"status\" must be a string`,\n );\n }\n\n if (!DAEMON_STATUS_VALUES.has(r.status)) {\n throw new VpResponseValidationError(\n `VP response validation failed: unrecognized status \"${r.status}\". Expected one of: ${[...DAEMON_STATUS_VALUES].join(\", \")}`,\n );\n }\n\n if (\n r.progress === null ||\n typeof r.progress !== \"object\" ||\n Array.isArray(r.progress)\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress\" must be an object`,\n );\n }\n\n validatePresigningProgressFields(r.progress as Record<string, unknown>);\n\n if (typeof r.health_info !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"health_info\" must be a string`,\n );\n }\n\n if (r.last_error !== undefined && typeof r.last_error !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"last_error\" must be a string if present, got ${preview(r.last_error)}`,\n );\n }\n}\n\n/**\n * Validate a requestDepositorPresignTransactions response.\n */\nexport function validateRequestDepositorPresignTransactionsResponse(\n response: unknown,\n): asserts response is RequestDepositorPresignTransactionsResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: requestDepositorPresignTransactions response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!Array.isArray(r.txs)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"txs\" must be an array`,\n );\n }\n\n for (let i = 0; i < r.txs.length; i++) {\n validateClaimerTransactions(r.txs[i], `txs[${i}]`);\n }\n\n if (r.depositor_graph === null || typeof r.depositor_graph !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"depositor_graph\" must be an object`,\n );\n }\n\n validateDepositorGraphTransactions(\n r.depositor_graph as Record<string, unknown>,\n );\n}\n\nfunction validateTransactionData(value: unknown, field: string): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n const tx = value as Record<string, unknown>;\n assertNonEmptyHex(tx.tx_hex, `${field}.tx_hex`);\n}\n\nfunction validateClaimerTransactions(value: unknown, field: string): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n\n const tx = value as Record<string, unknown>;\n\n assertBtcPubkey(tx.claimer_pubkey, `${field}.claimer_pubkey`);\n validateTransactionData(tx.claim_tx, `${field}.claim_tx`);\n validateTransactionData(tx.assert_tx, `${field}.assert_tx`);\n validateTransactionData(tx.payout_tx, `${field}.payout_tx`);\n assertNonEmptyString(tx.payout_psbt, `${field}.payout_psbt`);\n}\n\nfunction validateChallengeAssertConnectorData(\n value: unknown,\n field: string,\n): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n\n const c = value as Record<string, unknown>;\n assertNonEmptyString(c.wots_pks_json, `${field}.wots_pks_json`);\n assertNonEmptyString(c.gc_wots_keys_json, `${field}.gc_wots_keys_json`);\n}\n\nfunction validatePresignDataPerChallenger(value: unknown, field: string): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n\n const d = value as Record<string, unknown>;\n\n assertBtcPubkey(d.challenger_pubkey, `${field}.challenger_pubkey`);\n validateTransactionData(\n d.challenge_assert_x_tx,\n `${field}.challenge_assert_x_tx`,\n );\n validateTransactionData(\n d.challenge_assert_y_tx,\n `${field}.challenge_assert_y_tx`,\n );\n validateTransactionData(d.nopayout_tx, `${field}.nopayout_tx`);\n assertNonEmptyString(d.nopayout_psbt, `${field}.nopayout_psbt`);\n\n if (!Array.isArray(d.challenge_assert_connectors)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}.challenge_assert_connectors\" must be an array`,\n );\n }\n\n if (\n d.challenge_assert_connectors.length !==\n CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}.challenge_assert_connectors\" must have exactly ${CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER} entries, got ${d.challenge_assert_connectors.length}`,\n );\n }\n\n for (let i = 0; i < d.challenge_assert_connectors.length; i++) {\n validateChallengeAssertConnectorData(\n d.challenge_assert_connectors[i],\n `${field}.challenge_assert_connectors[${i}]`,\n );\n }\n\n if (!Array.isArray(d.output_label_hashes)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}.output_label_hashes\" must be an array`,\n );\n }\n\n for (let i = 0; i < d.output_label_hashes.length; i++) {\n assertNonEmptyHex(\n d.output_label_hashes[i],\n `${field}.output_label_hashes[${i}]`,\n );\n }\n}\n\n/**\n * Validate a requestDepositorClaimerArtifacts response.\n */\nexport function validateRequestDepositorClaimerArtifactsResponse(\n response: unknown,\n): asserts response is RequestDepositorClaimerArtifactsResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: requestDepositorClaimerArtifacts response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!isNonEmptyString(r.tx_graph_json)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"tx_graph_json\" must be a non-empty string, got ${preview(r.tx_graph_json)}`,\n );\n }\n\n if (!isNonEmptyHex(r.verifying_key_hex)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"verifying_key_hex\" must be a non-empty hex string, got ${preview(r.verifying_key_hex)}`,\n );\n }\n\n if (\n r.babe_sessions === null ||\n typeof r.babe_sessions !== \"object\" ||\n Array.isArray(r.babe_sessions)\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions\" must be an object`,\n );\n }\n\n const sessionEntries = Object.entries(\n r.babe_sessions as Record<string, unknown>,\n );\n if (sessionEntries.length === 0) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions\" must contain at least one challenger entry`,\n );\n }\n\n for (const [key, session] of sessionEntries) {\n assertBtcPubkey(key, `babe_sessions[\"${key}\"]`);\n if (session === null || typeof session !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions.${key}\" must be an object`,\n );\n }\n const s = session as Record<string, unknown>;\n if (!isNonEmptyHex(s.decryptor_artifacts_hex)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions.${key}.decryptor_artifacts_hex\" must be a non-empty hex string, got ${preview(s.decryptor_artifacts_hex)}`,\n );\n }\n }\n}\n\n/**\n * Validate a single pegout status payload. Embedded by\n * `validateBatchGetPegoutStatusResponse`. Mirrors btc-vault\n * `crates/vaultd/src/rpc/server/pegout_status.rs::GetPegoutStatusResponse`.\n */\nexport function validateGetPegoutStatusResponse(\n response: unknown,\n): asserts response is GetPegoutStatusResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: pegout status payload is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!isNonEmptyHex(r.pegin_txid) || r.pegin_txid.length !== TXID_HEX_LEN) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"pegin_txid\" must be a ${TXID_HEX_LEN}-char hex string (txid), got ${preview(r.pegin_txid)}`,\n );\n }\n\n if (typeof r.found !== \"boolean\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"found\" must be a boolean, got ${preview(r.found)}`,\n );\n }\n\n // `claimer` is `Option<ClaimerPegoutStatus>` server-side; null when absent.\n if (r.claimer !== null) {\n if (typeof r.claimer !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer\" must be an object or null, got ${preview(r.claimer)}`,\n );\n }\n validateClaimerPegoutStatus(r.claimer as Record<string, unknown>);\n }\n\n // `challengers: Vec<ChallengerStatus>` server-side; always present (possibly empty).\n if (!Array.isArray(r.challengers)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"challengers\" must be an array, got ${preview(r.challengers)}`,\n );\n }\n for (let i = 0; i < r.challengers.length; i++) {\n validateChallengerStatus(r.challengers[i], i);\n }\n}\n\nfunction validateClaimerPegoutStatus(value: Record<string, unknown>): void {\n assertNonEmptyString(value.status, \"claimer.status\");\n if (typeof value.failed !== \"boolean\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer.failed\" must be a boolean, got ${preview(value.failed)}`,\n );\n }\n assertNonEmptyString(value.claim_txid, \"claimer.claim_txid\");\n assertNonEmptyString(value.claimer_pubkey, \"claimer.claimer_pubkey\");\n assertNonEmptyString(value.assert_txid, \"claimer.assert_txid\");\n if (typeof value.created_at !== \"number\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer.created_at\" must be a number, got ${preview(value.created_at)}`,\n );\n }\n if (typeof value.updated_at !== \"number\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer.updated_at\" must be a number, got ${preview(value.updated_at)}`,\n );\n }\n}\n\nfunction validateChallengerStatus(value: unknown, index: number): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"challengers[${index}]\" must be an object, got ${preview(value)}`,\n );\n }\n const c = value as Record<string, unknown>;\n assertNonEmptyString(c.status, `challengers[${index}].status`);\n assertNonEmptyString(c.claim_txid, `challengers[${index}].claim_txid`);\n assertNonEmptyString(c.claimer_pubkey, `challengers[${index}].claimer_pubkey`);\n assertNullableString(c.assert_txid, `challengers[${index}].assert_txid`);\n assertNullableString(\n c.challenge_assert_x_txid,\n `challengers[${index}].challenge_assert_x_txid`,\n );\n assertNullableString(\n c.challenge_assert_y_txid,\n `challengers[${index}].challenge_assert_y_txid`,\n );\n assertNullableString(c.nopayout_txid, `challengers[${index}].nopayout_txid`);\n if (typeof c.created_at !== \"number\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"challengers[${index}].created_at\" must be a number, got ${preview(c.created_at)}`,\n );\n }\n if (typeof c.updated_at !== \"number\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"challengers[${index}].updated_at\" must be a number, got ${preview(c.updated_at)}`,\n );\n }\n}\n\nfunction assertNullableString(value: unknown, field: string): void {\n if (value !== null && typeof value !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a string or null, got ${preview(value)}`,\n );\n }\n}\n\n/**\n * Validate a `batchGetPeginStatus` response. Per-result envelope shape:\n * `{ pegin_txid, result: GetPeginStatusResponse | null, error: string | null }`.\n * The inner result (when non-null) is validated via the single-item validator.\n */\nexport function validateBatchGetPeginStatusResponse(\n response: unknown,\n): asserts response is BatchGetPeginStatusResponse {\n validateBatchEnvelope(response, \"batchGetPeginStatus\", (entry) => {\n if (entry.result !== null) {\n validateGetPeginStatusResponse(entry.result);\n }\n });\n}\n\n/** Validate a `batchGetPegoutStatus` response. Same envelope as peginStatus. */\nexport function validateBatchGetPegoutStatusResponse(\n response: unknown,\n): asserts response is BatchGetPegoutStatusResponse {\n validateBatchEnvelope(response, \"batchGetPegoutStatus\", (entry) => {\n if (entry.result !== null) {\n validateGetPegoutStatusResponse(entry.result);\n }\n });\n}\n\ninterface BatchResultEnvelope {\n pegin_txid: string;\n result: unknown;\n error: string | null;\n}\n\nfunction validateBatchEnvelope(\n response: unknown,\n rpcName: string,\n validateInnerResult: (entry: BatchResultEnvelope, index: number) => void,\n): void {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: ${rpcName} response is not an object`,\n );\n }\n const r = response as Record<string, unknown>;\n if (!Array.isArray(r.results)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${rpcName}.results\" must be an array, got ${preview(r.results)}`,\n );\n }\n for (let i = 0; i < r.results.length; i++) {\n const entry = r.results[i];\n if (entry === null || typeof entry !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${rpcName}.results[${i}]\" must be an object, got ${preview(entry)}`,\n );\n }\n const e = entry as Record<string, unknown>;\n if (\n !isNonEmptyHex(e.pegin_txid) ||\n e.pegin_txid.length !== TXID_HEX_LEN\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${rpcName}.results[${i}].pegin_txid\" must be a ${TXID_HEX_LEN}-char hex string, got ${preview(e.pegin_txid)}`,\n );\n }\n if (e.error !== null && typeof e.error !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${rpcName}.results[${i}].error\" must be a string or null, got ${preview(e.error)}`,\n );\n }\n // Exactly one of `result` / `error` must be populated. The server only\n // ever sets one per item; treating both-null as a protocol violation\n // surfaces server bugs early instead of letting them silently degrade.\n if (e.result === null && e.error === null) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${rpcName}.results[${i}]\" has neither \"result\" nor \"error\" populated`,\n );\n }\n if (e.result !== null && e.error !== null) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${rpcName}.results[${i}]\" has both \"result\" and \"error\" populated`,\n );\n }\n validateInnerResult(e as unknown as BatchResultEnvelope, i);\n }\n}\n\nfunction validateDepositorGraphTransactions(\n graph: Record<string, unknown>,\n): void {\n validateTransactionData(graph.claim_tx, \"depositor_graph.claim_tx\");\n validateTransactionData(graph.assert_tx, \"depositor_graph.assert_tx\");\n validateTransactionData(graph.payout_tx, \"depositor_graph.payout_tx\");\n assertNonEmptyString(graph.payout_psbt, \"depositor_graph.payout_psbt\");\n\n if (!Array.isArray(graph.challenger_presign_data)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"depositor_graph.challenger_presign_data\" must be an array`,\n );\n }\n\n for (let i = 0; i < graph.challenger_presign_data.length; i++) {\n validatePresignDataPerChallenger(\n graph.challenger_presign_data[i],\n `depositor_graph.challenger_presign_data[${i}]`,\n );\n }\n\n if (typeof graph.offchain_params_version !== \"number\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"depositor_graph.offchain_params_version\" must be a number`,\n );\n }\n}\n","/**\n * JSON-RPC client for the Vault Provider API.\n *\n * Wraps {@link JsonRpcClient} with typed methods matching the\n * `vaultProvider_*` RPC namespace defined in the btc-vault pegin spec.\n *\n * Implements the narrow service interfaces (PeginStatusReader, WotsKeySubmitter,\n * PresignClient, ClaimerArtifactsReader) so it can be passed directly to\n * any deposit protocol service function.\n *\n * @see https://github.com/babylonlabs-io/btc-vault/blob/main/docs/pegin.md\n */\n\nimport type { PeginStatusReader, WotsKeySubmitter, PresignClient, ClaimerArtifactsReader } from \"../../services/deposit/interfaces\";\n\nimport {\n type BearerTokenProvider,\n JsonRpcClient,\n type JsonRpcClientConfig,\n} from \"./json-rpc-client\";\nimport type {\n BatchGetPeginStatusParams,\n BatchGetPeginStatusResponse,\n BatchGetPegoutStatusParams,\n BatchGetPegoutStatusResponse,\n GetPeginStatusParams,\n GetPeginStatusResponse,\n RequestDepositorClaimerArtifactsParams,\n RequestDepositorClaimerArtifactsResponse,\n RequestDepositorPresignTransactionsParams,\n RequestDepositorPresignTransactionsResponse,\n SubmitDepositorPresignaturesParams,\n SubmitDepositorWotsKeyParams,\n} from \"./types\";\nimport {\n validateBatchGetPeginStatusResponse,\n validateBatchGetPegoutStatusResponse,\n validateGetPeginStatusResponse,\n validateRequestDepositorClaimerArtifactsResponse,\n validateRequestDepositorPresignTransactionsResponse,\n} from \"./validators\";\n\nexport interface VaultProviderRpcClientOptions {\n /** Timeout in milliseconds per request (default: 60000) */\n timeout?: number;\n /** Number of retry attempts for safe methods (default: 3) */\n retries?: number;\n /** Initial retry delay in milliseconds (default: 1000) */\n retryDelay?: number;\n /**\n * Custom retry predicate. Default retries only the idempotent read\n * methods: `getPeginStatus`, `batchGetPeginStatus`, `batchGetPegoutStatus`,\n * `requestDepositorPresignTransactions`.\n */\n retryableFor?: (method: string) => boolean;\n /** Custom headers. */\n headers?: Record<string, string>;\n /**\n * Per-request bearer-token source. A non-null return attaches\n * `Authorization: Bearer <token>`; `null` skips auth. Wire a\n * {@link VpTokenProvider} for depositor-gated methods.\n */\n tokenProvider?: BearerTokenProvider;\n /** Maximum response body size, in bytes, for typed JSON-RPC calls */\n maxResponseBytes?: number;\n}\n\nconst DEFAULT_TIMEOUT_MS = 60_000;\n\n/**\n * Concrete VP RPC client implementing all service interfaces.\n *\n * Usage:\n * ```ts\n * const client = new VaultProviderRpcClient(\"https://vp.example.com/rpc\");\n * const status = await client.getPeginStatus({ pegin_txid: \"abc...\" });\n * ```\n */\nexport class VaultProviderRpcClient\n implements PeginStatusReader, WotsKeySubmitter, PresignClient, ClaimerArtifactsReader\n{\n private client: JsonRpcClient;\n\n constructor(baseUrl: string, options?: VaultProviderRpcClientOptions) {\n const config: JsonRpcClientConfig = {\n baseUrl,\n timeout: options?.timeout ?? DEFAULT_TIMEOUT_MS,\n retries: options?.retries,\n retryDelay: options?.retryDelay,\n retryableFor: options?.retryableFor,\n headers: options?.headers,\n tokenProvider: options?.tokenProvider,\n maxResponseBytes: options?.maxResponseBytes,\n };\n this.client = new JsonRpcClient(config);\n }\n\n /**\n * Request the payout/claim/assert transactions that the depositor\n * needs to pre-sign before the vault can be activated on Bitcoin.\n */\n async requestDepositorPresignTransactions(\n params: RequestDepositorPresignTransactionsParams,\n signal?: AbortSignal,\n ): Promise<RequestDepositorPresignTransactionsResponse> {\n const response = await this.client.call<\n RequestDepositorPresignTransactionsParams,\n unknown\n >(\"vaultProvider_requestDepositorPresignTransactions\", params, signal);\n validateRequestDepositorPresignTransactionsResponse(response);\n return response;\n }\n\n /**\n * Submit the depositor's pre-signatures for the payout transactions\n * and the depositor-as-claimer graph.\n */\n async submitDepositorPresignatures(\n params: SubmitDepositorPresignaturesParams,\n signal?: AbortSignal,\n ): Promise<void> {\n return this.client.call<SubmitDepositorPresignaturesParams, void>(\n \"vaultProvider_submitDepositorPresignatures\",\n params,\n signal,\n );\n }\n\n /**\n * Submit the depositor's WOTS public key to the vault provider.\n * Called after the pegin is finalized on Ethereum, when the VP is in\n * `PendingDepositorWotsPK` status.\n */\n async submitDepositorWotsKey(\n params: SubmitDepositorWotsKeyParams,\n signal?: AbortSignal,\n ): Promise<void> {\n return this.client.call<SubmitDepositorWotsKeyParams, void>(\n \"vaultProvider_submitDepositorWotsKey\",\n params,\n signal,\n );\n }\n\n /**\n * Request the BaBe DecryptorArtifacts needed for the depositor to\n * independently evaluate garbled circuits during a challenge.\n */\n async requestDepositorClaimerArtifacts(\n params: RequestDepositorClaimerArtifactsParams,\n signal?: AbortSignal,\n ): Promise<RequestDepositorClaimerArtifactsResponse> {\n const response = await this.client.call<\n RequestDepositorClaimerArtifactsParams,\n unknown\n >(\"vaultProvider_requestDepositorClaimerArtifacts\", params, signal);\n validateRequestDepositorClaimerArtifactsResponse(response);\n return response;\n }\n\n /** Get the current pegin status from the vault provider daemon. */\n async getPeginStatus(\n params: GetPeginStatusParams,\n signal?: AbortSignal,\n ): Promise<GetPeginStatusResponse> {\n const response = await this.client.call<GetPeginStatusParams, unknown>(\n \"vaultProvider_getPeginStatus\",\n params,\n signal,\n );\n validateGetPeginStatusResponse(response);\n return response;\n }\n\n /**\n * Get pegin status for many txids in one round trip. Per-result envelope\n * isolates per-pegin failures from the overall RPC. Caller must chunk\n * inputs at `VP_BATCH_MAX_SIZE`.\n */\n async batchGetPeginStatus(\n params: BatchGetPeginStatusParams,\n signal?: AbortSignal,\n ): Promise<BatchGetPeginStatusResponse> {\n const response = await this.client.call<\n BatchGetPeginStatusParams,\n unknown\n >(\"vaultProvider_batchGetPeginStatus\", params, signal);\n validateBatchGetPeginStatusResponse(response);\n return response;\n }\n\n /**\n * Get pegout status for many txids in one round trip. Same per-result\n * envelope semantics as `batchGetPeginStatus`.\n */\n async batchGetPegoutStatus(\n params: BatchGetPegoutStatusParams,\n signal?: AbortSignal,\n ): Promise<BatchGetPegoutStatusResponse> {\n const response = await this.client.call<\n BatchGetPegoutStatusParams,\n unknown\n >(\"vaultProvider_batchGetPegoutStatus\", params, signal);\n validateBatchGetPegoutStatusResponse(response);\n return response;\n }\n}\n","/**\n * Defensive helper for attributing per-item results in a VP batch RPC\n * response back to the requested txids. The server promises 1:1 ordered\n * results, but we don't trust that promise — a server bug could duplicate,\n * skip, or scramble items, and silent attribution-by-array-index would\n * mask the bug.\n *\n * Lowercases all txids on both sides to absorb case mismatch (the FE\n * strips `0x` but doesn't otherwise normalize).\n *\n * @module tbv/core/clients/vault-provider/batchAttribution\n */\n\n/** Per-item entry in a VP batch response. */\nexport interface BatchResultEntry<T> {\n pegin_txid: string;\n result: T | null;\n error: string | null;\n}\n\n/** Output of {@link attributeBatchResults}. */\nexport interface BatchAttributionResult<T> {\n /** Lowercase requested txid -> per-item envelope. */\n byTxid: Map<string, { result: T | null; error: string | null }>;\n /** Requested txids that did not appear in the response. */\n missing: string[];\n /** Echoed txids that were not in the request — logged + dropped. */\n unexpected: string[];\n /** Echoed txids that appeared more than once — first kept, rest dropped. */\n duplicate: string[];\n}\n\n/**\n * Attribute batch results to requested txids defensively.\n *\n * Both `requestedTxids` and the echoed `pegin_txid` field on each result\n * are lowercased before lookup. Duplicates and unexpected echoes are\n * surfaced so callers can flag the affected items as errored rather than\n * silently overwriting state.\n *\n * `requestedTxids` may contain duplicates; they are de-duplicated for the\n * purposes of map keys (each unique txid becomes a single map entry).\n */\nexport function attributeBatchResults<T>(\n requestedTxids: string[],\n results: ReadonlyArray<BatchResultEntry<T>>,\n): BatchAttributionResult<T> {\n const requestedSet = new Set<string>();\n for (const txid of requestedTxids) {\n requestedSet.add(txid.toLowerCase());\n }\n\n const byTxid = new Map<\n string,\n { result: T | null; error: string | null }\n >();\n const seen = new Set<string>();\n const duplicate: string[] = [];\n const unexpected: string[] = [];\n\n for (const entry of results) {\n const lower = entry.pegin_txid.toLowerCase();\n if (!requestedSet.has(lower)) {\n unexpected.push(lower);\n continue;\n }\n if (seen.has(lower)) {\n duplicate.push(lower);\n continue;\n }\n seen.add(lower);\n byTxid.set(lower, { result: entry.result, error: entry.error });\n }\n\n const missing: string[] = [];\n for (const txid of requestedSet) {\n if (!seen.has(txid)) missing.push(txid);\n }\n\n return { byTxid, missing, unexpected, duplicate };\n}\n","/**\n * Generic chunk + attribute + dispatch loop for VP batch RPCs.\n *\n * Wraps {@link attributeBatchResults} with chunking and per-callback\n * dispatch so the FE polling hooks (and any future SDK consumer) only\n * have to declare per-item handlers — chunking by `VP_BATCH_MAX_SIZE`,\n * lowercase txid normalization, missing/duplicate/unexpected\n * surfacing, and the duplicate-skip invariant in the byTxid loop are\n * all owned here.\n *\n * @module tbv/core/clients/vault-provider/batchPoll\n */\n\nimport {\n attributeBatchResults,\n type BatchResultEntry,\n} from \"./batchAttribution\";\nimport { VP_BATCH_MAX_SIZE } from \"./types\";\n\nexport interface BatchPollByProviderOptions<TItem, TResult> {\n /** Items to poll for this provider, e.g. `DepositToPoll[]`. */\n items: TItem[];\n /** Extract the canonical txid for each item. Helper lowercases it. */\n getTxid: (item: TItem) => string;\n /**\n * Per-chunk RPC call. Receives lowercased txids; returns the batch\n * envelope. Caller wraps `rpcClient.batchGet*Status({ pegin_txids })`.\n */\n batchCall: (\n txids: string[],\n ) => Promise<{ results: ReadonlyArray<BatchResultEntry<TResult>> }>;\n /**\n * Handle a per-item envelope. Exactly one of `result` / `error` is\n * populated (validator invariant). Caller decides UI state, logging,\n * etc. Not invoked for txids surfaced via {@link onDuplicate}.\n *\n * Note: `envelope.pegin_txid` is the lowercased txid the helper\n * sent in the request, not whatever case/encoding the server echoed.\n */\n onItem: (item: TItem, envelope: BatchResultEntry<TResult>) => void;\n /** Server omitted this item from the response. */\n onMissing: (item: TItem) => void;\n /** Server returned this item more than once. Caller picks UI state. */\n onDuplicate: (item: TItem) => void;\n /**\n * Optional aggregate signal for an entire chunk where the server\n * returned duplicates. Fires once per chunk (only if `count > 0`)\n * AFTER all per-item `onDuplicate` dispatches. Caller typically logs\n * the count alongside the provider name.\n */\n onDuplicateBatch?: (count: number) => void;\n /**\n * The whole chunk's RPC call failed (transport or response\n * validation). Receives the chunk and the error. Caller decides how\n * to project that onto per-item state.\n */\n onWholeBatchError: (chunk: TItem[], error: unknown) => void;\n /**\n * Server returned txids that were not in the request. Caller\n * typically logs the count for observability — there's no recovery\n * action since the original request items are unaffected. Optional;\n * defaults to no-op.\n */\n onUnexpected?: (echoedTxids: string[]) => void;\n /**\n * Maximum items per RPC call. Defaults to {@link VP_BATCH_MAX_SIZE}.\n * Exposed for tests so chunking can be exercised without 50+\n * fixtures.\n */\n batchSize?: number;\n}\n\nexport async function batchPollByProvider<TItem, TResult>(\n options: BatchPollByProviderOptions<TItem, TResult>,\n): Promise<void> {\n const {\n items,\n getTxid,\n batchCall,\n onItem,\n onMissing,\n onDuplicate,\n onDuplicateBatch,\n onWholeBatchError,\n onUnexpected,\n batchSize = VP_BATCH_MAX_SIZE,\n } = options;\n\n if (!Number.isInteger(batchSize) || batchSize <= 0) {\n throw new Error(\n `batchPollByProvider: batchSize must be a positive integer, got ${batchSize}`,\n );\n }\n\n for (let i = 0; i < items.length; i += batchSize) {\n const chunk = items.slice(i, i + batchSize);\n const txidToItem = new Map<string, TItem>();\n const txids: string[] = [];\n for (const item of chunk) {\n const lowerTxid = getTxid(item).toLowerCase();\n txidToItem.set(lowerTxid, item);\n txids.push(lowerTxid);\n }\n\n // Both the RPC call and attribution sit inside the same try/catch\n // so a malformed-batch validator throw is routed through\n // `onWholeBatchError` rather than aborting the polling pass.\n let attribution;\n try {\n const response = await batchCall(txids);\n attribution = attributeBatchResults<TResult>(txids, response.results);\n } catch (error) {\n onWholeBatchError(chunk, error);\n continue;\n }\n\n if (onUnexpected && attribution.unexpected.length > 0) {\n onUnexpected(attribution.unexpected);\n }\n\n const duplicateTxids = new Set(attribution.duplicate);\n for (const txid of duplicateTxids) {\n const item = txidToItem.get(txid);\n if (item) onDuplicate(item);\n }\n if (onDuplicateBatch && duplicateTxids.size > 0) {\n onDuplicateBatch(duplicateTxids.size);\n }\n for (const txid of attribution.missing) {\n const item = txidToItem.get(txid);\n if (item) onMissing(item);\n }\n for (const [txid, envelope] of attribution.byTxid) {\n // Skip duplicates — already dispatched via onDuplicate above.\n if (duplicateTxids.has(txid)) continue;\n const item = txidToItem.get(txid);\n if (!item) continue;\n onItem(item, {\n pegin_txid: txid,\n result: envelope.result,\n error: envelope.error,\n });\n }\n }\n}\n"],"names":["DAEMON_STATUS_VALUES","DaemonStatus","VP_ERROR_PREVIEW_MAX_LEN","preview","value","_a","VP_VALIDATION_USER_MESSAGE","VpResponseValidationError","detail","__publicField","TXID_HEX_LEN","isNonEmptyHex","HEX_RE","isNonEmptyString","assertNonEmptyHex","field","assertNonEmptyString","assertBtcPubkey","X_ONLY_PUBKEY_HEX_LEN","COMPRESSED_PUBKEY_HEX_LEN","validatePresigningProgressFields","progress","presigning","p","validateGetPeginStatusResponse","response","r","validateRequestDepositorPresignTransactionsResponse","i","validateClaimerTransactions","validateDepositorGraphTransactions","validateTransactionData","tx","validateChallengeAssertConnectorData","c","validatePresignDataPerChallenger","d","CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER","validateRequestDepositorClaimerArtifactsResponse","sessionEntries","key","session","s","validateGetPegoutStatusResponse","validateClaimerPegoutStatus","validateChallengerStatus","index","assertNullableString","validateBatchGetPeginStatusResponse","validateBatchEnvelope","entry","validateBatchGetPegoutStatusResponse","rpcName","validateInnerResult","e","graph","DEFAULT_TIMEOUT_MS","VaultProviderRpcClient","baseUrl","options","config","JsonRpcClient","params","signal","attributeBatchResults","requestedTxids","results","requestedSet","txid","byTxid","seen","duplicate","unexpected","lower","missing","batchPollByProvider","items","getTxid","batchCall","onItem","onMissing","onDuplicate","onDuplicateBatch","onWholeBatchError","onUnexpected","batchSize","VP_BATCH_MAX_SIZE","chunk","txidToItem","txids","item","lowerTxid","attribution","error","duplicateTxids","envelope"],"mappings":"gTA4BMA,EAAuB,IAAI,IAAY,OAAO,OAAOC,EAAAA,YAAY,CAAC,EAElEC,EAA2B,IAEjC,SAASC,EAAQC,EAAwB,OACvC,QACEC,EAAA,KAAK,UAAUD,CAAK,IAApB,YAAAC,EAAuB,MAAM,EAAGH,KAA6B,WAEjE,CAEA,MAAMI,EACJ,2FAQK,MAAMC,UAAkC,KAAM,CAGnD,YAAYC,EAAgB,CAC1B,MAAMF,CAA0B,EAHzBG,EAAA,eAIP,KAAK,KAAO,4BACZ,KAAK,OAASD,CAChB,CACF,CAGA,MAAME,EAAe,GAErB,SAASC,EAAcP,EAAiC,CACtD,OAAO,OAAOA,GAAU,UAAYA,EAAM,OAAS,GAAKQ,EAAAA,OAAO,KAAKR,CAAK,CAC3E,CAEA,SAASS,EAAiBT,EAAiC,CACzD,OAAO,OAAOA,GAAU,UAAYA,EAAM,OAAS,CACrD,CAEA,SAASU,EAAkBV,EAAgBW,EAAqB,CAC9D,GAAI,CAACJ,EAAcP,CAAK,EACtB,MAAM,IAAIG,EACR,mCAAmCQ,CAAK,yCAAyCZ,EAAQC,CAAK,CAAC,EAAA,CAGrG,CAEA,SAASY,EAAqBZ,EAAgBW,EAAqB,CACjE,GAAI,CAACF,EAAiBT,CAAK,EACzB,MAAM,IAAIG,EACR,mCAAmCQ,CAAK,qCAAqCZ,EAAQC,CAAK,CAAC,EAAA,CAGjG,CAMA,SAASa,EAAgBb,EAAgBW,EAAqB,CAC5D,GACE,CAACJ,EAAcP,CAAK,GACnBA,EAAM,SAAWc,yBAChBd,EAAM,SAAWe,4BAEnB,MAAM,IAAIZ,EACR,mCAAmCQ,CAAK,eAAeG,EAAAA,qBAAqB,OAAOC,EAAAA,yBAAyB,sCAAsChB,EAAQC,CAAK,CAAC,EAAA,CAGtK,CAKA,SAASgB,EACPC,EACM,CAC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AO,CACxB,MAAMI,EAAYd,EAAQa,CAAI,EAAE,YAAA,EAChCF,EAAW,IAAIG,EAAWD,CAAI,EAC9BD,EAAM,KAAKE,CAAS,CACtB,CAKA,IAAIC,EACJ,GAAI,CACF,MAAMnE,EAAW,MAAMqD,EAAUW,CAAK,EACtCG,EAAc5B,GAA+ByB,EAAOhE,EAAS,OAAO,CACtE,OAASoE,EAAO,CACdV,EAAkBI,EAAOM,CAAK,EAC9B,QACF,CAEIT,GAAgBQ,EAAY,WAAW,OAAS,GAClDR,EAAaQ,EAAY,UAAU,EAGrC,MAAME,EAAiB,IAAI,IAAIF,EAAY,SAAS,EACpD,UAAWxB,KAAQ0B,EAAgB,CACjC,MAAMJ,EAAOF,EAAW,IAAIpB,CAAI,EAC5BsB,KAAkBA,CAAI,CAC5B,CACIR,GAAoBY,EAAe,KAAO,GAC5CZ,EAAiBY,EAAe,IAAI,EAEtC,UAAW1B,KAAQwB,EAAY,QAAS,CACtC,MAAMF,EAAOF,EAAW,IAAIpB,CAAI,EAC5BsB,KAAgBA,CAAI,CAC1B,CACA,SAAW,CAACtB,EAAM2B,CAAQ,IAAKH,EAAY,OAAQ,CAEjD,GAAIE,EAAe,IAAI1B,CAAI,EAAG,SAC9B,MAAMsB,EAAOF,EAAW,IAAIpB,CAAI,EAC3BsB,GACLX,EAAOW,EAAM,CACX,WAAYtB,EACZ,OAAQ2B,EAAS,OACjB,MAAOA,EAAS,KAAA,CACjB,CACH,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"index-CK1Xvq4K.cjs","sources":["../src/tbv/core/clients/vault-provider/validators.ts","../src/tbv/core/clients/vault-provider/api.ts","../src/tbv/core/clients/vault-provider/batchAttribution.ts","../src/tbv/core/clients/vault-provider/batchPoll.ts"],"sourcesContent":["/**\n * Runtime validation for vault provider RPC responses.\n *\n * All VP RPC methods return untyped JSON that TypeScript generics cast without\n * inspection. These validators check the critical top-level fields and\n * security-relevant values (status, txids, pubkeys). Optional progress\n * sub-fields (gc_data, ack_collection, claimer_graphs) are NOT validated\n * since they are informational and not used for signing or transaction\n * construction. Only `progress.presigning` sub-fields are checked.\n */\n\nimport { CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER } from \"../../primitives/psbt/constants\";\nimport {\n COMPRESSED_PUBKEY_HEX_LEN,\n HEX_RE,\n X_ONLY_PUBKEY_HEX_LEN,\n} from \"../../utils/validation\";\n\nimport type {\n BatchGetPeginStatusResponse,\n BatchGetPegoutStatusResponse,\n GetPeginStatusResponse,\n GetPegoutStatusResponse,\n RequestDepositorClaimerArtifactsResponse,\n RequestDepositorPresignTransactionsResponse,\n} from \"./types\";\nimport { DaemonStatus } from \"./types\";\n\nconst DAEMON_STATUS_VALUES = new Set<string>(Object.values(DaemonStatus));\n\nconst VP_ERROR_PREVIEW_MAX_LEN = 200;\n\nfunction preview(value: unknown): string {\n return (\n JSON.stringify(value)?.slice(0, VP_ERROR_PREVIEW_MAX_LEN) ?? \"undefined\"\n );\n}\n\nconst VP_VALIDATION_USER_MESSAGE =\n \"The vault provider returned an unexpected response. Please try again or contact support.\";\n\n/**\n * Thrown when a VP RPC response fails runtime validation.\n *\n * `.message` is a user-facing string safe to display in the UI.\n * `.detail` contains the technical reason, suitable for logging.\n */\nexport class VpResponseValidationError extends Error {\n readonly detail: string;\n\n constructor(detail: string) {\n super(VP_VALIDATION_USER_MESSAGE);\n this.name = \"VpResponseValidationError\";\n this.detail = detail;\n }\n}\n\n/** Expected length (in hex chars) of a Bitcoin transaction ID (32 bytes). */\nconst TXID_HEX_LEN = 64;\n\nfunction isNonEmptyHex(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0 && HEX_RE.test(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\nfunction assertNonEmptyHex(value: unknown, field: string): void {\n if (!isNonEmptyHex(value)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a non-empty hex string, got ${preview(value)}`,\n );\n }\n}\n\nfunction assertNonEmptyString(value: unknown, field: string): void {\n if (!isNonEmptyString(value)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a non-empty string, got ${preview(value)}`,\n );\n }\n}\n\n/**\n * Accept both x-only (64-char) and compressed (66-char) pubkeys from VP responses.\n * The signing code normalizes to x-only via processPublicKeyToXOnly().\n */\nfunction assertBtcPubkey(value: unknown, field: string): void {\n if (\n !isNonEmptyHex(value) ||\n (value.length !== X_ONLY_PUBKEY_HEX_LEN &&\n value.length !== COMPRESSED_PUBKEY_HEX_LEN)\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a ${X_ONLY_PUBKEY_HEX_LEN} or ${COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${preview(value)}`,\n );\n }\n}\n\n/**\n * Validate the optional presigning progress fields returned inside PeginProgressDetails.\n */\nfunction validatePresigningProgressFields(\n progress: Record<string, unknown>,\n): void {\n const presigning = progress.presigning;\n if (presigning === undefined || presigning === null) return;\n if (typeof presigning !== \"object\" || Array.isArray(presigning)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning\" must be an object if present`,\n );\n }\n\n const p = presigning as Record<string, unknown>;\n\n if (\n p.depositor_graph_created !== undefined &&\n typeof p.depositor_graph_created !== \"boolean\"\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning.depositor_graph_created\" must be a boolean if present, got ${preview(p.depositor_graph_created)}`,\n );\n }\n\n if (\n p.vk_challenger_presigning_completed !== undefined &&\n typeof p.vk_challenger_presigning_completed !== \"number\"\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning.vk_challenger_presigning_completed\" must be a number if present, got ${preview(p.vk_challenger_presigning_completed)}`,\n );\n }\n\n if (\n p.vk_challenger_presigning_total !== undefined &&\n typeof p.vk_challenger_presigning_total !== \"number\"\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning.vk_challenger_presigning_total\" must be a number if present, got ${preview(p.vk_challenger_presigning_total)}`,\n );\n }\n}\n\n/**\n * Validate a getPeginStatus response.\n *\n * Throws if the status field is not a recognized DaemonStatus value.\n */\nexport function validateGetPeginStatusResponse(\n response: unknown,\n): asserts response is GetPeginStatusResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: getPeginStatus response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!isNonEmptyHex(r.pegin_txid) || r.pegin_txid.length !== TXID_HEX_LEN) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"pegin_txid\" must be a ${TXID_HEX_LEN}-char hex string (txid), got ${preview(r.pegin_txid)}`,\n );\n }\n\n if (typeof r.status !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"status\" must be a string`,\n );\n }\n\n if (!DAEMON_STATUS_VALUES.has(r.status)) {\n throw new VpResponseValidationError(\n `VP response validation failed: unrecognized status \"${r.status}\". Expected one of: ${[...DAEMON_STATUS_VALUES].join(\", \")}`,\n );\n }\n\n if (\n r.progress === null ||\n typeof r.progress !== \"object\" ||\n Array.isArray(r.progress)\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress\" must be an object`,\n );\n }\n\n validatePresigningProgressFields(r.progress as Record<string, unknown>);\n\n if (typeof r.health_info !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"health_info\" must be a string`,\n );\n }\n\n if (r.last_error !== undefined && typeof r.last_error !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"last_error\" must be a string if present, got ${preview(r.last_error)}`,\n );\n }\n}\n\n/**\n * Validate a requestDepositorPresignTransactions response.\n */\nexport function validateRequestDepositorPresignTransactionsResponse(\n response: unknown,\n): asserts response is RequestDepositorPresignTransactionsResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: requestDepositorPresignTransactions response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!Array.isArray(r.txs)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"txs\" must be an array`,\n );\n }\n\n for (let i = 0; i < r.txs.length; i++) {\n validateClaimerTransactions(r.txs[i], `txs[${i}]`);\n }\n\n if (r.depositor_graph === null || typeof r.depositor_graph !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"depositor_graph\" must be an object`,\n );\n }\n\n validateDepositorGraphTransactions(\n r.depositor_graph as Record<string, unknown>,\n );\n}\n\nfunction validateTransactionData(value: unknown, field: string): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n const tx = value as Record<string, unknown>;\n assertNonEmptyHex(tx.tx_hex, `${field}.tx_hex`);\n}\n\nfunction validateClaimerTransactions(value: unknown, field: string): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n\n const tx = value as Record<string, unknown>;\n\n assertBtcPubkey(tx.claimer_pubkey, `${field}.claimer_pubkey`);\n validateTransactionData(tx.claim_tx, `${field}.claim_tx`);\n validateTransactionData(tx.assert_tx, `${field}.assert_tx`);\n validateTransactionData(tx.payout_tx, `${field}.payout_tx`);\n assertNonEmptyString(tx.payout_psbt, `${field}.payout_psbt`);\n}\n\nfunction validateChallengeAssertConnectorData(\n value: unknown,\n field: string,\n): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n\n const c = value as Record<string, unknown>;\n assertNonEmptyString(c.wots_pks_json, `${field}.wots_pks_json`);\n assertNonEmptyString(c.gc_wots_keys_json, `${field}.gc_wots_keys_json`);\n}\n\nfunction validatePresignDataPerChallenger(value: unknown, field: string): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n\n const d = value as Record<string, unknown>;\n\n assertBtcPubkey(d.challenger_pubkey, `${field}.challenger_pubkey`);\n validateTransactionData(\n d.challenge_assert_x_tx,\n `${field}.challenge_assert_x_tx`,\n );\n validateTransactionData(\n d.challenge_assert_y_tx,\n `${field}.challenge_assert_y_tx`,\n );\n validateTransactionData(d.nopayout_tx, `${field}.nopayout_tx`);\n assertNonEmptyString(d.nopayout_psbt, `${field}.nopayout_psbt`);\n\n if (!Array.isArray(d.challenge_assert_connectors)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}.challenge_assert_connectors\" must be an array`,\n );\n }\n\n if (\n d.challenge_assert_connectors.length !==\n CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}.challenge_assert_connectors\" must have exactly ${CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER} entries, got ${d.challenge_assert_connectors.length}`,\n );\n }\n\n for (let i = 0; i < d.challenge_assert_connectors.length; i++) {\n validateChallengeAssertConnectorData(\n d.challenge_assert_connectors[i],\n `${field}.challenge_assert_connectors[${i}]`,\n );\n }\n\n if (!Array.isArray(d.output_label_hashes)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}.output_label_hashes\" must be an array`,\n );\n }\n\n for (let i = 0; i < d.output_label_hashes.length; i++) {\n assertNonEmptyHex(\n d.output_label_hashes[i],\n `${field}.output_label_hashes[${i}]`,\n );\n }\n}\n\n/**\n * Validate a requestDepositorClaimerArtifacts response.\n */\nexport function validateRequestDepositorClaimerArtifactsResponse(\n response: unknown,\n): asserts response is RequestDepositorClaimerArtifactsResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: requestDepositorClaimerArtifacts response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!isNonEmptyString(r.tx_graph_json)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"tx_graph_json\" must be a non-empty string, got ${preview(r.tx_graph_json)}`,\n );\n }\n\n if (!isNonEmptyHex(r.verifying_key_hex)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"verifying_key_hex\" must be a non-empty hex string, got ${preview(r.verifying_key_hex)}`,\n );\n }\n\n if (\n r.babe_sessions === null ||\n typeof r.babe_sessions !== \"object\" ||\n Array.isArray(r.babe_sessions)\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions\" must be an object`,\n );\n }\n\n const sessionEntries = Object.entries(\n r.babe_sessions as Record<string, unknown>,\n );\n if (sessionEntries.length === 0) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions\" must contain at least one challenger entry`,\n );\n }\n\n for (const [key, session] of sessionEntries) {\n assertBtcPubkey(key, `babe_sessions[\"${key}\"]`);\n if (session === null || typeof session !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions.${key}\" must be an object`,\n );\n }\n const s = session as Record<string, unknown>;\n if (!isNonEmptyHex(s.decryptor_artifacts_hex)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions.${key}.decryptor_artifacts_hex\" must be a non-empty hex string, got ${preview(s.decryptor_artifacts_hex)}`,\n );\n }\n }\n}\n\n/**\n * Validate a single pegout status payload. Embedded by\n * `validateBatchGetPegoutStatusResponse`. Mirrors btc-vault\n * `crates/vaultd/src/rpc/server/pegout_status.rs::GetPegoutStatusResponse`.\n */\nexport function validateGetPegoutStatusResponse(\n response: unknown,\n): asserts response is GetPegoutStatusResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: pegout status payload is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!isNonEmptyHex(r.pegin_txid) || r.pegin_txid.length !== TXID_HEX_LEN) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"pegin_txid\" must be a ${TXID_HEX_LEN}-char hex string (txid), got ${preview(r.pegin_txid)}`,\n );\n }\n\n if (typeof r.found !== \"boolean\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"found\" must be a boolean, got ${preview(r.found)}`,\n );\n }\n\n // `claimer` is `Option<ClaimerPegoutStatus>` server-side; null when absent.\n if (r.claimer !== null) {\n if (typeof r.claimer !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer\" must be an object or null, got ${preview(r.claimer)}`,\n );\n }\n validateClaimerPegoutStatus(r.claimer as Record<string, unknown>);\n }\n\n // `challengers: Vec<ChallengerStatus>` server-side; always present (possibly empty).\n if (!Array.isArray(r.challengers)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"challengers\" must be an array, got ${preview(r.challengers)}`,\n );\n }\n for (let i = 0; i < r.challengers.length; i++) {\n validateChallengerStatus(r.challengers[i], i);\n }\n}\n\nfunction validateClaimerPegoutStatus(value: Record<string, unknown>): void {\n assertNonEmptyString(value.status, \"claimer.status\");\n if (typeof value.failed !== \"boolean\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer.failed\" must be a boolean, got ${preview(value.failed)}`,\n );\n }\n assertNonEmptyString(value.claim_txid, \"claimer.claim_txid\");\n assertNonEmptyString(value.claimer_pubkey, \"claimer.claimer_pubkey\");\n assertNonEmptyString(value.assert_txid, \"claimer.assert_txid\");\n if (typeof value.created_at !== \"number\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer.created_at\" must be a number, got ${preview(value.created_at)}`,\n );\n }\n if (typeof value.updated_at !== \"number\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer.updated_at\" must be a number, got ${preview(value.updated_at)}`,\n );\n }\n}\n\nfunction validateChallengerStatus(value: unknown, index: number): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"challengers[${index}]\" must be an object, got ${preview(value)}`,\n );\n }\n const c = value as Record<string, unknown>;\n assertNonEmptyString(c.status, `challengers[${index}].status`);\n assertNonEmptyString(c.claim_txid, `challengers[${index}].claim_txid`);\n assertNonEmptyString(c.claimer_pubkey, `challengers[${index}].claimer_pubkey`);\n assertNullableString(c.assert_txid, `challengers[${index}].assert_txid`);\n assertNullableString(\n c.challenge_assert_x_txid,\n `challengers[${index}].challenge_assert_x_txid`,\n );\n assertNullableString(\n c.challenge_assert_y_txid,\n `challengers[${index}].challenge_assert_y_txid`,\n );\n assertNullableString(c.nopayout_txid, `challengers[${index}].nopayout_txid`);\n if (typeof c.created_at !== \"number\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"challengers[${index}].created_at\" must be a number, got ${preview(c.created_at)}`,\n );\n }\n if (typeof c.updated_at !== \"number\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"challengers[${index}].updated_at\" must be a number, got ${preview(c.updated_at)}`,\n );\n }\n}\n\nfunction assertNullableString(value: unknown, field: string): void {\n if (value !== null && typeof value !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a string or null, got ${preview(value)}`,\n );\n }\n}\n\n/**\n * Validate a `batchGetPeginStatus` response. Per-result envelope shape:\n * `{ pegin_txid, result: GetPeginStatusResponse | null, error: string | null }`.\n * The inner result (when non-null) is validated via the single-item validator.\n */\nexport function validateBatchGetPeginStatusResponse(\n response: unknown,\n): asserts response is BatchGetPeginStatusResponse {\n validateBatchEnvelope(response, \"batchGetPeginStatus\", (entry) => {\n if (entry.result !== null) {\n validateGetPeginStatusResponse(entry.result);\n }\n });\n}\n\n/** Validate a `batchGetPegoutStatus` response. Same envelope as peginStatus. */\nexport function validateBatchGetPegoutStatusResponse(\n response: unknown,\n): asserts response is BatchGetPegoutStatusResponse {\n validateBatchEnvelope(response, \"batchGetPegoutStatus\", (entry) => {\n if (entry.result !== null) {\n validateGetPegoutStatusResponse(entry.result);\n }\n });\n}\n\ninterface BatchResultEnvelope {\n pegin_txid: string;\n result: unknown;\n error: string | null;\n}\n\nfunction validateBatchEnvelope(\n response: unknown,\n rpcName: string,\n validateInnerResult: (entry: BatchResultEnvelope, index: number) => void,\n): void {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: ${rpcName} response is not an object`,\n );\n }\n const r = response as Record<string, unknown>;\n if (!Array.isArray(r.results)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${rpcName}.results\" must be an array, got ${preview(r.results)}`,\n );\n }\n for (let i = 0; i < r.results.length; i++) {\n const entry = r.results[i];\n if (entry === null || typeof entry !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${rpcName}.results[${i}]\" must be an object, got ${preview(entry)}`,\n );\n }\n const e = entry as Record<string, unknown>;\n if (\n !isNonEmptyHex(e.pegin_txid) ||\n e.pegin_txid.length !== TXID_HEX_LEN\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${rpcName}.results[${i}].pegin_txid\" must be a ${TXID_HEX_LEN}-char hex string, got ${preview(e.pegin_txid)}`,\n );\n }\n if (e.error !== null && typeof e.error !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${rpcName}.results[${i}].error\" must be a string or null, got ${preview(e.error)}`,\n );\n }\n // Exactly one of `result` / `error` must be populated. The server only\n // ever sets one per item; treating both-null as a protocol violation\n // surfaces server bugs early instead of letting them silently degrade.\n if (e.result === null && e.error === null) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${rpcName}.results[${i}]\" has neither \"result\" nor \"error\" populated`,\n );\n }\n if (e.result !== null && e.error !== null) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${rpcName}.results[${i}]\" has both \"result\" and \"error\" populated`,\n );\n }\n validateInnerResult(e as unknown as BatchResultEnvelope, i);\n }\n}\n\nfunction validateDepositorGraphTransactions(\n graph: Record<string, unknown>,\n): void {\n validateTransactionData(graph.claim_tx, \"depositor_graph.claim_tx\");\n validateTransactionData(graph.assert_tx, \"depositor_graph.assert_tx\");\n validateTransactionData(graph.payout_tx, \"depositor_graph.payout_tx\");\n assertNonEmptyString(graph.payout_psbt, \"depositor_graph.payout_psbt\");\n\n if (!Array.isArray(graph.challenger_presign_data)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"depositor_graph.challenger_presign_data\" must be an array`,\n );\n }\n\n for (let i = 0; i < graph.challenger_presign_data.length; i++) {\n validatePresignDataPerChallenger(\n graph.challenger_presign_data[i],\n `depositor_graph.challenger_presign_data[${i}]`,\n );\n }\n\n if (typeof graph.offchain_params_version !== \"number\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"depositor_graph.offchain_params_version\" must be a number`,\n );\n }\n}\n","/**\n * JSON-RPC client for the Vault Provider API.\n *\n * Wraps {@link JsonRpcClient} with typed methods matching the\n * `vaultProvider_*` RPC namespace defined in the btc-vault pegin spec.\n *\n * Implements the narrow service interfaces (PeginStatusReader, WotsKeySubmitter,\n * PresignClient, ClaimerArtifactsReader) so it can be passed directly to\n * any deposit protocol service function.\n *\n * @see https://github.com/babylonlabs-io/btc-vault/blob/main/docs/pegin.md\n */\n\nimport type { PeginStatusReader, WotsKeySubmitter, PresignClient, ClaimerArtifactsReader } from \"../../services/deposit/interfaces\";\n\nimport {\n type BearerTokenProvider,\n JsonRpcClient,\n type JsonRpcClientConfig,\n} from \"./json-rpc-client\";\nimport type {\n BatchGetPeginStatusParams,\n BatchGetPeginStatusResponse,\n BatchGetPegoutStatusParams,\n BatchGetPegoutStatusResponse,\n GetPeginStatusParams,\n GetPeginStatusResponse,\n RequestDepositorClaimerArtifactsParams,\n RequestDepositorClaimerArtifactsResponse,\n RequestDepositorPresignTransactionsParams,\n RequestDepositorPresignTransactionsResponse,\n SubmitDepositorPresignaturesParams,\n SubmitDepositorWotsKeyParams,\n} from \"./types\";\nimport {\n validateBatchGetPeginStatusResponse,\n validateBatchGetPegoutStatusResponse,\n validateGetPeginStatusResponse,\n validateRequestDepositorClaimerArtifactsResponse,\n validateRequestDepositorPresignTransactionsResponse,\n} from \"./validators\";\n\nexport interface VaultProviderRpcClientOptions {\n /** Timeout in milliseconds per request (default: 60000) */\n timeout?: number;\n /** Number of retry attempts for safe methods (default: 3) */\n retries?: number;\n /** Initial retry delay in milliseconds (default: 1000) */\n retryDelay?: number;\n /**\n * Custom retry predicate. Default retries only the idempotent read\n * methods: `getPeginStatus`, `batchGetPeginStatus`, `batchGetPegoutStatus`,\n * `requestDepositorPresignTransactions`.\n */\n retryableFor?: (method: string) => boolean;\n /** Custom headers. */\n headers?: Record<string, string>;\n /**\n * Per-request bearer-token source. A non-null return attaches\n * `Authorization: Bearer <token>`; `null` skips auth. Wire a\n * {@link VpTokenProvider} for depositor-gated methods.\n */\n tokenProvider?: BearerTokenProvider;\n /** Maximum response body size, in bytes, for typed JSON-RPC calls */\n maxResponseBytes?: number;\n}\n\nconst DEFAULT_TIMEOUT_MS = 60_000;\n\n/**\n * Concrete VP RPC client implementing all service interfaces.\n *\n * Usage:\n * ```ts\n * const client = new VaultProviderRpcClient(\"https://vp.example.com/rpc\");\n * const status = await client.getPeginStatus({ pegin_txid: \"abc...\" });\n * ```\n */\nexport class VaultProviderRpcClient\n implements PeginStatusReader, WotsKeySubmitter, PresignClient, ClaimerArtifactsReader\n{\n private client: JsonRpcClient;\n\n constructor(baseUrl: string, options?: VaultProviderRpcClientOptions) {\n const config: JsonRpcClientConfig = {\n baseUrl,\n timeout: options?.timeout ?? DEFAULT_TIMEOUT_MS,\n retries: options?.retries,\n retryDelay: options?.retryDelay,\n retryableFor: options?.retryableFor,\n headers: options?.headers,\n tokenProvider: options?.tokenProvider,\n maxResponseBytes: options?.maxResponseBytes,\n };\n this.client = new JsonRpcClient(config);\n }\n\n /**\n * Request the payout/claim/assert transactions that the depositor\n * needs to pre-sign before the vault can be activated on Bitcoin.\n */\n async requestDepositorPresignTransactions(\n params: RequestDepositorPresignTransactionsParams,\n signal?: AbortSignal,\n ): Promise<RequestDepositorPresignTransactionsResponse> {\n const response = await this.client.call<\n RequestDepositorPresignTransactionsParams,\n unknown\n >(\"vaultProvider_requestDepositorPresignTransactions\", params, signal);\n validateRequestDepositorPresignTransactionsResponse(response);\n return response;\n }\n\n /**\n * Submit the depositor's pre-signatures for the payout transactions\n * and the depositor-as-claimer graph.\n */\n async submitDepositorPresignatures(\n params: SubmitDepositorPresignaturesParams,\n signal?: AbortSignal,\n ): Promise<void> {\n return this.client.call<SubmitDepositorPresignaturesParams, void>(\n \"vaultProvider_submitDepositorPresignatures\",\n params,\n signal,\n );\n }\n\n /**\n * Submit the depositor's WOTS public key to the vault provider.\n * Called after the pegin is finalized on Ethereum, when the VP is in\n * `PendingDepositorWotsPK` status.\n */\n async submitDepositorWotsKey(\n params: SubmitDepositorWotsKeyParams,\n signal?: AbortSignal,\n ): Promise<void> {\n return this.client.call<SubmitDepositorWotsKeyParams, void>(\n \"vaultProvider_submitDepositorWotsKey\",\n params,\n signal,\n );\n }\n\n /**\n * Request the BaBe DecryptorArtifacts needed for the depositor to\n * independently evaluate garbled circuits during a challenge.\n */\n async requestDepositorClaimerArtifacts(\n params: RequestDepositorClaimerArtifactsParams,\n signal?: AbortSignal,\n ): Promise<RequestDepositorClaimerArtifactsResponse> {\n const response = await this.client.call<\n RequestDepositorClaimerArtifactsParams,\n unknown\n >(\"vaultProvider_requestDepositorClaimerArtifacts\", params, signal);\n validateRequestDepositorClaimerArtifactsResponse(response);\n return response;\n }\n\n /** Get the current pegin status from the vault provider daemon. */\n async getPeginStatus(\n params: GetPeginStatusParams,\n signal?: AbortSignal,\n ): Promise<GetPeginStatusResponse> {\n const response = await this.client.call<GetPeginStatusParams, unknown>(\n \"vaultProvider_getPeginStatus\",\n params,\n signal,\n );\n validateGetPeginStatusResponse(response);\n return response;\n }\n\n /**\n * Get pegin status for many txids in one round trip. Per-result envelope\n * isolates per-pegin failures from the overall RPC. Caller must chunk\n * inputs at `VP_BATCH_MAX_SIZE`.\n */\n async batchGetPeginStatus(\n params: BatchGetPeginStatusParams,\n signal?: AbortSignal,\n ): Promise<BatchGetPeginStatusResponse> {\n const response = await this.client.call<\n BatchGetPeginStatusParams,\n unknown\n >(\"vaultProvider_batchGetPeginStatus\", params, signal);\n validateBatchGetPeginStatusResponse(response);\n return response;\n }\n\n /**\n * Get pegout status for many txids in one round trip. Same per-result\n * envelope semantics as `batchGetPeginStatus`.\n */\n async batchGetPegoutStatus(\n params: BatchGetPegoutStatusParams,\n signal?: AbortSignal,\n ): Promise<BatchGetPegoutStatusResponse> {\n const response = await this.client.call<\n BatchGetPegoutStatusParams,\n unknown\n >(\"vaultProvider_batchGetPegoutStatus\", params, signal);\n validateBatchGetPegoutStatusResponse(response);\n return response;\n }\n}\n","/**\n * Defensive helper for attributing per-item results in a VP batch RPC\n * response back to the requested txids. The server promises 1:1 ordered\n * results, but we don't trust that promise — a server bug could duplicate,\n * skip, or scramble items, and silent attribution-by-array-index would\n * mask the bug.\n *\n * Lowercases all txids on both sides to absorb case mismatch (the FE\n * strips `0x` but doesn't otherwise normalize).\n *\n * @module tbv/core/clients/vault-provider/batchAttribution\n */\n\n/** Per-item entry in a VP batch response. */\nexport interface BatchResultEntry<T> {\n pegin_txid: string;\n result: T | null;\n error: string | null;\n}\n\n/** Output of {@link attributeBatchResults}. */\nexport interface BatchAttributionResult<T> {\n /** Lowercase requested txid -> per-item envelope. */\n byTxid: Map<string, { result: T | null; error: string | null }>;\n /** Requested txids that did not appear in the response. */\n missing: string[];\n /** Echoed txids that were not in the request — logged + dropped. */\n unexpected: string[];\n /** Echoed txids that appeared more than once — first kept, rest dropped. */\n duplicate: string[];\n}\n\n/**\n * Attribute batch results to requested txids defensively.\n *\n * Both `requestedTxids` and the echoed `pegin_txid` field on each result\n * are lowercased before lookup. Duplicates and unexpected echoes are\n * surfaced so callers can flag the affected items as errored rather than\n * silently overwriting state.\n *\n * `requestedTxids` may contain duplicates; they are de-duplicated for the\n * purposes of map keys (each unique txid becomes a single map entry).\n */\nexport function attributeBatchResults<T>(\n requestedTxids: string[],\n results: ReadonlyArray<BatchResultEntry<T>>,\n): BatchAttributionResult<T> {\n const requestedSet = new Set<string>();\n for (const txid of requestedTxids) {\n requestedSet.add(txid.toLowerCase());\n }\n\n const byTxid = new Map<\n string,\n { result: T | null; error: string | null }\n >();\n const seen = new Set<string>();\n const duplicate: string[] = [];\n const unexpected: string[] = [];\n\n for (const entry of results) {\n const lower = entry.pegin_txid.toLowerCase();\n if (!requestedSet.has(lower)) {\n unexpected.push(lower);\n continue;\n }\n if (seen.has(lower)) {\n duplicate.push(lower);\n continue;\n }\n seen.add(lower);\n byTxid.set(lower, { result: entry.result, error: entry.error });\n }\n\n const missing: string[] = [];\n for (const txid of requestedSet) {\n if (!seen.has(txid)) missing.push(txid);\n }\n\n return { byTxid, missing, unexpected, duplicate };\n}\n","/**\n * Generic chunk + attribute + dispatch loop for VP batch RPCs.\n *\n * Wraps {@link attributeBatchResults} with chunking and per-callback\n * dispatch so the FE polling hooks (and any future SDK consumer) only\n * have to declare per-item handlers — chunking by `VP_BATCH_MAX_SIZE`,\n * lowercase txid normalization, missing/duplicate/unexpected\n * surfacing, and the duplicate-skip invariant in the byTxid loop are\n * all owned here.\n *\n * @module tbv/core/clients/vault-provider/batchPoll\n */\n\nimport {\n attributeBatchResults,\n type BatchResultEntry,\n} from \"./batchAttribution\";\nimport { VP_BATCH_MAX_SIZE } from \"./types\";\n\nexport interface BatchPollByProviderOptions<TItem, TResult> {\n /** Items to poll for this provider, e.g. `DepositToPoll[]`. */\n items: TItem[];\n /** Extract the canonical txid for each item. Helper lowercases it. */\n getTxid: (item: TItem) => string;\n /**\n * Per-chunk RPC call. Receives lowercased txids; returns the batch\n * envelope. Caller wraps `rpcClient.batchGet*Status({ pegin_txids })`.\n */\n batchCall: (\n txids: string[],\n ) => Promise<{ results: ReadonlyArray<BatchResultEntry<TResult>> }>;\n /**\n * Handle a per-item envelope. Exactly one of `result` / `error` is\n * populated (validator invariant). Caller decides UI state, logging,\n * etc. Not invoked for txids surfaced via {@link onDuplicate}.\n *\n * Note: `envelope.pegin_txid` is the lowercased txid the helper\n * sent in the request, not whatever case/encoding the server echoed.\n */\n onItem: (item: TItem, envelope: BatchResultEntry<TResult>) => void;\n /** Server omitted this item from the response. */\n onMissing: (item: TItem) => void;\n /** Server returned this item more than once. Caller picks UI state. */\n onDuplicate: (item: TItem) => void;\n /**\n * Optional aggregate signal for an entire chunk where the server\n * returned duplicates. Fires once per chunk (only if `count > 0`)\n * AFTER all per-item `onDuplicate` dispatches. Caller typically logs\n * the count alongside the provider name.\n */\n onDuplicateBatch?: (count: number) => void;\n /**\n * The whole chunk's RPC call failed (transport or response\n * validation). Receives the chunk and the error. Caller decides how\n * to project that onto per-item state.\n */\n onWholeBatchError: (chunk: TItem[], error: unknown) => void;\n /**\n * Server returned txids that were not in the request. Caller\n * typically logs the count for observability — there's no recovery\n * action since the original request items are unaffected. Optional;\n * defaults to no-op.\n */\n onUnexpected?: (echoedTxids: string[]) => void;\n /**\n * Maximum items per RPC call. Defaults to {@link VP_BATCH_MAX_SIZE}.\n * Exposed for tests so chunking can be exercised without 50+\n * fixtures.\n */\n batchSize?: number;\n}\n\nexport async function batchPollByProvider<TItem, TResult>(\n options: BatchPollByProviderOptions<TItem, TResult>,\n): Promise<void> {\n const {\n items,\n getTxid,\n batchCall,\n onItem,\n onMissing,\n onDuplicate,\n onDuplicateBatch,\n onWholeBatchError,\n onUnexpected,\n batchSize = VP_BATCH_MAX_SIZE,\n } = options;\n\n if (!Number.isInteger(batchSize) || batchSize <= 0) {\n throw new Error(\n `batchPollByProvider: batchSize must be a positive integer, got ${batchSize}`,\n );\n }\n\n for (let i = 0; i < items.length; i += batchSize) {\n const chunk = items.slice(i, i + batchSize);\n const txidToItem = new Map<string, TItem>();\n const txids: string[] = [];\n for (const item of chunk) {\n const lowerTxid = getTxid(item).toLowerCase();\n txidToItem.set(lowerTxid, item);\n txids.push(lowerTxid);\n }\n\n // Both the RPC call and attribution sit inside the same try/catch\n // so a malformed-batch validator throw is routed through\n // `onWholeBatchError` rather than aborting the polling pass.\n let attribution;\n try {\n const response = await batchCall(txids);\n attribution = attributeBatchResults<TResult>(txids, response.results);\n } catch (error) {\n onWholeBatchError(chunk, error);\n continue;\n }\n\n if (onUnexpected && attribution.unexpected.length > 0) {\n onUnexpected(attribution.unexpected);\n }\n\n const duplicateTxids = new Set(attribution.duplicate);\n for (const txid of duplicateTxids) {\n const item = txidToItem.get(txid);\n if (item) onDuplicate(item);\n }\n if (onDuplicateBatch && duplicateTxids.size > 0) {\n onDuplicateBatch(duplicateTxids.size);\n }\n for (const txid of attribution.missing) {\n const item = txidToItem.get(txid);\n if (item) onMissing(item);\n }\n for (const [txid, envelope] of attribution.byTxid) {\n // Skip duplicates — already dispatched via onDuplicate above.\n if (duplicateTxids.has(txid)) continue;\n const item = txidToItem.get(txid);\n if (!item) continue;\n onItem(item, {\n pegin_txid: txid,\n result: envelope.result,\n error: envelope.error,\n });\n }\n }\n}\n"],"names":["DAEMON_STATUS_VALUES","DaemonStatus","VP_ERROR_PREVIEW_MAX_LEN","preview","value","_a","VP_VALIDATION_USER_MESSAGE","VpResponseValidationError","detail","__publicField","TXID_HEX_LEN","isNonEmptyHex","HEX_RE","isNonEmptyString","assertNonEmptyHex","field","assertNonEmptyString","assertBtcPubkey","X_ONLY_PUBKEY_HEX_LEN","COMPRESSED_PUBKEY_HEX_LEN","validatePresigningProgressFields","progress","presigning","p","validateGetPeginStatusResponse","response","r","validateRequestDepositorPresignTransactionsResponse","i","validateClaimerTransactions","validateDepositorGraphTransactions","validateTransactionData","tx","validateChallengeAssertConnectorData","c","validatePresignDataPerChallenger","d","CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER","validateRequestDepositorClaimerArtifactsResponse","sessionEntries","key","session","s","validateGetPegoutStatusResponse","validateClaimerPegoutStatus","validateChallengerStatus","index","assertNullableString","validateBatchGetPeginStatusResponse","validateBatchEnvelope","entry","validateBatchGetPegoutStatusResponse","rpcName","validateInnerResult","e","graph","DEFAULT_TIMEOUT_MS","VaultProviderRpcClient","baseUrl","options","config","JsonRpcClient","params","signal","attributeBatchResults","requestedTxids","results","requestedSet","txid","byTxid","seen","duplicate","unexpected","lower","missing","batchPollByProvider","items","getTxid","batchCall","onItem","onMissing","onDuplicate","onDuplicateBatch","onWholeBatchError","onUnexpected","batch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,EAAQa,CAAI,EAAE,YAAA,EAChCF,EAAW,IAAIG,EAAWD,CAAI,EAC9BD,EAAM,KAAKE,CAAS,CACtB,CAKA,IAAIC,EACJ,GAAI,CACF,MAAMnE,EAAW,MAAMqD,EAAUW,CAAK,EACtCG,EAAc5B,GAA+ByB,EAAOhE,EAAS,OAAO,CACtE,OAASoE,EAAO,CACdV,EAAkBI,EAAOM,CAAK,EAC9B,QACF,CAEIT,GAAgBQ,EAAY,WAAW,OAAS,GAClDR,EAAaQ,EAAY,UAAU,EAGrC,MAAME,EAAiB,IAAI,IAAIF,EAAY,SAAS,EACpD,UAAWxB,KAAQ0B,EAAgB,CACjC,MAAMJ,EAAOF,EAAW,IAAIpB,CAAI,EAC5BsB,KAAkBA,CAAI,CAC5B,CACIR,GAAoBY,EAAe,KAAO,GAC5CZ,EAAiBY,EAAe,IAAI,EAEtC,UAAW1B,KAAQwB,EAAY,QAAS,CACtC,MAAMF,EAAOF,EAAW,IAAIpB,CAAI,EAC5BsB,KAAgBA,CAAI,CAC1B,CACA,SAAW,CAACtB,EAAM2B,CAAQ,IAAKH,EAAY,OAAQ,CAEjD,GAAIE,EAAe,IAAI1B,CAAI,EAAG,SAC9B,MAAMsB,EAAOF,EAAW,IAAIpB,CAAI,EAC3BsB,GACLX,EAAOW,EAAM,CACX,WAAYtB,EACZ,OAAQ2B,EAAS,OACjB,MAAOA,EAAS,KAAA,CACjB,CACH,CACF,CACF"}
|
|
@@ -2,7 +2,7 @@ var G = Object.defineProperty;
|
|
|
2
2
|
var N = (s, e, t) => e in s ? G(s, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : s[e] = t;
|
|
3
3
|
var V = (s, e, t) => N(s, typeof e != "symbol" ? e + "" : e, t);
|
|
4
4
|
import { D as O, a as H, e as M } from "./json-rpc-client-DuUARJvV.js";
|
|
5
|
-
import { C as A } from "./constants-
|
|
5
|
+
import { C as A } from "./constants-D5vORbQE.js";
|
|
6
6
|
import { H as q, X as k, C as D } from "./validation-OSC0xTHB.js";
|
|
7
7
|
const R = new Set(Object.values(O)), I = 200;
|
|
8
8
|
function a(s) {
|
|
@@ -502,4 +502,4 @@ export {
|
|
|
502
502
|
ue as b,
|
|
503
503
|
Y as v
|
|
504
504
|
};
|
|
505
|
-
//# sourceMappingURL=index-
|
|
505
|
+
//# sourceMappingURL=index-DQ5bfoT3.js.map
|