@babylonlabs-io/ts-sdk 0.31.0 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{PeginManager-DmVq6ffv.cjs → PeginManager-CTRPJo8m.cjs} +2 -2
- package/dist/{PeginManager-DmVq6ffv.cjs.map → PeginManager-CTRPJo8m.cjs.map} +1 -1
- package/dist/{PeginManager-c44Uvd1N.js → PeginManager-DUR1BTKM.js} +6 -6
- package/dist/{PeginManager-c44Uvd1N.js.map → PeginManager-DUR1BTKM.js.map} +1 -1
- package/dist/{bitcoin-B-Y0DlqR.js → bitcoin-0_T6KJON.js} +32 -28
- package/dist/bitcoin-0_T6KJON.js.map +1 -0
- package/dist/bitcoin-EYBKDtEW.cjs +2 -0
- package/dist/bitcoin-EYBKDtEW.cjs.map +1 -0
- package/dist/{buildAndBroadcastRefund-CLLaz8D3.cjs → buildAndBroadcastRefund-CIHhUmRv.cjs} +2 -2
- package/dist/{buildAndBroadcastRefund-CLLaz8D3.cjs.map → buildAndBroadcastRefund-CIHhUmRv.cjs.map} +1 -1
- package/dist/{buildAndBroadcastRefund-BRQaCQrJ.js → buildAndBroadcastRefund-DwrX_IBf.js} +3 -3
- package/dist/{buildAndBroadcastRefund-BRQaCQrJ.js.map → buildAndBroadcastRefund-DwrX_IBf.js.map} +1 -1
- package/dist/challengeAssert-DSlCIBoT.js +304 -0
- package/dist/challengeAssert-DSlCIBoT.js.map +1 -0
- package/dist/challengeAssert-DuhkzZG-.cjs +2 -0
- package/dist/challengeAssert-DuhkzZG-.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +7 -7
- package/dist/{noPayout-CwgYkZYs.cjs → noPayout-CDhbGn_B.cjs} +2 -2
- package/dist/{noPayout-CwgYkZYs.cjs.map → noPayout-CDhbGn_B.cjs.map} +1 -1
- package/dist/{noPayout-B8JiTaYt.js → noPayout-DohtepqZ.js} +2 -2
- package/dist/{noPayout-B8JiTaYt.js.map → noPayout-DohtepqZ.js.map} +1 -1
- package/dist/{psbtInputFields-CB8hqjQ5.cjs → psbtInputFields-BLi7Ta-T.cjs} +2 -2
- package/dist/{psbtInputFields-CB8hqjQ5.cjs.map → psbtInputFields-BLi7Ta-T.cjs.map} +1 -1
- package/dist/{psbtInputFields-DeTFSJOq.js → psbtInputFields-DPCFHgGd.js} +2 -2
- package/dist/{psbtInputFields-DeTFSJOq.js.map → psbtInputFields-DPCFHgGd.js.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 +7 -7
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.js +3 -3
- package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts +10 -7
- package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/constants.d.ts +26 -0
- package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -0
- package/dist/tbv/core/primitives/psbt/depositorPayout.d.ts +13 -6
- package/dist/tbv/core/primitives/psbt/depositorPayout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts +13 -0
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +1 -1
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +2 -2
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +7 -7
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/{vault-registry-reader-DdruADqa.cjs → vault-registry-reader-BBS1_AON.cjs} +2 -2
- package/dist/{vault-registry-reader-DdruADqa.cjs.map → vault-registry-reader-BBS1_AON.cjs.map} +1 -1
- package/dist/{vault-registry-reader-BywZhqJL.js → vault-registry-reader-CG6bea1S.js} +2 -2
- package/dist/{vault-registry-reader-BywZhqJL.js.map → vault-registry-reader-CG6bea1S.js.map} +1 -1
- package/package.json +1 -1
- package/dist/bitcoin-B-Y0DlqR.js.map +0 -1
- package/dist/bitcoin-DIN0OupO.cjs +0 -2
- package/dist/bitcoin-DIN0OupO.cjs.map +0 -1
- package/dist/challengeAssert-mYikGC34.js +0 -269
- package/dist/challengeAssert-mYikGC34.js.map +0 -1
- package/dist/challengeAssert-yYFflBOx.cjs +0 -2
- package/dist/challengeAssert-yYFflBOx.cjs.map +0 -1
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Buffer } from 'buffer';
|
|
1
2
|
import { networks } from 'bitcoinjs-lib';
|
|
2
3
|
import { Network } from '@babylonlabs-io/babylon-tbv-rust-wasm';
|
|
3
4
|
import { Hex } from 'viem';
|
|
@@ -61,6 +62,18 @@ export declare function hexToUint8Array(hex: string): Uint8Array;
|
|
|
61
62
|
* @returns Hex string without 0x prefix
|
|
62
63
|
*/
|
|
63
64
|
export declare function uint8ArrayToHex(bytes: Uint8Array): string;
|
|
65
|
+
/**
|
|
66
|
+
* Read the prevout txid (big-endian hex) from a bitcoinjs-lib transaction input.
|
|
67
|
+
*
|
|
68
|
+
* bitcoinjs-lib stores `hash` in little-endian internal byte order; txids are
|
|
69
|
+
* displayed in big-endian, so the bytes must be reversed before hex-encoding.
|
|
70
|
+
*
|
|
71
|
+
* @param input - Transaction input with a `hash` field (Buffer or Uint8Array)
|
|
72
|
+
* @returns Prevout txid as a hex string (big-endian, no 0x prefix)
|
|
73
|
+
*/
|
|
74
|
+
export declare function inputTxidHex(input: {
|
|
75
|
+
hash: Buffer | Uint8Array;
|
|
76
|
+
}): string;
|
|
64
77
|
/**
|
|
65
78
|
* Convert a 33-byte public key to 32-byte x-only format (removes first byte).
|
|
66
79
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bitcoin.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/core/primitives/utils/bitcoin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;
|
|
1
|
+
{"version":3,"file":"bitcoin.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/core/primitives/utils/bitcoin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,QAAQ,EAAY,MAAM,eAAe,CAAC;AAEnD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uCAAuC,CAAC;AACrE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AAEhC;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,MAAO,CAAC;AAE3C;;;GAGG;AACH,eAAO,MAAM,qBAAqB,KAAK,CAAC;AAExC;;;GAGG;AACH,eAAO,MAAM,yBAAyB,KAAK,CAAC;AAE5C;;;GAGG;AACH,eAAO,MAAM,2BAA2B,MAAM,CAAC;AAE/C;;GAEG;AACH,eAAO,MAAM,mBAAmB,MAAM,CAAC;AAEvC;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAElD;AAED;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAIhD;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAUvD;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAIzD;AAED;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE;IAClC,IAAI,EAAE,MAAM,GAAG,UAAU,CAAC;CAC3B,GAAG,MAAM,CAET;AAED;;;;;;;;GAQG;AACH,wBAAgB,OAAO,CAAC,MAAM,EAAE,UAAU,GAAG,UAAU,CAEtD;AAaD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,uBAAuB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CA0BpE;AAED;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAG/C;AAED;;GAEG;AACH,MAAM,WAAW,4BAA4B;IAC3C,yEAAyE;IACzE,eAAe,EAAE,MAAM,CAAC;IACxB,oEAAoE;IACpE,iBAAiB,EAAE,MAAM,CAAC;IAC1B,yDAAyD;IACzD,eAAe,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAClC,eAAe,EAAE,MAAM,EACvB,uBAAuB,CAAC,EAAE,MAAM,GAC/B,4BAA4B,CAa9B;AAQD;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAS5D;AA8BD;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,QAAQ,CAAC,OAAO,CAY7D;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAClC,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,OAAO,GACf,MAAM,CAWR;AAED;;;;;;;GAOG;AACH,wBAAgB,yBAAyB,CACvC,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,OAAO,GACf,MAAM,CAiBR;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,OAAO,GACf,OAAO,CAgCT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../../../buildAndBroadcastRefund-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../../../buildAndBroadcastRefund-CIHhUmRv.cjs"),e=require("../../../signing-DHSXjhLM.cjs");exports.BIP68NotMatureError=t.BIP68NotMatureError;exports.ClaimerPegoutStatusValue=t.ClaimerPegoutStatusValue;exports.REFUND_VSIZE=t.REFUND_VSIZE;exports.activateVault=t.activateVault;exports.buildAndBroadcastRefund=t.buildAndBroadcastRefund;exports.computeHashlock=t.computeHashlock;exports.estimateRefundFeeSats=t.estimateRefundFeeSats;exports.isDepositAmountValid=t.isDepositAmountValid;exports.isPegoutTerminalStatus=t.isPegoutTerminalStatus;exports.isRecognizedPegoutStatus=t.isRecognizedPegoutStatus;exports.pollAndSignPayouts=t.pollAndSignPayouts;exports.signDepositorGraph=t.signDepositorGraph;exports.submitWotsPublicKey=t.submitWotsPublicKey;exports.validateDepositAmount=t.validateDepositAmount;exports.validateMultiVaultDepositInputs=t.validateMultiVaultDepositInputs;exports.validateProviderSelection=t.validateProviderSelection;exports.validateRemainingCapacity=t.validateRemainingCapacity;exports.validateSecretAgainstHashlock=t.validateSecretAgainstHashlock;exports.validateVaultAmounts=t.validateVaultAmounts;exports.validateVaultProviderPubkey=t.validateVaultProviderPubkey;exports.waitForPeginStatus=t.waitForPeginStatus;exports.ContractStatus=e.ContractStatus;exports.PeginAction=e.PeginAction;exports.canPerformAction=e.canPerformAction;exports.getPeginProtocolState=e.getPeginProtocolState;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { B as s, C as e, R as i, a as o, m as u, h as l, n, i as r, l as d, k as c, p as P, b as g, s as m, v as p, g as v, d as S, c as A, j as V, e as f, f as R, w as b } from "../../../buildAndBroadcastRefund-
|
|
1
|
+
import { B as s, C as e, R as i, a as o, m as u, h as l, n, i as r, l as d, k as c, p as P, b as g, s as m, v as p, g as v, d as S, c as A, j as V, e as f, f as R, w as b } from "../../../buildAndBroadcastRefund-DwrX_IBf.js";
|
|
2
2
|
import { C as D, P as h, a as k, g as y } from "../../../signing-BZigafm0.js";
|
|
3
3
|
export {
|
|
4
4
|
s as BIP68NotMatureError,
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("../../../signing-DHSXjhLM.cjs"),T=require("../../../validation-u8W7Lp2x.cjs"),t=require("../../../fundPeginTransaction-DaWoYCgO.cjs"),e=require("../../../psbtInputFields-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("../../../signing-DHSXjhLM.cjs"),T=require("../../../validation-u8W7Lp2x.cjs"),t=require("../../../fundPeginTransaction-DaWoYCgO.cjs"),e=require("../../../psbtInputFields-BLi7Ta-T.cjs"),E=require("../../../bitcoin-EYBKDtEW.cjs");exports.createTaprootScriptPathSignOptions=_.createTaprootScriptPathSignOptions;exports.BITCOIN_ADDRESS_RE=T.BITCOIN_ADDRESS_RE;exports.HEX_RE=T.HEX_RE;exports.KNOWN_SCRIPT_PREFIXES=T.KNOWN_SCRIPT_PREFIXES;exports.MAX_REASONABLE_FEE_SATS=T.MAX_REASONABLE_FEE_SATS;exports.TXID_RE=T.TXID_RE;exports.BTC_DUST_SAT=t.BTC_DUST_SAT;exports.DUST_THRESHOLD=t.DUST_THRESHOLD;exports.FEE_SAFETY_MARGIN=t.FEE_SAFETY_MARGIN;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=t.LOW_RATE_ESTIMATION_ACCURACY_BUFFER;exports.MAX_NON_LEGACY_OUTPUT_SIZE=t.MAX_NON_LEGACY_OUTPUT_SIZE;exports.P2TR_INPUT_SIZE=t.P2TR_INPUT_SIZE;exports.PEGIN_AUTH_ANCHOR_OUTPUTS=t.PEGIN_AUTH_ANCHOR_OUTPUTS;exports.PEGIN_FIXED_OUTPUTS=t.PEGIN_FIXED_OUTPUTS;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=t.SPLIT_TX_FEE_SAFETY_MULTIPLIER;exports.TX_BUFFER_SIZE_OVERHEAD=t.TX_BUFFER_SIZE_OVERHEAD;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=t.WALLET_RELAY_FEE_RATE_THRESHOLD;exports.fundPeginTransaction=t.fundPeginTransaction;exports.parseUnfundedWasmTransaction=t.parseUnfundedWasmTransaction;exports.peginOutputCount=t.peginOutputCount;exports.rateBasedTxBufferFee=t.rateBasedTxBufferFee;exports.BitcoinScriptType=e.BitcoinScriptType;exports.UtxoNotAvailableError=e.UtxoNotAvailableError;exports.assertUtxosAvailable=e.assertUtxosAvailable;exports.calculateBtcTxHash=e.calculateBtcTxHash;exports.collectReservedUtxoRefs=e.collectReservedUtxoRefs;exports.extractInputsFromTransaction=e.extractInputsFromTransaction;exports.getDustThreshold=e.getDustThreshold;exports.getPsbtInputFields=e.getPsbtInputFields;exports.getScriptType=e.getScriptType;exports.selectUtxosForDeposit=e.selectUtxosForDeposit;exports.selectUtxosForPegin=e.selectUtxosForPegin;exports.shouldAddChangeOutput=e.shouldAddChangeOutput;exports.validateUtxosAvailable=e.validateUtxosAvailable;exports.getNetwork=E.getNetwork;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { c as t } from "../../../signing-BZigafm0.js";
|
|
2
2
|
import { B as T, H as _, K as E, M as o, T as r } from "../../../validation-CxqROCno.js";
|
|
3
3
|
import { B as A, D as R, F as U, L as i, M as p, P as I, b as c, a as n, S as F, T as l, W as O, f as P, c as x, p as N, r as u } from "../../../fundPeginTransaction-oV-dNJOU.js";
|
|
4
|
-
import { B as f, U as B, a as D, f as L, c as g, e as C, g as H, i as X, h, s as m, b as M, d as b, v } from "../../../psbtInputFields-
|
|
5
|
-
import { g as Y } from "../../../bitcoin-
|
|
4
|
+
import { B as f, U as B, a as D, f as L, c as g, e as C, g as H, i as X, h, s as m, b as M, d as b, v } from "../../../psbtInputFields-DPCFHgGd.js";
|
|
5
|
+
import { g as Y } from "../../../bitcoin-0_T6KJON.js";
|
|
6
6
|
export {
|
|
7
7
|
T as BITCOIN_ADDRESS_RE,
|
|
8
8
|
A as BTC_DUST_SAT,
|
package/dist/tbv/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("../challengeAssert-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("../challengeAssert-DuhkzZG-.cjs"),P=require("@babylonlabs-io/babylon-tbv-rust-wasm"),u=require("../noPayout-CDhbGn_B.cjs"),o=require("../bitcoin-EYBKDtEW.cjs"),l=require("../signing-DHSXjhLM.cjs"),d=require("../validation-u8W7Lp2x.cjs"),e=require("../buildAndBroadcastRefund-CIHhUmRv.cjs"),a=require("../fundPeginTransaction-DaWoYCgO.cjs"),i=require("../psbtInputFields-BLi7Ta-T.cjs"),r=require("../PeginManager-CTRPJo8m.cjs"),t=require("../vault-registry-reader-BBS1_AON.cjs"),s=require("../types-jmEyzzhY.cjs");exports.buildChallengeAssertPsbt=n.buildChallengeAssertPsbt;exports.buildDepositorPayoutPsbt=n.buildDepositorPayoutPsbt;exports.buildPeginInputPsbt=n.buildPeginInputPsbt;exports.buildPeginTxFromFundedPrePegin=n.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=n.buildPrePeginPsbt;exports.computeNumLocalChallengers=n.computeNumLocalChallengers;exports.extractPeginInputSignature=n.extractPeginInputSignature;exports.finalizePeginInputPsbt=n.finalizePeginInputPsbt;Object.defineProperty(exports,"computeMinClaimValue",{enumerable:!0,get:()=>P.computeMinClaimValue});Object.defineProperty(exports,"deriveVaultId",{enumerable:!0,get:()=>P.deriveVaultId});exports.assertPayoutOutputMatchesRegistered=u.assertPayoutOutputMatchesRegistered;exports.buildNoPayoutPsbt=u.buildNoPayoutPsbt;exports.buildPayoutPsbt=u.buildPayoutPsbt;exports.buildRefundPsbt=u.buildRefundPsbt;exports.createPayoutScript=u.createPayoutScript;exports.extractPayoutSignature=u.extractPayoutSignature;exports.deriveNativeSegwitAddress=o.deriveNativeSegwitAddress;exports.deriveTaprootAddress=o.deriveTaprootAddress;exports.ensureHexPrefix=o.ensureHexPrefix;exports.formatSatoshisToBtc=o.formatSatoshisToBtc;exports.getNetwork=o.getNetwork;exports.hexToUint8Array=o.hexToUint8Array;exports.isAddressFromPublicKey=o.isAddressFromPublicKey;exports.isValidHex=o.isValidHex;exports.processPublicKeyToXOnly=o.processPublicKeyToXOnly;exports.stripHexPrefix=o.stripHexPrefix;exports.toXOnly=o.toXOnly;exports.uint8ArrayToHex=o.uint8ArrayToHex;exports.validateWalletPubkey=o.validateWalletPubkey;exports.ContractStatus=l.ContractStatus;exports.PeginAction=l.PeginAction;exports.canPerformAction=l.canPerformAction;exports.createTaprootScriptPathSignOptions=l.createTaprootScriptPathSignOptions;exports.getPeginProtocolState=l.getPeginProtocolState;exports.BITCOIN_ADDRESS_RE=d.BITCOIN_ADDRESS_RE;exports.HEX_RE=d.HEX_RE;exports.KNOWN_SCRIPT_PREFIXES=d.KNOWN_SCRIPT_PREFIXES;exports.MAX_REASONABLE_FEE_SATS=d.MAX_REASONABLE_FEE_SATS;exports.TXID_RE=d.TXID_RE;exports.BIP68NotMatureError=e.BIP68NotMatureError;exports.ClaimerPegoutStatusValue=e.ClaimerPegoutStatusValue;exports.PayoutManager=e.PayoutManager;exports.REFUND_VSIZE=e.REFUND_VSIZE;exports.activateVault=e.activateVault;exports.buildAndBroadcastRefund=e.buildAndBroadcastRefund;exports.computeHashlock=e.computeHashlock;exports.estimateRefundFeeSats=e.estimateRefundFeeSats;exports.isDepositAmountValid=e.isDepositAmountValid;exports.isPegoutTerminalStatus=e.isPegoutTerminalStatus;exports.isRecognizedPegoutStatus=e.isRecognizedPegoutStatus;exports.pollAndSignPayouts=e.pollAndSignPayouts;exports.signDepositorGraph=e.signDepositorGraph;exports.submitWotsPublicKey=e.submitWotsPublicKey;exports.validateDepositAmount=e.validateDepositAmount;exports.validateMultiVaultDepositInputs=e.validateMultiVaultDepositInputs;exports.validateProviderSelection=e.validateProviderSelection;exports.validateRemainingCapacity=e.validateRemainingCapacity;exports.validateSecretAgainstHashlock=e.validateSecretAgainstHashlock;exports.validateVaultAmounts=e.validateVaultAmounts;exports.validateVaultProviderPubkey=e.validateVaultProviderPubkey;exports.waitForPeginStatus=e.waitForPeginStatus;exports.BTC_DUST_SAT=a.BTC_DUST_SAT;exports.DUST_THRESHOLD=a.DUST_THRESHOLD;exports.FEE_SAFETY_MARGIN=a.FEE_SAFETY_MARGIN;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=a.LOW_RATE_ESTIMATION_ACCURACY_BUFFER;exports.MAX_NON_LEGACY_OUTPUT_SIZE=a.MAX_NON_LEGACY_OUTPUT_SIZE;exports.P2TR_INPUT_SIZE=a.P2TR_INPUT_SIZE;exports.PEGIN_AUTH_ANCHOR_OUTPUTS=a.PEGIN_AUTH_ANCHOR_OUTPUTS;exports.PEGIN_FIXED_OUTPUTS=a.PEGIN_FIXED_OUTPUTS;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=a.SPLIT_TX_FEE_SAFETY_MULTIPLIER;exports.TX_BUFFER_SIZE_OVERHEAD=a.TX_BUFFER_SIZE_OVERHEAD;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=a.WALLET_RELAY_FEE_RATE_THRESHOLD;exports.fundPeginTransaction=a.fundPeginTransaction;exports.parseUnfundedWasmTransaction=a.parseUnfundedWasmTransaction;exports.peginOutputCount=a.peginOutputCount;exports.rateBasedTxBufferFee=a.rateBasedTxBufferFee;exports.BitcoinScriptType=i.BitcoinScriptType;exports.UtxoNotAvailableError=i.UtxoNotAvailableError;exports.assertUtxosAvailable=i.assertUtxosAvailable;exports.calculateBtcTxHash=i.calculateBtcTxHash;exports.collectReservedUtxoRefs=i.collectReservedUtxoRefs;exports.extractInputsFromTransaction=i.extractInputsFromTransaction;exports.getDustThreshold=i.getDustThreshold;exports.getPsbtInputFields=i.getPsbtInputFields;exports.getScriptType=i.getScriptType;exports.selectUtxosForDeposit=i.selectUtxosForDeposit;exports.selectUtxosForPegin=i.selectUtxosForPegin;exports.shouldAddChangeOutput=i.shouldAddChangeOutput;exports.validateUtxosAvailable=i.validateUtxosAvailable;exports.CONTRACT_ERRORS=r.CONTRACT_ERRORS;exports.PeginManager=r.PeginManager;exports.VAULT_APP_NAME=r.VAULT_APP_NAME;exports.buildFundingOutpointsCommitment=r.buildFundingOutpointsCommitment;exports.buildVaultContext=r.buildVaultContext;exports.computeWotsBlockPublicKeysHash=r.computeWotsBlockPublicKeysHash;exports.deriveVaultRoot=r.deriveVaultRoot;exports.deriveWotsBlocksFromSeed=r.deriveWotsBlocksFromSeed;exports.expandAuthAnchor=r.expandAuthAnchor;exports.expandHashlockSecret=r.expandHashlockSecret;exports.expandWotsSeed=r.expandWotsSeed;exports.extractErrorData=r.extractErrorData;exports.getContractErrorMessage=r.getContractErrorMessage;exports.handleContractError=r.handleContractError;exports.isKnownContractError=r.isKnownContractError;exports.isWotsMismatchError=r.isWotsMismatchError;exports.ApplicationRegistryABI=t.ApplicationRegistryABI;exports.MEMPOOL_API_URLS=t.MEMPOOL_API_URLS;exports.ProtocolParamsABI=t.ProtocolParamsABI;exports.ServerIdentityError=t.ServerIdentityError;exports.VaultProviderRpcClient=t.VaultProviderRpcClient;exports.ViemProtocolParamsReader=t.ViemProtocolParamsReader;exports.ViemUniversalChallengerReader=t.ViemUniversalChallengerReader;exports.ViemVaultKeeperReader=t.ViemVaultKeeperReader;exports.ViemVaultRegistryReader=t.ViemVaultRegistryReader;exports.VpResponseValidationError=t.VpResponseValidationError;exports.VpTokenProvider=t.VpTokenProvider;exports.getAddressTxs=t.getAddressTxs;exports.getAddressUtxos=t.getAddressUtxos;exports.getMempoolApiUrl=t.getMempoolApiUrl;exports.getNetworkFees=t.getNetworkFees;exports.getTxHex=t.getTxHex;exports.getTxInfo=t.getTxInfo;exports.getUtxoInfo=t.getUtxoInfo;exports.pushTx=t.pushTx;exports.resolveProtocolAddresses=t.resolveProtocolAddresses;exports.validateRequestDepositorClaimerArtifactsResponse=t.validateRequestDepositorClaimerArtifactsResponse;exports.verifyServerIdentity=t.verifyServerIdentity;exports.BTCVaultRegistryABI=s.BTCVaultRegistryABI;exports.DaemonStatus=s.DaemonStatus;exports.JSON_RPC_ERROR_CODES=s.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=s.JsonRpcClient;exports.JsonRpcError=s.JsonRpcError;exports.POST_WOTS_STATUSES=s.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=s.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=s.RpcErrorCode;exports.VP_TERMINAL_STATUSES=s.VP_TERMINAL_STATUSES;exports.VP_TRANSIENT_STATUSES=s.VP_TRANSIENT_STATUSES;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/tbv/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { h as e, g as t, d as r, a as o, b as i, c as n, e as l, f as u } from "../challengeAssert-
|
|
1
|
+
import { h as e, g as t, d as r, a as o, b as i, c as n, e as l, f as u } from "../challengeAssert-DSlCIBoT.js";
|
|
2
2
|
import { computeMinClaimValue as P, deriveVaultId as c } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
3
|
-
import { a as p, d as S, c as E, b as A, f as R, e as _ } from "../noPayout-
|
|
4
|
-
import { d as m, a as x, e as b, f as I, g as f, h as v, i as C, b as U, p as O, s as V, t as h, u as y, v as F } from "../bitcoin-
|
|
3
|
+
import { a as p, d as S, c as E, b as A, f as R, e as _ } from "../noPayout-DohtepqZ.js";
|
|
4
|
+
import { d as m, a as x, e as b, f as I, g as f, h as v, i as C, b as U, p as O, s as V, t as h, u as y, v as F } from "../bitcoin-0_T6KJON.js";
|
|
5
5
|
import { C as D, P as B, a as M, c as H, g as L } from "../signing-BZigafm0.js";
|
|
6
6
|
import { B as W, H as X, K, M as w, T as G } from "../validation-CxqROCno.js";
|
|
7
|
-
import { B as J, C as Z, P as j, R as z, a as q, m as Q, h as $, n as aa, i as sa, l as ea, k as ta, p as ra, b as oa, s as ia, v as na, g as la, d as ua, c as da, j as Pa, e as ca, f as Ta, w as pa } from "../buildAndBroadcastRefund-
|
|
7
|
+
import { B as J, C as Z, P as j, R as z, a as q, m as Q, h as $, n as aa, i as sa, l as ea, k as ta, p as ra, b as oa, s as ia, v as na, g as la, d as ua, c as da, j as Pa, e as ca, f as Ta, w as pa } from "../buildAndBroadcastRefund-DwrX_IBf.js";
|
|
8
8
|
import { B as Ea, D as Aa, F as Ra, L as _a, M as ga, P as ma, b as xa, a as ba, S as Ia, T as fa, W as va, f as Ca, c as Ua, p as Oa, r as Va } from "../fundPeginTransaction-oV-dNJOU.js";
|
|
9
|
-
import { B as ya, U as Fa, a as Na, f as Da, c as Ba, e as Ma, g as Ha, i as La, h as ka, s as Wa, b as Xa, d as Ka, v as wa } from "../psbtInputFields-
|
|
10
|
-
import { C as Ya, P as Ja, V as Za, k as ja, l as za, c as qa, m as Qa, d as $a, b as as, f as ss, j as es, e as ts, g as rs, h as os, i as is, a as ns } from "../PeginManager-
|
|
11
|
-
import { A as us, M as ds, P as Ps, S as cs, V as Ts, k as ps, l as Ss, m as Es, n as As, h as Rs, j as _s, g as gs, a as ms, b as xs, c as bs, d as Is, e as fs, f as vs, p as Cs, r as Us, v as Os, i as Vs } from "../vault-registry-reader-
|
|
9
|
+
import { B as ya, U as Fa, a as Na, f as Da, c as Ba, e as Ma, g as Ha, i as La, h as ka, s as Wa, b as Xa, d as Ka, v as wa } from "../psbtInputFields-DPCFHgGd.js";
|
|
10
|
+
import { C as Ya, P as Ja, V as Za, k as ja, l as za, c as qa, m as Qa, d as $a, b as as, f as ss, j as es, e as ts, g as rs, h as os, i as is, a as ns } from "../PeginManager-DUR1BTKM.js";
|
|
11
|
+
import { A as us, M as ds, P as Ps, S as cs, V as Ts, k as ps, l as Ss, m as Es, n as As, h as Rs, j as _s, g as gs, a as ms, b as xs, c as bs, d as Is, e as fs, f as vs, p as Cs, r as Us, v as Os, i as Vs } from "../vault-registry-reader-CG6bea1S.js";
|
|
12
12
|
import { B as ys, D as Fs, b as Ns, J as Ds, a as Bs, d as Ms, P as Hs, R as Ls, c as ks, V as Ws } from "../types-CnG3JsRs.js";
|
|
13
13
|
export {
|
|
14
14
|
us as ApplicationRegistryABI,
|
package/dist/testing/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var d=Object.defineProperty;var l=(i,t,e)=>t in i?d(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var r=(i,t,e)=>l(i,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("../sha2-CsTynrfJ.cjs"),o=require("buffer"),g=require("../bitcoin-
|
|
1
|
+
"use strict";var d=Object.defineProperty;var l=(i,t,e)=>t in i?d(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var r=(i,t,e)=>l(i,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("../sha2-CsTynrfJ.cjs"),o=require("buffer"),g=require("../bitcoin-EYBKDtEW.cjs"),q=require("../shared/index.cjs"),f=async(i,t)=>{const e=new TextEncoder,n=e.encode(i),s=e.encode(t),a=new Uint8Array(4+n.length+4+s.length),c=new DataView(a.buffer);return c.setUint32(0,n.length),a.set(n,4),c.setUint32(4+n.length,s.length),a.set(s,4+n.length+4),g.uint8ArrayToHex(u.sha256(a))},h={publicKeyHex:"a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2",address:"tb1pqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqkx6jks",network:q.BitcoinNetworks.SIGNET,shouldFailSigning:!1,deriveContextHash:f};class b{constructor(t={}){r(this,"config");this.config={...h,...t.publicKeyHex?{publicKeyHex:t.publicKeyHex}:{},...t.address?{address:t.address}:{},...t.network!==void 0?{network:t.network}:{},...t.shouldFailSigning!==void 0?{shouldFailSigning:t.shouldFailSigning}:{},...t.deriveContextHash?{deriveContextHash:t.deriveContextHash}:{}}}async getPublicKeyHex(){return this.config.publicKeyHex}async getAddress(){return this.config.address}async signPsbt(t){if(this.config.shouldFailSigning)throw new Error("Mock signing failed");if(!t||t.length===0)throw new Error("Invalid PSBT: empty hex string");return t+"deadbeef"}async signPsbts(t,e){const n=[];for(const s of t){const a=await this.signPsbt(s);n.push(a)}return n}async signMessage(t,e){if(this.config.shouldFailSigning)throw new Error("Mock signing failed");if(!t||t.length===0)throw new Error("Invalid message: empty string");return o.Buffer.from(`mock-signature-${e}-${t}-${this.config.publicKeyHex}`).toString("base64")}async getNetwork(){return this.config.network}async deriveContextHash(t,e){return this.config.deriveContextHash(t,e)}updateConfig(t){this.config={...this.config,...t}}reset(){this.config={...h}}}class y{constructor(t={}){r(this,"account");r(this,"chain");r(this,"shouldFailOperations");r(this,"transactionDelay");r(this,"nonce",0);this.account={address:t.address||"0x742d35cc6634c0532925a3b844bc9e7595f0beb0"},this.chain={id:t.chainId??11155111},this.shouldFailOperations=t.shouldFailOperations??!1,this.transactionDelay=t.transactionDelay??0,this.signMessage=this.signMessage.bind(this),this.sendTransaction=this.sendTransaction.bind(this)}async signMessage(t){const e=t.message,n=t.account||this.account.address;if(this.shouldFailOperations)throw new Error("Mock signing failed");if(!e||e.length===0)throw new Error("Invalid message: empty string");const s=`personal_sign:${e}-${n}-${this.chain.id}`;return`0x${o.Buffer.from(s).toString("hex").slice(0,130).padEnd(130,"0")}`}async sendTransaction(t){var s;if(this.shouldFailOperations)throw new Error("Mock transaction failed");if(!t.to)throw new Error("Invalid transaction: missing 'to' address");this.transactionDelay>0&&await new Promise(a=>setTimeout(a,this.transactionDelay)),this.nonce++;const e=JSON.stringify({from:this.account.address,to:t.to,value:((s=t.value)==null?void 0:s.toString())||"0",nonce:this.nonce,chainId:this.chain.id});return`0x${o.Buffer.from(e).toString("hex").slice(0,64).padEnd(64,"0")}`}updateConfig(t){t.address!==void 0&&(this.account.address=t.address),t.chainId!==void 0&&(this.chain.id=t.chainId),t.shouldFailOperations!==void 0&&(this.shouldFailOperations=t.shouldFailOperations),t.transactionDelay!==void 0&&(this.transactionDelay=t.transactionDelay)}reset(){this.account.address="0x742d35cc6634c0532925a3b844bc9e7595f0beb0",this.chain.id=11155111,this.shouldFailOperations=!1,this.transactionDelay=0,this.nonce=0}getCurrentNonce(){return this.nonce}}exports.MockBitcoinWallet=b;exports.MockEthereumWallet=y;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/testing/index.js
CHANGED
|
@@ -3,7 +3,7 @@ var l = (e, t, s) => t in e ? d(e, t, { enumerable: !0, configurable: !0, writab
|
|
|
3
3
|
var o = (e, t, s) => l(e, typeof t != "symbol" ? t + "" : t, s);
|
|
4
4
|
import { s as g } from "../sha2-6wN58S6R.js";
|
|
5
5
|
import { Buffer as r } from "buffer";
|
|
6
|
-
import { u } from "../bitcoin-
|
|
6
|
+
import { u } from "../bitcoin-0_T6KJON.js";
|
|
7
7
|
import { BitcoinNetworks as q } from "../shared/index.js";
|
|
8
8
|
const f = async (e, t) => {
|
|
9
9
|
const s = new TextEncoder(), n = s.encode(e), i = s.encode(t), a = new Uint8Array(4 + n.length + 4 + i.length), c = new DataView(a.buffer);
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var ae=Object.defineProperty;var oe=(n,e,t)=>e in n?ae(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var l=(n,e,t)=>oe(n,typeof e!="symbol"?e+"":e,t);const h=require("./validation-u8W7Lp2x.cjs"),_=require("./types-jmEyzzhY.cjs"),p=require("./bitcoin-DIN0OupO.cjs"),ce=require("@bitcoin-js/tiny-secp256k1-asmjs"),P=require("bitcoinjs-lib"),g=require("buffer"),O=require("./sha2-CsTynrfJ.cjs");function le(n){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const t in n)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>n[t]})}}return e.default=n,Object.freeze(e)}const B=le(ce),ue=21e6*1e8,F=3e4;async function $(n,e){const t=new AbortController,r=setTimeout(()=>t.abort(),F),s=[t.signal,e==null?void 0:e.signal].filter(Boolean);try{return await fetch(n,{...e,signal:AbortSignal.any(s)})}catch(i){throw clearTimeout(r),i!=null&&typeof i=="object"&&"name"in i&&i.name==="AbortError"?new Error(`Mempool API request timed out after ${F}ms: ${n}`):i}}const L=1e4;function q(n){return Number.isInteger(n)&&n>0&&n<=ue}function pe(n){return Number.isInteger(n)&&n>0&&n<=L}function Y(n,e){return!Number.isInteger(n)||n<0?!1:e===void 0||n<e}function I(n){if(!h.TXID_RE.test(n))throw new Error(`Invalid transaction ID format: ${n}`)}function G(n){if(!h.BITCOIN_ADDRESS_RE.test(n))throw new Error(`Invalid Bitcoin address format: ${n}`)}function W(n,e){if(!h.HEX_RE.test(n))throw new Error(`Invalid scriptPubKey: not valid hex for ${e}`);if(!h.KNOWN_SCRIPT_PREFIXES.some(r=>n.toLowerCase().startsWith(r)))throw new Error(`Unrecognized scriptPubKey type for ${e}: prefix ${n.slice(0,6)} does not match any known Bitcoin script type`)}const J={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function x(n,e){try{const t=await $(n,e);if(!t.ok){const s=await t.text();throw new Error(`Mempool API error (${t.status}): ${s||t.statusText}`)}const r=t.headers.get("content-type");return r!=null&&r.includes("application/json")?await t.json():await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to fetch from mempool API: ${t.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function de(n,e){try{const t=await $(`${e}/tx`,{method:"POST",body:n,headers:{"Content-Type":"text/plain"}});if(!t.ok){const s=await t.text();let i;try{i=JSON.parse(s).message}catch{i=s}throw new Error(i||`Failed to broadcast transaction: ${t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to broadcast BTC transaction: ${t.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function z(n,e){return I(n),x(`${e}/tx/${n}`)}async function fe(n,e){I(n);try{const t=await $(`${e}/tx/${n}/hex`);if(!t.ok){const r=await t.text();throw new Error(`Mempool API error (${t.status}): ${r||t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to get transaction hex for ${n}: ${t.message}`):new Error(`Failed to get transaction hex for ${n}: Unknown error`)}}async function me(n,e,t){I(n);const r=await z(n,t);if(!Y(e,r.vout.length))throw new Error(`Invalid vout ${e} for transaction ${n} (has ${r.vout.length} outputs)`);const s=r.vout[e];if(!q(s.value))throw new Error(`Invalid UTXO value ${s.value} for ${n}:${e}`);return W(s.scriptpubkey,`${n}:${e}`),{txid:n,vout:e,value:s.value,scriptPubKey:s.scriptpubkey}}async function he(n,e){G(n);try{const t=await x(`${e}/address/${n}/utxo`),r=await x(`${e}/v1/validate-address/${n}`);if(!r.isvalid)throw new Error(`Invalid Bitcoin address: ${n}. Mempool API validation failed.`);W(r.scriptPubKey,n);for(const i of t){if(I(i.txid),!Y(i.vout))throw new Error(`Invalid vout ${i.vout} for ${i.txid}`);if(!q(i.value))throw new Error(`Invalid UTXO value ${i.value} for ${i.txid}:${i.vout}`)}return t.sort((i,c)=>c.value-i.value).map(i=>({txid:i.txid,vout:i.vout,value:i.value,scriptPubKey:r.scriptPubKey,confirmed:i.status.confirmed}))}catch(t){throw t instanceof Error?new Error(`Failed to get UTXOs for address ${n}: ${t.message}`):new Error(`Failed to get UTXOs for address ${n}: Unknown error`)}}function ye(n){return J[n]}async function ge(n,e){return G(n),x(`${e}/address/${n}/txs`)}async function _e(n){const e=await $(`${n}/v1/fees/recommended`);if(!e.ok)throw new Error(`Failed to fetch network fees: ${e.status} ${e.statusText}`);const t=await e.json(),r=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const s of r)if(!pe(t[s]))throw new Error(`Invalid fee rate ${s}=${t[s]} from mempool API: expected a positive number ≤ ${L}`);if(t.minimumFee>t.economyFee||t.economyFee>t.hourFee||t.hourFee>t.halfHourFee||t.halfHourFee>t.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${t.minimumFee}) <= economyFee (${t.economyFee}) <= hourFee (${t.hourFee}) <= halfHourFee (${t.halfHourFee}) <= fastestFee (${t.fastestFee}).`);return t}const T=[{type:"function",name:"getVaultKeepersByVersion",inputs:[{name:"appEntryPoint",type:"address",internalType:"address"},{name:"versionNumber",type:"uint16",internalType:"uint16"}],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"getCurrentVaultKeepers",inputs:[{name:"appEntryPoint",type:"address",internalType:"address"}],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"getCurrentVaultKeepersVersion",inputs:[{name:"appEntryPoint",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint16",internalType:"uint16"}],stateMutability:"view"}],f=[{type:"function",name:"getTBVProtocolParams",inputs:[],outputs:[{name:"",type:"tuple",internalType:"struct IProtocolParams.TBVProtocolParams",components:[{name:"minimumPegInAmount",type:"uint64",internalType:"uint64"},{name:"maxPegInAmount",type:"uint64",internalType:"uint64"},{name:"pegInAckTimeout",type:"uint64",internalType:"uint64"},{name:"pegInActivationTimeout",type:"uint64",internalType:"uint64"},{name:"maxHtlcOutputCount",type:"uint8",internalType:"uint8"}]}],stateMutability:"view"},{type:"function",name:"getLatestOffchainParams",inputs:[],outputs:[{name:"",type:"tuple",internalType:"struct IProtocolParams.VersionedOffchainParams",components:[{name:"timelockAssert",type:"uint256",internalType:"uint256"},{name:"timelockChallengeAssert",type:"uint256",internalType:"uint256"},{name:"securityCouncilKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"councilQuorum",type:"uint8",internalType:"uint8"},{name:"feeRate",type:"uint64",internalType:"uint64"},{name:"babeTotalInstances",type:"uint16",internalType:"uint16"},{name:"babeInstancesToFinalize",type:"uint8",internalType:"uint8"},{name:"minVpCommissionBps",type:"uint16",internalType:"uint16"},{name:"tRefund",type:"uint32",internalType:"uint32"},{name:"tStale",type:"uint32",internalType:"uint32"},{name:"minPeginFeeRate",type:"uint64",internalType:"uint64"},{name:"proverProgramVersion",type:"uint16",internalType:"uint16"},{name:"minPrepeginDepth",type:"uint32",internalType:"uint32"}]}],stateMutability:"view"},{type:"function",name:"getOffchainParamsByVersion",inputs:[{name:"versionNumber",type:"uint16",internalType:"uint16"}],outputs:[{name:"",type:"tuple",internalType:"struct IProtocolParams.VersionedOffchainParams",components:[{name:"timelockAssert",type:"uint256",internalType:"uint256"},{name:"timelockChallengeAssert",type:"uint256",internalType:"uint256"},{name:"securityCouncilKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"councilQuorum",type:"uint8",internalType:"uint8"},{name:"feeRate",type:"uint64",internalType:"uint64"},{name:"babeTotalInstances",type:"uint16",internalType:"uint16"},{name:"babeInstancesToFinalize",type:"uint8",internalType:"uint8"},{name:"minVpCommissionBps",type:"uint16",internalType:"uint16"},{name:"tRefund",type:"uint32",internalType:"uint32"},{name:"tStale",type:"uint32",internalType:"uint32"},{name:"minPeginFeeRate",type:"uint64",internalType:"uint64"},{name:"proverProgramVersion",type:"uint16",internalType:"uint16"},{name:"minPrepeginDepth",type:"uint32",internalType:"uint32"}]}],stateMutability:"view"},{type:"function",name:"latestOffchainParamsVersion",inputs:[],outputs:[{name:"",type:"uint16",internalType:"uint16"}],stateMutability:"view"},{type:"function",name:"getUniversalChallengersByVersion",inputs:[{name:"versionNumber",type:"uint16",internalType:"uint16"}],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"getCurrentUniversalChallengers",inputs:[],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"latestUniversalChallengersVersion",inputs:[],outputs:[{name:"",type:"uint16",internalType:"uint16"}],stateMutability:"view"}],U=new Set(Object.values(_.DaemonStatus)),be=200;function o(n){var e;return((e=JSON.stringify(n))==null?void 0:e.slice(0,be))??"undefined"}const we="The vault provider returned an unexpected response. Please try again or contact support.";class a extends Error{constructor(t){super(we);l(this,"detail");this.name="VpResponseValidationError",this.detail=t}}const A=64;function b(n){return typeof n=="string"&&n.length>0&&h.HEX_RE.test(n)}function Q(n){return typeof n=="string"&&n.length>0}function Z(n,e){if(!b(n))throw new a(`VP response validation failed: "${e}" must be a non-empty hex string, got ${o(n)}`)}function w(n,e){if(!Q(n))throw new a(`VP response validation failed: "${e}" must be a non-empty string, got ${o(n)}`)}function ee(n,e){if(!b(n)||n.length!==p.X_ONLY_PUBKEY_HEX_LEN&&n.length!==p.COMPRESSED_PUBKEY_HEX_LEN)throw new a(`VP response validation failed: "${e}" must be a ${p.X_ONLY_PUBKEY_HEX_LEN} or ${p.COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${o(n)}`)}function Pe(n){const e=n.presigning;if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new a('VP response validation failed: "progress.presigning" must be an object if present');const t=e;if(t.depositor_graph_created!==void 0&&typeof t.depositor_graph_created!="boolean")throw new a(`VP response validation failed: "progress.presigning.depositor_graph_created" must be a boolean if present, got ${o(t.depositor_graph_created)}`);if(t.vk_challenger_presigning_completed!==void 0&&typeof t.vk_challenger_presigning_completed!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_completed" must be a number if present, got ${o(t.vk_challenger_presigning_completed)}`);if(t.vk_challenger_presigning_total!==void 0&&typeof t.vk_challenger_presigning_total!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_total" must be a number if present, got ${o(t.vk_challenger_presigning_total)}`)}function ve(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: getPeginStatus response is not an object");const e=n;if(!b(e.pegin_txid)||e.pegin_txid.length!==A)throw new a(`VP response validation failed: "pegin_txid" must be a ${A}-char hex string (txid), got ${o(e.pegin_txid)}`);if(typeof e.status!="string")throw new a('VP response validation failed: "status" must be a string');if(!U.has(e.status))throw new a(`VP response validation failed: unrecognized status "${e.status}". Expected one of: ${[...U].join(", ")}`);if(e.progress===null||typeof e.progress!="object"||Array.isArray(e.progress))throw new a('VP response validation failed: "progress" must be an object');if(Pe(e.progress),typeof e.health_info!="string")throw new a('VP response validation failed: "health_info" must be a string');if(e.last_error!==void 0&&typeof e.last_error!="string")throw new a(`VP response validation failed: "last_error" must be a string if present, got ${o(e.last_error)}`)}function Te(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: requestDepositorPresignTransactions response is not an object");const e=n;if(!Array.isArray(e.txs))throw new a('VP response validation failed: "txs" must be an array');for(let t=0;t<e.txs.length;t++)xe(e.txs[t],`txs[${t}]`);if(e.depositor_graph===null||typeof e.depositor_graph!="object")throw new a('VP response validation failed: "depositor_graph" must be an object');$e(e.depositor_graph)}function y(n,e){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${e}" must be an object`);Z(n.tx_hex,`${e}.tx_hex`)}function xe(n,e){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=n;ee(t.claimer_pubkey,`${e}.claimer_pubkey`),y(t.claim_tx,`${e}.claim_tx`),y(t.assert_tx,`${e}.assert_tx`),y(t.payout_tx,`${e}.payout_tx`),w(t.payout_psbt,`${e}.payout_psbt`)}function Ae(n,e){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=n;w(t.wots_pks_json,`${e}.wots_pks_json`),w(t.gc_wots_keys_json,`${e}.gc_wots_keys_json`)}function Ve(n,e){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=n;if(ee(t.challenger_pubkey,`${e}.challenger_pubkey`),y(t.challenge_assert_x_tx,`${e}.challenge_assert_x_tx`),y(t.challenge_assert_y_tx,`${e}.challenge_assert_y_tx`),y(t.nopayout_tx,`${e}.nopayout_tx`),w(t.nopayout_psbt,`${e}.nopayout_psbt`),!Array.isArray(t.challenge_assert_connectors))throw new a(`VP response validation failed: "${e}.challenge_assert_connectors" must be an array`);for(let r=0;r<t.challenge_assert_connectors.length;r++)Ae(t.challenge_assert_connectors[r],`${e}.challenge_assert_connectors[${r}]`);if(!Array.isArray(t.output_label_hashes))throw new a(`VP response validation failed: "${e}.output_label_hashes" must be an array`);for(let r=0;r<t.output_label_hashes.length;r++)Z(t.output_label_hashes[r],`${e}.output_label_hashes[${r}]`)}function te(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const e=n;if(!Q(e.tx_graph_json))throw new a(`VP response validation failed: "tx_graph_json" must be a non-empty string, got ${o(e.tx_graph_json)}`);if(!b(e.verifying_key_hex))throw new a(`VP response validation failed: "verifying_key_hex" must be a non-empty hex string, got ${o(e.verifying_key_hex)}`);if(e.babe_sessions===null||typeof e.babe_sessions!="object")throw new a('VP response validation failed: "babe_sessions" must be an object');for(const[t,r]of Object.entries(e.babe_sessions)){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "babe_sessions.${t}" must be an object`);const s=r;if(!b(s.decryptor_artifacts_hex))throw new a(`VP response validation failed: "babe_sessions.${t}.decryptor_artifacts_hex" must be a non-empty hex string, got ${o(s.decryptor_artifacts_hex)}`)}}function Ee(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: getPegoutStatus response is not an object");const e=n;if(!b(e.pegin_txid)||e.pegin_txid.length!==A)throw new a(`VP response validation failed: "pegin_txid" must be a ${A}-char hex string (txid), got ${o(e.pegin_txid)}`);if(typeof e.found!="boolean")throw new a(`VP response validation failed: "found" must be a boolean, got ${o(e.found)}`);if(e.claimer!==void 0){if(e.claimer===null||typeof e.claimer!="object")throw new a('VP response validation failed: "claimer" must be an object if present');const t=e.claimer;if(typeof t.status!="string")throw new a(`VP response validation failed: "claimer.status" must be a string, got ${o(t.status)}`);if(typeof t.failed!="boolean")throw new a(`VP response validation failed: "claimer.failed" must be a boolean, got ${o(t.failed)}`)}if(e.challenger!==void 0){if(e.challenger===null||typeof e.challenger!="object")throw new a('VP response validation failed: "challenger" must be an object if present');const t=e.challenger;if(typeof t.status!="string")throw new a(`VP response validation failed: "challenger.status" must be a string, got ${o(t.status)}`)}}function $e(n){if(y(n.claim_tx,"depositor_graph.claim_tx"),y(n.assert_tx,"depositor_graph.assert_tx"),y(n.payout_tx,"depositor_graph.payout_tx"),w(n.payout_psbt,"depositor_graph.payout_psbt"),!Array.isArray(n.challenger_presign_data))throw new a('VP response validation failed: "depositor_graph.challenger_presign_data" must be an array');for(let e=0;e<n.challenger_presign_data.length;e++)Ve(n.challenger_presign_data[e],`depositor_graph.challenger_presign_data[${e}]`);if(typeof n.offchain_params_version!="number")throw new a('VP response validation failed: "depositor_graph.offchain_params_version" must be a number')}const Ie=6e4;class Ce{constructor(e,t){l(this,"client");const r={baseUrl:e,timeout:(t==null?void 0:t.timeout)??Ie,retries:t==null?void 0:t.retries,retryDelay:t==null?void 0:t.retryDelay,retryableFor:t==null?void 0:t.retryableFor,headers:t==null?void 0:t.headers};this.client=new _.JsonRpcClient(r)}async requestDepositorPresignTransactions(e,t){const r=await this.client.call("vaultProvider_requestDepositorPresignTransactions",e,t);return Te(r),r}async submitDepositorPresignatures(e,t){return this.client.call("vaultProvider_submitDepositorPresignatures",e,t)}async submitDepositorWotsKey(e,t){return this.client.call("vaultProvider_submitDepositorWotsKey",e,t)}async requestDepositorClaimerArtifacts(e,t){const r=await this.client.call("vaultProvider_requestDepositorClaimerArtifacts",e,t);return te(r),r}async getPeginStatus(e,t){const r=await this.client.call("vaultProvider_getPeginStatus",e,t);return ve(r),r}async getPegoutStatus(e,t){const r=await this.client.call("vaultProvider_getPegoutStatus",e,t);return Ee(r),r}}const Se="BIP0322-signed-message",ke="TapTweak",ne=32,Be=64;function re(n,e){const t=new TextEncoder().encode(n),r=O.sha256(t),s=new Uint8Array(r.length*2+e.length);return s.set(r,0),s.set(r,r.length),s.set(e,r.length*2),O.sha256(s)}function Re(n){if(n.length!==ne)return null;const e=re(ke,n),t=B.xOnlyPointAddTweak(n,e);return t?t.xOnlyPubkey:null}function Ne(n,e,t){if(e.length!==ne||t.length!==Be)return!1;try{const r=re(Se,n),s=P.payments.p2tr({internalPubkey:g.Buffer.from(e)});if(!s.output)return!1;const i=s.output,c=0,m=new P.Transaction;m.version=0,m.locktime=0;const C=g.Buffer.concat([g.Buffer.from([0,32]),g.Buffer.from(r)]);m.addInput(g.Buffer.alloc(32,0),4294967295,0,C),m.addOutput(i,c);const d=new P.Transaction;d.version=0,d.locktime=0;const S=m.getHash();d.addInput(S,0,0),d.addOutput(g.Buffer.from([106]),c);const R=d.hashForWitnessV1(0,[i],[c],P.Transaction.SIGHASH_DEFAULT),N=Re(e);return N?B.verifySchnorr(R,N,t):!1}catch{return!1}}function V(n,e){const t=(n&7)<<5,r=typeof e=="bigint"?e:BigInt(e);if(r<0n)throw new Error("cborHead: negative argument");if(r<24n)return new Uint8Array([t|Number(r)]);if(r<0x100n)return new Uint8Array([t|24,Number(r)]);if(r<0x10000n){const i=Number(r);return new Uint8Array([t|25,i>>>8&255,i&255])}if(r<0x100000000n){const i=Number(r);return new Uint8Array([t|26,i>>>24&255,i>>>16&255,i>>>8&255,i&255])}const s=new Uint8Array(9);s[0]=t|27;for(let i=7;i>=0;i--)s[1+i]=Number(r>>BigInt((7-i)*8))&255;return s}function ie(...n){const e=n.reduce((s,i)=>s+i.length,0),t=new Uint8Array(e);let r=0;for(const s of n)t.set(s,r),r+=s.length;return t}function H(n){const t=[V(4,n.length)];for(const r of n)t.push(V(0,r));return ie(...t)}function Oe(n,e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`encodeServerIdentityPayload: expires_at must be a non-negative safe integer, got ${t}`);const r=V(4,3),s=H(n),i=H(e),c=V(0,t);return ie(r,s,i,c)}const Fe=new TextEncoder().encode("btc-auth.server-identity.v1");class u extends Error{constructor(e,t){super(e),this.reason=t,this.name="ServerIdentityError"}}function v(n){const e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function se(n){const{proof:e,pinnedServerPubkey:t,now:r}=n,s=p.stripHexPrefix(t).toLowerCase();if(s.length!==p.X_ONLY_PUBKEY_HEX_LEN||!h.HEX_RE.test(s))throw new u(`pinnedServerPubkey must be 32-byte hex; got ${s.length} chars`,"invalid_pubkey_encoding");const i=p.stripHexPrefix(e.server_pubkey).toLowerCase();if(i.length!==p.X_ONLY_PUBKEY_HEX_LEN||!h.HEX_RE.test(i))throw new u(`server_pubkey must be 32-byte hex; got ${i.length} chars`,"invalid_pubkey_encoding");if(i!==s)throw new u(`server_pubkey does not match pinned value: expected ${s}, got ${i}`,"pinned_pubkey_mismatch");if(!Number.isSafeInteger(e.expires_at))throw new u(`expires_at must be a finite integer; got ${JSON.stringify(e.expires_at)}`,"invalid_expires_at");if(!Number.isSafeInteger(r))throw new u(`now must be a finite integer; got ${JSON.stringify(r)}`,"invalid_expires_at");if(e.expires_at<=r)throw new u(`server identity proof expired at ${e.expires_at}, now ${r}`,"expired");const c=p.stripHexPrefix(e.ephemeral_pubkey).toLowerCase();if(c.length!==p.COMPRESSED_PUBKEY_HEX_LEN||!h.HEX_RE.test(c))throw new u(`ephemeral_pubkey must be 33-byte compressed hex; got ${c.length} chars`,"invalid_ephemeral_pubkey");const m=c.slice(0,2);if(m!=="02"&&m!=="03")throw new u(`ephemeral_pubkey must be compressed (prefix 02/03); got ${m}`,"invalid_ephemeral_pubkey");const C=v(c);if(!B.isPoint(C))throw new u("ephemeral_pubkey is not a valid secp256k1 point","invalid_ephemeral_pubkey");const d=p.stripHexPrefix(e.signature).toLowerCase();if(d.length!==p.SCHNORR_SIG_HEX_LEN||!h.HEX_RE.test(d))throw new u(`signature must be 64-byte Schnorr hex; got ${d.length} chars`,"invalid_signature_encoding");const S=Oe(Fe,v(c),e.expires_at);if(!Ne(S,v(i),v(d)))throw new u("BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey","signature_verification_failed")}const K="auth_createDepositorToken",j=4102444800,Ue=30;class He{constructor(e){l(this,"client");l(this,"peginTxid");l(this,"authAnchorHex");l(this,"pinnedServerPubkey");l(this,"authGatedMethods");l(this,"refreshSkewSecs");l(this,"now");l(this,"cached",null);l(this,"inFlight",null);this.client=e.client,this.peginTxid=e.peginTxid,this.authAnchorHex=e.authAnchorHex,this.pinnedServerPubkey=e.pinnedServerPubkey,this.authGatedMethods=e.authGatedMethods,this.refreshSkewSecs=e.refreshSkewSecs??Ue,this.now=e.now??(()=>Math.floor(Date.now()/1e3))}async getToken(e){if(e===K||!this.authGatedMethods.has(e))return null;const t=this.cached;return t&&this.now()+this.refreshSkewSecs<t.expiresAt?t.token:(await this.acquireSingleFlight()).token}invalidate(){this.cached=null}acquireSingleFlight(){const e=this.inFlight;if(e)return e;const t=(async()=>{try{const r=await this.client.call(K,{pegin_txid:this.peginTxid,auth_anchor:this.authAnchorHex});if(se({proof:r.server_identity,pinnedServerPubkey:this.pinnedServerPubkey,now:this.now()}),typeof r.token!="string"||r.token.length===0)throw new Error(`VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof r.token})`);const s=this.now();if(!Number.isSafeInteger(r.expires_at)||r.expires_at<=s||r.expires_at>j)throw new Error(`VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(r.expires_at)}; must be a safe integer in (${s}, ${j}])`);const i={token:r.token,expiresAt:r.expires_at};return this.cached=i,i}finally{this.inFlight=null}})();return this.inFlight=t,t}}async function Ke(n,e){const[t,r]=await n.multicall({contracts:[{address:e,abi:_.BTCVaultRegistryABI,functionName:"protocolParams"},{address:e,abi:_.BTCVaultRegistryABI,functionName:"applicationRegistry"}],allowFailure:!1});return{protocolParams:t,applicationRegistry:r}}const D=65535;function k(n){return{timelockAssert:n.timelockAssert,timelockChallengeAssert:n.timelockChallengeAssert,securityCouncilKeys:[...n.securityCouncilKeys],councilQuorum:n.councilQuorum,feeRate:n.feeRate,babeTotalInstances:n.babeTotalInstances,babeInstancesToFinalize:n.babeInstancesToFinalize,minVpCommissionBps:n.minVpCommissionBps,tRefund:n.tRefund,tStale:n.tStale,minPeginFeeRate:n.minPeginFeeRate,proverProgramVersion:n.proverProgramVersion,minPrepeginDepth:n.minPrepeginDepth}}function M(n){return{minimumPegInAmount:n.minimumPegInAmount,maxPegInAmount:n.maxPegInAmount,pegInAckTimeout:n.pegInAckTimeout,pegInActivationTimeout:n.pegInActivationTimeout,maxHtlcOutputCount:n.maxHtlcOutputCount}}function X(n){if(n>BigInt(D))throw new Error(`timelockAssert value ${n} exceeds uint16 max (${D})`);return Number(n)}class je{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getTBVProtocolParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getTBVProtocolParams"});return M(e)}async getLatestOffchainParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getLatestOffchainParams"});return k(e)}async getOffchainParamsByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getOffchainParamsByVersion",args:[e]});return k(t)}async getLatestOffchainParamsVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"latestOffchainParamsVersion"})}async getTimelockPeginByVersion(e){const t=await this.getOffchainParamsByVersion(e);return X(t.timelockAssert)}async getPegInConfiguration(){const e=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:f,functionName:"getTBVProtocolParams"},{address:this.contractAddress,abi:f,functionName:"getLatestOffchainParams"}],allowFailure:!1}),t=M(e[0]),r=k(e[1]);return{minimumPegInAmount:t.minimumPegInAmount,maxPegInAmount:t.maxPegInAmount,pegInAckTimeout:t.pegInAckTimeout,pegInActivationTimeout:t.pegInActivationTimeout,maxHtlcOutputCount:t.maxHtlcOutputCount,timelockPegin:X(r.timelockAssert),timelockRefund:r.tRefund,minVpCommissionBps:r.minVpCommissionBps,offchainParams:r}}}function E(n){return n.map(e=>({ethAddress:e.ethAddress,btcPubKey:e.btcPubKey}))}class De{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getVaultKeepersByVersion(e,t){const r=await this.publicClient.readContract({address:this.contractAddress,abi:T,functionName:"getVaultKeepersByVersion",args:[e,t]});return E(r)}async getCurrentVaultKeepers(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:T,functionName:"getCurrentVaultKeepers",args:[e]});return E(t)}async getCurrentVaultKeepersVersion(e){return await this.publicClient.readContract({address:this.contractAddress,abi:T,functionName:"getCurrentVaultKeepersVersion",args:[e]})}}class Me{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getUniversalChallengersByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getUniversalChallengersByVersion",args:[e]});return E(t)}async getCurrentUniversalChallengers(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getCurrentUniversalChallengers"});return E(e)}async getLatestUniversalChallengersVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"latestUniversalChallengersVersion"})}}class Xe{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getVaultBasicInfo(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:_.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]});return{depositor:t.depositor,depositorBtcPubKey:t.depositorBtcPubKey,amount:t.amount,vaultProvider:t.vaultProvider,status:t.status,applicationEntryPoint:t.applicationEntryPoint,createdAt:t.createdAt}}async getVaultProtocolInfo(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:_.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return{depositorSignedPeginTx:t.depositorSignedPeginTx,universalChallengersVersion:t.universalChallengersVersion,appVaultKeepersVersion:t.appVaultKeepersVersion,offchainParamsVersion:t.offchainParamsVersion,verifiedAt:t.verifiedAt,depositorWotsPkHash:t.depositorWotsPkHash,hashlock:t.hashlock,htlcVout:t.htlcVout,depositorPopSignature:t.depositorPopSignature,prePeginTxHash:t.prePeginTxHash,vaultProviderCommissionBps:t.vaultProviderCommissionBps}}async getVaultData(e){const[t,r]=await Promise.all([this.getVaultBasicInfo(e),this.getVaultProtocolInfo(e)]);if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e} not found on-chain or has no pegin transaction`);return{basic:t,protocol:r}}}exports.ApplicationRegistryABI=T;exports.MEMPOOL_API_URLS=J;exports.ProtocolParamsABI=f;exports.ServerIdentityError=u;exports.VaultProviderRpcClient=Ce;exports.ViemProtocolParamsReader=je;exports.ViemUniversalChallengerReader=Me;exports.ViemVaultKeeperReader=De;exports.ViemVaultRegistryReader=Xe;exports.VpResponseValidationError=a;exports.VpTokenProvider=He;exports.getAddressTxs=ge;exports.getAddressUtxos=he;exports.getMempoolApiUrl=ye;exports.getNetworkFees=_e;exports.getTxHex=fe;exports.getTxInfo=z;exports.getUtxoInfo=me;exports.pushTx=de;exports.resolveProtocolAddresses=Ke;exports.validateRequestDepositorClaimerArtifactsResponse=te;exports.verifyServerIdentity=se;
|
|
2
|
-
//# sourceMappingURL=vault-registry-reader-
|
|
1
|
+
"use strict";var ae=Object.defineProperty;var oe=(n,e,t)=>e in n?ae(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var l=(n,e,t)=>oe(n,typeof e!="symbol"?e+"":e,t);const h=require("./validation-u8W7Lp2x.cjs"),_=require("./types-jmEyzzhY.cjs"),p=require("./bitcoin-EYBKDtEW.cjs"),ce=require("@bitcoin-js/tiny-secp256k1-asmjs"),P=require("bitcoinjs-lib"),g=require("buffer"),O=require("./sha2-CsTynrfJ.cjs");function le(n){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const t in n)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>n[t]})}}return e.default=n,Object.freeze(e)}const B=le(ce),ue=21e6*1e8,F=3e4;async function $(n,e){const t=new AbortController,r=setTimeout(()=>t.abort(),F),s=[t.signal,e==null?void 0:e.signal].filter(Boolean);try{return await fetch(n,{...e,signal:AbortSignal.any(s)})}catch(i){throw clearTimeout(r),i!=null&&typeof i=="object"&&"name"in i&&i.name==="AbortError"?new Error(`Mempool API request timed out after ${F}ms: ${n}`):i}}const L=1e4;function q(n){return Number.isInteger(n)&&n>0&&n<=ue}function pe(n){return Number.isInteger(n)&&n>0&&n<=L}function Y(n,e){return!Number.isInteger(n)||n<0?!1:e===void 0||n<e}function I(n){if(!h.TXID_RE.test(n))throw new Error(`Invalid transaction ID format: ${n}`)}function G(n){if(!h.BITCOIN_ADDRESS_RE.test(n))throw new Error(`Invalid Bitcoin address format: ${n}`)}function W(n,e){if(!h.HEX_RE.test(n))throw new Error(`Invalid scriptPubKey: not valid hex for ${e}`);if(!h.KNOWN_SCRIPT_PREFIXES.some(r=>n.toLowerCase().startsWith(r)))throw new Error(`Unrecognized scriptPubKey type for ${e}: prefix ${n.slice(0,6)} does not match any known Bitcoin script type`)}const J={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function x(n,e){try{const t=await $(n,e);if(!t.ok){const s=await t.text();throw new Error(`Mempool API error (${t.status}): ${s||t.statusText}`)}const r=t.headers.get("content-type");return r!=null&&r.includes("application/json")?await t.json():await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to fetch from mempool API: ${t.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function de(n,e){try{const t=await $(`${e}/tx`,{method:"POST",body:n,headers:{"Content-Type":"text/plain"}});if(!t.ok){const s=await t.text();let i;try{i=JSON.parse(s).message}catch{i=s}throw new Error(i||`Failed to broadcast transaction: ${t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to broadcast BTC transaction: ${t.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function z(n,e){return I(n),x(`${e}/tx/${n}`)}async function fe(n,e){I(n);try{const t=await $(`${e}/tx/${n}/hex`);if(!t.ok){const r=await t.text();throw new Error(`Mempool API error (${t.status}): ${r||t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to get transaction hex for ${n}: ${t.message}`):new Error(`Failed to get transaction hex for ${n}: Unknown error`)}}async function me(n,e,t){I(n);const r=await z(n,t);if(!Y(e,r.vout.length))throw new Error(`Invalid vout ${e} for transaction ${n} (has ${r.vout.length} outputs)`);const s=r.vout[e];if(!q(s.value))throw new Error(`Invalid UTXO value ${s.value} for ${n}:${e}`);return W(s.scriptpubkey,`${n}:${e}`),{txid:n,vout:e,value:s.value,scriptPubKey:s.scriptpubkey}}async function he(n,e){G(n);try{const t=await x(`${e}/address/${n}/utxo`),r=await x(`${e}/v1/validate-address/${n}`);if(!r.isvalid)throw new Error(`Invalid Bitcoin address: ${n}. Mempool API validation failed.`);W(r.scriptPubKey,n);for(const i of t){if(I(i.txid),!Y(i.vout))throw new Error(`Invalid vout ${i.vout} for ${i.txid}`);if(!q(i.value))throw new Error(`Invalid UTXO value ${i.value} for ${i.txid}:${i.vout}`)}return t.sort((i,c)=>c.value-i.value).map(i=>({txid:i.txid,vout:i.vout,value:i.value,scriptPubKey:r.scriptPubKey,confirmed:i.status.confirmed}))}catch(t){throw t instanceof Error?new Error(`Failed to get UTXOs for address ${n}: ${t.message}`):new Error(`Failed to get UTXOs for address ${n}: Unknown error`)}}function ye(n){return J[n]}async function ge(n,e){return G(n),x(`${e}/address/${n}/txs`)}async function _e(n){const e=await $(`${n}/v1/fees/recommended`);if(!e.ok)throw new Error(`Failed to fetch network fees: ${e.status} ${e.statusText}`);const t=await e.json(),r=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const s of r)if(!pe(t[s]))throw new Error(`Invalid fee rate ${s}=${t[s]} from mempool API: expected a positive number ≤ ${L}`);if(t.minimumFee>t.economyFee||t.economyFee>t.hourFee||t.hourFee>t.halfHourFee||t.halfHourFee>t.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${t.minimumFee}) <= economyFee (${t.economyFee}) <= hourFee (${t.hourFee}) <= halfHourFee (${t.halfHourFee}) <= fastestFee (${t.fastestFee}).`);return t}const T=[{type:"function",name:"getVaultKeepersByVersion",inputs:[{name:"appEntryPoint",type:"address",internalType:"address"},{name:"versionNumber",type:"uint16",internalType:"uint16"}],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"getCurrentVaultKeepers",inputs:[{name:"appEntryPoint",type:"address",internalType:"address"}],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"getCurrentVaultKeepersVersion",inputs:[{name:"appEntryPoint",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint16",internalType:"uint16"}],stateMutability:"view"}],f=[{type:"function",name:"getTBVProtocolParams",inputs:[],outputs:[{name:"",type:"tuple",internalType:"struct IProtocolParams.TBVProtocolParams",components:[{name:"minimumPegInAmount",type:"uint64",internalType:"uint64"},{name:"maxPegInAmount",type:"uint64",internalType:"uint64"},{name:"pegInAckTimeout",type:"uint64",internalType:"uint64"},{name:"pegInActivationTimeout",type:"uint64",internalType:"uint64"},{name:"maxHtlcOutputCount",type:"uint8",internalType:"uint8"}]}],stateMutability:"view"},{type:"function",name:"getLatestOffchainParams",inputs:[],outputs:[{name:"",type:"tuple",internalType:"struct IProtocolParams.VersionedOffchainParams",components:[{name:"timelockAssert",type:"uint256",internalType:"uint256"},{name:"timelockChallengeAssert",type:"uint256",internalType:"uint256"},{name:"securityCouncilKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"councilQuorum",type:"uint8",internalType:"uint8"},{name:"feeRate",type:"uint64",internalType:"uint64"},{name:"babeTotalInstances",type:"uint16",internalType:"uint16"},{name:"babeInstancesToFinalize",type:"uint8",internalType:"uint8"},{name:"minVpCommissionBps",type:"uint16",internalType:"uint16"},{name:"tRefund",type:"uint32",internalType:"uint32"},{name:"tStale",type:"uint32",internalType:"uint32"},{name:"minPeginFeeRate",type:"uint64",internalType:"uint64"},{name:"proverProgramVersion",type:"uint16",internalType:"uint16"},{name:"minPrepeginDepth",type:"uint32",internalType:"uint32"}]}],stateMutability:"view"},{type:"function",name:"getOffchainParamsByVersion",inputs:[{name:"versionNumber",type:"uint16",internalType:"uint16"}],outputs:[{name:"",type:"tuple",internalType:"struct IProtocolParams.VersionedOffchainParams",components:[{name:"timelockAssert",type:"uint256",internalType:"uint256"},{name:"timelockChallengeAssert",type:"uint256",internalType:"uint256"},{name:"securityCouncilKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"councilQuorum",type:"uint8",internalType:"uint8"},{name:"feeRate",type:"uint64",internalType:"uint64"},{name:"babeTotalInstances",type:"uint16",internalType:"uint16"},{name:"babeInstancesToFinalize",type:"uint8",internalType:"uint8"},{name:"minVpCommissionBps",type:"uint16",internalType:"uint16"},{name:"tRefund",type:"uint32",internalType:"uint32"},{name:"tStale",type:"uint32",internalType:"uint32"},{name:"minPeginFeeRate",type:"uint64",internalType:"uint64"},{name:"proverProgramVersion",type:"uint16",internalType:"uint16"},{name:"minPrepeginDepth",type:"uint32",internalType:"uint32"}]}],stateMutability:"view"},{type:"function",name:"latestOffchainParamsVersion",inputs:[],outputs:[{name:"",type:"uint16",internalType:"uint16"}],stateMutability:"view"},{type:"function",name:"getUniversalChallengersByVersion",inputs:[{name:"versionNumber",type:"uint16",internalType:"uint16"}],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"getCurrentUniversalChallengers",inputs:[],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"latestUniversalChallengersVersion",inputs:[],outputs:[{name:"",type:"uint16",internalType:"uint16"}],stateMutability:"view"}],U=new Set(Object.values(_.DaemonStatus)),be=200;function o(n){var e;return((e=JSON.stringify(n))==null?void 0:e.slice(0,be))??"undefined"}const we="The vault provider returned an unexpected response. Please try again or contact support.";class a extends Error{constructor(t){super(we);l(this,"detail");this.name="VpResponseValidationError",this.detail=t}}const A=64;function b(n){return typeof n=="string"&&n.length>0&&h.HEX_RE.test(n)}function Q(n){return typeof n=="string"&&n.length>0}function Z(n,e){if(!b(n))throw new a(`VP response validation failed: "${e}" must be a non-empty hex string, got ${o(n)}`)}function w(n,e){if(!Q(n))throw new a(`VP response validation failed: "${e}" must be a non-empty string, got ${o(n)}`)}function ee(n,e){if(!b(n)||n.length!==p.X_ONLY_PUBKEY_HEX_LEN&&n.length!==p.COMPRESSED_PUBKEY_HEX_LEN)throw new a(`VP response validation failed: "${e}" must be a ${p.X_ONLY_PUBKEY_HEX_LEN} or ${p.COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${o(n)}`)}function Pe(n){const e=n.presigning;if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new a('VP response validation failed: "progress.presigning" must be an object if present');const t=e;if(t.depositor_graph_created!==void 0&&typeof t.depositor_graph_created!="boolean")throw new a(`VP response validation failed: "progress.presigning.depositor_graph_created" must be a boolean if present, got ${o(t.depositor_graph_created)}`);if(t.vk_challenger_presigning_completed!==void 0&&typeof t.vk_challenger_presigning_completed!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_completed" must be a number if present, got ${o(t.vk_challenger_presigning_completed)}`);if(t.vk_challenger_presigning_total!==void 0&&typeof t.vk_challenger_presigning_total!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_total" must be a number if present, got ${o(t.vk_challenger_presigning_total)}`)}function ve(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: getPeginStatus response is not an object");const e=n;if(!b(e.pegin_txid)||e.pegin_txid.length!==A)throw new a(`VP response validation failed: "pegin_txid" must be a ${A}-char hex string (txid), got ${o(e.pegin_txid)}`);if(typeof e.status!="string")throw new a('VP response validation failed: "status" must be a string');if(!U.has(e.status))throw new a(`VP response validation failed: unrecognized status "${e.status}". Expected one of: ${[...U].join(", ")}`);if(e.progress===null||typeof e.progress!="object"||Array.isArray(e.progress))throw new a('VP response validation failed: "progress" must be an object');if(Pe(e.progress),typeof e.health_info!="string")throw new a('VP response validation failed: "health_info" must be a string');if(e.last_error!==void 0&&typeof e.last_error!="string")throw new a(`VP response validation failed: "last_error" must be a string if present, got ${o(e.last_error)}`)}function Te(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: requestDepositorPresignTransactions response is not an object");const e=n;if(!Array.isArray(e.txs))throw new a('VP response validation failed: "txs" must be an array');for(let t=0;t<e.txs.length;t++)xe(e.txs[t],`txs[${t}]`);if(e.depositor_graph===null||typeof e.depositor_graph!="object")throw new a('VP response validation failed: "depositor_graph" must be an object');$e(e.depositor_graph)}function y(n,e){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${e}" must be an object`);Z(n.tx_hex,`${e}.tx_hex`)}function xe(n,e){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=n;ee(t.claimer_pubkey,`${e}.claimer_pubkey`),y(t.claim_tx,`${e}.claim_tx`),y(t.assert_tx,`${e}.assert_tx`),y(t.payout_tx,`${e}.payout_tx`),w(t.payout_psbt,`${e}.payout_psbt`)}function Ae(n,e){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=n;w(t.wots_pks_json,`${e}.wots_pks_json`),w(t.gc_wots_keys_json,`${e}.gc_wots_keys_json`)}function Ve(n,e){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=n;if(ee(t.challenger_pubkey,`${e}.challenger_pubkey`),y(t.challenge_assert_x_tx,`${e}.challenge_assert_x_tx`),y(t.challenge_assert_y_tx,`${e}.challenge_assert_y_tx`),y(t.nopayout_tx,`${e}.nopayout_tx`),w(t.nopayout_psbt,`${e}.nopayout_psbt`),!Array.isArray(t.challenge_assert_connectors))throw new a(`VP response validation failed: "${e}.challenge_assert_connectors" must be an array`);for(let r=0;r<t.challenge_assert_connectors.length;r++)Ae(t.challenge_assert_connectors[r],`${e}.challenge_assert_connectors[${r}]`);if(!Array.isArray(t.output_label_hashes))throw new a(`VP response validation failed: "${e}.output_label_hashes" must be an array`);for(let r=0;r<t.output_label_hashes.length;r++)Z(t.output_label_hashes[r],`${e}.output_label_hashes[${r}]`)}function te(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const e=n;if(!Q(e.tx_graph_json))throw new a(`VP response validation failed: "tx_graph_json" must be a non-empty string, got ${o(e.tx_graph_json)}`);if(!b(e.verifying_key_hex))throw new a(`VP response validation failed: "verifying_key_hex" must be a non-empty hex string, got ${o(e.verifying_key_hex)}`);if(e.babe_sessions===null||typeof e.babe_sessions!="object")throw new a('VP response validation failed: "babe_sessions" must be an object');for(const[t,r]of Object.entries(e.babe_sessions)){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "babe_sessions.${t}" must be an object`);const s=r;if(!b(s.decryptor_artifacts_hex))throw new a(`VP response validation failed: "babe_sessions.${t}.decryptor_artifacts_hex" must be a non-empty hex string, got ${o(s.decryptor_artifacts_hex)}`)}}function Ee(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: getPegoutStatus response is not an object");const e=n;if(!b(e.pegin_txid)||e.pegin_txid.length!==A)throw new a(`VP response validation failed: "pegin_txid" must be a ${A}-char hex string (txid), got ${o(e.pegin_txid)}`);if(typeof e.found!="boolean")throw new a(`VP response validation failed: "found" must be a boolean, got ${o(e.found)}`);if(e.claimer!==void 0){if(e.claimer===null||typeof e.claimer!="object")throw new a('VP response validation failed: "claimer" must be an object if present');const t=e.claimer;if(typeof t.status!="string")throw new a(`VP response validation failed: "claimer.status" must be a string, got ${o(t.status)}`);if(typeof t.failed!="boolean")throw new a(`VP response validation failed: "claimer.failed" must be a boolean, got ${o(t.failed)}`)}if(e.challenger!==void 0){if(e.challenger===null||typeof e.challenger!="object")throw new a('VP response validation failed: "challenger" must be an object if present');const t=e.challenger;if(typeof t.status!="string")throw new a(`VP response validation failed: "challenger.status" must be a string, got ${o(t.status)}`)}}function $e(n){if(y(n.claim_tx,"depositor_graph.claim_tx"),y(n.assert_tx,"depositor_graph.assert_tx"),y(n.payout_tx,"depositor_graph.payout_tx"),w(n.payout_psbt,"depositor_graph.payout_psbt"),!Array.isArray(n.challenger_presign_data))throw new a('VP response validation failed: "depositor_graph.challenger_presign_data" must be an array');for(let e=0;e<n.challenger_presign_data.length;e++)Ve(n.challenger_presign_data[e],`depositor_graph.challenger_presign_data[${e}]`);if(typeof n.offchain_params_version!="number")throw new a('VP response validation failed: "depositor_graph.offchain_params_version" must be a number')}const Ie=6e4;class Ce{constructor(e,t){l(this,"client");const r={baseUrl:e,timeout:(t==null?void 0:t.timeout)??Ie,retries:t==null?void 0:t.retries,retryDelay:t==null?void 0:t.retryDelay,retryableFor:t==null?void 0:t.retryableFor,headers:t==null?void 0:t.headers};this.client=new _.JsonRpcClient(r)}async requestDepositorPresignTransactions(e,t){const r=await this.client.call("vaultProvider_requestDepositorPresignTransactions",e,t);return Te(r),r}async submitDepositorPresignatures(e,t){return this.client.call("vaultProvider_submitDepositorPresignatures",e,t)}async submitDepositorWotsKey(e,t){return this.client.call("vaultProvider_submitDepositorWotsKey",e,t)}async requestDepositorClaimerArtifacts(e,t){const r=await this.client.call("vaultProvider_requestDepositorClaimerArtifacts",e,t);return te(r),r}async getPeginStatus(e,t){const r=await this.client.call("vaultProvider_getPeginStatus",e,t);return ve(r),r}async getPegoutStatus(e,t){const r=await this.client.call("vaultProvider_getPegoutStatus",e,t);return Ee(r),r}}const Se="BIP0322-signed-message",ke="TapTweak",ne=32,Be=64;function re(n,e){const t=new TextEncoder().encode(n),r=O.sha256(t),s=new Uint8Array(r.length*2+e.length);return s.set(r,0),s.set(r,r.length),s.set(e,r.length*2),O.sha256(s)}function Re(n){if(n.length!==ne)return null;const e=re(ke,n),t=B.xOnlyPointAddTweak(n,e);return t?t.xOnlyPubkey:null}function Ne(n,e,t){if(e.length!==ne||t.length!==Be)return!1;try{const r=re(Se,n),s=P.payments.p2tr({internalPubkey:g.Buffer.from(e)});if(!s.output)return!1;const i=s.output,c=0,m=new P.Transaction;m.version=0,m.locktime=0;const C=g.Buffer.concat([g.Buffer.from([0,32]),g.Buffer.from(r)]);m.addInput(g.Buffer.alloc(32,0),4294967295,0,C),m.addOutput(i,c);const d=new P.Transaction;d.version=0,d.locktime=0;const S=m.getHash();d.addInput(S,0,0),d.addOutput(g.Buffer.from([106]),c);const R=d.hashForWitnessV1(0,[i],[c],P.Transaction.SIGHASH_DEFAULT),N=Re(e);return N?B.verifySchnorr(R,N,t):!1}catch{return!1}}function V(n,e){const t=(n&7)<<5,r=typeof e=="bigint"?e:BigInt(e);if(r<0n)throw new Error("cborHead: negative argument");if(r<24n)return new Uint8Array([t|Number(r)]);if(r<0x100n)return new Uint8Array([t|24,Number(r)]);if(r<0x10000n){const i=Number(r);return new Uint8Array([t|25,i>>>8&255,i&255])}if(r<0x100000000n){const i=Number(r);return new Uint8Array([t|26,i>>>24&255,i>>>16&255,i>>>8&255,i&255])}const s=new Uint8Array(9);s[0]=t|27;for(let i=7;i>=0;i--)s[1+i]=Number(r>>BigInt((7-i)*8))&255;return s}function ie(...n){const e=n.reduce((s,i)=>s+i.length,0),t=new Uint8Array(e);let r=0;for(const s of n)t.set(s,r),r+=s.length;return t}function H(n){const t=[V(4,n.length)];for(const r of n)t.push(V(0,r));return ie(...t)}function Oe(n,e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`encodeServerIdentityPayload: expires_at must be a non-negative safe integer, got ${t}`);const r=V(4,3),s=H(n),i=H(e),c=V(0,t);return ie(r,s,i,c)}const Fe=new TextEncoder().encode("btc-auth.server-identity.v1");class u extends Error{constructor(e,t){super(e),this.reason=t,this.name="ServerIdentityError"}}function v(n){const e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function se(n){const{proof:e,pinnedServerPubkey:t,now:r}=n,s=p.stripHexPrefix(t).toLowerCase();if(s.length!==p.X_ONLY_PUBKEY_HEX_LEN||!h.HEX_RE.test(s))throw new u(`pinnedServerPubkey must be 32-byte hex; got ${s.length} chars`,"invalid_pubkey_encoding");const i=p.stripHexPrefix(e.server_pubkey).toLowerCase();if(i.length!==p.X_ONLY_PUBKEY_HEX_LEN||!h.HEX_RE.test(i))throw new u(`server_pubkey must be 32-byte hex; got ${i.length} chars`,"invalid_pubkey_encoding");if(i!==s)throw new u(`server_pubkey does not match pinned value: expected ${s}, got ${i}`,"pinned_pubkey_mismatch");if(!Number.isSafeInteger(e.expires_at))throw new u(`expires_at must be a finite integer; got ${JSON.stringify(e.expires_at)}`,"invalid_expires_at");if(!Number.isSafeInteger(r))throw new u(`now must be a finite integer; got ${JSON.stringify(r)}`,"invalid_expires_at");if(e.expires_at<=r)throw new u(`server identity proof expired at ${e.expires_at}, now ${r}`,"expired");const c=p.stripHexPrefix(e.ephemeral_pubkey).toLowerCase();if(c.length!==p.COMPRESSED_PUBKEY_HEX_LEN||!h.HEX_RE.test(c))throw new u(`ephemeral_pubkey must be 33-byte compressed hex; got ${c.length} chars`,"invalid_ephemeral_pubkey");const m=c.slice(0,2);if(m!=="02"&&m!=="03")throw new u(`ephemeral_pubkey must be compressed (prefix 02/03); got ${m}`,"invalid_ephemeral_pubkey");const C=v(c);if(!B.isPoint(C))throw new u("ephemeral_pubkey is not a valid secp256k1 point","invalid_ephemeral_pubkey");const d=p.stripHexPrefix(e.signature).toLowerCase();if(d.length!==p.SCHNORR_SIG_HEX_LEN||!h.HEX_RE.test(d))throw new u(`signature must be 64-byte Schnorr hex; got ${d.length} chars`,"invalid_signature_encoding");const S=Oe(Fe,v(c),e.expires_at);if(!Ne(S,v(i),v(d)))throw new u("BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey","signature_verification_failed")}const K="auth_createDepositorToken",j=4102444800,Ue=30;class He{constructor(e){l(this,"client");l(this,"peginTxid");l(this,"authAnchorHex");l(this,"pinnedServerPubkey");l(this,"authGatedMethods");l(this,"refreshSkewSecs");l(this,"now");l(this,"cached",null);l(this,"inFlight",null);this.client=e.client,this.peginTxid=e.peginTxid,this.authAnchorHex=e.authAnchorHex,this.pinnedServerPubkey=e.pinnedServerPubkey,this.authGatedMethods=e.authGatedMethods,this.refreshSkewSecs=e.refreshSkewSecs??Ue,this.now=e.now??(()=>Math.floor(Date.now()/1e3))}async getToken(e){if(e===K||!this.authGatedMethods.has(e))return null;const t=this.cached;return t&&this.now()+this.refreshSkewSecs<t.expiresAt?t.token:(await this.acquireSingleFlight()).token}invalidate(){this.cached=null}acquireSingleFlight(){const e=this.inFlight;if(e)return e;const t=(async()=>{try{const r=await this.client.call(K,{pegin_txid:this.peginTxid,auth_anchor:this.authAnchorHex});if(se({proof:r.server_identity,pinnedServerPubkey:this.pinnedServerPubkey,now:this.now()}),typeof r.token!="string"||r.token.length===0)throw new Error(`VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof r.token})`);const s=this.now();if(!Number.isSafeInteger(r.expires_at)||r.expires_at<=s||r.expires_at>j)throw new Error(`VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(r.expires_at)}; must be a safe integer in (${s}, ${j}])`);const i={token:r.token,expiresAt:r.expires_at};return this.cached=i,i}finally{this.inFlight=null}})();return this.inFlight=t,t}}async function Ke(n,e){const[t,r]=await n.multicall({contracts:[{address:e,abi:_.BTCVaultRegistryABI,functionName:"protocolParams"},{address:e,abi:_.BTCVaultRegistryABI,functionName:"applicationRegistry"}],allowFailure:!1});return{protocolParams:t,applicationRegistry:r}}const D=65535;function k(n){return{timelockAssert:n.timelockAssert,timelockChallengeAssert:n.timelockChallengeAssert,securityCouncilKeys:[...n.securityCouncilKeys],councilQuorum:n.councilQuorum,feeRate:n.feeRate,babeTotalInstances:n.babeTotalInstances,babeInstancesToFinalize:n.babeInstancesToFinalize,minVpCommissionBps:n.minVpCommissionBps,tRefund:n.tRefund,tStale:n.tStale,minPeginFeeRate:n.minPeginFeeRate,proverProgramVersion:n.proverProgramVersion,minPrepeginDepth:n.minPrepeginDepth}}function M(n){return{minimumPegInAmount:n.minimumPegInAmount,maxPegInAmount:n.maxPegInAmount,pegInAckTimeout:n.pegInAckTimeout,pegInActivationTimeout:n.pegInActivationTimeout,maxHtlcOutputCount:n.maxHtlcOutputCount}}function X(n){if(n>BigInt(D))throw new Error(`timelockAssert value ${n} exceeds uint16 max (${D})`);return Number(n)}class je{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getTBVProtocolParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getTBVProtocolParams"});return M(e)}async getLatestOffchainParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getLatestOffchainParams"});return k(e)}async getOffchainParamsByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getOffchainParamsByVersion",args:[e]});return k(t)}async getLatestOffchainParamsVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"latestOffchainParamsVersion"})}async getTimelockPeginByVersion(e){const t=await this.getOffchainParamsByVersion(e);return X(t.timelockAssert)}async getPegInConfiguration(){const e=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:f,functionName:"getTBVProtocolParams"},{address:this.contractAddress,abi:f,functionName:"getLatestOffchainParams"}],allowFailure:!1}),t=M(e[0]),r=k(e[1]);return{minimumPegInAmount:t.minimumPegInAmount,maxPegInAmount:t.maxPegInAmount,pegInAckTimeout:t.pegInAckTimeout,pegInActivationTimeout:t.pegInActivationTimeout,maxHtlcOutputCount:t.maxHtlcOutputCount,timelockPegin:X(r.timelockAssert),timelockRefund:r.tRefund,minVpCommissionBps:r.minVpCommissionBps,offchainParams:r}}}function E(n){return n.map(e=>({ethAddress:e.ethAddress,btcPubKey:e.btcPubKey}))}class De{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getVaultKeepersByVersion(e,t){const r=await this.publicClient.readContract({address:this.contractAddress,abi:T,functionName:"getVaultKeepersByVersion",args:[e,t]});return E(r)}async getCurrentVaultKeepers(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:T,functionName:"getCurrentVaultKeepers",args:[e]});return E(t)}async getCurrentVaultKeepersVersion(e){return await this.publicClient.readContract({address:this.contractAddress,abi:T,functionName:"getCurrentVaultKeepersVersion",args:[e]})}}class Me{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getUniversalChallengersByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getUniversalChallengersByVersion",args:[e]});return E(t)}async getCurrentUniversalChallengers(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getCurrentUniversalChallengers"});return E(e)}async getLatestUniversalChallengersVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"latestUniversalChallengersVersion"})}}class Xe{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getVaultBasicInfo(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:_.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]});return{depositor:t.depositor,depositorBtcPubKey:t.depositorBtcPubKey,amount:t.amount,vaultProvider:t.vaultProvider,status:t.status,applicationEntryPoint:t.applicationEntryPoint,createdAt:t.createdAt}}async getVaultProtocolInfo(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:_.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return{depositorSignedPeginTx:t.depositorSignedPeginTx,universalChallengersVersion:t.universalChallengersVersion,appVaultKeepersVersion:t.appVaultKeepersVersion,offchainParamsVersion:t.offchainParamsVersion,verifiedAt:t.verifiedAt,depositorWotsPkHash:t.depositorWotsPkHash,hashlock:t.hashlock,htlcVout:t.htlcVout,depositorPopSignature:t.depositorPopSignature,prePeginTxHash:t.prePeginTxHash,vaultProviderCommissionBps:t.vaultProviderCommissionBps}}async getVaultData(e){const[t,r]=await Promise.all([this.getVaultBasicInfo(e),this.getVaultProtocolInfo(e)]);if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e} not found on-chain or has no pegin transaction`);return{basic:t,protocol:r}}}exports.ApplicationRegistryABI=T;exports.MEMPOOL_API_URLS=J;exports.ProtocolParamsABI=f;exports.ServerIdentityError=u;exports.VaultProviderRpcClient=Ce;exports.ViemProtocolParamsReader=je;exports.ViemUniversalChallengerReader=Me;exports.ViemVaultKeeperReader=De;exports.ViemVaultRegistryReader=Xe;exports.VpResponseValidationError=a;exports.VpTokenProvider=He;exports.getAddressTxs=ge;exports.getAddressUtxos=he;exports.getMempoolApiUrl=ye;exports.getNetworkFees=_e;exports.getTxHex=fe;exports.getTxInfo=z;exports.getUtxoInfo=me;exports.pushTx=de;exports.resolveProtocolAddresses=Ke;exports.validateRequestDepositorClaimerArtifactsResponse=te;exports.verifyServerIdentity=se;
|
|
2
|
+
//# sourceMappingURL=vault-registry-reader-BBS1_AON.cjs.map
|