@babylonlabs-io/ts-sdk 0.36.3 → 0.37.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/PayoutManager-BxAY2x0g.cjs +2 -0
- package/dist/PayoutManager-BxAY2x0g.cjs.map +1 -0
- package/dist/{PayoutManager-s_uH8Uuj.js → PayoutManager-sfxuOBGq.js} +51 -43
- package/dist/PayoutManager-sfxuOBGq.js.map +1 -0
- package/dist/{PeginManager-CB-dVkT2.js → PeginManager-B1Mh8dJ3.js} +332 -323
- package/dist/PeginManager-B1Mh8dJ3.js.map +1 -0
- package/dist/PeginManager-BbHPyz-G.cjs +2 -0
- package/dist/PeginManager-BbHPyz-G.cjs.map +1 -0
- package/dist/assertPsbtUnsignedTxMatches-BoHwgW30.cjs +2 -0
- package/dist/assertPsbtUnsignedTxMatches-BoHwgW30.cjs.map +1 -0
- package/dist/assertPsbtUnsignedTxMatches-D7RxpR4A.js +263 -0
- package/dist/assertPsbtUnsignedTxMatches-D7RxpR4A.js.map +1 -0
- package/dist/{bitcoin-B0S8SHCX.js → bitcoin-B5aNKtsk.js} +77 -60
- package/dist/{bitcoin-B0S8SHCX.js.map → bitcoin-B5aNKtsk.js.map} +1 -1
- package/dist/bitcoin-CHfKAhcI.cjs +2 -0
- package/dist/{bitcoin-B3aqjuMP.cjs.map → bitcoin-CHfKAhcI.cjs.map} +1 -1
- package/dist/{buildAndBroadcastRefund-C2VqXiOx.js → buildAndBroadcastRefund-Ck_ddlLk.js} +333 -328
- package/dist/buildAndBroadcastRefund-Ck_ddlLk.js.map +1 -0
- package/dist/buildAndBroadcastRefund-DyPQyghx.cjs +2 -0
- package/dist/buildAndBroadcastRefund-DyPQyghx.cjs.map +1 -0
- package/dist/{challengeAssert-Yyyj-EdR.cjs → challengeAssert-BKDS_ADt.cjs} +2 -2
- package/dist/{challengeAssert-Yyyj-EdR.cjs.map → challengeAssert-BKDS_ADt.cjs.map} +1 -1
- package/dist/{challengeAssert-BzxQmdZy.js → challengeAssert-BXESW00N.js} +7 -7
- package/dist/{challengeAssert-BzxQmdZy.js.map → challengeAssert-BXESW00N.js.map} +1 -1
- package/dist/fundPeginTransaction-BBE3wTjR.cjs +2 -0
- package/dist/{fundPeginTransaction-DaWoYCgO.cjs.map → fundPeginTransaction-BBE3wTjR.cjs.map} +1 -1
- package/dist/fundPeginTransaction-t-6TsHAY.js +84 -0
- package/dist/{fundPeginTransaction-oV-dNJOU.js.map → fundPeginTransaction-t-6TsHAY.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +174 -166
- package/dist/{noPayout-BXeUw0Qq.cjs → noPayout-B6s8vrW6.cjs} +2 -2
- package/dist/{noPayout-BXeUw0Qq.cjs.map → noPayout-B6s8vrW6.cjs.map} +1 -1
- package/dist/{noPayout-DBX6G96_.js → noPayout-BhgknZBx.js} +2 -2
- package/dist/{noPayout-DBX6G96_.js.map → noPayout-BhgknZBx.js.map} +1 -1
- package/dist/{peginInput-tbw9BpZy.cjs → peginInput-57FK2O99.cjs} +2 -2
- package/dist/{peginInput-tbw9BpZy.cjs.map → peginInput-57FK2O99.cjs.map} +1 -1
- package/dist/{peginInput-C2QPvuhR.js → peginInput-CYJzbuwA.js} +3 -3
- package/dist/{peginInput-C2QPvuhR.js.map → peginInput-CYJzbuwA.js.map} +1 -1
- package/dist/{reservation-fZUvejYK.js → reservation-CB-4FBPk.js} +3 -3
- package/dist/{reservation-fZUvejYK.js.map → reservation-CB-4FBPk.js.map} +1 -1
- package/dist/{reservation-DF0uiCUC.cjs → reservation-hjXStM03.cjs} +2 -2
- package/dist/{reservation-DF0uiCUC.cjs.map → reservation-hjXStM03.cjs.map} +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +172 -164
- package/dist/tbv/core/managers/PayoutManager.d.ts.map +1 -1
- package/dist/tbv/core/managers/PeginManager.d.ts +7 -8
- package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
- 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.d.ts +3 -1
- package/dist/tbv/core/primitives/index.d.ts.map +1 -1
- package/dist/tbv/core/primitives/index.js +31 -27
- package/dist/tbv/core/primitives/psbt/__tests__/assertPsbtUnsignedTxMatches.test.d.ts +5 -0
- package/dist/tbv/core/primitives/psbt/__tests__/assertPsbtUnsignedTxMatches.test.d.ts.map +1 -0
- package/dist/tbv/core/primitives/psbt/assertPsbtUnsignedTxMatches.d.ts +31 -0
- package/dist/tbv/core/primitives/psbt/assertPsbtUnsignedTxMatches.d.ts.map +1 -0
- package/dist/tbv/core/primitives/psbt/index.d.ts +2 -0
- package/dist/tbv/core/primitives/psbt/index.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts +33 -3
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/index.d.ts +1 -1
- package/dist/tbv/core/primitives/utils/index.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/signDepositorGraph.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/services/refund/buildAndBroadcastRefund.d.ts.map +1 -1
- package/dist/tbv/core/utils/fee/__tests__/peginFeeMath.test.d.ts +19 -0
- package/dist/tbv/core/utils/fee/__tests__/peginFeeMath.test.d.ts.map +1 -0
- package/dist/tbv/core/utils/fee/index.d.ts +1 -0
- package/dist/tbv/core/utils/fee/index.d.ts.map +1 -1
- package/dist/tbv/core/utils/fee/peginFeeMath.d.ts +99 -0
- package/dist/tbv/core/utils/fee/peginFeeMath.d.ts.map +1 -0
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +44 -40
- package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts.map +1 -1
- package/dist/tbv/core/utils/utxo/selectUtxos.d.ts.map +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +172 -164
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/{vault-registry-reader-Br9m8bHF.cjs → vault-registry-reader-7gOYnrQD.cjs} +2 -2
- package/dist/{vault-registry-reader-Br9m8bHF.cjs.map → vault-registry-reader-7gOYnrQD.cjs.map} +1 -1
- package/dist/{vault-registry-reader-CohvzvoH.js → vault-registry-reader-Blhu9FW2.js} +2 -2
- package/dist/{vault-registry-reader-CohvzvoH.js.map → vault-registry-reader-Blhu9FW2.js.map} +1 -1
- package/dist/waitForTransactionReceiptSmartAware-CmgFXFza.js +265 -0
- package/dist/waitForTransactionReceiptSmartAware-CmgFXFza.js.map +1 -0
- package/dist/waitForTransactionReceiptSmartAware-tv1mtSIY.cjs +2 -0
- package/dist/waitForTransactionReceiptSmartAware-tv1mtSIY.cjs.map +1 -0
- package/package.json +1 -1
- package/dist/PayoutManager-BhJoQZsG.cjs +0 -2
- package/dist/PayoutManager-BhJoQZsG.cjs.map +0 -1
- package/dist/PayoutManager-s_uH8Uuj.js.map +0 -1
- package/dist/PeginManager-BPXVXu8t.cjs +0 -2
- package/dist/PeginManager-BPXVXu8t.cjs.map +0 -1
- package/dist/PeginManager-CB-dVkT2.js.map +0 -1
- package/dist/bitcoin-B3aqjuMP.cjs +0 -2
- package/dist/buildAndBroadcastRefund-C2VqXiOx.js.map +0 -1
- package/dist/buildAndBroadcastRefund-CBIfcF47.cjs +0 -2
- package/dist/buildAndBroadcastRefund-CBIfcF47.cjs.map +0 -1
- package/dist/fundPeginTransaction-DaWoYCgO.cjs +0 -2
- package/dist/fundPeginTransaction-oV-dNJOU.js +0 -76
- package/dist/payout-BNFMBXS6.js +0 -193
- package/dist/payout-BNFMBXS6.js.map +0 -1
- package/dist/payout-DQ_fmJUA.cjs +0 -2
- package/dist/payout-DQ_fmJUA.cjs.map +0 -1
- package/dist/waitForTransactionReceiptSmartAware-Cj_DKm0G.js +0 -217
- package/dist/waitForTransactionReceiptSmartAware-Cj_DKm0G.js.map +0 -1
- package/dist/waitForTransactionReceiptSmartAware-D9ykVriz.cjs +0 -2
- package/dist/waitForTransactionReceiptSmartAware-D9ykVriz.cjs.map +0 -1
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { script as E, Transaction as T } from "bitcoinjs-lib";
|
|
2
|
+
import { Buffer as d } from "buffer";
|
|
3
|
+
import { D as p, M as m, r as I, P as _, T as P, B as v } from "./fundPeginTransaction-t-6TsHAY.js";
|
|
4
|
+
function S(t) {
|
|
5
|
+
const { numInputs: e, numOutputs: n, feeRate: a } = t;
|
|
6
|
+
if (!Number.isInteger(e) || e < 0)
|
|
7
|
+
throw new Error(
|
|
8
|
+
`computePeginBaseFeeSats: numInputs must be a non-negative integer, got ${e}`
|
|
9
|
+
);
|
|
10
|
+
if (!Number.isInteger(n) || n < 1)
|
|
11
|
+
throw new Error(
|
|
12
|
+
`computePeginBaseFeeSats: numOutputs must be a positive integer, got ${n}`
|
|
13
|
+
);
|
|
14
|
+
const r = e * _ + n * m + P;
|
|
15
|
+
return BigInt(Math.ceil(r * a)) + BigInt(I(a));
|
|
16
|
+
}
|
|
17
|
+
function U(t) {
|
|
18
|
+
return BigInt(Math.ceil(m * t));
|
|
19
|
+
}
|
|
20
|
+
function $(t) {
|
|
21
|
+
const { totalInputValue: e, peginAmount: n, baseFee: a, changeOutputFee: r } = t, c = e - n - a;
|
|
22
|
+
if (c < 0n)
|
|
23
|
+
throw new Error(
|
|
24
|
+
`applyChangeOutputPolicy: insufficient funds (need ${n + a} sats, have ${e})`
|
|
25
|
+
);
|
|
26
|
+
const i = c - r;
|
|
27
|
+
return i > p ? {
|
|
28
|
+
fee: a + r,
|
|
29
|
+
changeAmount: i,
|
|
30
|
+
emitChangeOutput: !0
|
|
31
|
+
} : {
|
|
32
|
+
fee: a + c,
|
|
33
|
+
changeAmount: 0n,
|
|
34
|
+
emitChangeOutput: !1
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function N(t) {
|
|
38
|
+
const { numInputs: e, numOutputs: n, totalBalance: a, feeRate: r } = t;
|
|
39
|
+
if (a <= 0n) return null;
|
|
40
|
+
const c = S({ numInputs: e, numOutputs: n, feeRate: r }), i = a - c;
|
|
41
|
+
return i > 0n ? i : 0n;
|
|
42
|
+
}
|
|
43
|
+
function O(t) {
|
|
44
|
+
const e = /* @__PURE__ */ new Set();
|
|
45
|
+
for (const n of t) {
|
|
46
|
+
const a = `${n.txid.toLowerCase()}:${n.vout}`;
|
|
47
|
+
if (e.has(a))
|
|
48
|
+
throw new Error(
|
|
49
|
+
`Duplicate UTXO detected: ${n.txid}:${n.vout}. This indicates a data integrity issue with the UTXO source.`
|
|
50
|
+
);
|
|
51
|
+
e.add(a);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function L(t, e, n, a) {
|
|
55
|
+
if (!Number.isInteger(a) || a < 1)
|
|
56
|
+
throw new Error(
|
|
57
|
+
`Invalid numOutputs: expected a positive integer, got ${a}`
|
|
58
|
+
);
|
|
59
|
+
if (t.length === 0)
|
|
60
|
+
throw new Error("Insufficient funds: no UTXOs available");
|
|
61
|
+
O(t);
|
|
62
|
+
const r = t.filter((o) => {
|
|
63
|
+
const s = d.from(o.scriptPubKey, "hex");
|
|
64
|
+
return !!E.decompile(s);
|
|
65
|
+
});
|
|
66
|
+
if (r.length === 0)
|
|
67
|
+
throw new Error(
|
|
68
|
+
"Insufficient funds: no valid UTXOs available (all have invalid scripts)"
|
|
69
|
+
);
|
|
70
|
+
const c = [...r].sort((o, s) => s.value - o.value), i = [];
|
|
71
|
+
let u = 0n, f = 0n;
|
|
72
|
+
for (const o of c) {
|
|
73
|
+
i.push(o), u += BigInt(o.value);
|
|
74
|
+
const s = S({
|
|
75
|
+
numInputs: i.length,
|
|
76
|
+
numOutputs: a,
|
|
77
|
+
feeRate: n
|
|
78
|
+
}), l = U(n);
|
|
79
|
+
if (u < e + s) {
|
|
80
|
+
f = s;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
const w = $({
|
|
84
|
+
totalInputValue: u,
|
|
85
|
+
peginAmount: e,
|
|
86
|
+
baseFee: s,
|
|
87
|
+
changeOutputFee: l
|
|
88
|
+
});
|
|
89
|
+
return {
|
|
90
|
+
selectedUTXOs: i,
|
|
91
|
+
totalValue: u,
|
|
92
|
+
fee: w.fee,
|
|
93
|
+
changeAmount: w.changeAmount
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
throw new Error(
|
|
97
|
+
`Insufficient funds: need ${e + f} sats (${e} pegin + ${f} fee), have ${u} sats`
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
function M(t) {
|
|
101
|
+
return t > p;
|
|
102
|
+
}
|
|
103
|
+
function V() {
|
|
104
|
+
return v;
|
|
105
|
+
}
|
|
106
|
+
function X(t) {
|
|
107
|
+
const e = t.startsWith("0x") ? t.slice(2) : t;
|
|
108
|
+
return `0x${T.fromHex(e).getId()}`;
|
|
109
|
+
}
|
|
110
|
+
var h = /* @__PURE__ */ ((t) => (t.P2PKH = "P2PKH", t.P2SH = "P2SH", t.P2WPKH = "P2WPKH", t.P2WSH = "P2WSH", t.P2TR = "P2TR", t.UNKNOWN = "UNKNOWN", t))(h || {});
|
|
111
|
+
function F(t) {
|
|
112
|
+
const e = t.length;
|
|
113
|
+
return e === 25 && t[0] === 118 && // OP_DUP
|
|
114
|
+
t[1] === 169 && // OP_HASH160
|
|
115
|
+
t[2] === 20 && // Push 20 bytes
|
|
116
|
+
t[23] === 136 && // OP_EQUALVERIFY
|
|
117
|
+
t[24] === 172 ? "P2PKH" : e === 23 && t[0] === 169 && // OP_HASH160
|
|
118
|
+
t[1] === 20 && // Push 20 bytes
|
|
119
|
+
t[22] === 135 ? "P2SH" : e === 22 && t[0] === 0 && // OP_0
|
|
120
|
+
t[1] === 20 ? "P2WPKH" : e === 34 && t[0] === 0 && // OP_0
|
|
121
|
+
t[1] === 32 ? "P2WSH" : e === 34 && t[0] === 81 && // OP_1
|
|
122
|
+
t[1] === 32 ? "P2TR" : "UNKNOWN";
|
|
123
|
+
}
|
|
124
|
+
function b(t, e) {
|
|
125
|
+
const n = d.from(t.scriptPubKey, "hex"), a = F(n);
|
|
126
|
+
switch (a) {
|
|
127
|
+
case h.P2WPKH:
|
|
128
|
+
return {
|
|
129
|
+
witnessUtxo: {
|
|
130
|
+
script: n,
|
|
131
|
+
value: t.value
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
case h.P2WSH: {
|
|
135
|
+
if (!t.witnessScript)
|
|
136
|
+
throw new Error("Missing witnessScript for P2WSH input");
|
|
137
|
+
return {
|
|
138
|
+
witnessUtxo: {
|
|
139
|
+
script: n,
|
|
140
|
+
value: t.value
|
|
141
|
+
},
|
|
142
|
+
witnessScript: d.from(t.witnessScript, "hex")
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
case h.P2TR: {
|
|
146
|
+
if (e && e.length !== 32)
|
|
147
|
+
throw new Error(
|
|
148
|
+
`Invalid tapInternalKey length: expected 32 bytes, got ${e.length}`
|
|
149
|
+
);
|
|
150
|
+
return {
|
|
151
|
+
witnessUtxo: {
|
|
152
|
+
script: n,
|
|
153
|
+
value: t.value
|
|
154
|
+
},
|
|
155
|
+
// tapInternalKey is needed for Taproot signing
|
|
156
|
+
...e && { tapInternalKey: e }
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
default:
|
|
160
|
+
throw new Error(`Unsupported script type: ${a}`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const A = {
|
|
164
|
+
1: "https://safe-transaction-mainnet.safe.global",
|
|
165
|
+
11155111: "https://safe-transaction-sepolia.safe.global"
|
|
166
|
+
}, x = 5e3, H = 14400 * 1e3, R = 1e4;
|
|
167
|
+
async function q(t) {
|
|
168
|
+
const {
|
|
169
|
+
publicClient: e,
|
|
170
|
+
walletAddress: n,
|
|
171
|
+
hash: a,
|
|
172
|
+
confirmations: r,
|
|
173
|
+
timeout: c,
|
|
174
|
+
safePollTimeoutMs: i = H,
|
|
175
|
+
safePollIntervalMs: u = x
|
|
176
|
+
} = t, f = await e.getCode({ address: n });
|
|
177
|
+
if (!(f !== void 0 && f !== "0x"))
|
|
178
|
+
return e.waitForTransactionReceipt({
|
|
179
|
+
hash: a,
|
|
180
|
+
confirmations: r,
|
|
181
|
+
timeout: c
|
|
182
|
+
});
|
|
183
|
+
const s = await e.getChainId(), l = await C({
|
|
184
|
+
chainId: s,
|
|
185
|
+
safeTxHash: a,
|
|
186
|
+
pollIntervalMs: u,
|
|
187
|
+
timeoutMs: i
|
|
188
|
+
});
|
|
189
|
+
return e.waitForTransactionReceipt({
|
|
190
|
+
hash: l,
|
|
191
|
+
confirmations: r
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
async function C({
|
|
195
|
+
chainId: t,
|
|
196
|
+
safeTxHash: e,
|
|
197
|
+
pollIntervalMs: n,
|
|
198
|
+
timeoutMs: a
|
|
199
|
+
}) {
|
|
200
|
+
const r = A[t];
|
|
201
|
+
if (!r)
|
|
202
|
+
throw new Error(
|
|
203
|
+
`Safe Transaction Service not configured for chainId ${t}. Connected wallet appears to be a smart-contract account, but this chain is not in the supported list. Either connect an EOA or extend SAFE_TX_SERVICE_BASE_URLS in waitForTransactionReceiptSmartAware.ts.`
|
|
204
|
+
);
|
|
205
|
+
const c = `${r}/api/v1/multisig-transactions/${e}/`, i = Date.now() + a;
|
|
206
|
+
for (; Date.now() < i; ) {
|
|
207
|
+
const u = new AbortController(), f = setTimeout(
|
|
208
|
+
() => u.abort(),
|
|
209
|
+
R
|
|
210
|
+
);
|
|
211
|
+
let o;
|
|
212
|
+
try {
|
|
213
|
+
o = await fetch(c, { signal: u.signal });
|
|
214
|
+
} catch (s) {
|
|
215
|
+
console.warn(
|
|
216
|
+
`Safe Transaction Service request failed (will retry in ${n}ms): ` + (s instanceof Error ? s.message : String(s))
|
|
217
|
+
), await g(n);
|
|
218
|
+
continue;
|
|
219
|
+
} finally {
|
|
220
|
+
clearTimeout(f);
|
|
221
|
+
}
|
|
222
|
+
if (o.ok) {
|
|
223
|
+
const s = await o.json();
|
|
224
|
+
if (s.isExecuted) {
|
|
225
|
+
if (s.isSuccessful === !1)
|
|
226
|
+
throw new Error(
|
|
227
|
+
`Safe transaction ${e} was executed on chain but reverted. Check the Safe queue UI for details.`
|
|
228
|
+
);
|
|
229
|
+
if (s.transactionHash)
|
|
230
|
+
return s.transactionHash;
|
|
231
|
+
}
|
|
232
|
+
} else if (o.status !== 404) if (o.status >= 500)
|
|
233
|
+
console.warn(
|
|
234
|
+
`Safe Transaction Service returned ${o.status} for ${e}; retrying in ${n}ms.`
|
|
235
|
+
);
|
|
236
|
+
else
|
|
237
|
+
throw new Error(
|
|
238
|
+
`Safe Transaction Service returned ${o.status} for ${e}.`
|
|
239
|
+
);
|
|
240
|
+
await g(n);
|
|
241
|
+
}
|
|
242
|
+
throw new Error(
|
|
243
|
+
`Timed out after ${a}ms waiting for Safe transaction ${e} to reach quorum and execute. The proposal is still pending in the Safe queue — co-signers must sign and execute it before the dApp can proceed.`
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
function g(t) {
|
|
247
|
+
return new Promise((e) => {
|
|
248
|
+
setTimeout(e, t);
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
export {
|
|
252
|
+
h as B,
|
|
253
|
+
$ as a,
|
|
254
|
+
N as b,
|
|
255
|
+
U as c,
|
|
256
|
+
S as d,
|
|
257
|
+
M as e,
|
|
258
|
+
X as f,
|
|
259
|
+
V as g,
|
|
260
|
+
F as h,
|
|
261
|
+
b as i,
|
|
262
|
+
L as s,
|
|
263
|
+
q as w
|
|
264
|
+
};
|
|
265
|
+
//# sourceMappingURL=waitForTransactionReceiptSmartAware-CmgFXFza.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"waitForTransactionReceiptSmartAware-CmgFXFza.js","sources":["../src/tbv/core/utils/fee/peginFeeMath.ts","../src/tbv/core/utils/utxo/selectUtxos.ts","../src/tbv/core/utils/transaction/btcTxHash.ts","../src/tbv/core/utils/btc/scriptType.ts","../src/tbv/core/utils/btc/psbtInputFields.ts","../src/tbv/core/utils/eth/waitForTransactionReceiptSmartAware.ts"],"sourcesContent":["/**\n * Pre-PegIn fee math primitives used by both UTXO selection and\n * transaction funding so they make bit-identical decisions about base\n * fee, change-output fee, and whether to emit change at all.\n *\n * Dust handling matches the wallet-side check in\n * `babylon-vault crates/btc-wallet-remote/src/client.rs` (dust-change\n * rejection): a change output is emitted only when the post-fee residual\n * exceeds DUST_THRESHOLD (546 sats). Broader fee-estimation behaviors\n * (output sizing, safety margins) are NOT cross-stack guarantees — see\n * JS-vs-Rust parity fixtures in `__tests__/peginFeeMath.test.ts` for the\n * invariants we pin.\n */\n\nimport {\n DUST_THRESHOLD,\n MAX_NON_LEGACY_OUTPUT_SIZE,\n P2TR_INPUT_SIZE,\n rateBasedTxBufferFee,\n TX_BUFFER_SIZE_OVERHEAD,\n} from \"./constants\";\n\nexport interface ComputeBaseFeeParams {\n numInputs: number;\n /**\n * Number of outputs in the unfunded transaction (HTLC vault outputs +\n * CPFP anchor + optional auth-anchor OP_RETURN). Excludes the change\n * output — `applyChangeOutputPolicy` adds the change-output fee\n * separately.\n */\n numOutputs: number;\n feeRate: number;\n}\n\n/**\n * Compute the base fee (sats) for a Pre-PegIn transaction with no change\n * output, including the low-fee-rate buffer.\n *\n * Used as the starting point by `applyChangeOutputPolicy`, which then\n * decides whether to add the incremental change-output fee.\n */\nexport function computePeginBaseFeeSats(\n params: ComputeBaseFeeParams,\n): bigint {\n const { numInputs, numOutputs, feeRate } = params;\n if (!Number.isInteger(numInputs) || numInputs < 0) {\n throw new Error(\n `computePeginBaseFeeSats: numInputs must be a non-negative integer, got ${numInputs}`,\n );\n }\n if (!Number.isInteger(numOutputs) || numOutputs < 1) {\n throw new Error(\n `computePeginBaseFeeSats: numOutputs must be a positive integer, got ${numOutputs}`,\n );\n }\n const txVsize =\n numInputs * P2TR_INPUT_SIZE +\n numOutputs * MAX_NON_LEGACY_OUTPUT_SIZE +\n TX_BUFFER_SIZE_OVERHEAD;\n return (\n BigInt(Math.ceil(txVsize * feeRate)) +\n BigInt(rateBasedTxBufferFee(feeRate))\n );\n}\n\n/**\n * Incremental fee (sats) for adding one P2TR-sized change output at the\n * given fee rate. Does NOT include the low-fee-rate buffer — that is part\n * of the base fee, paid once per transaction.\n */\nexport function computeChangeOutputFeeSats(feeRate: number): bigint {\n return BigInt(Math.ceil(MAX_NON_LEGACY_OUTPUT_SIZE * feeRate));\n}\n\nexport interface ApplyChangeOutputPolicyParams {\n totalInputValue: bigint;\n peginAmount: bigint;\n baseFee: bigint;\n changeOutputFee: bigint;\n}\n\nexport interface ChangeOutputPolicyResult {\n /** Final transaction fee (sats). */\n fee: bigint;\n /**\n * Final change amount (sats). 0n when no change output is emitted.\n * When `emitChangeOutput` is false, the would-be change is paid to\n * miners as part of `fee` — i.e. it is dust by policy.\n */\n changeAmount: bigint;\n /** Whether the funded transaction must include a change output. */\n emitChangeOutput: boolean;\n}\n\n/**\n * Apply the change-output dust policy: emit a change output iff the\n * post-change-output-fee residual strictly exceeds DUST_THRESHOLD.\n *\n * Returns `{ fee, changeAmount, emitChangeOutput }` so the selector and\n * funder both end up with the same fee and same change decision for the\n * same inputs.\n *\n * Inputs:\n * - `totalInputValue`: sum of selected UTXO values\n * - `peginAmount`: amount being pegged in\n * - `baseFee`: fee assuming no change output (from `computePeginBaseFeeSats`)\n * - `changeOutputFee`: incremental fee for adding one change output\n * (from `computeChangeOutputFeeSats`)\n *\n * @throws If `totalInputValue < peginAmount + baseFee` (insufficient funds\n * even before considering change). Callers that need to surface\n * \"insufficient funds\" with their own error wording should check the\n * precondition themselves before invoking this.\n */\nexport function applyChangeOutputPolicy(\n params: ApplyChangeOutputPolicyParams,\n): ChangeOutputPolicyResult {\n const { totalInputValue, peginAmount, baseFee, changeOutputFee } = params;\n\n const residualBeforeChange = totalInputValue - peginAmount - baseFee;\n if (residualBeforeChange < 0n) {\n throw new Error(\n `applyChangeOutputPolicy: insufficient funds (need ${peginAmount + baseFee} sats, have ${totalInputValue})`,\n );\n }\n\n const residualWithChangeOutput = residualBeforeChange - changeOutputFee;\n if (residualWithChangeOutput > DUST_THRESHOLD) {\n return {\n fee: baseFee + changeOutputFee,\n changeAmount: residualWithChangeOutput,\n emitChangeOutput: true,\n };\n }\n\n // Dust-revert: the would-be change is below (or equal to) the dust\n // threshold once the change-output fee is paid, so we omit the change\n // output and let the residual go to miners. The reported `fee` is the\n // ACTUAL on-wire fee — `baseFee + residualBeforeChange` — not just\n // `baseFee`, otherwise fee displays would under-report by up to\n // (changeOutputFee + DUST_THRESHOLD) sats whenever dust gets absorbed.\n return {\n fee: baseFee + residualBeforeChange,\n changeAmount: 0n,\n emitChangeOutput: false,\n };\n}\n\nexport interface ComputeMaxDepositParams {\n numInputs: number;\n /**\n * Number of outputs in the unfunded transaction. Use the worst-case\n * count for the use case being budgeted (e.g. max-batch with\n * auth-anchor) — `computeMaxDeposit` is intentionally an UPPER BOUND\n * and assumes no change output.\n */\n numOutputs: number;\n totalBalance: bigint;\n feeRate: number;\n}\n\n/**\n * Compute the maximum depositable amount (sats) given a fixed-cost\n * sweep: every UTXO is spent, no change output is emitted, fee is the\n * base fee for the requested input/output count.\n *\n * Returns null when `totalBalance <= 0n`. Returns 0n if the base fee\n * alone exceeds the balance.\n */\nexport function computeMaxDeposit(\n params: ComputeMaxDepositParams,\n): bigint | null {\n const { numInputs, numOutputs, totalBalance, feeRate } = params;\n if (totalBalance <= 0n) return null;\n const fee = computePeginBaseFeeSats({ numInputs, numOutputs, feeRate });\n const max = totalBalance - fee;\n return max > 0n ? max : 0n;\n}\n","/**\n * UTXO selection utilities for peg-in transactions.\n * Follows btc-staking-ts methodology with iterative fee calculation.\n */\n\nimport { script as bitcoinScript } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { BTC_DUST_SAT, DUST_THRESHOLD } from \"../fee/constants\";\nimport {\n applyChangeOutputPolicy,\n computeChangeOutputFeeSats,\n computePeginBaseFeeSats,\n} from \"../fee/peginFeeMath\";\n\n/**\n * Unspent Transaction Output (UTXO) for funding peg-in transactions.\n */\nexport interface UTXO {\n /**\n * Transaction ID of the UTXO (64-char hex without 0x prefix).\n */\n txid: string;\n\n /**\n * Output index within the transaction.\n */\n vout: number;\n\n /**\n * Value in satoshis.\n */\n value: number;\n\n /**\n * Script public key hex.\n */\n scriptPubKey: string;\n}\n\nexport interface UTXOSelectionResult {\n selectedUTXOs: UTXO[];\n totalValue: bigint;\n fee: bigint;\n changeAmount: bigint;\n}\n\n/**\n * Assert that no two UTXOs share the same txid:vout outpoint.\n * Duplicates from a buggy or compromised UTXO source would produce\n * an invalid Bitcoin transaction that double-spends the same outpoint.\n */\nfunction assertNoDuplicateUtxos(utxos: UTXO[]): void {\n const seen = new Set<string>();\n for (const utxo of utxos) {\n const key = `${utxo.txid.toLowerCase()}:${utxo.vout}`;\n if (seen.has(key)) {\n throw new Error(\n `Duplicate UTXO detected: ${utxo.txid}:${utxo.vout}. ` +\n `This indicates a data integrity issue with the UTXO source.`,\n );\n }\n seen.add(key);\n }\n}\n\n/**\n * Selects UTXOs to fund a peg-in transaction with iterative fee calculation.\n *\n * This function implements the btc-staking-ts approach:\n * 1. Filter UTXOs for script validity (no minimum value filter)\n * 2. Sort by value (largest first) to minimize number of inputs\n * 3. Iteratively add UTXOs and recalculate fee until we have enough\n *\n * The fee recalculation is critical because:\n * - Each UTXO added increases transaction size → increases fee\n * - More fee needed might require another UTXO\n * - Change output detection affects fee (adds output size if needed)\n *\n * @param availableUTXOs - All available UTXOs from wallet\n * @param peginAmount - Amount to peg in (satoshis)\n * @param feeRate - Fee rate (sat/vbyte)\n * @param numOutputs - Number of outputs in the unfunded transaction (HTLC + CPFP anchor, before change)\n * @returns Selected UTXOs, total value, calculated fee, and change amount\n * @throws Error if insufficient funds or no valid UTXOs\n */\nexport function selectUtxosForPegin(\n availableUTXOs: UTXO[],\n peginAmount: bigint,\n feeRate: number,\n numOutputs: number,\n): UTXOSelectionResult {\n if (!Number.isInteger(numOutputs) || numOutputs < 1) {\n throw new Error(\n `Invalid numOutputs: expected a positive integer, got ${numOutputs}`,\n );\n }\n\n if (availableUTXOs.length === 0) {\n throw new Error(\"Insufficient funds: no UTXOs available\");\n }\n\n assertNoDuplicateUtxos(availableUTXOs);\n\n // Filter for script validity ONLY (matching btc-staking-ts approach)\n // No minimum value filter - we accept any UTXO with valid script\n const validUTXOs = availableUTXOs.filter((utxo) => {\n const script = Buffer.from(utxo.scriptPubKey, \"hex\");\n const decompiledScript = bitcoinScript.decompile(script);\n return !!decompiledScript;\n });\n\n if (validUTXOs.length === 0) {\n throw new Error(\n \"Insufficient funds: no valid UTXOs available (all have invalid scripts)\",\n );\n }\n\n // Sort by value: HIGHEST to LOWEST (use big UTXOs first)\n // Use spread to avoid mutating the original array\n const sortedUTXOs = [...validUTXOs].sort((a, b) => b.value - a.value);\n\n const selectedUTXOs: UTXO[] = [];\n let accumulatedValue = 0n;\n let estimatedFee = 0n;\n\n // Iteratively select UTXOs, recalculating the fee through the shared\n // `applyChangeOutputPolicy` helper so the selector and the funder\n // agree on (fee, change output emission, change amount) for the same\n // inputs. Without that, the funder can omit a change output the\n // selector charged for — silent depositor overpayment at the dust\n // boundary.\n for (const utxo of sortedUTXOs) {\n selectedUTXOs.push(utxo);\n accumulatedValue += BigInt(utxo.value);\n\n const baseFee = computePeginBaseFeeSats({\n numInputs: selectedUTXOs.length,\n numOutputs,\n feeRate,\n });\n const changeOutputFee = computeChangeOutputFeeSats(feeRate);\n\n if (accumulatedValue < peginAmount + baseFee) {\n estimatedFee = baseFee;\n continue;\n }\n\n const policy = applyChangeOutputPolicy({\n totalInputValue: accumulatedValue,\n peginAmount,\n baseFee,\n changeOutputFee,\n });\n\n return {\n selectedUTXOs,\n totalValue: accumulatedValue,\n fee: policy.fee,\n changeAmount: policy.changeAmount,\n };\n }\n\n // If we get here, we don't have enough funds\n throw new Error(\n `Insufficient funds: need ${peginAmount + estimatedFee} sats (${peginAmount} pegin + ${estimatedFee} fee), have ${accumulatedValue} sats`,\n );\n}\n\n/**\n * Checks if change amount is above dust threshold.\n *\n * @param changeAmount - Change amount in satoshis\n * @returns true if change should be added as output, false if it should go to miners\n */\nexport function shouldAddChangeOutput(changeAmount: bigint): boolean {\n return changeAmount > DUST_THRESHOLD;\n}\n\n/**\n * Gets the dust threshold value.\n *\n * @returns Dust threshold in satoshis\n */\nexport function getDustThreshold(): number {\n return BTC_DUST_SAT;\n}\n","/**\n * Bitcoin Transaction Hash Utilities\n *\n * Provides utilities for calculating Bitcoin transaction hashes in a way that matches\n * the contract's BtcUtils.hashBtcTx() implementation.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport type { Hex } from \"viem\";\n\n/**\n * Calculate Bitcoin transaction hash\n *\n * This matches the contract's BtcUtils.hashBtcTx() implementation:\n * 1. Double SHA256 the transaction bytes\n * 2. Reverse the byte order (Bitcoin convention)\n *\n * The resulting hash is used as the unique vault identifier in the BTCVaultRegistry contract.\n *\n * @param txHex - Transaction hex (with or without 0x prefix)\n * @returns The transaction hash as Hex (with 0x prefix)\n */\nexport function calculateBtcTxHash(txHex: string): Hex {\n // Remove 0x prefix if present\n const cleanHex = txHex.startsWith(\"0x\") ? txHex.slice(2) : txHex;\n\n // Use bitcoinjs-lib to calculate transaction ID (already does double SHA256 + reverse)\n const tx = Transaction.fromHex(cleanHex);\n const txid = tx.getId();\n\n // Return with 0x prefix to match Ethereum hex format\n return `0x${txid}` as Hex;\n}\n","/**\n * Bitcoin Script Type Detection\n *\n * Utilities to detect Bitcoin script types for proper PSBT input construction.\n *\n * @module utils/btc/scriptType\n */\n\n/**\n * Bitcoin script types.\n */\nexport enum BitcoinScriptType {\n P2PKH = \"P2PKH\",\n P2SH = \"P2SH\",\n P2WPKH = \"P2WPKH\",\n P2WSH = \"P2WSH\",\n P2TR = \"P2TR\",\n UNKNOWN = \"UNKNOWN\",\n}\n\n/**\n * Detect the type of a Bitcoin script.\n *\n * @param scriptPubKey - The script public key buffer\n * @returns The detected script type\n *\n * @example\n * ```typescript\n * const scriptType = getScriptType(Buffer.from(scriptPubKeyHex, 'hex'));\n * if (scriptType === BitcoinScriptType.P2TR) {\n * // Handle Taproot input\n * }\n * ```\n */\nexport function getScriptType(scriptPubKey: Buffer): BitcoinScriptType {\n const length = scriptPubKey.length;\n\n // P2PKH: OP_DUP OP_HASH160 <20 bytes> OP_EQUALVERIFY OP_CHECKSIG (25 bytes)\n if (\n length === 25 &&\n scriptPubKey[0] === 0x76 && // OP_DUP\n scriptPubKey[1] === 0xa9 && // OP_HASH160\n scriptPubKey[2] === 0x14 && // Push 20 bytes\n scriptPubKey[23] === 0x88 && // OP_EQUALVERIFY\n scriptPubKey[24] === 0xac // OP_CHECKSIG\n ) {\n return BitcoinScriptType.P2PKH;\n }\n\n // P2SH: OP_HASH160 <20 bytes> OP_EQUAL (23 bytes)\n if (\n length === 23 &&\n scriptPubKey[0] === 0xa9 && // OP_HASH160\n scriptPubKey[1] === 0x14 && // Push 20 bytes\n scriptPubKey[22] === 0x87 // OP_EQUAL\n ) {\n return BitcoinScriptType.P2SH;\n }\n\n // P2WPKH: OP_0 <20 bytes> (22 bytes)\n if (\n length === 22 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x14 // Push 20 bytes\n ) {\n return BitcoinScriptType.P2WPKH;\n }\n\n // P2WSH: OP_0 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2WSH;\n }\n\n // P2TR (Taproot): OP_1 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x51 && // OP_1\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2TR;\n }\n\n return BitcoinScriptType.UNKNOWN;\n}\n\n","/**\n * PSBT Input Field Construction\n *\n * Constructs the correct PSBT input fields for a given UTXO based on its script type.\n *\n * @module utils/btc/psbtInputFields\n */\n\nimport { Buffer } from \"buffer\";\n\nimport { BitcoinScriptType, getScriptType } from \"./scriptType\";\n\n/**\n * PSBT input fields for supported script types (P2TR, P2WPKH, P2WSH).\n */\nexport interface PsbtInputFields {\n witnessUtxo?: {\n script: Buffer;\n value: number;\n };\n witnessScript?: Buffer;\n tapInternalKey?: Buffer;\n}\n\n/**\n * UTXO information for PSBT construction.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n */\nexport interface UtxoForPsbt {\n /** Transaction ID of the UTXO */\n txid: string;\n /** Output index (vout) of the UTXO */\n vout: number;\n /** Value of the UTXO in satoshis */\n value: number;\n /** ScriptPubKey of the UTXO (hex string) */\n scriptPubKey: string;\n /** Witness script (required for P2WSH) */\n witnessScript?: string;\n}\n\n/**\n * Get PSBT input fields for a given UTXO based on its script type.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param utxo - The unspent transaction output to process\n * @param publicKeyNoCoord - The x-only public key (32 bytes) for Taproot signing\n * @returns PSBT input fields object containing the necessary data\n * @throws Error if required input data is missing or unsupported script type\n */\nexport function getPsbtInputFields(\n utxo: UtxoForPsbt,\n publicKeyNoCoord?: Buffer,\n): PsbtInputFields {\n const scriptPubKey = Buffer.from(utxo.scriptPubKey, \"hex\");\n const type = getScriptType(scriptPubKey);\n\n switch (type) {\n case BitcoinScriptType.P2WPKH: {\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n };\n }\n\n case BitcoinScriptType.P2WSH: {\n if (!utxo.witnessScript) {\n throw new Error(\"Missing witnessScript for P2WSH input\");\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n witnessScript: Buffer.from(utxo.witnessScript, \"hex\"),\n };\n }\n\n case BitcoinScriptType.P2TR: {\n if (publicKeyNoCoord && publicKeyNoCoord.length !== 32) {\n throw new Error(\n `Invalid tapInternalKey length: expected 32 bytes, got ${publicKeyNoCoord.length}`,\n );\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n // tapInternalKey is needed for Taproot signing\n ...(publicKeyNoCoord && { tapInternalKey: publicKeyNoCoord }),\n };\n }\n\n default:\n throw new Error(`Unsupported script type: ${type}`);\n }\n}\n\n","/**\n * Smart-account-aware wrapper around viem's `waitForTransactionReceipt`.\n *\n * Externally Owned Accounts (EOAs) — wallets controlled by a single private\n * key, e.g. MetaMask or a hardware wallet. `eth_sendTransaction` returns a real\n * Ethereum tx hash, which viem can poll directly. This wrapper detects an EOA\n * via `eth_getCode` returning empty bytecode and delegates unchanged.\n *\n * Smart-contract accounts (e.g. Safe multisigs) — the wallet address is a\n * deployed contract that decides whether to accept a transaction. WalletConnect's\n * `eth_sendTransaction` returns a `safeTxHash` (an EIP-712 hash of the\n * *proposal*) rather than a real tx hash, and the proposal is held in Safe's\n * off-chain Transaction Service until quorum signs and executes it. We poll\n * that service for the proposal until execution, then wait for receipt on the\n * real Ethereum tx hash exposed in the service's response.\n *\n * @module utils/eth\n */\n\nimport type {\n Address,\n Hash,\n PublicClient,\n TransactionReceipt,\n} from \"viem\";\n\n/**\n * Chains where the Safe Transaction Service is supported by this utility.\n * Extend the map as more Safe-enabled chains are needed.\n */\nconst SAFE_TX_SERVICE_BASE_URLS: Record<number, string> = {\n 1: \"https://safe-transaction-mainnet.safe.global\",\n 11155111: \"https://safe-transaction-sepolia.safe.global\",\n};\n\nconst DEFAULT_SAFE_POLL_INTERVAL_MS = 5_000;\nconst DEFAULT_SAFE_POLL_TIMEOUT_MS = 4 * 60 * 60 * 1_000;\nconst SAFE_TX_SERVICE_FETCH_TIMEOUT_MS = 10_000;\n\nexport interface WaitForTransactionReceiptSmartAwareParams {\n publicClient: PublicClient;\n walletAddress: Address;\n hash: Hash;\n confirmations?: number;\n /**\n * Forwarded to viem on the EOA (externally owned account) path.\n * Ignored on the smart-account path — see safePollTimeoutMs.\n */\n timeout?: number;\n /** Total budget for waiting on Safe quorum + execution. Default 4h. */\n safePollTimeoutMs?: number;\n /** Poll cadence against the Safe Transaction Service. Default 5s. */\n safePollIntervalMs?: number;\n}\n\nexport async function waitForTransactionReceiptSmartAware(\n params: WaitForTransactionReceiptSmartAwareParams,\n): Promise<TransactionReceipt> {\n const {\n publicClient,\n walletAddress,\n hash,\n confirmations,\n timeout,\n safePollTimeoutMs = DEFAULT_SAFE_POLL_TIMEOUT_MS,\n safePollIntervalMs = DEFAULT_SAFE_POLL_INTERVAL_MS,\n } = params;\n\n const code = await publicClient.getCode({ address: walletAddress });\n const isSmartAccount = code !== undefined && code !== \"0x\";\n\n if (!isSmartAccount) {\n return publicClient.waitForTransactionReceipt({\n hash,\n confirmations,\n timeout,\n });\n }\n\n const chainId = await publicClient.getChainId();\n const realTxHash = await pollSafeTransactionServiceUntilExecuted({\n chainId,\n safeTxHash: hash,\n pollIntervalMs: safePollIntervalMs,\n timeoutMs: safePollTimeoutMs,\n });\n\n return publicClient.waitForTransactionReceipt({\n hash: realTxHash,\n confirmations,\n });\n}\n\ninterface SafeMultisigTransaction {\n isExecuted: boolean;\n isSuccessful: boolean | null;\n transactionHash: Hash | null;\n}\n\nasync function pollSafeTransactionServiceUntilExecuted({\n chainId,\n safeTxHash,\n pollIntervalMs,\n timeoutMs,\n}: {\n chainId: number;\n safeTxHash: Hash;\n pollIntervalMs: number;\n timeoutMs: number;\n}): Promise<Hash> {\n const baseUrl = SAFE_TX_SERVICE_BASE_URLS[chainId];\n if (!baseUrl) {\n throw new Error(\n `Safe Transaction Service not configured for chainId ${chainId}. ` +\n `Connected wallet appears to be a smart-contract account, but this ` +\n `chain is not in the supported list. Either connect an EOA or extend ` +\n `SAFE_TX_SERVICE_BASE_URLS in waitForTransactionReceiptSmartAware.ts.`,\n );\n }\n\n const url = `${baseUrl}/api/v1/multisig-transactions/${safeTxHash}/`;\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() < deadline) {\n const controller = new AbortController();\n const fetchTimeoutId = setTimeout(\n () => controller.abort(),\n SAFE_TX_SERVICE_FETCH_TIMEOUT_MS,\n );\n\n let response: Response;\n try {\n response = await fetch(url, { signal: controller.signal });\n } catch (err) {\n // Transient failure (AbortError on per-request timeout, DNS hiccup,\n // connection reset, etc.). Log and continue to the next poll iteration\n // instead of consuming the entire safePollTimeoutMs budget on one blip.\n // The outer `while (Date.now() < deadline)` is what enforces the overall\n // budget; this catch deliberately preserves it.\n console.warn(\n `Safe Transaction Service request failed (will retry in ${pollIntervalMs}ms): ` +\n (err instanceof Error ? err.message : String(err)),\n );\n await sleep(pollIntervalMs);\n continue;\n } finally {\n clearTimeout(fetchTimeoutId);\n }\n\n if (response.ok) {\n const data = (await response.json()) as SafeMultisigTransaction;\n if (data.isExecuted) {\n if (data.isSuccessful === false) {\n throw new Error(\n `Safe transaction ${safeTxHash} was executed on chain but reverted. ` +\n `Check the Safe queue UI for details.`,\n );\n }\n if (data.transactionHash) {\n return data.transactionHash;\n }\n }\n } else if (response.status === 404) {\n // Proposal not yet indexed — keep polling silently.\n } else if (response.status >= 500) {\n // Transient server error — same treatment as a hung connection: log and retry.\n console.warn(\n `Safe Transaction Service returned ${response.status} for ${safeTxHash}; retrying in ${pollIntervalMs}ms.`,\n );\n } else {\n // Other 4xx (403, 410, etc.) is likely permanent — surface immediately.\n throw new Error(\n `Safe Transaction Service returned ${response.status} for ${safeTxHash}.`,\n );\n }\n\n await sleep(pollIntervalMs);\n }\n\n throw new Error(\n `Timed out after ${timeoutMs}ms waiting for Safe transaction ${safeTxHash} ` +\n `to reach quorum and execute. The proposal is still pending in the Safe ` +\n `queue — co-signers must sign and execute it before the dApp can proceed.`,\n );\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n"],"names":["computePeginBaseFeeSats","params","numInputs","numOutputs","feeRate","txVsize","P2TR_INPUT_SIZE","MAX_NON_LEGACY_OUTPUT_SIZE","TX_BUFFER_SIZE_OVERHEAD","rateBasedTxBufferFee","computeChangeOutputFeeSats","applyChangeOutputPolicy","totalInputValue","peginAmount","baseFee","changeOutputFee","residualBeforeChange","residualWithChangeOutput","DUST_THRESHOLD","computeMaxDeposit","totalBalance","fee","max","assertNoDuplicateUtxos","utxos","seen","utxo","key","selectUtxosForPegin","availableUTXOs","validUTXOs","script","Buffer","bitcoinScript","sortedUTXOs","a","b","selectedUTXOs","accumulatedValue","estimatedFee","policy","shouldAddChangeOutput","changeAmount","getDustThreshold","BTC_DUST_SAT","calculateBtcTxHash","txHex","cleanHex","Transaction","BitcoinScriptType","getScriptType","scriptPubKey","length","getPsbtInputFields","publicKeyNoCoord","type","SAFE_TX_SERVICE_BASE_URLS","DEFAULT_SAFE_POLL_INTERVAL_MS","DEFAULT_SAFE_POLL_TIMEOUT_MS","SAFE_TX_SERVICE_FETCH_TIMEOUT_MS","waitForTransactionReceiptSmartAware","publicClient","walletAddress","hash","confirmations","timeout","safePollTimeoutMs","safePollIntervalMs","code","chainId","realTxHash","pollSafeTransactionServiceUntilExecuted","safeTxHash","pollIntervalMs","timeoutMs","baseUrl","url","deadline","controller","fetchTimeoutId","response","err","sleep","data","ms","resolve"],"mappings":";;;AAyCO,SAASA,EACdC,GACQ;AACR,QAAM,EAAE,WAAAC,GAAW,YAAAC,GAAY,SAAAC,EAAA,IAAYH;AAC3C,MAAI,CAAC,OAAO,UAAUC,CAAS,KAAKA,IAAY;AAC9C,UAAM,IAAI;AAAA,MACR,0EAA0EA,CAAS;AAAA,IAAA;AAGvF,MAAI,CAAC,OAAO,UAAUC,CAAU,KAAKA,IAAa;AACh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BX,CAAU;AAAA,UAAA;AAIlC,YAAIW,EAAK;AACP,iBAAOA,EAAK;AAAA,MAEhB;AAAA,IACF,WAAWH,EAAS,WAAW,IAE/B,KAAWA,EAAS,UAAU;AAE5B,cAAQ;AAAA,QACN,qCAAqCA,EAAS,MAAM,QAAQR,CAAU,iBAAiBC,CAAc;AAAA,MAAA;AAAA;AAIvG,YAAM,IAAI;AAAA,QACR,qCAAqCO,EAAS,MAAM,QAAQR,CAAU;AAAA,MAAA;AAI1E,UAAMU,EAAMT,CAAc;AAAA,EAC5B;AAEA,QAAM,IAAI;AAAA,IACR,mBAAmBC,CAAS,mCAAmCF,CAAU;AAAA,EAAA;AAI7E;AAEA,SAASU,EAAME,GAA2B;AACxC,SAAO,IAAI,QAAQ,CAACC,MAAY;AAC9B,eAAWA,GAASD,CAAE;AAAA,EACxB,CAAC;AACH;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const m=require("bitcoinjs-lib"),g=require("buffer"),f=require("./fundPeginTransaction-BBE3wTjR.cjs");function p(e){const{numInputs:t,numOutputs:n,feeRate:r}=e;if(!Number.isInteger(t)||t<0)throw new Error(`computePeginBaseFeeSats: numInputs must be a non-negative integer, got ${t}`);if(!Number.isInteger(n)||n<1)throw new Error(`computePeginBaseFeeSats: numOutputs must be a positive integer, got ${n}`);const s=t*f.P2TR_INPUT_SIZE+n*f.MAX_NON_LEGACY_OUTPUT_SIZE+f.TX_BUFFER_SIZE_OVERHEAD;return BigInt(Math.ceil(s*r))+BigInt(f.rateBasedTxBufferFee(r))}function T(e){return BigInt(Math.ceil(f.MAX_NON_LEGACY_OUTPUT_SIZE*e))}function E(e){const{totalInputValue:t,peginAmount:n,baseFee:r,changeOutputFee:s}=e,c=t-n-r;if(c<0n)throw new Error(`applyChangeOutputPolicy: insufficient funds (need ${n+r} sats, have ${t})`);const i=c-s;return i>f.DUST_THRESHOLD?{fee:r+s,changeAmount:i,emitChangeOutput:!0}:{fee:r+c,changeAmount:0n,emitChangeOutput:!1}}function I(e){const{numInputs:t,numOutputs:n,totalBalance:r,feeRate:s}=e;if(r<=0n)return null;const c=p({numInputs:t,numOutputs:n,feeRate:s}),i=r-c;return i>0n?i:0n}function P(e){const t=new Set;for(const n of e){const r=`${n.txid.toLowerCase()}:${n.vout}`;if(t.has(r))throw new Error(`Duplicate UTXO detected: ${n.txid}:${n.vout}. This indicates a data integrity issue with the UTXO source.`);t.add(r)}}function O(e,t,n,r){if(!Number.isInteger(r)||r<1)throw new Error(`Invalid numOutputs: expected a positive integer, got ${r}`);if(e.length===0)throw new Error("Insufficient funds: no UTXOs available");P(e);const s=e.filter(o=>{const a=g.Buffer.from(o.scriptPubKey,"hex");return!!m.script.decompile(a)});if(s.length===0)throw new Error("Insufficient funds: no valid UTXOs available (all have invalid scripts)");const c=[...s].sort((o,a)=>a.value-o.value),i=[];let u=0n,l=0n;for(const o of c){i.push(o),u+=BigInt(o.value);const a=p({numInputs:i.length,numOutputs:r,feeRate:n}),d=T(n);if(u<t+a){l=a;continue}const w=E({totalInputValue:u,peginAmount:t,baseFee:a,changeOutputFee:d});return{selectedUTXOs:i,totalValue:u,fee:w.fee,changeAmount:w.changeAmount}}throw new Error(`Insufficient funds: need ${t+l} sats (${t} pegin + ${l} fee), have ${u} sats`)}function U(e){return e>f.DUST_THRESHOLD}function F(){return f.BTC_DUST_SAT}function v(e){const t=e.startsWith("0x")?e.slice(2):e;return`0x${m.Transaction.fromHex(t).getId()}`}var h=(e=>(e.P2PKH="P2PKH",e.P2SH="P2SH",e.P2WPKH="P2WPKH",e.P2WSH="P2WSH",e.P2TR="P2TR",e.UNKNOWN="UNKNOWN",e))(h||{});function _(e){const t=e.length;return t===25&&e[0]===118&&e[1]===169&&e[2]===20&&e[23]===136&&e[24]===172?"P2PKH":t===23&&e[0]===169&&e[1]===20&&e[22]===135?"P2SH":t===22&&e[0]===0&&e[1]===20?"P2WPKH":t===34&&e[0]===0&&e[1]===32?"P2WSH":t===34&&e[0]===81&&e[1]===32?"P2TR":"UNKNOWN"}function A(e,t){const n=g.Buffer.from(e.scriptPubKey,"hex"),r=_(n);switch(r){case h.P2WPKH:return{witnessUtxo:{script:n,value:e.value}};case h.P2WSH:{if(!e.witnessScript)throw new Error("Missing witnessScript for P2WSH input");return{witnessUtxo:{script:n,value:e.value},witnessScript:g.Buffer.from(e.witnessScript,"hex")}}case h.P2TR:{if(t&&t.length!==32)throw new Error(`Invalid tapInternalKey length: expected 32 bytes, got ${t.length}`);return{witnessUtxo:{script:n,value:e.value},...t&&{tapInternalKey:t}}}default:throw new Error(`Unsupported script type: ${r}`)}}const $={1:"https://safe-transaction-mainnet.safe.global",11155111:"https://safe-transaction-sepolia.safe.global"},x=5e3,H=14400*1e3,C=1e4;async function R(e){const{publicClient:t,walletAddress:n,hash:r,confirmations:s,timeout:c,safePollTimeoutMs:i=H,safePollIntervalMs:u=x}=e,l=await t.getCode({address:n});if(!(l!==void 0&&l!=="0x"))return t.waitForTransactionReceipt({hash:r,confirmations:s,timeout:c});const a=await t.getChainId(),d=await B({chainId:a,safeTxHash:r,pollIntervalMs:u,timeoutMs:i});return t.waitForTransactionReceipt({hash:d,confirmations:s})}async function B({chainId:e,safeTxHash:t,pollIntervalMs:n,timeoutMs:r}){const s=$[e];if(!s)throw new Error(`Safe Transaction Service not configured for chainId ${e}. Connected wallet appears to be a smart-contract account, but this chain is not in the supported list. Either connect an EOA or extend SAFE_TX_SERVICE_BASE_URLS in waitForTransactionReceiptSmartAware.ts.`);const c=`${s}/api/v1/multisig-transactions/${t}/`,i=Date.now()+r;for(;Date.now()<i;){const u=new AbortController,l=setTimeout(()=>u.abort(),C);let o;try{o=await fetch(c,{signal:u.signal})}catch(a){console.warn(`Safe Transaction Service request failed (will retry in ${n}ms): `+(a instanceof Error?a.message:String(a))),await S(n);continue}finally{clearTimeout(l)}if(o.ok){const a=await o.json();if(a.isExecuted){if(a.isSuccessful===!1)throw new Error(`Safe transaction ${t} was executed on chain but reverted. Check the Safe queue UI for details.`);if(a.transactionHash)return a.transactionHash}}else if(o.status!==404)if(o.status>=500)console.warn(`Safe Transaction Service returned ${o.status} for ${t}; retrying in ${n}ms.`);else throw new Error(`Safe Transaction Service returned ${o.status} for ${t}.`);await S(n)}throw new Error(`Timed out after ${r}ms waiting for Safe transaction ${t} to reach quorum and execute. The proposal is still pending in the Safe queue — co-signers must sign and execute it before the dApp can proceed.`)}function S(e){return new Promise(t=>{setTimeout(t,e)})}exports.BitcoinScriptType=h;exports.applyChangeOutputPolicy=E;exports.calculateBtcTxHash=v;exports.computeChangeOutputFeeSats=T;exports.computeMaxDeposit=I;exports.computePeginBaseFeeSats=p;exports.getDustThreshold=F;exports.getPsbtInputFields=A;exports.getScriptType=_;exports.selectUtxosForPegin=O;exports.shouldAddChangeOutput=U;exports.waitForTransactionReceiptSmartAware=R;
|
|
2
|
+
//# sourceMappingURL=waitForTransactionReceiptSmartAware-tv1mtSIY.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"waitForTransactionReceiptSmartAware-tv1mtSIY.cjs","sources":["../src/tbv/core/utils/fee/peginFeeMath.ts","../src/tbv/core/utils/utxo/selectUtxos.ts","../src/tbv/core/utils/transaction/btcTxHash.ts","../src/tbv/core/utils/btc/scriptType.ts","../src/tbv/core/utils/btc/psbtInputFields.ts","../src/tbv/core/utils/eth/waitForTransactionReceiptSmartAware.ts"],"sourcesContent":["/**\n * Pre-PegIn fee math primitives used by both UTXO selection and\n * transaction funding so they make bit-identical decisions about base\n * fee, change-output fee, and whether to emit change at all.\n *\n * Dust handling matches the wallet-side check in\n * `babylon-vault crates/btc-wallet-remote/src/client.rs` (dust-change\n * rejection): a change output is emitted only when the post-fee residual\n * exceeds DUST_THRESHOLD (546 sats). Broader fee-estimation behaviors\n * (output sizing, safety margins) are NOT cross-stack guarantees — see\n * JS-vs-Rust parity fixtures in `__tests__/peginFeeMath.test.ts` for the\n * invariants we pin.\n */\n\nimport {\n DUST_THRESHOLD,\n MAX_NON_LEGACY_OUTPUT_SIZE,\n P2TR_INPUT_SIZE,\n rateBasedTxBufferFee,\n TX_BUFFER_SIZE_OVERHEAD,\n} from \"./constants\";\n\nexport interface ComputeBaseFeeParams {\n numInputs: number;\n /**\n * Number of outputs in the unfunded transaction (HTLC vault outputs +\n * CPFP anchor + optional auth-anchor OP_RETURN). Excludes the change\n * output — `applyChangeOutputPolicy` adds the change-output fee\n * separately.\n */\n numOutputs: number;\n feeRate: number;\n}\n\n/**\n * Compute the base fee (sats) for a Pre-PegIn transaction with no change\n * output, including the low-fee-rate buffer.\n *\n * Used as the starting point by `applyChangeOutputPolicy`, which then\n * decides whether to add the incremental change-output fee.\n */\nexport function computePeginBaseFeeSats(\n params: ComputeBaseFeeParams,\n): bigint {\n const { numInputs, numOutputs, feeRate } = params;\n if (!Number.isInteger(numInputs) || numInputs < 0) {\n throw new Error(\n `computePeginBaseFeeSats: numInputs must be a non-negative integer, got ${numInputs}`,\n );\n }\n if (!Number.isInteger(numOutputs) || numOutputs < 1) {\n throw new Error(\n `computePeginBaseFeeSats: numOutputs must be a positive integer, got ${numOutputs}`,\n );\n }\n const txVsize =\n numInputs * P2TR_INPUT_SIZE +\n numOutputs * MAX_NON_LEGACY_OUTPUT_SIZE +\n TX_BUFFER_SIZE_OVERHEAD;\n return (\n BigInt(Math.ceil(txVsize * feeRate)) +\n BigInt(rateBasedTxBufferFee(feeRate))\n );\n}\n\n/**\n * Incremental fee (sats) for adding one P2TR-sized change output at the\n * given fee rate. Does NOT include the low-fee-rate buffer — that is part\n * of the base fee, paid once per transaction.\n */\nexport function computeChangeOutputFeeSats(feeRate: number): bigint {\n return BigInt(Math.ceil(MAX_NON_LEGACY_OUTPUT_SIZE * feeRate));\n}\n\nexport interface ApplyChangeOutputPolicyParams {\n totalInputValue: bigint;\n peginAmount: bigint;\n baseFee: bigint;\n changeOutputFee: bigint;\n}\n\nexport interface ChangeOutputPolicyResult {\n /** Final transaction fee (sats). */\n fee: bigint;\n /**\n * Final change amount (sats). 0n when no change output is emitted.\n * When `emitChangeOutput` is false, the would-be change is paid to\n * miners as part of `fee` — i.e. it is dust by policy.\n */\n changeAmount: bigint;\n /** Whether the funded transaction must include a change output. */\n emitChangeOutput: boolean;\n}\n\n/**\n * Apply the change-output dust policy: emit a change output iff the\n * post-change-output-fee residual strictly exceeds DUST_THRESHOLD.\n *\n * Returns `{ fee, changeAmount, emitChangeOutput }` so the selector and\n * funder both end up with the same fee and same change decision for the\n * same inputs.\n *\n * Inputs:\n * - `totalInputValue`: sum of selected UTXO values\n * - `peginAmount`: amount being pegged in\n * - `baseFee`: fee assuming no change output (from `computePeginBaseFeeSats`)\n * - `changeOutputFee`: incremental fee for adding one change output\n * (from `computeChangeOutputFeeSats`)\n *\n * @throws If `totalInputValue < peginAmount + baseFee` (insufficient funds\n * even before considering change). Callers that need to surface\n * \"insufficient funds\" with their own error wording should check the\n * precondition themselves before invoking this.\n */\nexport function applyChangeOutputPolicy(\n params: ApplyChangeOutputPolicyParams,\n): ChangeOutputPolicyResult {\n const { totalInputValue, peginAmount, baseFee, changeOutputFee } = params;\n\n const residualBeforeChange = totalInputValue - peginAmount - baseFee;\n if (residualBeforeChange < 0n) {\n throw new Error(\n `applyChangeOutputPolicy: insufficient funds (need ${peginAmount + baseFee} sats, have ${totalInputValue})`,\n );\n }\n\n const residualWithChangeOutput = residualBeforeChange - changeOutputFee;\n if (residualWithChangeOutput > DUST_THRESHOLD) {\n return {\n fee: baseFee + changeOutputFee,\n changeAmount: residualWithChangeOutput,\n emitChangeOutput: true,\n };\n }\n\n // Dust-revert: the would-be change is below (or equal to) the dust\n // threshold once the change-output fee is paid, so we omit the change\n // output and let the residual go to miners. The reported `fee` is the\n // ACTUAL on-wire fee — `baseFee + residualBeforeChange` — not just\n // `baseFee`, otherwise fee displays would under-report by up to\n // (changeOutputFee + DUST_THRESHOLD) sats whenever dust gets absorbed.\n return {\n fee: baseFee + residualBeforeChange,\n changeAmount: 0n,\n emitChangeOutput: false,\n };\n}\n\nexport interface ComputeMaxDepositParams {\n numInputs: number;\n /**\n * Number of outputs in the unfunded transaction. Use the worst-case\n * count for the use case being budgeted (e.g. max-batch with\n * auth-anchor) — `computeMaxDeposit` is intentionally an UPPER BOUND\n * and assumes no change output.\n */\n numOutputs: number;\n totalBalance: bigint;\n feeRate: number;\n}\n\n/**\n * Compute the maximum depositable amount (sats) given a fixed-cost\n * sweep: every UTXO is spent, no change output is emitted, fee is the\n * base fee for the requested input/output count.\n *\n * Returns null when `totalBalance <= 0n`. Returns 0n if the base fee\n * alone exceeds the balance.\n */\nexport function computeMaxDeposit(\n params: ComputeMaxDepositParams,\n): bigint | null {\n const { numInputs, numOutputs, totalBalance, feeRate } = params;\n if (totalBalance <= 0n) return null;\n const fee = computePeginBaseFeeSats({ numInputs, numOutputs, feeRate });\n const max = totalBalance - fee;\n return max > 0n ? max : 0n;\n}\n","/**\n * UTXO selection utilities for peg-in transactions.\n * Follows btc-staking-ts methodology with iterative fee calculation.\n */\n\nimport { script as bitcoinScript } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { BTC_DUST_SAT, DUST_THRESHOLD } from \"../fee/constants\";\nimport {\n applyChangeOutputPolicy,\n computeChangeOutputFeeSats,\n computePeginBaseFeeSats,\n} from \"../fee/peginFeeMath\";\n\n/**\n * Unspent Transaction Output (UTXO) for funding peg-in transactions.\n */\nexport interface UTXO {\n /**\n * Transaction ID of the UTXO (64-char hex without 0x prefix).\n */\n txid: string;\n\n /**\n * Output index within the transaction.\n */\n vout: number;\n\n /**\n * Value in satoshis.\n */\n value: number;\n\n /**\n * Script public key hex.\n */\n scriptPubKey: string;\n}\n\nexport interface UTXOSelectionResult {\n selectedUTXOs: UTXO[];\n totalValue: bigint;\n fee: bigint;\n changeAmount: bigint;\n}\n\n/**\n * Assert that no two UTXOs share the same txid:vout outpoint.\n * Duplicates from a buggy or compromised UTXO source would produce\n * an invalid Bitcoin transaction that double-spends the same outpoint.\n */\nfunction assertNoDuplicateUtxos(utxos: UTXO[]): void {\n const seen = new Set<string>();\n for (const utxo of utxos) {\n const key = `${utxo.txid.toLowerCase()}:${utxo.vout}`;\n if (seen.has(key)) {\n throw new Error(\n `Duplicate UTXO detected: ${utxo.txid}:${utxo.vout}. ` +\n `This indicates a data integrity issue with the UTXO source.`,\n );\n }\n seen.add(key);\n }\n}\n\n/**\n * Selects UTXOs to fund a peg-in transaction with iterative fee calculation.\n *\n * This function implements the btc-staking-ts approach:\n * 1. Filter UTXOs for script validity (no minimum value filter)\n * 2. Sort by value (largest first) to minimize number of inputs\n * 3. Iteratively add UTXOs and recalculate fee until we have enough\n *\n * The fee recalculation is critical because:\n * - Each UTXO added increases transaction size → increases fee\n * - More fee needed might require another UTXO\n * - Change output detection affects fee (adds output size if needed)\n *\n * @param availableUTXOs - All available UTXOs from wallet\n * @param peginAmount - Amount to peg in (satoshis)\n * @param feeRate - Fee rate (sat/vbyte)\n * @param numOutputs - Number of outputs in the unfunded transaction (HTLC + CPFP anchor, before change)\n * @returns Selected UTXOs, total value, calculated fee, and change amount\n * @throws Error if insufficient funds or no valid UTXOs\n */\nexport function selectUtxosForPegin(\n availableUTXOs: UTXO[],\n peginAmount: bigint,\n feeRate: number,\n numOutputs: number,\n): UTXOSelectionResult {\n if (!Number.isInteger(numOutputs) || numOutputs < 1) {\n throw new Error(\n `Invalid numOutputs: expected a positive integer, got ${numOutputs}`,\n );\n }\n\n if (availableUTXOs.length === 0) {\n throw new Error(\"Insufficient funds: no UTXOs available\");\n }\n\n assertNoDuplicateUtxos(availableUTXOs);\n\n // Filter for script validity ONLY (matching btc-staking-ts approach)\n // No minimum value filter - we accept any UTXO with valid script\n const validUTXOs = availableUTXOs.filter((utxo) => {\n const script = Buffer.from(utxo.scriptPubKey, \"hex\");\n const decompiledScript = bitcoinScript.decompile(script);\n return !!decompiledScript;\n });\n\n if (validUTXOs.length === 0) {\n throw new Error(\n \"Insufficient funds: no valid UTXOs available (all have invalid scripts)\",\n );\n }\n\n // Sort by value: HIGHEST to LOWEST (use big UTXOs first)\n // Use spread to avoid mutating the original array\n const sortedUTXOs = [...validUTXOs].sort((a, b) => b.value - a.value);\n\n const selectedUTXOs: UTXO[] = [];\n let accumulatedValue = 0n;\n let estimatedFee = 0n;\n\n // Iteratively select UTXOs, recalculating the fee through the shared\n // `applyChangeOutputPolicy` helper so the selector and the funder\n // agree on (fee, change output emission, change amount) for the same\n // inputs. Without that, the funder can omit a change output the\n // selector charged for — silent depositor overpayment at the dust\n // boundary.\n for (const utxo of sortedUTXOs) {\n selectedUTXOs.push(utxo);\n accumulatedValue += BigInt(utxo.value);\n\n const baseFee = computePeginBaseFeeSats({\n numInputs: selectedUTXOs.length,\n numOutputs,\n feeRate,\n });\n const changeOutputFee = computeChangeOutputFeeSats(feeRate);\n\n if (accumulatedValue < peginAmount + baseFee) {\n estimatedFee = baseFee;\n continue;\n }\n\n const policy = applyChangeOutputPolicy({\n totalInputValue: accumulatedValue,\n peginAmount,\n baseFee,\n changeOutputFee,\n });\n\n return {\n selectedUTXOs,\n totalValue: accumulatedValue,\n fee: policy.fee,\n changeAmount: policy.changeAmount,\n };\n }\n\n // If we get here, we don't have enough funds\n throw new Error(\n `Insufficient funds: need ${peginAmount + estimatedFee} sats (${peginAmount} pegin + ${estimatedFee} fee), have ${accumulatedValue} sats`,\n );\n}\n\n/**\n * Checks if change amount is above dust threshold.\n *\n * @param changeAmount - Change amount in satoshis\n * @returns true if change should be added as output, false if it should go to miners\n */\nexport function shouldAddChangeOutput(changeAmount: bigint): boolean {\n return changeAmount > DUST_THRESHOLD;\n}\n\n/**\n * Gets the dust threshold value.\n *\n * @returns Dust threshold in satoshis\n */\nexport function getDustThreshold(): number {\n return BTC_DUST_SAT;\n}\n","/**\n * Bitcoin Transaction Hash Utilities\n *\n * Provides utilities for calculating Bitcoin transaction hashes in a way that matches\n * the contract's BtcUtils.hashBtcTx() implementation.\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport type { Hex } from \"viem\";\n\n/**\n * Calculate Bitcoin transaction hash\n *\n * This matches the contract's BtcUtils.hashBtcTx() implementation:\n * 1. Double SHA256 the transaction bytes\n * 2. Reverse the byte order (Bitcoin convention)\n *\n * The resulting hash is used as the unique vault identifier in the BTCVaultRegistry contract.\n *\n * @param txHex - Transaction hex (with or without 0x prefix)\n * @returns The transaction hash as Hex (with 0x prefix)\n */\nexport function calculateBtcTxHash(txHex: string): Hex {\n // Remove 0x prefix if present\n const cleanHex = txHex.startsWith(\"0x\") ? txHex.slice(2) : txHex;\n\n // Use bitcoinjs-lib to calculate transaction ID (already does double SHA256 + reverse)\n const tx = Transaction.fromHex(cleanHex);\n const txid = tx.getId();\n\n // Return with 0x prefix to match Ethereum hex format\n return `0x${txid}` as Hex;\n}\n","/**\n * Bitcoin Script Type Detection\n *\n * Utilities to detect Bitcoin script types for proper PSBT input construction.\n *\n * @module utils/btc/scriptType\n */\n\n/**\n * Bitcoin script types.\n */\nexport enum BitcoinScriptType {\n P2PKH = \"P2PKH\",\n P2SH = \"P2SH\",\n P2WPKH = \"P2WPKH\",\n P2WSH = \"P2WSH\",\n P2TR = \"P2TR\",\n UNKNOWN = \"UNKNOWN\",\n}\n\n/**\n * Detect the type of a Bitcoin script.\n *\n * @param scriptPubKey - The script public key buffer\n * @returns The detected script type\n *\n * @example\n * ```typescript\n * const scriptType = getScriptType(Buffer.from(scriptPubKeyHex, 'hex'));\n * if (scriptType === BitcoinScriptType.P2TR) {\n * // Handle Taproot input\n * }\n * ```\n */\nexport function getScriptType(scriptPubKey: Buffer): BitcoinScriptType {\n const length = scriptPubKey.length;\n\n // P2PKH: OP_DUP OP_HASH160 <20 bytes> OP_EQUALVERIFY OP_CHECKSIG (25 bytes)\n if (\n length === 25 &&\n scriptPubKey[0] === 0x76 && // OP_DUP\n scriptPubKey[1] === 0xa9 && // OP_HASH160\n scriptPubKey[2] === 0x14 && // Push 20 bytes\n scriptPubKey[23] === 0x88 && // OP_EQUALVERIFY\n scriptPubKey[24] === 0xac // OP_CHECKSIG\n ) {\n return BitcoinScriptType.P2PKH;\n }\n\n // P2SH: OP_HASH160 <20 bytes> OP_EQUAL (23 bytes)\n if (\n length === 23 &&\n scriptPubKey[0] === 0xa9 && // OP_HASH160\n scriptPubKey[1] === 0x14 && // Push 20 bytes\n scriptPubKey[22] === 0x87 // OP_EQUAL\n ) {\n return BitcoinScriptType.P2SH;\n }\n\n // P2WPKH: OP_0 <20 bytes> (22 bytes)\n if (\n length === 22 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x14 // Push 20 bytes\n ) {\n return BitcoinScriptType.P2WPKH;\n }\n\n // P2WSH: OP_0 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x00 && // OP_0\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2WSH;\n }\n\n // P2TR (Taproot): OP_1 <32 bytes> (34 bytes)\n if (\n length === 34 &&\n scriptPubKey[0] === 0x51 && // OP_1\n scriptPubKey[1] === 0x20 // Push 32 bytes\n ) {\n return BitcoinScriptType.P2TR;\n }\n\n return BitcoinScriptType.UNKNOWN;\n}\n\n","/**\n * PSBT Input Field Construction\n *\n * Constructs the correct PSBT input fields for a given UTXO based on its script type.\n *\n * @module utils/btc/psbtInputFields\n */\n\nimport { Buffer } from \"buffer\";\n\nimport { BitcoinScriptType, getScriptType } from \"./scriptType\";\n\n/**\n * PSBT input fields for supported script types (P2TR, P2WPKH, P2WSH).\n */\nexport interface PsbtInputFields {\n witnessUtxo?: {\n script: Buffer;\n value: number;\n };\n witnessScript?: Buffer;\n tapInternalKey?: Buffer;\n}\n\n/**\n * UTXO information for PSBT construction.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n */\nexport interface UtxoForPsbt {\n /** Transaction ID of the UTXO */\n txid: string;\n /** Output index (vout) of the UTXO */\n vout: number;\n /** Value of the UTXO in satoshis */\n value: number;\n /** ScriptPubKey of the UTXO (hex string) */\n scriptPubKey: string;\n /** Witness script (required for P2WSH) */\n witnessScript?: string;\n}\n\n/**\n * Get PSBT input fields for a given UTXO based on its script type.\n *\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param utxo - The unspent transaction output to process\n * @param publicKeyNoCoord - The x-only public key (32 bytes) for Taproot signing\n * @returns PSBT input fields object containing the necessary data\n * @throws Error if required input data is missing or unsupported script type\n */\nexport function getPsbtInputFields(\n utxo: UtxoForPsbt,\n publicKeyNoCoord?: Buffer,\n): PsbtInputFields {\n const scriptPubKey = Buffer.from(utxo.scriptPubKey, \"hex\");\n const type = getScriptType(scriptPubKey);\n\n switch (type) {\n case BitcoinScriptType.P2WPKH: {\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n };\n }\n\n case BitcoinScriptType.P2WSH: {\n if (!utxo.witnessScript) {\n throw new Error(\"Missing witnessScript for P2WSH input\");\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n witnessScript: Buffer.from(utxo.witnessScript, \"hex\"),\n };\n }\n\n case BitcoinScriptType.P2TR: {\n if (publicKeyNoCoord && publicKeyNoCoord.length !== 32) {\n throw new Error(\n `Invalid tapInternalKey length: expected 32 bytes, got ${publicKeyNoCoord.length}`,\n );\n }\n return {\n witnessUtxo: {\n script: scriptPubKey,\n value: utxo.value,\n },\n // tapInternalKey is needed for Taproot signing\n ...(publicKeyNoCoord && { tapInternalKey: publicKeyNoCoord }),\n };\n }\n\n default:\n throw new Error(`Unsupported script type: ${type}`);\n }\n}\n\n","/**\n * Smart-account-aware wrapper around viem's `waitForTransactionReceipt`.\n *\n * Externally Owned Accounts (EOAs) — wallets controlled by a single private\n * key, e.g. MetaMask or a hardware wallet. `eth_sendTransaction` returns a real\n * Ethereum tx hash, which viem can poll directly. This wrapper detects an EOA\n * via `eth_getCode` returning empty bytecode and delegates unchanged.\n *\n * Smart-contract accounts (e.g. Safe multisigs) — the wallet address is a\n * deployed contract that decides whether to accept a transaction. WalletConnect's\n * `eth_sendTransaction` returns a `safeTxHash` (an EIP-712 hash of the\n * *proposal*) rather than a real tx hash, and the proposal is held in Safe's\n * off-chain Transaction Service until quorum signs and executes it. We poll\n * that service for the proposal until execution, then wait for receipt on the\n * real Ethereum tx hash exposed in the service's response.\n *\n * @module utils/eth\n */\n\nimport type {\n Address,\n Hash,\n PublicClient,\n TransactionReceipt,\n} from \"viem\";\n\n/**\n * Chains where the Safe Transaction Service is supported by this utility.\n * Extend the map as more Safe-enabled chains are needed.\n */\nconst SAFE_TX_SERVICE_BASE_URLS: Record<number, string> = {\n 1: \"https://safe-transaction-mainnet.safe.global\",\n 11155111: \"https://safe-transaction-sepolia.safe.global\",\n};\n\nconst DEFAULT_SAFE_POLL_INTERVAL_MS = 5_000;\nconst DEFAULT_SAFE_POLL_TIMEOUT_MS = 4 * 60 * 60 * 1_000;\nconst SAFE_TX_SERVICE_FETCH_TIMEOUT_MS = 10_000;\n\nexport interface WaitForTransactionReceiptSmartAwareParams {\n publicClient: PublicClient;\n walletAddress: Address;\n hash: Hash;\n confirmations?: number;\n /**\n * Forwarded to viem on the EOA (externally owned account) path.\n * Ignored on the smart-account path — see safePollTimeoutMs.\n */\n timeout?: number;\n /** Total budget for waiting on Safe quorum + execution. Default 4h. */\n safePollTimeoutMs?: number;\n /** Poll cadence against the Safe Transaction Service. Default 5s. */\n safePollIntervalMs?: number;\n}\n\nexport async function waitForTransactionReceiptSmartAware(\n params: WaitForTransactionReceiptSmartAwareParams,\n): Promise<TransactionReceipt> {\n const {\n publicClient,\n walletAddress,\n hash,\n confirmations,\n timeout,\n safePollTimeoutMs = DEFAULT_SAFE_POLL_TIMEOUT_MS,\n safePollIntervalMs = DEFAULT_SAFE_POLL_INTERVAL_MS,\n } = params;\n\n const code = await publicClient.getCode({ address: walletAddress });\n const isSmartAccount = code !== undefined && code !== \"0x\";\n\n if (!isSmartAccount) {\n return publicClient.waitForTransactionReceipt({\n hash,\n confirmations,\n timeout,\n });\n }\n\n const chainId = await publicClient.getChainId();\n const realTxHash = await pollSafeTransactionServiceUntilExecuted({\n chainId,\n safeTxHash: hash,\n pollIntervalMs: safePollIntervalMs,\n timeoutMs: safePollTimeoutMs,\n });\n\n return publicClient.waitForTransactionReceipt({\n hash: realTxHash,\n confirmations,\n });\n}\n\ninterface SafeMultisigTransaction {\n isExecuted: boolean;\n isSuccessful: boolean | null;\n transactionHash: Hash | null;\n}\n\nasync function pollSafeTransactionServiceUntilExecuted({\n chainId,\n safeTxHash,\n pollIntervalMs,\n timeoutMs,\n}: {\n chainId: number;\n safeTxHash: Hash;\n pollIntervalMs: number;\n timeoutMs: number;\n}): Promise<Hash> {\n const baseUrl = SAFE_TX_SERVICE_BASE_URLS[chainId];\n if (!baseUrl) {\n throw new Error(\n `Safe Transaction Service not configured for chainId ${chainId}. ` +\n `Connected wallet appears to be a smart-contract account, but this ` +\n `chain is not in the supported list. Either connect an EOA or extend ` +\n `SAFE_TX_SERVICE_BASE_URLS in waitForTransactionReceiptSmartAware.ts.`,\n );\n }\n\n const url = `${baseUrl}/api/v1/multisig-transactions/${safeTxHash}/`;\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() < deadline) {\n const controller = new AbortController();\n const fetchTimeoutId = setTimeout(\n () => controller.abort(),\n SAFE_TX_SERVICE_FETCH_TIMEOUT_MS,\n );\n\n let response: Response;\n try {\n response = await fetch(url, { signal: controller.signal });\n } catch (err) {\n // Transient failure (AbortError on per-request timeout, DNS hiccup,\n // connection reset, etc.). Log and continue to the next poll iteration\n // instead of consuming the entire safePollTimeoutMs budget on one blip.\n // The outer `while (Date.now() < deadline)` is what enforces the overall\n // budget; this catch deliberately preserves it.\n console.warn(\n `Safe Transaction Service request failed (will retry in ${pollIntervalMs}ms): ` +\n (err instanceof Error ? err.message : String(err)),\n );\n await sleep(pollIntervalMs);\n continue;\n } finally {\n clearTimeout(fetchTimeoutId);\n }\n\n if (response.ok) {\n const data = (await response.json()) as SafeMultisigTransaction;\n if (data.isExecuted) {\n if (data.isSuccessful === false) {\n throw new Error(\n `Safe transaction ${safeTxHash} was executed on chain but reverted. ` +\n `Check the Safe queue UI for details.`,\n );\n }\n if (data.transactionHash) {\n return data.transactionHash;\n }\n }\n } else if (response.status === 404) {\n // Proposal not yet indexed — keep polling silently.\n } else if (response.status >= 500) {\n // Transient server error — same treatment as a hung connection: log and retry.\n console.warn(\n `Safe Transaction Service returned ${response.status} for ${safeTxHash}; retrying in ${pollIntervalMs}ms.`,\n );\n } else {\n // Other 4xx (403, 410, etc.) is likely permanent — surface immediately.\n throw new Error(\n `Safe Transaction Service returned ${response.status} for ${safeTxHash}.`,\n );\n }\n\n await sleep(pollIntervalMs);\n }\n\n throw new Error(\n `Timed out after ${timeoutMs}ms waiting for Safe transaction ${safeTxHash} ` +\n `to reach quorum and execute. The proposal is still pending in the Safe ` +\n `queue — co-signers must sign and execute it before the dApp can proceed.`,\n );\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n"],"names":["computePeginBaseFeeSats","params","numInputs","numOutputs","feeRate","txVsize","P2TR_INPUT_SIZE","MAX_NON_LEGACY_OUTPUT_SIZE","TX_BUFFER_SIZE_OVERHEAD","rateBasedTxBufferFee","computeChangeOutputFeeSats","applyChangeOutputPolicy","totalInputValue","peginAmount","baseFee","changeOutputFee","residualBeforeChange","residualWithChangeOutput","DUST_THRESHOLD","computeMaxDeposit","totalBalance","fee","max","assertNoDuplicateUtxos","utxos","seen","utxo","key","selectUtxosForPegin","availableUTXOs","validUTXOs","script","Buffer","bitcoinScript","sortedUTXOs","a","b","selectedUTXOs","accumulatedValue","estimatedFee","policy","shouldAddChangeOutput","changeAmount","getDustThreshold","BTC_DUST_SAT","calculateBtcTxHash","txHex","cleanHex","Transaction","BitcoinScriptType","getScriptType","scriptPubKey","length","getPsbtInputFields","publicKeyNoCoord","type","SAFE_TX_SERVICE_BASE_URLS","DEFAULT_SAFE_POLL_INTERVAL_MS","DEFAULT_SAFE_POLL_TIMEOUT_MS","SAFE_TX_SERVICE_FETCH_TIMEOUT_MS","waitForTransactionReceiptSmartAware","publicClient","walletAddress","hash","confirmations","timeout","safePollTimeoutMs","safePollIntervalMs","code","chainId","realTxHash","pollSafeTransactionServiceUntilExecuted","safeTxHash","pollIntervalMs","timeoutMs","baseUrl","url","deadline","controller","fetchTimeoutId","response","err","sleep","data","ms","resolve"],"mappings":"mHAyCO,SAASA,EACdC,EACQ,CACR,KAAM,CAAE,UAAAC,EAAW,WAAAC,EAAY,QAAAC,CAAA,EAAYH,EAC3C,GAAI,CAAC,OAAO,UAAUC,CAAS,GAAKA,EAAY,EAC9C,MAAM,IAAI,MACR,0EAA0EA,CAAS,EAAA,EAGvF,GAAI,CAAC,OAAO,UAAUC,CAAU,GAAKA,EAAa,EAChD,MAAM,IAAI,MACR,uEAAuEA,CAAU,EAAA,EAGrF,MAAME,EACJH,EAAYI,EAAAA,gBACZH,EAAaI,EAAAA,2BACbC,EAAAA,wBACF,OACE,OAAO,KAAK,KAAKH,EAAUD,CAAO,CAAC,EACnC,OAAOK,uBAAqBL,CAAO,CAAC,CAExC,CAOO,SAASM,EAA2BN,EAAyB,CAClE,OAAO,OAAO,KAAK,KAAKG,EAAAA,2BAA6BH,CAAO,CAAC,CAC/D,CA0CO,SAASO,EACdV,EAC0B,CAC1B,KAAM,CAAE,gBAAAW,EAAiB,YAAAC,EAAa,QAAAC,EAAS,gBAAAC,GAAoBd,EAE7De,EAAuBJ,EAAkBC,EAAcC,EAC7D,GAAIE,EAAuB,GACzB,MAAM,IAAI,MACR,qDAAqDH,EAAcC,CAAO,eAAeF,CAAe,GAAA,EAI5G,MAAMK,EAA2BD,EAAuBD,EACxD,OAAIE,EAA2BC,EAAAA,eACtB,CACL,IAAKJ,EAAUC,EACf,aAAcE,EACd,iBAAkB,EAAA,EAUf,CACL,IAAKH,EAAUE,EACf,aAAc,GACd,iBAAkB,EAAA,CAEt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/B,GAAWA,EAAS,QAAU,IAE5B,QAAQ,KACN,qCAAqCA,EAAS,MAAM,QAAQR,CAAU,iBAAiBC,CAAc,KAAA,MAIvG,OAAM,IAAI,MACR,qCAAqCO,EAAS,MAAM,QAAQR,CAAU,GAAA,EAI1E,MAAMU,EAAMT,CAAc,CAC5B,CAEA,MAAM,IAAI,MACR,mBAAmBC,CAAS,mCAAmCF,CAAU,kJAAA,CAI7E,CAEA,SAASU,EAAME,EAA2B,CACxC,OAAO,IAAI,QAASC,GAAY,CAC9B,WAAWA,EAASD,CAAE,CACxB,CAAC,CACH"}
|
package/package.json
CHANGED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var k=Object.defineProperty;var w=(e,t,o)=>t in e?k(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o;var P=(e,t,o)=>w(e,typeof t!="symbol"?t+"":t,o);const f=require("./sha2-DsrLC4NM.cjs"),h=require("./signing-Bnsro0hE.cjs");require("@babylonlabs-io/babylon-tbv-rust-wasm");const r=require("./payout-DQ_fmJUA.cjs"),b=require("./bitcoin-B3aqjuMP.cjs"),p=66;function x(e){if(!e.startsWith("0x")&&!e.startsWith("0X"))throw new Error("Expected 0x-prefixed hex string");const t=e.slice(2);if(t.length%2!==0)throw new Error(`Hex string has odd length: ${t.length}`);if(!/^[0-9a-fA-F]*$/.test(t))throw new Error("Hex string contains non-hex characters");const o=new Uint8Array(t.length/2);for(let n=0;n<o.length;n++)o[n]=parseInt(t.slice(n*2,n*2+2),16);return o}function H(e){return`0x${Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}`}function g(e,t){if(e.length!==p)throw new Error(`${t} must be exactly 32 bytes (${p} hex chars with 0x prefix), got ${e.length}`)}function d(e){g(e,"Secret");const t=x(e),o=f.sha256(t);return H(o)}function B(e,t){return g(e,"Secret"),g(t,"Hashlock"),x(t),d(e).toLowerCase()===t.toLowerCase()}class v{constructor(t){P(this,"config");this.config=t}async signPayoutTransaction(t){this.validatePayoutOutputs(t.payoutTxHex,t.registeredPayoutScriptPubKey);const o=await this.config.btcWallet.getPublicKeyHex(),{depositorPubkey:n}=b.validateWalletPubkey(o,t.depositorBtcPubkey),a=await r.buildPayoutPsbt({payoutTxHex:t.payoutTxHex,peginTxHex:t.peginTxHex,assertTxHex:t.assertTxHex,depositorBtcPubkey:n,vaultProviderBtcPubkey:t.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:t.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:t.universalChallengerBtcPubkeys,timelockPegin:t.timelockPegin,network:this.config.network}),u=await this.config.btcWallet.signPsbt(a.psbtHex,h.createTaprootScriptPathSignOptions(o,1));return{signature:r.extractPayoutSignature(u,n),depositorBtcPubkey:n}}getNetwork(){return this.config.network}supportsBatchSigning(){return typeof this.config.btcWallet.signPsbts=="function"}async signPayoutTransactionsBatch(t){if(!this.supportsBatchSigning())throw new Error("Wallet does not support batch signing (signPsbts method not available)");const o=await this.config.btcWallet.getPublicKeyHex(),n=[],a=[],u=[];for(const s of t){this.validatePayoutOutputs(s.payoutTxHex,s.registeredPayoutScriptPubKey);const{depositorPubkey:i}=b.validateWalletPubkey(o,s.depositorBtcPubkey);u.push(i);const l=await r.buildPayoutPsbt({payoutTxHex:s.payoutTxHex,peginTxHex:s.peginTxHex,assertTxHex:s.assertTxHex,depositorBtcPubkey:i,vaultProviderBtcPubkey:s.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:s.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:s.universalChallengerBtcPubkeys,timelockPegin:s.timelockPegin,network:this.config.network});n.push(l.psbtHex),a.push(h.createTaprootScriptPathSignOptions(o,1))}const c=await this.config.btcWallet.signPsbts(n,a);if(c.length!==t.length)throw new Error(`Expected ${t.length} signed PSBTs but received ${c.length}`);const y=[];for(let s=0;s<t.length;s++){const i=u[s],l=r.extractPayoutSignature(c[s],i);y.push({payoutSignature:l,depositorBtcPubkey:i})}return y}validatePayoutOutputs(t,o){r.assertPayoutOutputMatchesRegistered(t,o)}}exports.PayoutManager=v;exports.computeHashlock=d;exports.validateSecretAgainstHashlock=B;
|
|
2
|
-
//# sourceMappingURL=PayoutManager-BhJoQZsG.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"PayoutManager-BhJoQZsG.cjs","sources":["../src/tbv/core/services/htlc/index.ts","../src/tbv/core/managers/PayoutManager.ts"],"sourcesContent":["/**\n * HTLC Secret / Hashlock Utilities\n *\n * Pure functions for computing and validating SHA-256 hashlocks used in the\n * vault deposit protocol's HTLC (Hash Time Lock Contract).\n *\n * The SDK does NOT generate secrets — that is the caller's responsibility.\n * Today callers use `crypto.getRandomValues(32)`; when the `deriveContextHash`\n * wallet API ships, callers will use `wallet.deriveContextHash(\"babylon-btc-vault\", ctx)`.\n * These utilities work identically regardless of how the secret was produced.\n *\n * On-chain contract validation (BTCVaultRegistry.activateVaultWithSecret):\n * if (sha256(abi.encodePacked(s)) != hashlock) revert InvalidSecret();\n *\n * @module htlc\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport type { Hex } from \"viem\";\n\n/** Expected hex length for a 0x-prefixed bytes32 value. */\nconst HEX_BYTES32_LENGTH = 66; // \"0x\" + 64 hex chars\n\n/**\n * Decode a 0x-prefixed hex string to bytes, with strict validation.\n * @throws if the input is not a valid 0x-prefixed hex string\n */\nfunction hexToBytes(hex: Hex): Uint8Array {\n if (!hex.startsWith(\"0x\") && !hex.startsWith(\"0X\")) {\n throw new Error(\"Expected 0x-prefixed hex string\");\n }\n const clean = hex.slice(2);\n if (clean.length % 2 !== 0) {\n throw new Error(`Hex string has odd length: ${clean.length}`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error(\"Hex string contains non-hex characters\");\n }\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Encode a Uint8Array as a 0x-prefixed lowercase hex string.\n */\nfunction bytesToHex(bytes: Uint8Array): Hex {\n return `0x${Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n}\n\n/**\n * Validate that a value is a 0x-prefixed bytes32 (exactly 32 bytes).\n * @throws if the value is not exactly 32 bytes\n */\nfunction assertBytes32(value: Hex, label: string): void {\n if (value.length !== HEX_BYTES32_LENGTH) {\n throw new Error(\n `${label} must be exactly 32 bytes (${HEX_BYTES32_LENGTH} hex chars with 0x prefix), got ${value.length}`,\n );\n }\n}\n\n/**\n * Compute the SHA-256 hashlock from a secret preimage.\n *\n * Matches the on-chain validation: `sha256(abi.encodePacked(s))` where `s` is a `bytes32`.\n * `abi.encodePacked(bytes32)` is just the raw 32 bytes — no ABI padding.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @returns 0x-prefixed bytes32 SHA-256 hash\n * @throws if secret is not exactly 32 bytes\n */\nexport function computeHashlock(secret: Hex): Hex {\n assertBytes32(secret, \"Secret\");\n const secretBytes = hexToBytes(secret);\n const hash = sha256(secretBytes);\n return bytesToHex(hash);\n}\n\n/**\n * Validate that a secret's SHA-256 hash matches the expected hashlock.\n *\n * Use this for client-side pre-validation before sending the activation\n * transaction to avoid wasting gas on a contract revert.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @param hashlock - 0x-prefixed bytes32 expected hashlock from the vault\n * @returns true if SHA-256(secret) matches the hashlock\n * @throws if secret or hashlock is not exactly 32 bytes\n */\nexport function validateSecretAgainstHashlock(\n secret: Hex,\n hashlock: Hex,\n): boolean {\n assertBytes32(secret, \"Secret\");\n assertBytes32(hashlock, \"Hashlock\");\n // Validate hashlock is valid hex (secret is validated inside computeHashlock)\n hexToBytes(hashlock);\n\n const computed = computeHashlock(secret);\n return computed.toLowerCase() === hashlock.toLowerCase();\n}\n","/**\n * Payout Manager\n *\n * High-level manager that orchestrates the payout signing flow by coordinating\n * SDK primitives ({@link buildPayoutPsbt}, {@link extractPayoutSignature})\n * with a user-provided Bitcoin wallet.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @see {@link PeginManager} - For Steps 1–4 of the peg-in flow\n * @see {@link buildPayoutPsbt} - Lower-level primitive for custom implementations\n * @see {@link extractPayoutSignature} - Extract signatures from signed PSBTs\n *\n * @module managers/PayoutManager\n */\n\nimport type {\n BitcoinWallet,\n SignPsbtOptions,\n} from \"../../../shared/wallets\";\nimport { createTaprootScriptPathSignOptions } from \"../utils/signing\";\nimport {\n assertPayoutOutputMatchesRegistered,\n buildPayoutPsbt,\n extractPayoutSignature,\n validateWalletPubkey,\n type Network,\n} from \"../primitives\";\n\n/**\n * Configuration for the PayoutManager.\n */\nexport interface PayoutManagerConfig {\n /**\n * Bitcoin network to use for transactions.\n */\n network: Network;\n\n /**\n * Bitcoin wallet for signing payout transactions.\n */\n btcWallet: BitcoinWallet;\n}\n\n/**\n * Base parameters shared by both payout transaction types.\n */\ninterface SignPayoutBaseParams {\n /**\n * Peg-in transaction hex.\n * The original transaction that created the vault output being spent.\n */\n peginTxHex: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex).\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex).\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex).\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex). This MUST be the\n * key registered on-chain for the vault — typically read from\n * `BTCVaultRegistry.getBtcVaultBasicInfo(...).depositorBtcPubKey`.\n *\n * Required: omitting it would degrade `validateWalletPubkey` to a\n * self-comparison, allowing the wrong wallet to produce a signature\n * over a script tree that doesn't match the on-chain UTXO.\n */\n depositorBtcPubkey: string;\n\n /**\n * The on-chain registered depositor payout scriptPubKey (hex, with or without 0x prefix).\n * Used to validate that the VP-provided payout transaction actually pays to the\n * correct depositor payout address before signing.\n */\n registeredPayoutScriptPubKey: string;\n}\n\n/**\n * Parameters for signing a Payout transaction.\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface SignPayoutParams extends SignPayoutBaseParams {\n /**\n * Payout transaction hex (unsigned).\n * This is the transaction from the vault provider that needs depositor signature.\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex.\n * Payout input 1 references Assert output 0.\n */\n assertTxHex: string;\n}\n\n/**\n * Result of signing a payout transaction.\n */\nexport interface PayoutSignatureResult {\n /**\n * 64-byte Schnorr signature (128 hex characters).\n */\n signature: string;\n\n /**\n * Depositor's BTC public key used for signing.\n */\n depositorBtcPubkey: string;\n}\n\n/**\n * High-level manager for payout transaction signing.\n *\n * @remarks\n * After registering your peg-in on Ethereum (Step 3), the vault provider prepares\n * claim/payout transaction pairs. You must sign each payout transaction using this\n * manager and submit the signatures to the vault provider's RPC API.\n *\n * **What happens internally:**\n * 1. Validates your wallet's public key matches the vault's depositor\n * 2. Builds an unsigned PSBT with taproot script path spend info\n * 3. Signs input 0 (the vault UTXO) with your wallet\n * 4. Extracts the 64-byte Schnorr signature\n *\n * **Note:** The payout transaction has 2 inputs. PayoutManager only signs input 0\n * (from the peg-in tx). Input 1 (from the assert tx) is signed by the vault provider.\n *\n * @see {@link PeginManager} - For the complete peg-in flow context\n * @see {@link buildPayoutPsbt} - Lower-level primitive used internally\n * @see {@link extractPayoutSignature} - Signature extraction primitive\n */\nexport class PayoutManager {\n private readonly config: PayoutManagerConfig;\n\n /**\n * Creates a new PayoutManager instance.\n *\n * @param config - Manager configuration including wallet\n */\n constructor(config: PayoutManagerConfig) {\n this.config = config;\n }\n\n /**\n * Signs a Payout transaction and extracts the Schnorr signature.\n *\n * Flow:\n * 1. Vault provider submits Claim transaction\n * 2. Claimer submits Assert transaction to prove validity\n * 3. Payout can be executed (references Assert tx)\n *\n * This method orchestrates the following steps:\n * 1. Get wallet's public key and convert to x-only format\n * 2. Validate wallet pubkey matches on-chain depositor pubkey (if provided)\n * 3. Build unsigned PSBT using primitives\n * 4. Sign PSBT via btcWallet.signPsbt()\n * 5. Extract 64-byte Schnorr signature using primitives\n *\n * The returned signature can be submitted to the vault provider API.\n *\n * @param params - Payout signing parameters\n * @returns Signature result with 64-byte Schnorr signature and depositor pubkey\n * @throws Error if wallet pubkey doesn't match depositor pubkey\n * @throws Error if wallet operations fail or signature extraction fails\n */\n async signPayoutTransaction(\n params: SignPayoutParams,\n ): Promise<PayoutSignatureResult> {\n // Validate payout TX outputs pay to the registered depositor payout address\n this.validatePayoutOutputs(\n params.payoutTxHex,\n params.registeredPayoutScriptPubKey,\n );\n\n // Validate wallet pubkey matches depositor and get both formats\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n params.depositorBtcPubkey,\n );\n\n // Build unsigned PSBT for Payout (uses Assert tx)\n const payoutPsbt = await buildPayoutPsbt({\n payoutTxHex: params.payoutTxHex,\n peginTxHex: params.peginTxHex,\n assertTxHex: params.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: params.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: params.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: this.config.network,\n });\n\n // Sign PSBT via wallet (Taproot script-path spend, input 0 only)\n const signedPsbtHex = await this.config.btcWallet.signPsbt(\n payoutPsbt.psbtHex,\n createTaprootScriptPathSignOptions(walletPubkeyRaw, 1),\n );\n\n // Extract Schnorr signature\n const signature = extractPayoutSignature(signedPsbtHex, depositorPubkey);\n\n return {\n signature,\n depositorBtcPubkey: depositorPubkey,\n };\n }\n\n /**\n * Gets the configured Bitcoin network.\n *\n * @returns The Bitcoin network (mainnet, testnet, signet, regtest)\n */\n getNetwork(): Network {\n return this.config.network;\n }\n\n /**\n * Checks if the wallet supports batch signing (signPsbts).\n *\n * @returns true if batch signing is supported\n */\n supportsBatchSigning(): boolean {\n return typeof this.config.btcWallet.signPsbts === \"function\";\n }\n\n /**\n * Batch signs multiple payout transactions (1 per claimer).\n * This allows signing all transactions with a single wallet interaction.\n *\n * @param transactions - Array of payout params to sign\n * @returns Array of signature results matching input order\n * @throws Error if wallet doesn't support batch signing\n * @throws Error if any signing operation fails\n */\n async signPayoutTransactionsBatch(\n transactions: SignPayoutParams[],\n ): Promise<\n Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }>\n > {\n if (!this.supportsBatchSigning()) {\n throw new Error(\n \"Wallet does not support batch signing (signPsbts method not available)\",\n );\n }\n\n // Get wallet pubkey once\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n\n // Build all PSBTs (1 per claimer)\n const psbtsToSign: string[] = [];\n const signOptions: SignPsbtOptions[] = [];\n const depositorPubkeys: string[] = [];\n\n for (const tx of transactions) {\n // Validate payout TX outputs pay to the registered depositor payout address\n this.validatePayoutOutputs(\n tx.payoutTxHex,\n tx.registeredPayoutScriptPubKey,\n );\n\n // Validate wallet pubkey matches depositor\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n tx.depositorBtcPubkey,\n );\n depositorPubkeys.push(depositorPubkey);\n\n // Build Payout PSBT\n const payoutPsbt = await buildPayoutPsbt({\n payoutTxHex: tx.payoutTxHex,\n peginTxHex: tx.peginTxHex,\n assertTxHex: tx.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: tx.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: tx.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: tx.universalChallengerBtcPubkeys,\n timelockPegin: tx.timelockPegin,\n network: this.config.network,\n });\n psbtsToSign.push(payoutPsbt.psbtHex);\n signOptions.push(createTaprootScriptPathSignOptions(walletPubkeyRaw, 1));\n }\n\n // Batch sign all PSBTs with single wallet interaction\n const signedPsbts = await this.config.btcWallet.signPsbts!(\n psbtsToSign,\n signOptions,\n );\n\n // Validate that wallet returned the expected number of signed PSBTs\n if (signedPsbts.length !== transactions.length) {\n throw new Error(\n `Expected ${transactions.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n\n // Extract signatures from signed PSBTs\n const results: Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }> = [];\n\n for (let i = 0; i < transactions.length; i++) {\n const depositorPubkey = depositorPubkeys[i];\n const payoutSignature = extractPayoutSignature(\n signedPsbts[i],\n depositorPubkey,\n );\n\n results.push({\n payoutSignature,\n depositorBtcPubkey: depositorPubkey,\n });\n }\n\n return results;\n }\n\n /**\n * Validates that the payout transaction's largest output pays to the\n * registered depositor payout address (scriptPubKey).\n *\n * This prevents two attack vectors from a malicious vault provider:\n * 1. Substituting a completely different payout address\n * 2. Including a dust output to the correct address while routing\n * the actual funds to an attacker-controlled address\n *\n * @param payoutTxHex - Raw payout transaction hex\n * @param registeredPayoutScriptPubKey - On-chain registered scriptPubKey (hex, with or without 0x prefix)\n * @throws Error if scriptPubKey is invalid hex\n * @throws Error if the largest output does not pay to the registered address\n */\n private validatePayoutOutputs(\n payoutTxHex: string,\n registeredPayoutScriptPubKey: string,\n ): void {\n assertPayoutOutputMatchesRegistered(\n payoutTxHex,\n registeredPayoutScriptPubKey,\n );\n }\n}\n"],"names":["HEX_BYTES32_LENGTH","hexToBytes","hex","clean","bytes","i","bytesToHex","b","assertBytes32","value","label","computeHashlock","secret","secretBytes","hash","sha256","validateSecretAgainstHashlock","hashlock","PayoutManager","config","__publicField","params","walletPubkeyRaw","depositorPubkey","validateWalletPubkey","payoutPsbt","buildPayoutPsbt","signedPsbtHex","createTaprootScriptPathSignOptions","extractPayoutSignature","transactions","psbtsToSign","signOptions","depositorPubkeys","tx","signedPsbts","results","payoutSignature","payoutTxHex","registeredPayoutScriptPubKey","assertPayoutOutputMatchesRegistered"],"mappings":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BAAwBW,EAAG,uBAC3B,sBAAuBA,EAAG,sBAC1B,8BAA+BA,EAAG,8BAClC,cAAeA,EAAG,cAClB,QAAS,KAAK,OAAO,OAAA,CACtB,EACDH,EAAY,KAAKN,EAAW,OAAO,EACnCO,EAAY,KAAKJ,EAAAA,mCAAmCN,EAAiB,CAAC,CAAC,CACzE,CAGA,MAAMa,EAAc,MAAM,KAAK,OAAO,UAAU,UAC9CJ,EACAC,CAAA,EAIF,GAAIG,EAAY,SAAWL,EAAa,OACtC,MAAM,IAAI,MACR,YAAYA,EAAa,MAAM,8BAA8BK,EAAY,MAAM,EAAA,EAKnF,MAAMC,EAGD,CAAA,EAEL,QAAS/B,EAAI,EAAGA,EAAIyB,EAAa,OAAQzB,IAAK,CAC5C,MAAMkB,EAAkBU,EAAiB5B,CAAC,EACpCgC,EAAkBR,EAAAA,uBACtBM,EAAY9B,CAAC,EACbkB,CAAA,EAGFa,EAAQ,KAAK,CACX,gBAAAC,EACA,mBAAoBd,CAAA,CACrB,CACH,CAEA,OAAOa,CACT,CAgBQ,sBACNE,EACAC,EACM,CACNC,EAAAA,oCACEF,EACAC,CAAA,CAEJ,CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"PayoutManager-s_uH8Uuj.js","sources":["../src/tbv/core/services/htlc/index.ts","../src/tbv/core/managers/PayoutManager.ts"],"sourcesContent":["/**\n * HTLC Secret / Hashlock Utilities\n *\n * Pure functions for computing and validating SHA-256 hashlocks used in the\n * vault deposit protocol's HTLC (Hash Time Lock Contract).\n *\n * The SDK does NOT generate secrets — that is the caller's responsibility.\n * Today callers use `crypto.getRandomValues(32)`; when the `deriveContextHash`\n * wallet API ships, callers will use `wallet.deriveContextHash(\"babylon-btc-vault\", ctx)`.\n * These utilities work identically regardless of how the secret was produced.\n *\n * On-chain contract validation (BTCVaultRegistry.activateVaultWithSecret):\n * if (sha256(abi.encodePacked(s)) != hashlock) revert InvalidSecret();\n *\n * @module htlc\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport type { Hex } from \"viem\";\n\n/** Expected hex length for a 0x-prefixed bytes32 value. */\nconst HEX_BYTES32_LENGTH = 66; // \"0x\" + 64 hex chars\n\n/**\n * Decode a 0x-prefixed hex string to bytes, with strict validation.\n * @throws if the input is not a valid 0x-prefixed hex string\n */\nfunction hexToBytes(hex: Hex): Uint8Array {\n if (!hex.startsWith(\"0x\") && !hex.startsWith(\"0X\")) {\n throw new Error(\"Expected 0x-prefixed hex string\");\n }\n const clean = hex.slice(2);\n if (clean.length % 2 !== 0) {\n throw new Error(`Hex string has odd length: ${clean.length}`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error(\"Hex string contains non-hex characters\");\n }\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Encode a Uint8Array as a 0x-prefixed lowercase hex string.\n */\nfunction bytesToHex(bytes: Uint8Array): Hex {\n return `0x${Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n}\n\n/**\n * Validate that a value is a 0x-prefixed bytes32 (exactly 32 bytes).\n * @throws if the value is not exactly 32 bytes\n */\nfunction assertBytes32(value: Hex, label: string): void {\n if (value.length !== HEX_BYTES32_LENGTH) {\n throw new Error(\n `${label} must be exactly 32 bytes (${HEX_BYTES32_LENGTH} hex chars with 0x prefix), got ${value.length}`,\n );\n }\n}\n\n/**\n * Compute the SHA-256 hashlock from a secret preimage.\n *\n * Matches the on-chain validation: `sha256(abi.encodePacked(s))` where `s` is a `bytes32`.\n * `abi.encodePacked(bytes32)` is just the raw 32 bytes — no ABI padding.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @returns 0x-prefixed bytes32 SHA-256 hash\n * @throws if secret is not exactly 32 bytes\n */\nexport function computeHashlock(secret: Hex): Hex {\n assertBytes32(secret, \"Secret\");\n const secretBytes = hexToBytes(secret);\n const hash = sha256(secretBytes);\n return bytesToHex(hash);\n}\n\n/**\n * Validate that a secret's SHA-256 hash matches the expected hashlock.\n *\n * Use this for client-side pre-validation before sending the activation\n * transaction to avoid wasting gas on a contract revert.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @param hashlock - 0x-prefixed bytes32 expected hashlock from the vault\n * @returns true if SHA-256(secret) matches the hashlock\n * @throws if secret or hashlock is not exactly 32 bytes\n */\nexport function validateSecretAgainstHashlock(\n secret: Hex,\n hashlock: Hex,\n): boolean {\n assertBytes32(secret, \"Secret\");\n assertBytes32(hashlock, \"Hashlock\");\n // Validate hashlock is valid hex (secret is validated inside computeHashlock)\n hexToBytes(hashlock);\n\n const computed = computeHashlock(secret);\n return computed.toLowerCase() === hashlock.toLowerCase();\n}\n","/**\n * Payout Manager\n *\n * High-level manager that orchestrates the payout signing flow by coordinating\n * SDK primitives ({@link buildPayoutPsbt}, {@link extractPayoutSignature})\n * with a user-provided Bitcoin wallet.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @see {@link PeginManager} - For Steps 1–4 of the peg-in flow\n * @see {@link buildPayoutPsbt} - Lower-level primitive for custom implementations\n * @see {@link extractPayoutSignature} - Extract signatures from signed PSBTs\n *\n * @module managers/PayoutManager\n */\n\nimport type {\n BitcoinWallet,\n SignPsbtOptions,\n} from \"../../../shared/wallets\";\nimport { createTaprootScriptPathSignOptions } from \"../utils/signing\";\nimport {\n assertPayoutOutputMatchesRegistered,\n buildPayoutPsbt,\n extractPayoutSignature,\n validateWalletPubkey,\n type Network,\n} from \"../primitives\";\n\n/**\n * Configuration for the PayoutManager.\n */\nexport interface PayoutManagerConfig {\n /**\n * Bitcoin network to use for transactions.\n */\n network: Network;\n\n /**\n * Bitcoin wallet for signing payout transactions.\n */\n btcWallet: BitcoinWallet;\n}\n\n/**\n * Base parameters shared by both payout transaction types.\n */\ninterface SignPayoutBaseParams {\n /**\n * Peg-in transaction hex.\n * The original transaction that created the vault output being spent.\n */\n peginTxHex: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex).\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex).\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex).\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex). This MUST be the\n * key registered on-chain for the vault — typically read from\n * `BTCVaultRegistry.getBtcVaultBasicInfo(...).depositorBtcPubKey`.\n *\n * Required: omitting it would degrade `validateWalletPubkey` to a\n * self-comparison, allowing the wrong wallet to produce a signature\n * over a script tree that doesn't match the on-chain UTXO.\n */\n depositorBtcPubkey: string;\n\n /**\n * The on-chain registered depositor payout scriptPubKey (hex, with or without 0x prefix).\n * Used to validate that the VP-provided payout transaction actually pays to the\n * correct depositor payout address before signing.\n */\n registeredPayoutScriptPubKey: string;\n}\n\n/**\n * Parameters for signing a Payout transaction.\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface SignPayoutParams extends SignPayoutBaseParams {\n /**\n * Payout transaction hex (unsigned).\n * This is the transaction from the vault provider that needs depositor signature.\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex.\n * Payout input 1 references Assert output 0.\n */\n assertTxHex: string;\n}\n\n/**\n * Result of signing a payout transaction.\n */\nexport interface PayoutSignatureResult {\n /**\n * 64-byte Schnorr signature (128 hex characters).\n */\n signature: string;\n\n /**\n * Depositor's BTC public key used for signing.\n */\n depositorBtcPubkey: string;\n}\n\n/**\n * High-level manager for payout transaction signing.\n *\n * @remarks\n * After registering your peg-in on Ethereum (Step 3), the vault provider prepares\n * claim/payout transaction pairs. You must sign each payout transaction using this\n * manager and submit the signatures to the vault provider's RPC API.\n *\n * **What happens internally:**\n * 1. Validates your wallet's public key matches the vault's depositor\n * 2. Builds an unsigned PSBT with taproot script path spend info\n * 3. Signs input 0 (the vault UTXO) with your wallet\n * 4. Extracts the 64-byte Schnorr signature\n *\n * **Note:** The payout transaction has 2 inputs. PayoutManager only signs input 0\n * (from the peg-in tx). Input 1 (from the assert tx) is signed by the vault provider.\n *\n * @see {@link PeginManager} - For the complete peg-in flow context\n * @see {@link buildPayoutPsbt} - Lower-level primitive used internally\n * @see {@link extractPayoutSignature} - Signature extraction primitive\n */\nexport class PayoutManager {\n private readonly config: PayoutManagerConfig;\n\n /**\n * Creates a new PayoutManager instance.\n *\n * @param config - Manager configuration including wallet\n */\n constructor(config: PayoutManagerConfig) {\n this.config = config;\n }\n\n /**\n * Signs a Payout transaction and extracts the Schnorr signature.\n *\n * Flow:\n * 1. Vault provider submits Claim transaction\n * 2. Claimer submits Assert transaction to prove validity\n * 3. Payout can be executed (references Assert tx)\n *\n * This method orchestrates the following steps:\n * 1. Get wallet's public key and convert to x-only format\n * 2. Validate wallet pubkey matches on-chain depositor pubkey (if provided)\n * 3. Build unsigned PSBT using primitives\n * 4. Sign PSBT via btcWallet.signPsbt()\n * 5. Extract 64-byte Schnorr signature using primitives\n *\n * The returned signature can be submitted to the vault provider API.\n *\n * @param params - Payout signing parameters\n * @returns Signature result with 64-byte Schnorr signature and depositor pubkey\n * @throws Error if wallet pubkey doesn't match depositor pubkey\n * @throws Error if wallet operations fail or signature extraction fails\n */\n async signPayoutTransaction(\n params: SignPayoutParams,\n ): Promise<PayoutSignatureResult> {\n // Validate payout TX outputs pay to the registered depositor payout address\n this.validatePayoutOutputs(\n params.payoutTxHex,\n params.registeredPayoutScriptPubKey,\n );\n\n // Validate wallet pubkey matches depositor and get both formats\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n params.depositorBtcPubkey,\n );\n\n // Build unsigned PSBT for Payout (uses Assert tx)\n const payoutPsbt = await buildPayoutPsbt({\n payoutTxHex: params.payoutTxHex,\n peginTxHex: params.peginTxHex,\n assertTxHex: params.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: params.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: params.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: this.config.network,\n });\n\n // Sign PSBT via wallet (Taproot script-path spend, input 0 only)\n const signedPsbtHex = await this.config.btcWallet.signPsbt(\n payoutPsbt.psbtHex,\n createTaprootScriptPathSignOptions(walletPubkeyRaw, 1),\n );\n\n // Extract Schnorr signature\n const signature = extractPayoutSignature(signedPsbtHex, depositorPubkey);\n\n return {\n signature,\n depositorBtcPubkey: depositorPubkey,\n };\n }\n\n /**\n * Gets the configured Bitcoin network.\n *\n * @returns The Bitcoin network (mainnet, testnet, signet, regtest)\n */\n getNetwork(): Network {\n return this.config.network;\n }\n\n /**\n * Checks if the wallet supports batch signing (signPsbts).\n *\n * @returns true if batch signing is supported\n */\n supportsBatchSigning(): boolean {\n return typeof this.config.btcWallet.signPsbts === \"function\";\n }\n\n /**\n * Batch signs multiple payout transactions (1 per claimer).\n * This allows signing all transactions with a single wallet interaction.\n *\n * @param transactions - Array of payout params to sign\n * @returns Array of signature results matching input order\n * @throws Error if wallet doesn't support batch signing\n * @throws Error if any signing operation fails\n */\n async signPayoutTransactionsBatch(\n transactions: SignPayoutParams[],\n ): Promise<\n Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }>\n > {\n if (!this.supportsBatchSigning()) {\n throw new Error(\n \"Wallet does not support batch signing (signPsbts method not available)\",\n );\n }\n\n // Get wallet pubkey once\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n\n // Build all PSBTs (1 per claimer)\n const psbtsToSign: string[] = [];\n const signOptions: SignPsbtOptions[] = [];\n const depositorPubkeys: string[] = [];\n\n for (const tx of transactions) {\n // Validate payout TX outputs pay to the registered depositor payout address\n this.validatePayoutOutputs(\n tx.payoutTxHex,\n tx.registeredPayoutScriptPubKey,\n );\n\n // Validate wallet pubkey matches depositor\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n tx.depositorBtcPubkey,\n );\n depositorPubkeys.push(depositorPubkey);\n\n // Build Payout PSBT\n const payoutPsbt = await buildPayoutPsbt({\n payoutTxHex: tx.payoutTxHex,\n peginTxHex: tx.peginTxHex,\n assertTxHex: tx.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: tx.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: tx.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: tx.universalChallengerBtcPubkeys,\n timelockPegin: tx.timelockPegin,\n network: this.config.network,\n });\n psbtsToSign.push(payoutPsbt.psbtHex);\n signOptions.push(createTaprootScriptPathSignOptions(walletPubkeyRaw, 1));\n }\n\n // Batch sign all PSBTs with single wallet interaction\n const signedPsbts = await this.config.btcWallet.signPsbts!(\n psbtsToSign,\n signOptions,\n );\n\n // Validate that wallet returned the expected number of signed PSBTs\n if (signedPsbts.length !== transactions.length) {\n throw new Error(\n `Expected ${transactions.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n\n // Extract signatures from signed PSBTs\n const results: Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }> = [];\n\n for (let i = 0; i < transactions.length; i++) {\n const depositorPubkey = depositorPubkeys[i];\n const payoutSignature = extractPayoutSignature(\n signedPsbts[i],\n depositorPubkey,\n );\n\n results.push({\n payoutSignature,\n depositorBtcPubkey: depositorPubkey,\n });\n }\n\n return results;\n }\n\n /**\n * Validates that the payout transaction's largest output pays to the\n * registered depositor payout address (scriptPubKey).\n *\n * This prevents two attack vectors from a malicious vault provider:\n * 1. Substituting a completely different payout address\n * 2. Including a dust output to the correct address while routing\n * the actual funds to an attacker-controlled address\n *\n * @param payoutTxHex - Raw payout transaction hex\n * @param registeredPayoutScriptPubKey - On-chain registered scriptPubKey (hex, with or without 0x prefix)\n * @throws Error if scriptPubKey is invalid hex\n * @throws Error if the largest output does not pay to the registered address\n */\n private validatePayoutOutputs(\n payoutTxHex: string,\n registeredPayoutScriptPubKey: string,\n ): void {\n assertPayoutOutputMatchesRegistered(\n payoutTxHex,\n registeredPayoutScriptPubKey,\n );\n }\n}\n"],"names":["HEX_BYTES32_LENGTH","hexToBytes","hex","clean","bytes","i","bytesToHex","b","assertBytes32","value","label","computeHashlock","secret","secretBytes","hash","sha256","validateSecretAgainstHashlock","hashlock","PayoutManager","config","__publicField","params","walletPubkeyRaw","depositorPubkey","validateWalletPubkey","payoutPsbt","buildPayoutPsbt","signedPsbtHex","createTaprootScriptPathSignOptions","extractPayoutSignature","transactions","psbtsToSign","signOptions","depositorPubkeys","tx","signedPsbts","results","payoutSignature","payoutTxHex","registeredPayoutScriptPubKey","assertPayoutOutputMatchesRegistered"],"mappings":";;;;;;;;AAqBA,MAAMA,IAAqB;AAM3B,SAASC,EAAWC,GAAsB;AACxC,MAAI,CAACA,EAAI,WAAW,IAAI,KAAK,CAACA,EAAI,WAAW,IAAI;AAC/C,UAAM,IAAI,MAAM,iCAAiC;AAEnD,QAAMC,IAAQD,EAAI,MAAM,CAAC;AACzB,MAAIC,EAAM,SAAS,MAAM;AACvB,UAAM,IAAI,MAAM,8BAA8BA,EAAM,MAAM,EAAE;AAE9D,MAAI,CAAC,iBAAiB,KAAKA,CAAK;AAC9B,UAAM,IAAI,MAAM,wCAAwC;AAE1D,QAAMC,IAAQ,IAAI,WAAWD,EAAM,SAAS,CAAC;AAC7C,WAASE,IAAI,GAAGA,IAAID,EAAM,QAAQC;AAChC,IAAAD,EAAMC,CAAC,IAAI,SAASF,EAAM,MAAME,IAAI,GAAGA,IAAI,IAAI,CAAC,GAAG,EAAE;AAEvD,SAAOD;AACT;AAKA,SAASE,EAAWF,GAAwB;AAC1C,SAAO,KAAK,MAAM,KAAKA,CAAK,EACzB,IAAI,CAACG,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AAS,KAAK,OAAO;AAAA,MAAA,CACtB;AACD,MAAAH,EAAY,KAAKN,EAAW,OAAO,GACnCO,EAAY,KAAKJ,EAAmCN,GAAiB,CAAC,CAAC;AAAA,IACzE;AAGA,UAAMa,IAAc,MAAM,KAAK,OAAO,UAAU;AAAA,MAC9CJ;AAAA,MACAC;AAAA,IAAA;AAIF,QAAIG,EAAY,WAAWL,EAAa;AACtC,YAAM,IAAI;AAAA,QACR,YAAYA,EAAa,MAAM,8BAA8BK,EAAY,MAAM;AAAA,MAAA;AAKnF,UAAMC,IAGD,CAAA;AAEL,aAAS/B,IAAI,GAAGA,IAAIyB,EAAa,QAAQzB,KAAK;AAC5C,YAAMkB,IAAkBU,EAAiB5B,CAAC,GACpCgC,IAAkBR;AAAA,QACtBM,EAAY9B,CAAC;AAAA,QACbkB;AAAA,MAAA;AAGF,MAAAa,EAAQ,KAAK;AAAA,QACX,iBAAAC;AAAA,QACA,oBAAoBd;AAAA,MAAA,CACrB;AAAA,IACH;AAEA,WAAOa;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBQ,sBACNE,GACAC,GACM;AACN,IAAAC;AAAA,MACEF;AAAA,MACAC;AAAA,IAAA;AAAA,EAEJ;AACF;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var Ut=Object.defineProperty;var Vt=(n,t,e)=>t in n?Ut(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var T=(n,t,e)=>Vt(n,typeof t!="symbol"?t+"":t,e);const P=require("./sha2-DsrLC4NM.cjs"),K=require("bitcoinjs-lib"),Y=require("buffer"),C=require("viem"),$=require("./BTCVaultRegistry.abi-ZdPpION2.cjs"),H=require("./errors-BP73_stm.cjs"),L=require("@babylonlabs-io/babylon-tbv-rust-wasm"),R=require("./peginInput-tbw9BpZy.cjs"),u=require("./bitcoin-B3aqjuMP.cjs"),Nt=require("./signing-Bnsro0hE.cjs"),st=require("./validation-u8W7Lp2x.cjs"),Lt=require("./PayoutManager-BhJoQZsG.cjs"),S=require("./waitForTransactionReceiptSmartAware-D9ykVriz.cjs"),ot=require("./fundPeginTransaction-DaWoYCgO.cjs"),pt=require("./mempoolApi-YNkKjQCU.cjs");function Wt(n){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const e in n)if(e!=="default"){const r=Object.getOwnPropertyDescriptor(n,e);Object.defineProperty(t,e,r.get?r:{enumerable:!0,get:()=>n[e]})}}return t.default=n,Object.freeze(t)}const mt=Wt(K),W=BigInt(2**32-1),it=BigInt(32);function Ft(n,t=!1){return t?{h:Number(n&W),l:Number(n>>it&W)}:{h:Number(n>>it&W)|0,l:Number(n&W)|0}}function Mt(n,t=!1){const e=n.length;let r=new Uint32Array(e),s=new Uint32Array(e);for(let o=0;o<e;o++){const{h:i,l:a}=Ft(n[o],t);[r[o],s[o]]=[i,a]}return[r,s]}const Xt=(n,t,e)=>n<<e|t>>>32-e,Kt=(n,t,e)=>t<<e|n>>>32-e,Dt=(n,t,e)=>t<<e-32|n>>>64-e,qt=(n,t,e)=>n<<e-32|t>>>64-e,zt=106,jt=32,at=34;function Gt(n,t,e){const r=u.stripHexPrefix(n),s=mt.Transaction.fromHex(r);if(s.outs.length<=t)throw new Error(`Pre-PegIn auth-anchor OP_RETURN missing: tx has ${s.outs.length} outputs, expected at least ${t+1} (vault outputs + OP_RETURN)`);const o=s.outs[t],i=o.script;if(i.length!==at||i[0]!==zt||i[1]!==jt)throw new Error(`Pre-PegIn auth-anchor OP_RETURN at vout ${t} has unexpected script encoding (got ${i.length}-byte script with prefix 0x${i.slice(0,Math.min(2,i.length)).toString("hex")}; expected ${at}-byte OP_RETURN + PUSH32 layout)`);const a=i.slice(2).toString("hex").toLowerCase();if(a!==e.toLowerCase())throw new Error(`Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${t}: tx pushes ${a}, expected ${e}`);if(o.value!==0)throw new Error(`Pre-PegIn auth-anchor OP_RETURN at vout ${t} has non-zero value ${o.value}; OP_RETURN outputs must be 0-value`)}const N=32,j=32,J=36,Pt=32,D=4,Zt=D+N+D+Pt;function tt(n,t,e){n[t]=e>>>24&255,n[t+1]=e>>>16&255,n[t+2]=e>>>8&255,n[t+3]=e&255}function Qt(n){if(n.txid.length!==j)throw new Error(`outpoint.txid must be exactly ${j} bytes, got ${n.txid.length}`);if(!Number.isInteger(n.vout)||n.vout<0||n.vout>4294967295)throw new Error(`outpoint.vout must be a u32, got ${n.vout}`);const t=new Uint8Array(J);return t.set(n.txid,0),tt(t,j,n.vout),t}function ct(n,t){const e=Math.min(n.length,t.length);for(let r=0;r<e;r++)if(n[r]!==t[r])return n[r]-t[r];return n.length-t.length}function xt(n){if(n.length===0)throw new Error("buildFundingOutpointsCommitment: outpoints must be non-empty");const t=n.map(Qt);t.sort(ct);for(let r=1;r<t.length;r++)if(ct(t[r-1],t[r])===0)throw new Error("buildFundingOutpointsCommitment: duplicate outpoint detected");const e=new Uint8Array(t.length*J);for(let r=0;r<t.length;r++)e.set(t[r],r*J);return P.sha256(e)}function wt(n){if(n.depositorBtcPubkey.length!==N)throw new Error(`vaultContext: depositorBtcPubkey must be exactly ${N} bytes, got ${n.depositorBtcPubkey.length}`);const t=xt(n.fundingOutpoints),e=new Uint8Array(Zt);let r=0;return tt(e,r,N),r+=D,e.set(n.depositorBtcPubkey,r),r+=N,tt(e,r,Pt),r+=D,e.set(t,r),e}const bt="babylon-btc-vault",yt=32,lt=yt*2,Yt=/^[0-9a-f]+$/;async function kt(n,t){const e=wt(t),r=u.uint8ArrayToHex(e),s=await n.deriveContextHash(bt,r);if(typeof s!="string")throw new Error(`deriveVaultRoot: wallet must return a string, got ${typeof s}`);if(s.length!==lt)throw new Error(`deriveVaultRoot: wallet must return a ${lt}-character hex string (${yt} bytes), got length ${s.length}`);if(!Yt.test(s))throw new Error("deriveVaultRoot: wallet must return lowercase hex per derive-context-hash.md §2.1; got value with non-lowercase or non-hex characters");return u.hexToUint8Array(s)}const Jt=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Et=Uint8Array.from(new Array(16).fill(0).map((n,t)=>t)),te=Et.map(n=>(9*n+5)%16),Tt=(()=>{const e=[[Et],[te]];for(let r=0;r<4;r++)for(let s of e)s.push(s[r].map(o=>Jt[o]));return e})(),_t=Tt[0],Bt=Tt[1],vt=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(n=>Uint8Array.from(n)),ee=_t.map((n,t)=>n.map(e=>vt[t][e])),ne=Bt.map((n,t)=>n.map(e=>vt[t][e])),re=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),se=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function ut(n,t,e,r){return n===0?t^e^r:n===1?t&e|~t&r:n===2?(t|~e)^r:n===3?t&r|e&~r:t^(e|~r)}const F=new Uint32Array(16);class oe extends P.HashMD{constructor(){super(64,20,8,!0);T(this,"h0",1732584193);T(this,"h1",-271733879);T(this,"h2",-1732584194);T(this,"h3",271733878);T(this,"h4",-1009589776)}get(){const{h0:e,h1:r,h2:s,h3:o,h4:i}=this;return[e,r,s,o,i]}set(e,r,s,o,i){this.h0=e|0,this.h1=r|0,this.h2=s|0,this.h3=o|0,this.h4=i|0}process(e,r){for(let g=0;g<16;g++,r+=4)F[g]=e.getUint32(r,!0);let s=this.h0|0,o=s,i=this.h1|0,a=i,c=this.h2|0,h=c,l=this.h3|0,x=l,w=this.h4|0,b=w;for(let g=0;g<5;g++){const f=4-g,_=re[g],A=se[g],p=_t[g],k=Bt[g],E=ee[g],m=ne[g];for(let y=0;y<16;y++){const d=P.rotl(s+ut(g,i,c,l)+F[p[y]]+_,E[y])+w|0;s=w,w=l,l=P.rotl(c,10)|0,c=i,i=d}for(let y=0;y<16;y++){const d=P.rotl(o+ut(f,a,h,x)+F[k[y]]+A,m[y])+b|0;o=b,b=x,x=P.rotl(h,10)|0,h=a,a=d}}this.set(this.h1+c+x|0,this.h2+l+b|0,this.h3+w+o|0,this.h4+s+a|0,this.h0+i+h|0)}roundClean(){P.clean(F)}destroy(){this.destroyed=!0,P.clean(this.buffer),this.set(0,0,0,0,0)}}const ie=P.createHasher(()=>new oe),ae=BigInt(0),U=BigInt(1),ce=BigInt(2),le=BigInt(7),ue=BigInt(256),he=BigInt(113),At=[],It=[],St=[];for(let n=0,t=U,e=1,r=0;n<24;n++){[e,r]=[r,(2*e+3*r)%5],At.push(2*(5*r+e)),It.push((n+1)*(n+2)/2%64);let s=ae;for(let o=0;o<7;o++)t=(t<<U^(t>>le)*he)%ue,t&ce&&(s^=U<<(U<<BigInt(o))-U);St.push(s)}const Ht=Mt(St,!0),de=Ht[0],ge=Ht[1],ht=(n,t,e)=>e>32?Dt(n,t,e):Xt(n,t,e),dt=(n,t,e)=>e>32?qt(n,t,e):Kt(n,t,e);function fe(n,t=24){const e=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let i=0;i<10;i++)e[i]=n[i]^n[i+10]^n[i+20]^n[i+30]^n[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,h=e[c],l=e[c+1],x=ht(h,l,1)^e[a],w=dt(h,l,1)^e[a+1];for(let b=0;b<50;b+=10)n[i+b]^=x,n[i+b+1]^=w}let s=n[2],o=n[3];for(let i=0;i<24;i++){const a=It[i],c=ht(s,o,a),h=dt(s,o,a),l=At[i];s=n[l],o=n[l+1],n[l]=c,n[l+1]=h}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)e[a]=n[i+a];for(let a=0;a<10;a++)n[i+a]^=~e[(a+2)%10]&e[(a+4)%10]}n[0]^=de[r],n[1]^=ge[r]}P.clean(e)}class nt{constructor(t,e,r,s=!1,o=24){T(this,"state");T(this,"pos",0);T(this,"posOut",0);T(this,"finished",!1);T(this,"state32");T(this,"destroyed",!1);T(this,"blockLen");T(this,"suffix");T(this,"outputLen");T(this,"enableXOF",!1);T(this,"rounds");if(this.blockLen=t,this.suffix=e,this.outputLen=r,this.enableXOF=s,this.rounds=o,P.anumber(r,"outputLen"),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=P.u32(this.state)}clone(){return this._cloneInto()}keccak(){P.swap32IfBE(this.state32),fe(this.state32,this.rounds),P.swap32IfBE(this.state32),this.posOut=0,this.pos=0}update(t){P.aexists(this),P.abytes(t);const{blockLen:e,state:r}=this,s=t.length;for(let o=0;o<s;){const i=Math.min(e-this.pos,s-o);for(let a=0;a<i;a++)r[this.pos++]^=t[o++];this.pos===e&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:e,pos:r,blockLen:s}=this;t[r]^=e,(e&128)!==0&&r===s-1&&this.keccak(),t[s-1]^=128,this.keccak()}writeInto(t){P.aexists(this,!1),P.abytes(t),this.finish();const e=this.state,{blockLen:r}=this;for(let s=0,o=t.length;s<o;){this.posOut>=r&&this.keccak();const i=Math.min(r-this.posOut,o-s);t.set(e.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return P.anumber(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(P.aoutput(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,P.clean(this.state)}_cloneInto(t){const{blockLen:e,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return t||(t=new nt(e,r,s,i,o)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=o,t.suffix=r,t.outputLen=s,t.enableXOF=i,t.destroyed=this.destroyed,t}}const pe=(n,t,e,r={})=>P.createHasher(()=>new nt(t,n,e),r),me=pe(1,136,32),gt=64,B=20,et=4,Rt=2,Pe=0,xe=1,M=[64,64],we=n=>Array.from(n).map(t=>t.toString(16).padStart(2,"0")).join("");function rt(n){return ie(P.sha256(n))}function Ot(n){return(1<<n)-1}function be(n){let t=1;for(;t*t<n+1;)t++;return Math.max(t,2)}function ye(n){const t=et,e=n*Ot(t);return{d:t,n,checksum_radix:be(e)}}function G(n,t){const e=[];let r=t;for(;r>0;)e.push(r&255),r>>>=8;const s=new Uint8Array(n.length+e.length);s.set(n);for(let o=0;o<e.length;o++)s[n.length+o]=e[o];return rt(s)}function Z(n,t){let e=n;for(let r=0;r<t;r++)e=rt(e);return e}function ke(n,t){const e=Ot(t.d),r=t.checksum_radix-1,s=Math.floor(t.n*e/t.checksum_radix),o=[];for(let l=0;l<t.n;l++){const x=G(n,l+Rt),w=Z(x,e);o.push(Array.from(w))}const i=G(n,Pe),a=Z(i,r),c=G(n,xe),h=Z(c,s);return{config:t,message_terminals:o,checksum_major_terminal:Array.from(h),checksum_minor_terminal:Array.from(a)}}async function Ct(n){try{if(n.length!==gt)throw new Error(`WOTS seed must be exactly ${gt} bytes, got ${n.length}`);const t=[];for(let e=0;e<M.length;e++){const r=M[e],s=ye(r),o=new Uint8Array(n.length+1);o.set(n),o[n.length]=e;const i=rt(o);try{const a=ke(i,s);if(a.config.d!==et)throw new Error(`Block ${e}: expected d=${et}, got d=${a.config.d}`);if(a.config.n!==r)throw new Error(`Block ${e}: expected n=${r}, got n=${a.config.n}`);if(a.message_terminals.length!==r)throw new Error(`Block ${e}: expected ${r} message terminals, got ${a.message_terminals.length}`);for(let c=0;c<a.message_terminals.length;c++)if(a.message_terminals[c].length!==B)throw new Error(`Block ${e} terminal ${c}: expected ${B} bytes, got ${a.message_terminals[c].length}`);if(a.checksum_minor_terminal.length!==B)throw new Error(`Block ${e} checksum_minor: expected ${B} bytes`);if(a.checksum_major_terminal.length!==B)throw new Error(`Block ${e} checksum_major: expected ${B} bytes`);t.push(a)}finally{o.fill(0),i.fill(0)}}if(t.length!==M.length)throw new Error(`Expected ${M.length} blocks, got ${t.length}`);return t}finally{n.fill(0)}}function Q(n,t,e){if(n.length!==B)throw new Error(`Block ${t} ${e}: expected ${B} bytes, got ${n.length}`);for(let r=0;r<n.length;r++){const s=n[r];if(!Number.isInteger(s)||s<0||s>255)throw new Error(`Block ${t} ${e}[${r}]: invalid byte value ${s}`)}}function $t(n){if(n.length===0)throw new Error("Public keys array must not be empty");for(let o=0;o<n.length;o++){const i=n[o];Q(i.checksum_minor_terminal,o,"checksum_minor_terminal"),Q(i.checksum_major_terminal,o,"checksum_major_terminal");for(let a=0;a<i.message_terminals.length;a++)Q(i.message_terminals[a],o,`message_terminal[${a}]`)}let t=0;for(const o of n)t+=Rt+o.message_terminals.length;const e=new Uint8Array(t*B);let r=0;for(const o of n){e.set(o.checksum_minor_terminal,r),r+=B,e.set(o.checksum_major_terminal,r),r+=B;for(const i of o.message_terminals)e.set(i,r),r+=B}const s=me(e);return`0x${we(s)}`}async function Ee(n,t){const e=[],r=[],s=[],o=[];try{for(let i=0;i<t;i++){const a=await L.expandWotsSeed(n,i);try{const h=await Ct(a);e.push(h),r.push($t(h))}finally{a.fill(0)}const c=await L.expandHashlockSecret(n,i);try{const h=u.uint8ArrayToHex(c);s.push(h),o.push(Lt.computeHashlock(u.ensureHexPrefix(h)).slice(2))}finally{c.fill(0)}}}finally{n.fill(0)}return{perVaultWotsKeys:e,wotsPkHashes:r,htlcSecretHexes:s,hashlocks:o}}const Te=/^0x[0-9a-f]+$/i,_e=/^[0-9a-f]+$/i,Be=/^[A-Za-z0-9+/]+={0,2}$/;function V(n){if(typeof n!="string"||n.length===0)throw new Error("BTC wallet returned empty public key");return u.processPublicKeyToXOnly(n).toLowerCase()}function ve(n){if(typeof n!="string"||n.length===0)throw new Error("BTC wallet returned empty BIP-322 signature");if(n.startsWith("0x")||n.startsWith("0X")){if(!Te.test(n)||n.length<4||n.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return n.toLowerCase()}if(_e.test(n)){if(n.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return`0x${n.toLowerCase()}`}if(!Be.test(n)||n.length%4!==0)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");const t=Y.Buffer.from(n,"base64");if(t.length===0||t.toString("base64")!==n)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");return`0x${t.toString("hex")}`}async function Ae(n,t,e){if(typeof n.signPsbts=="function"){const s=await n.signPsbts(t,e);if(s.length!==t.length)throw new Error(`Expected ${t.length} signed PSBTs but received ${s.length}`);return s}const r=[];for(let s=0;s<t.length;s++){const o=await n.signPsbt(t[s],e[s]);r.push(o)}return r}const Ie=0,X="00".repeat(32);function Se(n,t,e,r){const s=e==null?void 0:e[`${n}:${t}`];return s?Promise.resolve({txid:n,vout:t,value:s.value,scriptPubKey:s.scriptPubKey}):pt.getUtxoInfo(n,t,r)}const ft=12e4;class He{constructor(t){T(this,"config");this.config=t}async preparePegin(t){if(t.amounts.length===0)throw new Error("amounts must contain at least one entry");const e=await this.config.btcWallet.getPublicKeyHex(),r=V(e);if(!u.isAddressFromPublicKey(t.changeAddress,e,this.config.btcNetwork))throw new Error(`Pre-PegIn changeAddress "${t.changeAddress}" is not derived from the connected wallet's public key. Refusing to build a tx that would send change to an address the signing key doesn't control.`);const s=await this.prepareSizing(r,t),o=s.selectedUTXOs.map(f=>({txid:u.hexToUint8Array(f.txid),vout:f.vout})),i=await kt(this.config.btcWallet,{depositorBtcPubkey:u.hexToUint8Array(r),fundingOutpoints:o});let a,c;try{const f=await L.expandAuthAnchor(i);try{a=u.uint8ArrayToHex(f),c=u.uint8ArrayToHex(P.sha256(f))}finally{f.fill(0)}}catch(f){throw i.fill(0),f}const h=await Ee(i,t.amounts.length),{perVaultWotsKeys:l,wotsPkHashes:x,htlcSecretHexes:w,hashlocks:b}=h,g=await this.preparePeginCommit({depositorBtcPubkeyRaw:e,depositorBtcPubkey:r,hashlocks:b,authAnchorHash:c,sizing:s,params:t});for(let f=0;f<g.perVault.length;f++)if(g.perVault[f].htlcVout!==f)throw new Error(`Internal invariant violation: htlcVout/index mismatch at vault ${f} (expected ${f}, got ${g.perVault[f].htlcVout})`);return Gt(g.fundedPrePeginTxHex,t.amounts.length,c),{transaction:{...g,selectedUTXOs:s.selectedUTXOs,fee:s.fee,changeAmount:s.changeAmount},depositorBtcPubkey:r,derivedSecrets:{perVaultWotsKeys:l,wotsPkHashes:x,htlcSecretHexes:w,authAnchorHex:a}}}async prepareSizing(t,e){const r=e.amounts.map(()=>X),s=e.vaultKeeperBtcPubkeys.length,o=await R.buildPrePeginPsbt({depositorPubkey:t,vaultProviderPubkey:u.stripHexPrefix(e.vaultProviderBtcPubkey),vaultKeeperPubkeys:e.vaultKeeperBtcPubkeys.map(u.stripHexPrefix),universalChallengerPubkeys:e.universalChallengerBtcPubkeys.map(u.stripHexPrefix),hashlocks:r,timelockRefund:e.timelockRefund,pegInAmounts:e.amounts,feeRate:e.protocolFeeRate,numLocalChallengers:s,councilQuorum:e.councilQuorum,councilSize:e.councilSize,network:this.config.btcNetwork,authAnchorHash:X}),i=S.selectUtxosForPegin([...e.availableUTXOs],o.totalOutputValue,e.mempoolFeeRate,ot.peginOutputCount(o.htlcValues.length,X));return{selectedUTXOs:i.selectedUTXOs,fee:i.fee,changeAmount:i.changeAmount}}async preparePeginCommit(t){const{depositorBtcPubkeyRaw:e,depositorBtcPubkey:r,hashlocks:s,authAnchorHash:o,sizing:i,params:a}=t,c=X.toLowerCase();for(let d=0;d<s.length;d++)if(s[d].toLowerCase()===c)throw new Error(`preparePeginCommit refusing to build with sizing-pass placeholder hashlock at vault ${d} — internal substitution bug`);if(o.toLowerCase()===c)throw new Error("preparePeginCommit refusing to build with sizing-pass placeholder auth-anchor hash — internal substitution bug");const h=u.stripHexPrefix(a.vaultProviderBtcPubkey),l=a.vaultKeeperBtcPubkeys.map(u.stripHexPrefix),x=a.universalChallengerBtcPubkeys.map(u.stripHexPrefix),w=l.length,b={depositorPubkey:r,vaultProviderPubkey:h,vaultKeeperPubkeys:l,universalChallengerPubkeys:x,hashlocks:s,timelockRefund:a.timelockRefund,pegInAmounts:a.amounts,feeRate:a.protocolFeeRate,numLocalChallengers:w,councilQuorum:a.councilQuorum,councilSize:a.councilSize,network:this.config.btcNetwork,authAnchorHash:o},g=await R.buildPrePeginPsbt(b),f=u.getNetwork(this.config.btcNetwork),_=ot.fundPeginTransaction({unfundedTxHex:g.psbtHex,selectedUTXOs:i.selectedUTXOs,changeAddress:a.changeAddress,changeAmount:i.changeAmount,network:f}),A=u.stripHexPrefix(S.calculateBtcTxHash(_)),p=[],k=[],E=[];for(let d=0;d<s.length;d++){const I=await R.buildPeginTxFromFundedPrePegin({prePeginParams:b,timelockPegin:a.timelockPegin,fundedPrePeginTxHex:_,htlcVout:d}),v=await R.buildPeginInputPsbt({peginTxHex:I.txHex,fundedPrePeginTxHex:_,depositorPubkey:r,vaultProviderPubkey:h,vaultKeeperPubkeys:l,universalChallengerPubkeys:x,hashlock:s[d],timelockRefund:a.timelockRefund,network:this.config.btcNetwork});p.push(I),k.push(v.psbtHex),E.push(Nt.createTaprootScriptPathSignOptions(e,1))}const m=await Ae(this.config.btcWallet,k,E),y=[];for(let d=0;d<m.length;d++){const I=R.extractPeginInputSignature(m[d],r),v=R.finalizePeginInputPsbt(m[d]);y.push({htlcVout:d,htlcValue:g.htlcValues[d],peginTxHex:v,peginTxid:p[d].txid,peginInputSignature:I,vaultScriptPubKey:p[d].vaultScriptPubKey})}return{fundedPrePeginTxHex:_,prePeginTxid:A,perVault:y}}async signAndBroadcast(t){const{fundedPrePeginTxHex:e,depositorBtcPubkey:r}=t,s=e.startsWith("0x")?e.slice(2):e,o=K.Transaction.fromHex(s);if(o.ins.length===0)throw new Error("Transaction has no inputs");const i=new K.Psbt;i.setVersion(o.version),i.setLocktime(o.locktime);const a=Y.Buffer.from(V(r),"hex"),c=this.config.mempoolApiUrl,h=o.ins.map(p=>{const k=Y.Buffer.from(p.hash).reverse().toString("hex"),E=p.index;return Se(k,E,t.localPrevouts,c).then(m=>({input:p,utxoData:m,txid:k,vout:E}))}),l=await Promise.all(h),x=l.reduce((p,k)=>p+BigInt(k.utxoData.value),0n),w=o.outs.reduce((p,k)=>p+BigInt(k.value),0n);if(x<w)throw new Error(`UTXO value mismatch: total input value (${x} sat) is less than total output value (${w} sat). This may indicate the mempool API returned manipulated UTXO data.`);const b=x-w;if(b>st.MAX_REASONABLE_FEE_SATS)throw new Error(`Implied transaction fee (${b} sat) exceeds maximum reasonable fee (${st.MAX_REASONABLE_FEE_SATS} sat). This may indicate manipulated UTXO data.`);for(const{input:p,utxoData:k,txid:E,vout:m}of l){const y=S.getPsbtInputFields({value:k.value,scriptPubKey:k.scriptPubKey},a);i.addInput({hash:p.hash,index:p.index,sequence:p.sequence,...y})}for(const p of o.outs)i.addOutput({script:p.script,value:p.value});const g=await this.config.btcWallet.signPsbt(i.toHex()),f=K.Psbt.fromHex(g);try{f.finalizeAllInputs()}catch(p){if(!f.data.inputs.every(E=>E.finalScriptWitness||E.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${p}`)}const _=f.extractTransaction().toHex();return await pt.pushTx(_,c)}async registerPeginOnChain(t){const{unsignedPrePeginTx:e,depositorSignedPeginTx:r,vaultProvider:s,hashlock:o,htlcVout:i,depositorPayoutBtcAddress:a,depositorWotsPkHash:c,popSignature:h}=t;if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const l=this.config.ethWallet.account.address;if(!C.isAddressEqual(h.depositorEthAddress,l))throw new Error(`Proof of possession was signed for ${h.depositorEthAddress} but the Ethereum wallet is currently connected to ${l}. Reconnect the original account or call signProofOfPossession() again.`);const x=await this.assertPopMatchesBtcWallet(h),w=h.btcPopSignature,b=u.ensureHexPrefix(h.depositorBtcPubkey),g=u.ensureHexPrefix(e),f=u.ensureHexPrefix(r),_=a??await this.config.btcWallet.getAddress(),A=this.resolvePayoutScriptPubKey(x,_),p=S.calculateBtcTxHash(f),k=await L.deriveVaultId(u.stripHexPrefix(p),u.stripHexPrefix(l)),E=u.ensureHexPrefix(k);if(await this.checkVaultExists(E))throw new Error(`Vault already exists (ID: ${E}, peginTxHash: ${p}). Vault IDs are derived from the pegin transaction hash and depositor address. To create a new vault, use different UTXOs or a different amount to generate a unique transaction.`);const y=this.config.publicClient;let d;try{d=await y.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:$.BTCVaultRegistryABI,functionName:"getPegInFee",args:[s]})}catch(O){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",{cause:O})}const I=C.encodeFunctionData({abi:$.BTCVaultRegistryABI,functionName:"submitPeginRequest",args:[l,b,w,g,f,s,o,i,A,c]});let v;try{v=await y.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:I,value:d,account:this.config.ethWallet.account.address})}catch(O){H.handleContractError(O)}let q;try{q=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:I,value:d,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:v})}catch(O){H.handleContractError(O)}const z=await S.waitForTransactionReceiptSmartAware({publicClient:y,walletAddress:this.config.ethWallet.account.address,hash:q,timeout:ft});return z.status==="reverted"&&H.handleContractError(new Error(`Transaction reverted. Hash: ${z.transactionHash}. Check the transaction on block explorer for details.`)),{ethTxHash:z.transactionHash,vaultId:E,peginTxHash:p}}async registerPeginBatchOnChain(t){const{vaultProvider:e,unsignedPrePeginTx:r,requests:s,popSignature:o}=t;if(s.length===0)throw new Error("Batch pegin requires at least one request");if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const i=this.config.ethWallet.account.address;if(!C.isAddressEqual(o.depositorEthAddress,i))throw new Error(`Proof of possession was signed for ${o.depositorEthAddress} but the Ethereum wallet is currently connected to ${i}. Reconnect the original account or call signProofOfPossession() again.`);const a=await this.assertPopMatchesBtcWallet(o),c=o.btcPopSignature,h=s.map(m=>this.resolvePayoutScriptPubKey(a,m.depositorPayoutBtcAddress)),l=[];for(const m of s){const y=u.ensureHexPrefix(m.depositorSignedPeginTx),d=S.calculateBtcTxHash(y),I=await L.deriveVaultId(u.stripHexPrefix(d),u.stripHexPrefix(i)),v=u.ensureHexPrefix(I);if(await this.checkVaultExists(v))throw new Error(`Vault already exists (ID: ${v}, peginTxHash: ${d}). To create a new vault, use different UTXOs or a different amount.`);l.push({vaultId:v,peginTxHash:d})}const x=this.config.publicClient;let w;try{w=await x.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:$.BTCVaultRegistryABI,functionName:"getPegInFee",args:[e]})}catch(m){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",{cause:m})}const b=w*BigInt(s.length),g=u.ensureHexPrefix(o.depositorBtcPubkey),f=u.ensureHexPrefix(r),_=s.map((m,y)=>({depositorBtcPubKey:g,btcPopSignature:c,unsignedPrePeginTx:f,depositorSignedPeginTx:u.ensureHexPrefix(m.depositorSignedPeginTx),hashlock:m.hashlock,htlcVout:m.htlcVout,referralCode:Ie,depositorPayoutBtcAddress:h[y],depositorWotsPkHash:m.depositorWotsPkHash})),A=C.encodeFunctionData({abi:$.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[i,e,_]});let p;try{p=await x.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:A,value:b,account:this.config.ethWallet.account.address})}catch(m){H.handleContractError(m)}let k;try{k=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:A,value:b,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:p})}catch(m){H.handleContractError(m)}const E=await S.waitForTransactionReceiptSmartAware({publicClient:x,walletAddress:this.config.ethWallet.account.address,hash:k,timeout:ft});return E.status==="reverted"&&H.handleContractError(new Error(`Batch transaction reverted. Hash: ${E.transactionHash}. Check the transaction on block explorer for details.`)),{ethTxHash:E.transactionHash,vaults:l}}async checkVaultExists(t){return(await this.config.publicClient.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:$.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]})).depositor!==C.zeroAddress}resolvePayoutScriptPubKey(t,e){if(!u.isAddressFromPublicKey(e,t,this.config.btcNetwork))throw new Error(`BTC payout address "${e}" is not derived from the connected wallet's public key. The payout sink must be controlled by the same key that signs the pegin; refusing to register a mismatched address.`);const r=u.getNetwork(this.config.btcNetwork);try{return`0x${mt.address.toOutputScript(e,r).toString("hex")}`}catch{throw new Error(`Invalid BTC payout address: "${e}". Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`)}}async signProofOfPossession(){if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const t=this.config.ethWallet.account.address,e=V(await this.config.btcWallet.getPublicKeyHex()),r=this.config.vaultContracts.btcVaultRegistry,s=`${t.toLowerCase()}:${this.config.ethChain.id}:pegin:${r.toLowerCase()}`,o=await this.config.btcWallet.signMessage(s,"bip322-simple");return{btcPopSignature:ve(o),depositorEthAddress:t,depositorBtcPubkey:e}}async assertPopMatchesBtcWallet(t){const e=await this.config.btcWallet.getPublicKeyHex(),r=V(e),s=V(t.depositorBtcPubkey);if(r!==s)throw new Error(`Proof of possession was signed with BTC pubkey ${s} but the BTC wallet is currently connected to ${r}. Reconnect the original wallet or call signProofOfPossession() again.`);return e}getNetwork(){return this.config.btcNetwork}getVaultContractAddress(){return this.config.vaultContracts.btcVaultRegistry}}exports.PeginManager=He;exports.VAULT_APP_NAME=bt;exports.buildFundingOutpointsCommitment=xt;exports.buildVaultContext=wt;exports.computeWotsBlockPublicKeysHash=$t;exports.deriveVaultRoot=kt;exports.deriveWotsBlocksFromSeed=Ct;
|
|
2
|
-
//# sourceMappingURL=PeginManager-BPXVXu8t.cjs.map
|