@babylonlabs-io/ts-sdk 0.17.1 → 0.18.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.
Files changed (36) hide show
  1. package/dist/{errors-DKLboMnq.cjs → errors-DAKpPfl7.cjs} +2 -2
  2. package/dist/{errors-DKLboMnq.cjs.map → errors-DAKpPfl7.cjs.map} +1 -1
  3. package/dist/{errors-KY63mgWT.js → errors-DARTQrP3.js} +2 -2
  4. package/dist/{errors-KY63mgWT.js.map → errors-DARTQrP3.js.map} +1 -1
  5. package/dist/index-DKfhZvdn.cjs +2 -0
  6. package/dist/index-DKfhZvdn.cjs.map +1 -0
  7. package/dist/{index-Dw7FAwne.js → index-qIcjkxLw.js} +135 -137
  8. package/dist/index-qIcjkxLw.js.map +1 -0
  9. package/dist/index.cjs +1 -1
  10. package/dist/index.js +2 -2
  11. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
  12. package/dist/tbv/core/clients/index.cjs +1 -1
  13. package/dist/tbv/core/clients/index.js +1 -1
  14. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +54 -0
  15. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
  16. package/dist/tbv/core/index.cjs +1 -1
  17. package/dist/tbv/core/index.js +2 -2
  18. package/dist/tbv/index.cjs +1 -1
  19. package/dist/tbv/index.js +2 -2
  20. package/dist/tbv/integrations/aave/clients/abis/AaveSpoke.abi.json.d.ts +140 -0
  21. package/dist/tbv/integrations/aave/clients/index.d.ts +1 -1
  22. package/dist/tbv/integrations/aave/clients/index.d.ts.map +1 -1
  23. package/dist/tbv/integrations/aave/clients/query.d.ts +12 -1
  24. package/dist/tbv/integrations/aave/clients/query.d.ts.map +1 -1
  25. package/dist/tbv/integrations/aave/index.cjs +1 -1
  26. package/dist/tbv/integrations/aave/index.cjs.map +1 -1
  27. package/dist/tbv/integrations/aave/index.d.ts +2 -2
  28. package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
  29. package/dist/tbv/integrations/aave/index.js +141 -129
  30. package/dist/tbv/integrations/aave/index.js.map +1 -1
  31. package/dist/tbv/integrations/aave/types.d.ts +10 -0
  32. package/dist/tbv/integrations/aave/types.d.ts.map +1 -1
  33. package/package.json +1 -1
  34. package/dist/index-D3z3SZAj.cjs +0 -2
  35. package/dist/index-D3z3SZAj.cjs.map +0 -1
  36. package/dist/index-Dw7FAwne.js.map +0 -1
@@ -1,8 +1,8 @@
1
- var V = Object.defineProperty;
2
- var E = (n, t, e) => t in n ? V(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
- var g = (n, t, e) => E(n, typeof t != "symbol" ? t + "" : t, e);
4
- import { D as A, J as I } from "./types-D1rYwwCu.js";
5
- const S = 21e6 * 1e8, m = 3e4;
1
+ var E = Object.defineProperty;
2
+ var A = (n, t, e) => t in n ? E(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
+ var g = (n, t, e) => A(n, typeof t != "symbol" ? t + "" : t, e);
4
+ import { D as I, J as S } from "./types-D1rYwwCu.js";
5
+ const F = 21e6 * 1e8, m = 3e4;
6
6
  async function d(n, t) {
7
7
  const e = new AbortController(), r = setTimeout(
8
8
  () => e.abort(),
@@ -21,17 +21,17 @@ async function d(n, t) {
21
21
  ) : s;
22
22
  }
23
23
  }
24
- const w = 1e4;
25
- function P(n) {
26
- return Number.isInteger(n) && n > 0 && n <= S;
24
+ const P = 1e4;
25
+ function v(n) {
26
+ return Number.isInteger(n) && n > 0 && n <= F;
27
27
  }
28
- function F(n) {
29
- return Number.isInteger(n) && n > 0 && n <= w;
28
+ function k(n) {
29
+ return Number.isInteger(n) && n > 0 && n <= P;
30
30
  }
31
- function v(n, t) {
31
+ function T(n, t) {
32
32
  return !Number.isInteger(n) || n < 0 ? !1 : t === void 0 || n < t;
33
33
  }
34
- const k = {
34
+ const j = {
35
35
  mainnet: "https://mempool.space/api",
36
36
  testnet: "https://mempool.space/testnet/api",
37
37
  signet: "https://mempool.space/signet/api"
@@ -51,7 +51,7 @@ async function c(n, t) {
51
51
  throw e instanceof Error ? new Error(`Failed to fetch from mempool API: ${e.message}`) : new Error("Failed to fetch from mempool API: Unknown error");
52
52
  }
53
53
  }
54
- async function z(n, t) {
54
+ async function Y(n, t) {
55
55
  try {
56
56
  const e = await d(`${t}/tx`, {
57
57
  method: "POST",
@@ -77,10 +77,10 @@ async function z(n, t) {
77
77
  throw e instanceof Error ? new Error(`Failed to broadcast BTC transaction: ${e.message}`) : new Error("Failed to broadcast BTC transaction: Unknown error");
78
78
  }
79
79
  }
80
- async function j(n, t) {
80
+ async function B(n, t) {
81
81
  return c(`${t}/tx/${n}`);
82
82
  }
83
- async function Q(n, t) {
83
+ async function z(n, t) {
84
84
  try {
85
85
  const e = await d(`${t}/tx/${n}/hex`);
86
86
  if (!e.ok) {
@@ -94,14 +94,14 @@ async function Q(n, t) {
94
94
  throw e instanceof Error ? new Error(`Failed to get transaction hex for ${n}: ${e.message}`) : new Error(`Failed to get transaction hex for ${n}: Unknown error`);
95
95
  }
96
96
  }
97
- async function Z(n, t, e) {
98
- const r = await j(n, e);
99
- if (!v(t, r.vout.length))
97
+ async function Q(n, t, e) {
98
+ const r = await B(n, e);
99
+ if (!T(t, r.vout.length))
100
100
  throw new Error(
101
101
  `Invalid vout ${t} for transaction ${n} (has ${r.vout.length} outputs)`
102
102
  );
103
103
  const o = r.vout[t];
104
- if (!P(o.value))
104
+ if (!v(o.value))
105
105
  throw new Error(`Invalid UTXO value ${o.value} for ${n}:${t}`);
106
106
  return {
107
107
  txid: n,
@@ -110,7 +110,7 @@ async function Z(n, t, e) {
110
110
  scriptPubKey: o.scriptpubkey
111
111
  };
112
112
  }
113
- async function ee(n, t) {
113
+ async function Z(n, t) {
114
114
  try {
115
115
  const e = await c(`${t}/address/${n}/utxo`), r = await c(`${t}/v1/validate-address/${n}`);
116
116
  if (!r.isvalid)
@@ -118,9 +118,9 @@ async function ee(n, t) {
118
118
  `Invalid Bitcoin address: ${n}. Mempool API validation failed.`
119
119
  );
120
120
  for (const s of e) {
121
- if (!v(s.vout))
121
+ if (!T(s.vout))
122
122
  throw new Error(`Invalid vout ${s.vout} for ${s.txid}`);
123
- if (!P(s.value))
123
+ if (!v(s.value))
124
124
  throw new Error(
125
125
  `Invalid UTXO value ${s.value} for ${s.txid}:${s.vout}`
126
126
  );
@@ -140,13 +140,13 @@ async function ee(n, t) {
140
140
  );
141
141
  }
142
142
  }
143
- function te(n) {
144
- return k[n];
143
+ function ee(n) {
144
+ return j[n];
145
145
  }
146
- async function ne(n, t) {
146
+ async function te(n, t) {
147
147
  return c(`${t}/address/${n}/txs`);
148
148
  }
149
- async function re(n) {
149
+ async function ne(n) {
150
150
  const t = await d(`${n}/v1/fees/recommended`);
151
151
  if (!t.ok)
152
152
  throw new Error(
@@ -160,9 +160,9 @@ async function re(n) {
160
160
  "minimumFee"
161
161
  ];
162
162
  for (const o of r)
163
- if (!F(e[o]))
163
+ if (!k(e[o]))
164
164
  throw new Error(
165
- `Invalid fee rate ${o}=${e[o]} from mempool API: expected a positive number ≤ ${w}`
165
+ `Invalid fee rate ${o}=${e[o]} from mempool API: expected a positive number ≤ ${P}`
166
166
  );
167
167
  if (e.minimumFee > e.economyFee || e.economyFee > e.hourFee || e.hourFee > e.halfHourFee || e.halfHourFee > e.fastestFee)
168
168
  throw new Error(
@@ -170,7 +170,7 @@ async function re(n) {
170
170
  );
171
171
  return e;
172
172
  }
173
- const B = [
173
+ const h = [
174
174
  {
175
175
  type: "function",
176
176
  name: "submitPeginRequest",
@@ -445,8 +445,77 @@ const B = [
445
445
  type: "error",
446
446
  name: "PeginSignaturesIncomplete",
447
447
  inputs: []
448
+ },
449
+ {
450
+ type: "function",
451
+ name: "getBtcVaultProtocolInfo",
452
+ inputs: [
453
+ {
454
+ name: "vaultId",
455
+ type: "bytes32",
456
+ internalType: "bytes32"
457
+ }
458
+ ],
459
+ outputs: [
460
+ {
461
+ name: "depositorSignedPeginTx",
462
+ type: "bytes",
463
+ internalType: "bytes"
464
+ },
465
+ {
466
+ name: "universalChallengersVersion",
467
+ type: "uint32",
468
+ internalType: "uint32"
469
+ },
470
+ {
471
+ name: "appVaultKeepersVersion",
472
+ type: "uint32",
473
+ internalType: "uint32"
474
+ },
475
+ {
476
+ name: "offchainParamsVersion",
477
+ type: "uint32",
478
+ internalType: "uint32"
479
+ },
480
+ {
481
+ name: "verifiedAt",
482
+ type: "uint256",
483
+ internalType: "uint256"
484
+ },
485
+ {
486
+ name: "depositorWotsPkHash",
487
+ type: "bytes32",
488
+ internalType: "bytes32"
489
+ },
490
+ {
491
+ name: "hashlock",
492
+ type: "bytes32",
493
+ internalType: "bytes32"
494
+ },
495
+ {
496
+ name: "htlcVout",
497
+ type: "uint8",
498
+ internalType: "uint8"
499
+ },
500
+ {
501
+ name: "depositorPopSignature",
502
+ type: "bytes",
503
+ internalType: "bytes"
504
+ },
505
+ {
506
+ name: "prePeginTxHash",
507
+ type: "bytes32",
508
+ internalType: "bytes32"
509
+ },
510
+ {
511
+ name: "vaultProviderCommissionBps",
512
+ type: "uint16",
513
+ internalType: "uint16"
514
+ }
515
+ ],
516
+ stateMutability: "view"
448
517
  }
449
- ], h = new Set(Object.values(A)), C = 200;
518
+ ], b = new Set(Object.values(I)), C = 200;
450
519
  function i(n) {
451
520
  var t;
452
521
  return ((t = JSON.stringify(n)) == null ? void 0 : t.slice(0, C)) ?? "undefined";
@@ -459,29 +528,29 @@ class a extends Error {
459
528
  this.name = "VpResponseValidationError", this.detail = e;
460
529
  }
461
530
  }
462
- const D = /^[0-9a-fA-F]+$/, b = 64, _ = 66, y = 64;
531
+ const D = /^[0-9a-fA-F]+$/, _ = 64, w = 66, y = 64;
463
532
  function p(n) {
464
533
  return typeof n == "string" && n.length > 0 && D.test(n);
465
534
  }
466
- function T(n) {
535
+ function x(n) {
467
536
  return typeof n == "string" && n.length > 0;
468
537
  }
469
- function x(n, t) {
538
+ function $(n, t) {
470
539
  if (!p(n))
471
540
  throw new a(
472
541
  `VP response validation failed: "${t}" must be a non-empty hex string, got ${i(n)}`
473
542
  );
474
543
  }
475
544
  function u(n, t) {
476
- if (!T(n))
545
+ if (!x(n))
477
546
  throw new a(
478
547
  `VP response validation failed: "${t}" must be a non-empty string, got ${i(n)}`
479
548
  );
480
549
  }
481
- function $(n, t) {
482
- if (!p(n) || n.length !== b && n.length !== _)
550
+ function V(n, t) {
551
+ if (!p(n) || n.length !== _ && n.length !== w)
483
552
  throw new a(
484
- `VP response validation failed: "${t}" must be a ${b} or ${_}-char hex string (BTC pubkey), got ${i(n)}`
553
+ `VP response validation failed: "${t}" must be a ${_} or ${w}-char hex string (BTC pubkey), got ${i(n)}`
485
554
  );
486
555
  }
487
556
  function M(n) {
@@ -519,9 +588,9 @@ function O(n) {
519
588
  throw new a(
520
589
  'VP response validation failed: "status" must be a string'
521
590
  );
522
- if (!h.has(t.status))
591
+ if (!b.has(t.status))
523
592
  throw new a(
524
- `VP response validation failed: unrecognized status "${t.status}". Expected one of: ${[...h].join(", ")}`
593
+ `VP response validation failed: unrecognized status "${t.status}". Expected one of: ${[...b].join(", ")}`
525
594
  );
526
595
  if (t.progress === null || typeof t.progress != "object" || Array.isArray(t.progress))
527
596
  throw new a(
@@ -536,7 +605,7 @@ function O(n) {
536
605
  `VP response validation failed: "last_error" must be a string if present, got ${i(t.last_error)}`
537
606
  );
538
607
  }
539
- function U(n) {
608
+ function H(n) {
540
609
  if (n === null || typeof n != "object")
541
610
  throw new a(
542
611
  "VP response validation failed: requestDepositorPresignTransactions response is not an object"
@@ -547,7 +616,7 @@ function U(n) {
547
616
  'VP response validation failed: "txs" must be an array'
548
617
  );
549
618
  for (let e = 0; e < t.txs.length; e++)
550
- H(t.txs[e], `txs[${e}]`);
619
+ U(t.txs[e], `txs[${e}]`);
551
620
  if (t.depositor_graph === null || typeof t.depositor_graph != "object")
552
621
  throw new a(
553
622
  'VP response validation failed: "depositor_graph" must be an object'
@@ -561,15 +630,15 @@ function l(n, t) {
561
630
  throw new a(
562
631
  `VP response validation failed: "${t}" must be an object`
563
632
  );
564
- x(n.tx_hex, `${t}.tx_hex`);
633
+ $(n.tx_hex, `${t}.tx_hex`);
565
634
  }
566
- function H(n, t) {
635
+ function U(n, t) {
567
636
  if (n === null || typeof n != "object")
568
637
  throw new a(
569
638
  `VP response validation failed: "${t}" must be an object`
570
639
  );
571
640
  const e = n;
572
- $(e.claimer_pubkey, `${t}.claimer_pubkey`), l(e.claim_tx, `${t}.claim_tx`), l(e.assert_tx, `${t}.assert_tx`), l(e.payout_tx, `${t}.payout_tx`), u(e.payout_psbt, `${t}.payout_psbt`);
641
+ V(e.claimer_pubkey, `${t}.claimer_pubkey`), l(e.claim_tx, `${t}.claim_tx`), l(e.assert_tx, `${t}.assert_tx`), l(e.payout_tx, `${t}.payout_tx`), u(e.payout_psbt, `${t}.payout_psbt`);
573
642
  }
574
643
  function N(n, t) {
575
644
  if (n === null || typeof n != "object")
@@ -585,7 +654,7 @@ function q(n, t) {
585
654
  `VP response validation failed: "${t}" must be an object`
586
655
  );
587
656
  const e = n;
588
- if ($(e.challenger_pubkey, `${t}.challenger_pubkey`), l(
657
+ if (V(e.challenger_pubkey, `${t}.challenger_pubkey`), l(
589
658
  e.challenge_assert_x_tx,
590
659
  `${t}.challenge_assert_x_tx`
591
660
  ), l(
@@ -605,7 +674,7 @@ function q(n, t) {
605
674
  `VP response validation failed: "${t}.output_label_hashes" must be an array`
606
675
  );
607
676
  for (let r = 0; r < e.output_label_hashes.length; r++)
608
- x(
677
+ $(
609
678
  e.output_label_hashes[r],
610
679
  `${t}.output_label_hashes[${r}]`
611
680
  );
@@ -616,7 +685,7 @@ function X(n) {
616
685
  "VP response validation failed: requestDepositorClaimerArtifacts response is not an object"
617
686
  );
618
687
  const t = n;
619
- if (!T(t.tx_graph_json))
688
+ if (!x(t.tx_graph_json))
620
689
  throw new a(
621
690
  `VP response validation failed: "tx_graph_json" must be a non-empty string, got ${i(t.tx_graph_json)}`
622
691
  );
@@ -699,7 +768,7 @@ function L(n) {
699
768
  );
700
769
  }
701
770
  const W = 6e4;
702
- class ae {
771
+ class re {
703
772
  constructor(t, e) {
704
773
  g(this, "client");
705
774
  const r = {
@@ -710,7 +779,7 @@ class ae {
710
779
  retryableFor: e == null ? void 0 : e.retryableFor,
711
780
  headers: e == null ? void 0 : e.headers
712
781
  };
713
- this.client = new I(r);
782
+ this.client = new S(r);
714
783
  }
715
784
  /**
716
785
  * Request the payout/claim/assert transactions that the depositor
@@ -718,7 +787,7 @@ class ae {
718
787
  */
719
788
  async requestDepositorPresignTransactions(t, e) {
720
789
  const r = await this.client.call("vaultProvider_requestDepositorPresignTransactions", t, e);
721
- return U(r), r;
790
+ return H(r), r;
722
791
  }
723
792
  /**
724
793
  * Submit the depositor's pre-signatures for the payout transactions
@@ -770,85 +839,14 @@ class ae {
770
839
  return K(r), r;
771
840
  }
772
841
  }
773
- const J = [
774
- {
775
- type: "function",
776
- name: "getBtcVaultProtocolInfo",
777
- inputs: [
778
- {
779
- name: "vaultId",
780
- type: "bytes32",
781
- internalType: "bytes32"
782
- }
783
- ],
784
- outputs: [
785
- {
786
- name: "depositorSignedPeginTx",
787
- type: "bytes",
788
- internalType: "bytes"
789
- },
790
- {
791
- name: "universalChallengersVersion",
792
- type: "uint32",
793
- internalType: "uint32"
794
- },
795
- {
796
- name: "appVaultKeepersVersion",
797
- type: "uint32",
798
- internalType: "uint32"
799
- },
800
- {
801
- name: "offchainParamsVersion",
802
- type: "uint32",
803
- internalType: "uint32"
804
- },
805
- {
806
- name: "verifiedAt",
807
- type: "uint256",
808
- internalType: "uint256"
809
- },
810
- {
811
- name: "depositorWotsPkHash",
812
- type: "bytes32",
813
- internalType: "bytes32"
814
- },
815
- {
816
- name: "hashlock",
817
- type: "bytes32",
818
- internalType: "bytes32"
819
- },
820
- {
821
- name: "htlcVout",
822
- type: "uint8",
823
- internalType: "uint8"
824
- },
825
- {
826
- name: "depositorPopSignature",
827
- type: "bytes",
828
- internalType: "bytes"
829
- },
830
- {
831
- name: "prePeginTxHash",
832
- type: "bytes32",
833
- internalType: "bytes32"
834
- },
835
- {
836
- name: "vaultProviderCommissionBps",
837
- type: "uint16",
838
- internalType: "uint16"
839
- }
840
- ],
841
- stateMutability: "view"
842
- }
843
- ];
844
- class se {
842
+ class ae {
845
843
  constructor(t, e) {
846
844
  this.publicClient = t, this.contractAddress = e;
847
845
  }
848
846
  async getVaultBasicInfo(t) {
849
847
  const e = await this.publicClient.readContract({
850
848
  address: this.contractAddress,
851
- abi: B,
849
+ abi: h,
852
850
  functionName: "getBtcVaultBasicInfo",
853
851
  args: [t]
854
852
  });
@@ -865,7 +863,7 @@ class se {
865
863
  async getVaultProtocolInfo(t) {
866
864
  const e = await this.publicClient.readContract({
867
865
  address: this.contractAddress,
868
- abi: J,
866
+ abi: h,
869
867
  functionName: "getBtcVaultProtocolInfo",
870
868
  args: [t]
871
869
  });
@@ -896,18 +894,18 @@ class se {
896
894
  }
897
895
  }
898
896
  export {
899
- B,
900
- k as M,
901
- ae as V,
902
- ee as a,
903
- te as b,
904
- re as c,
905
- Q as d,
906
- j as e,
907
- Z as f,
908
- ne as g,
897
+ h as B,
898
+ j as M,
899
+ re as V,
900
+ Z as a,
901
+ ee as b,
902
+ ne as c,
903
+ z as d,
904
+ B as e,
905
+ Q as f,
906
+ te as g,
909
907
  a as h,
910
- se as i,
911
- z as p
908
+ ae as i,
909
+ Y as p
912
910
  };
913
- //# sourceMappingURL=index-Dw7FAwne.js.map
911
+ //# sourceMappingURL=index-qIcjkxLw.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-qIcjkxLw.js","sources":["../src/tbv/core/clients/mempool/mempoolApi.ts","../src/tbv/core/contracts/abis/BTCVaultRegistry.abi.ts","../src/tbv/core/clients/vault-provider/validators.ts","../src/tbv/core/clients/vault-provider/api.ts","../src/tbv/core/clients/eth/vault-registry-reader.ts"],"sourcesContent":["/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport type { MempoolUTXO, NetworkFees, TxInfo, UtxoInfo } from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers\n return await fetch(url, {\n ...options,\n signal: AbortSignal.any(signals),\n });\n } catch (error) {\n clearTimeout(timeoutId);\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the hex representation of a transaction.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns The transaction hex string\n * @throws Error if the request fails or transaction is not found\n */\nexport async function getTxHex(txid: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx/${txid}/hex`);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n return await response.text();\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to get transaction hex for ${txid}: ${error.message}`);\n }\n throw new Error(`Failed to get transaction hex for ${txid}: Unknown error`);\n }\n}\n\n/**\n * Get UTXO information for a specific transaction output.\n *\n * This is used for constructing PSBTs where we need the witnessUtxo data.\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param txid - The transaction ID containing the UTXO\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns UTXO information with value and scriptPubKey\n */\nexport async function getUtxoInfo(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<UtxoInfo> {\n const txInfo = await getTxInfo(txid, apiUrl);\n\n if (!isValidVout(vout, txInfo.vout.length)) {\n throw new Error(\n `Invalid vout ${vout} for transaction ${txid} (has ${txInfo.vout.length} outputs)`,\n );\n }\n\n const output = txInfo.vout[vout];\n if (!isValidSatoshiValue(output.value)) {\n throw new Error(`Invalid UTXO value ${output.value} for ${txid}:${vout}`);\n }\n\n return {\n txid,\n vout,\n value: output.value,\n scriptPubKey: output.scriptpubkey,\n };\n}\n\n/**\n * Get all UTXOs for a Bitcoin address.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of UTXOs sorted by value (largest first)\n */\nexport async function getAddressUtxos(\n address: string,\n apiUrl: string,\n): Promise<MempoolUTXO[]> {\n try {\n // Fetch UTXOs for the address\n const utxos = await fetchApi<\n {\n txid: string;\n vout: number;\n value: number;\n status: {\n confirmed: boolean;\n };\n }[]\n >(`${apiUrl}/address/${address}/utxo`);\n\n // Fetch scriptPubKey for the address\n const addressInfo = await fetchApi<{\n isvalid: boolean;\n scriptPubKey: string;\n }>(`${apiUrl}/v1/validate-address/${address}`);\n\n if (!addressInfo.isvalid) {\n throw new Error(\n `Invalid Bitcoin address: ${address}. Mempool API validation failed.`,\n );\n }\n\n // Validate UTXO fields from the external API.\n // Note: upper-bound vout check is omitted because we don't fetch\n // full transactions here. Out-of-range indices surface downstream.\n for (const utxo of utxos) {\n if (!isValidVout(utxo.vout)) {\n throw new Error(`Invalid vout ${utxo.vout} for ${utxo.txid}`);\n }\n if (!isValidSatoshiValue(utxo.value)) {\n throw new Error(\n `Invalid UTXO value ${utxo.value} for ${utxo.txid}:${utxo.vout}`,\n );\n }\n }\n\n // Sort by value (largest first) and map to our UTXO format\n const sortedUTXOs = utxos.sort((a, b) => b.value - a.value);\n\n return sortedUTXOs.map((utxo) => ({\n txid: utxo.txid,\n vout: utxo.vout,\n value: utxo.value,\n scriptPubKey: addressInfo.scriptPubKey,\n confirmed: utxo.status.confirmed,\n }));\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(\n `Failed to get UTXOs for address ${address}: ${error.message}`,\n );\n }\n throw new Error(\n `Failed to get UTXOs for address ${address}: Unknown error`,\n );\n }\n}\n\n/**\n * Get the mempool API URL for a given network.\n *\n * @param network - Bitcoin network (mainnet, testnet, signet)\n * @returns The mempool API URL\n */\nexport function getMempoolApiUrl(\n network: \"mainnet\" | \"testnet\" | \"signet\",\n): string {\n return MEMPOOL_API_URLS[network];\n}\n\n/**\n * Transaction summary from address transactions endpoint.\n */\nexport interface AddressTx {\n txid: string;\n status: {\n confirmed: boolean;\n block_height?: number;\n };\n}\n\n/**\n * Get recent transactions for a Bitcoin address.\n *\n * Returns the last 25 confirmed transactions plus any unconfirmed (mempool) transactions.\n * This is useful for checking if a specific transaction has been broadcast.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of recent transactions\n */\nexport async function getAddressTxs(\n address: string,\n apiUrl: string,\n): Promise<AddressTx[]> {\n return fetchApi<AddressTx[]>(`${apiUrl}/address/${address}/txs`);\n}\n\n/**\n * Fetches Bitcoin network fee recommendations from mempool.space API.\n *\n * @param apiUrl - Mempool API base URL\n * @returns Fee rates in sat/vbyte for different confirmation times\n * @throws Error if request fails or returns invalid data\n *\n * @see https://mempool.space/docs/api/rest#get-recommended-fees\n */\nexport async function getNetworkFees(apiUrl: string): Promise<NetworkFees> {\n const response = await fetchWithTimeout(`${apiUrl}/v1/fees/recommended`);\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch network fees: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n\n const feeFields = [\n \"fastestFee\",\n \"halfHourFee\",\n \"hourFee\",\n \"economyFee\",\n \"minimumFee\",\n ] as const;\n\n for (const field of feeFields) {\n if (!isValidFeeRate(data[field])) {\n throw new Error(\n `Invalid fee rate ${field}=${data[field]} from mempool API: expected a positive number ≤ ${MAX_FEE_RATE}`,\n );\n }\n }\n\n if (\n data.minimumFee > data.economyFee ||\n data.economyFee > data.hourFee ||\n data.hourFee > data.halfHourFee ||\n data.halfHourFee > data.fastestFee\n ) {\n throw new Error(\n `Fee rate ordering violation from mempool API: expected ` +\n `minimumFee (${data.minimumFee}) <= economyFee (${data.economyFee}) <= ` +\n `hourFee (${data.hourFee}) <= halfHourFee (${data.halfHourFee}) <= ` +\n `fastestFee (${data.fastestFee}).`,\n );\n }\n\n return data as NetworkFees;\n}\n\n","/**\n * BTCVaultRegistry Contract ABI\n *\n * Minimal ABI containing only the functions needed by the SDK.\n * Full ABI is available in the vault service package.\n *\n * @module contracts/abis/BTCVaultRegistry\n */\n\n/**\n * Minimal ABI for BTCVaultRegistry contract.\n * Contains submitPeginRequest, submitPeginRequestBatch, activateVaultWithSecret, getPegInFee, and getBtcVaultBasicInfo.\n */\nexport const BTCVaultRegistryABI = [\n {\n type: \"function\",\n name: \"submitPeginRequest\",\n inputs: [\n {\n name: \"depositor\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"btcPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"unsignedPrePeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPayoutBtcAddress\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"submitPeginRequest\",\n inputs: [\n {\n name: \"depositor\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"btcPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"unsignedPrePeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"referralCode\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"depositorPayoutBtcAddress\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"submitPeginRequestBatch\",\n inputs: [\n { name: \"depositor\", type: \"address\", internalType: \"address\" },\n { name: \"vaultProvider\", type: \"address\", internalType: \"address\" },\n {\n name: \"requests\",\n type: \"tuple[]\",\n internalType: \"struct IBTCVaultRegistry.BatchPeginRequest[]\",\n components: [\n { name: \"depositorBtcPubKey\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"btcPopSignature\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"unsignedPrePeginTx\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"depositorSignedPeginTx\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"hashlock\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"htlcVout\", type: \"uint8\", internalType: \"uint8\" },\n { name: \"referralCode\", type: \"uint32\", internalType: \"uint32\" },\n { name: \"depositorPayoutBtcAddress\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"depositorWotsPkHash\", type: \"bytes32\", internalType: \"bytes32\" },\n ],\n },\n ],\n outputs: [\n { name: \"vaultIds\", type: \"bytes32[]\", internalType: \"bytes32[]\" },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"activateVaultWithSecret\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"s\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"activationMetadata\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"getPegInFee\",\n inputs: [\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [\n {\n name: \"totalFee\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getBtcVaultBasicInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n { name: \"depositor\", type: \"address\", internalType: \"address\" },\n { name: \"depositorBtcPubKey\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"vaultProvider\", type: \"address\", internalType: \"address\" },\n { name: \"status\", type: \"uint8\", internalType: \"enum IBTCVaultRegistry.BTCVaultStatus\" },\n { name: \"applicationEntryPoint\", type: \"address\", internalType: \"address\" },\n { name: \"createdAt\", type: \"uint256\", internalType: \"uint256\" },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"error\",\n name: \"InvalidPeginFee\",\n inputs: [\n {\n name: \"provided\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"required\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n ],\n },\n {\n type: \"error\",\n name: \"InvalidSecret\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"ActivationDeadlineExpired\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"InvalidHashlock\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"DuplicateHashlock\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"CapExceeded\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"InvalidOutputIndex\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"PeginSignaturesIncomplete\",\n inputs: [],\n },\n {\n type: \"function\",\n name: \"getBtcVaultProtocolInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"universalChallengersVersion\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"appVaultKeepersVersion\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"offchainParamsVersion\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"verifiedAt\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"prePeginTxHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"vaultProviderCommissionBps\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n ],\n stateMutability: \"view\",\n },\n] as const;\n","/**\n * Runtime validation for vault provider RPC responses.\n *\n * All VP RPC methods return untyped JSON that TypeScript generics cast without\n * inspection. These validators check the critical top-level fields and\n * security-relevant values (status, txids, pubkeys). Optional progress\n * sub-fields (gc_data, ack_collection, claimer_graphs) are NOT validated\n * since they are informational and not used for signing or transaction\n * construction. Only `progress.presigning` sub-fields are checked.\n */\n\nimport { DaemonStatus } from \"./types\";\nimport type {\n GetPeginStatusResponse,\n GetPegoutStatusResponse,\n RequestDepositorClaimerArtifactsResponse,\n RequestDepositorPresignTransactionsResponse,\n} from \"./types\";\n\nconst DAEMON_STATUS_VALUES = new Set<string>(Object.values(DaemonStatus));\n\nconst VP_ERROR_PREVIEW_MAX_LEN = 200;\n\nfunction preview(value: unknown): string {\n return (\n JSON.stringify(value)?.slice(0, VP_ERROR_PREVIEW_MAX_LEN) ?? \"undefined\"\n );\n}\n\nconst VP_VALIDATION_USER_MESSAGE =\n \"The vault provider returned an unexpected response. Please try again or contact support.\";\n\n/**\n * Thrown when a VP RPC response fails runtime validation.\n *\n * `.message` is a user-facing string safe to display in the UI.\n * `.detail` contains the technical reason, suitable for logging.\n */\nexport class VpResponseValidationError extends Error {\n readonly detail: string;\n\n constructor(detail: string) {\n super(VP_VALIDATION_USER_MESSAGE);\n this.name = \"VpResponseValidationError\";\n this.detail = detail;\n }\n}\n\n/** Non-empty string of hexadecimal characters (case-insensitive). */\nconst HEX_RE = /^[0-9a-fA-F]+$/;\n\n/** Expected length (in hex chars) of an x-only Bitcoin public key (32 bytes). */\nconst X_ONLY_PUBKEY_HEX_LEN = 64;\n/** Expected length (in hex chars) of a compressed Bitcoin public key (33 bytes). */\nconst COMPRESSED_PUBKEY_HEX_LEN = 66;\n\n/** Expected length (in hex chars) of a Bitcoin transaction ID (32 bytes). */\nconst TXID_HEX_LEN = 64;\n\nfunction isNonEmptyHex(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0 && HEX_RE.test(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\nfunction assertNonEmptyHex(value: unknown, field: string): void {\n if (!isNonEmptyHex(value)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a non-empty hex string, got ${preview(value)}`,\n );\n }\n}\n\nfunction assertNonEmptyString(value: unknown, field: string): void {\n if (!isNonEmptyString(value)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a non-empty string, got ${preview(value)}`,\n );\n }\n}\n\n/**\n * Accept both x-only (64-char) and compressed (66-char) pubkeys from VP responses.\n * The signing code normalizes to x-only via processPublicKeyToXOnly().\n */\nfunction assertBtcPubkey(value: unknown, field: string): void {\n if (\n !isNonEmptyHex(value) ||\n (value.length !== X_ONLY_PUBKEY_HEX_LEN &&\n value.length !== COMPRESSED_PUBKEY_HEX_LEN)\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a ${X_ONLY_PUBKEY_HEX_LEN} or ${COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${preview(value)}`,\n );\n }\n}\n\n/**\n * Validate the optional presigning progress fields returned inside PeginProgressDetails.\n */\nfunction validatePresigningProgressFields(\n progress: Record<string, unknown>,\n): void {\n const presigning = progress.presigning;\n if (presigning === undefined || presigning === null) return;\n if (typeof presigning !== \"object\" || Array.isArray(presigning)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning\" must be an object if present`,\n );\n }\n\n const p = presigning as Record<string, unknown>;\n\n if (\n p.depositor_graph_created !== undefined &&\n typeof p.depositor_graph_created !== \"boolean\"\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning.depositor_graph_created\" must be a boolean if present, got ${preview(p.depositor_graph_created)}`,\n );\n }\n\n if (\n p.vk_challenger_presigning_completed !== undefined &&\n typeof p.vk_challenger_presigning_completed !== \"number\"\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning.vk_challenger_presigning_completed\" must be a number if present, got ${preview(p.vk_challenger_presigning_completed)}`,\n );\n }\n\n if (\n p.vk_challenger_presigning_total !== undefined &&\n typeof p.vk_challenger_presigning_total !== \"number\"\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning.vk_challenger_presigning_total\" must be a number if present, got ${preview(p.vk_challenger_presigning_total)}`,\n );\n }\n}\n\n/**\n * Validate a getPeginStatus response.\n *\n * Throws if the status field is not a recognized DaemonStatus value.\n */\nexport function validateGetPeginStatusResponse(\n response: unknown,\n): asserts response is GetPeginStatusResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: getPeginStatus response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!isNonEmptyHex(r.pegin_txid) || r.pegin_txid.length !== TXID_HEX_LEN) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"pegin_txid\" must be a ${TXID_HEX_LEN}-char hex string (txid), got ${preview(r.pegin_txid)}`,\n );\n }\n\n if (typeof r.status !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"status\" must be a string`,\n );\n }\n\n if (!DAEMON_STATUS_VALUES.has(r.status)) {\n throw new VpResponseValidationError(\n `VP response validation failed: unrecognized status \"${r.status}\". Expected one of: ${[...DAEMON_STATUS_VALUES].join(\", \")}`,\n );\n }\n\n if (\n r.progress === null ||\n typeof r.progress !== \"object\" ||\n Array.isArray(r.progress)\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress\" must be an object`,\n );\n }\n\n validatePresigningProgressFields(r.progress as Record<string, unknown>);\n\n if (typeof r.health_info !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"health_info\" must be a string`,\n );\n }\n\n if (r.last_error !== undefined && typeof r.last_error !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"last_error\" must be a string if present, got ${preview(r.last_error)}`,\n );\n }\n}\n\n/**\n * Validate a requestDepositorPresignTransactions response.\n */\nexport function validateRequestDepositorPresignTransactionsResponse(\n response: unknown,\n): asserts response is RequestDepositorPresignTransactionsResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: requestDepositorPresignTransactions response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!Array.isArray(r.txs)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"txs\" must be an array`,\n );\n }\n\n for (let i = 0; i < r.txs.length; i++) {\n validateClaimerTransactions(r.txs[i], `txs[${i}]`);\n }\n\n if (r.depositor_graph === null || typeof r.depositor_graph !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"depositor_graph\" must be an object`,\n );\n }\n\n validateDepositorGraphTransactions(\n r.depositor_graph as Record<string, unknown>,\n );\n}\n\nfunction validateTransactionData(value: unknown, field: string): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n const tx = value as Record<string, unknown>;\n assertNonEmptyHex(tx.tx_hex, `${field}.tx_hex`);\n}\n\nfunction validateClaimerTransactions(value: unknown, field: string): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n\n const tx = value as Record<string, unknown>;\n\n assertBtcPubkey(tx.claimer_pubkey, `${field}.claimer_pubkey`);\n validateTransactionData(tx.claim_tx, `${field}.claim_tx`);\n validateTransactionData(tx.assert_tx, `${field}.assert_tx`);\n validateTransactionData(tx.payout_tx, `${field}.payout_tx`);\n assertNonEmptyString(tx.payout_psbt, `${field}.payout_psbt`);\n}\n\nfunction validateChallengeAssertConnectorData(\n value: unknown,\n field: string,\n): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n\n const c = value as Record<string, unknown>;\n assertNonEmptyString(c.wots_pks_json, `${field}.wots_pks_json`);\n assertNonEmptyString(c.gc_wots_keys_json, `${field}.gc_wots_keys_json`);\n}\n\nfunction validatePresignDataPerChallenger(value: unknown, field: string): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n\n const d = value as Record<string, unknown>;\n\n assertBtcPubkey(d.challenger_pubkey, `${field}.challenger_pubkey`);\n validateTransactionData(\n d.challenge_assert_x_tx,\n `${field}.challenge_assert_x_tx`,\n );\n validateTransactionData(\n d.challenge_assert_y_tx,\n `${field}.challenge_assert_y_tx`,\n );\n validateTransactionData(d.nopayout_tx, `${field}.nopayout_tx`);\n assertNonEmptyString(d.nopayout_psbt, `${field}.nopayout_psbt`);\n\n if (!Array.isArray(d.challenge_assert_connectors)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}.challenge_assert_connectors\" must be an array`,\n );\n }\n\n for (let i = 0; i < d.challenge_assert_connectors.length; i++) {\n validateChallengeAssertConnectorData(\n d.challenge_assert_connectors[i],\n `${field}.challenge_assert_connectors[${i}]`,\n );\n }\n\n if (!Array.isArray(d.output_label_hashes)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}.output_label_hashes\" must be an array`,\n );\n }\n\n for (let i = 0; i < d.output_label_hashes.length; i++) {\n assertNonEmptyHex(\n d.output_label_hashes[i],\n `${field}.output_label_hashes[${i}]`,\n );\n }\n}\n\n/**\n * Validate a requestDepositorClaimerArtifacts response.\n */\nexport function validateRequestDepositorClaimerArtifactsResponse(\n response: unknown,\n): asserts response is RequestDepositorClaimerArtifactsResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: requestDepositorClaimerArtifacts response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!isNonEmptyString(r.tx_graph_json)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"tx_graph_json\" must be a non-empty string, got ${preview(r.tx_graph_json)}`,\n );\n }\n\n if (!isNonEmptyHex(r.verifying_key_hex)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"verifying_key_hex\" must be a non-empty hex string, got ${preview(r.verifying_key_hex)}`,\n );\n }\n\n if (r.babe_sessions === null || typeof r.babe_sessions !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions\" must be an object`,\n );\n }\n\n for (const [key, session] of Object.entries(\n r.babe_sessions as Record<string, unknown>,\n )) {\n if (session === null || typeof session !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions.${key}\" must be an object`,\n );\n }\n const s = session as Record<string, unknown>;\n if (!isNonEmptyHex(s.decryptor_artifacts_hex)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions.${key}.decryptor_artifacts_hex\" must be a non-empty hex string, got ${preview(s.decryptor_artifacts_hex)}`,\n );\n }\n }\n}\n\n/**\n * Validate a getPegoutStatus response.\n */\nexport function validateGetPegoutStatusResponse(\n response: unknown,\n): asserts response is GetPegoutStatusResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: getPegoutStatus response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!isNonEmptyHex(r.pegin_txid) || r.pegin_txid.length !== TXID_HEX_LEN) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"pegin_txid\" must be a ${TXID_HEX_LEN}-char hex string (txid), got ${preview(r.pegin_txid)}`,\n );\n }\n\n if (typeof r.found !== \"boolean\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"found\" must be a boolean, got ${preview(r.found)}`,\n );\n }\n\n if (r.claimer !== undefined) {\n if (r.claimer === null || typeof r.claimer !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer\" must be an object if present`,\n );\n }\n const claimer = r.claimer as Record<string, unknown>;\n if (typeof claimer.status !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer.status\" must be a string, got ${preview(claimer.status)}`,\n );\n }\n if (typeof claimer.failed !== \"boolean\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer.failed\" must be a boolean, got ${preview(claimer.failed)}`,\n );\n }\n }\n\n if (r.challenger !== undefined) {\n if (r.challenger === null || typeof r.challenger !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"challenger\" must be an object if present`,\n );\n }\n const challenger = r.challenger as Record<string, unknown>;\n if (typeof challenger.status !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"challenger.status\" must be a string, got ${preview(challenger.status)}`,\n );\n }\n }\n}\n\nfunction validateDepositorGraphTransactions(\n graph: Record<string, unknown>,\n): void {\n validateTransactionData(graph.claim_tx, \"depositor_graph.claim_tx\");\n validateTransactionData(graph.assert_tx, \"depositor_graph.assert_tx\");\n validateTransactionData(graph.payout_tx, \"depositor_graph.payout_tx\");\n assertNonEmptyString(graph.payout_psbt, \"depositor_graph.payout_psbt\");\n\n if (!Array.isArray(graph.challenger_presign_data)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"depositor_graph.challenger_presign_data\" must be an array`,\n );\n }\n\n for (let i = 0; i < graph.challenger_presign_data.length; i++) {\n validatePresignDataPerChallenger(\n graph.challenger_presign_data[i],\n `depositor_graph.challenger_presign_data[${i}]`,\n );\n }\n\n if (typeof graph.offchain_params_version !== \"number\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"depositor_graph.offchain_params_version\" must be a number`,\n );\n }\n}\n","/**\n * JSON-RPC client for the Vault Provider API.\n *\n * Wraps {@link JsonRpcClient} with typed methods matching the\n * `vaultProvider_*` RPC namespace defined in the btc-vault pegin spec.\n *\n * Implements the narrow service interfaces (PeginStatusReader, WotsKeySubmitter,\n * PresignClient, ClaimerArtifactsReader) so it can be passed directly to\n * any deposit protocol service function.\n *\n * @see https://github.com/babylonlabs-io/btc-vault/blob/main/docs/pegin.md\n */\n\nimport type { PeginStatusReader, WotsKeySubmitter, PresignClient, ClaimerArtifactsReader } from \"../../services/deposit/interfaces\";\n\nimport { JsonRpcClient, type JsonRpcClientConfig } from \"./json-rpc-client\";\nimport type {\n GetPeginStatusParams,\n GetPeginStatusResponse,\n GetPegoutStatusParams,\n GetPegoutStatusResponse,\n RequestDepositorClaimerArtifactsParams,\n RequestDepositorClaimerArtifactsResponse,\n RequestDepositorPresignTransactionsParams,\n RequestDepositorPresignTransactionsResponse,\n SubmitDepositorPresignaturesParams,\n SubmitDepositorWotsKeyParams,\n} from \"./types\";\nimport {\n validateGetPeginStatusResponse,\n validateGetPegoutStatusResponse,\n validateRequestDepositorClaimerArtifactsResponse,\n validateRequestDepositorPresignTransactionsResponse,\n} from \"./validators\";\n\nexport interface VaultProviderRpcClientOptions {\n /** Timeout in milliseconds per request (default: 60000) */\n timeout?: number;\n /** Number of retry attempts for safe methods (default: 3) */\n retries?: number;\n /** Initial retry delay in milliseconds (default: 1000) */\n retryDelay?: number;\n /** Custom retry predicate (default: only retry get* status methods) */\n retryableFor?: (method: string) => boolean;\n /** Custom headers */\n headers?: Record<string, string>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 60_000;\n\n/**\n * Concrete VP RPC client implementing all service interfaces.\n *\n * Usage:\n * ```ts\n * const client = new VaultProviderRpcClient(\"https://vp.example.com/rpc\");\n * const status = await client.getPeginStatus({ pegin_txid: \"abc...\" });\n * ```\n */\nexport class VaultProviderRpcClient\n implements PeginStatusReader, WotsKeySubmitter, PresignClient, ClaimerArtifactsReader\n{\n private client: JsonRpcClient;\n\n constructor(baseUrl: string, options?: VaultProviderRpcClientOptions) {\n const config: JsonRpcClientConfig = {\n baseUrl,\n timeout: options?.timeout ?? DEFAULT_TIMEOUT_MS,\n retries: options?.retries,\n retryDelay: options?.retryDelay,\n retryableFor: options?.retryableFor,\n headers: options?.headers,\n };\n this.client = new JsonRpcClient(config);\n }\n\n /**\n * Request the payout/claim/assert transactions that the depositor\n * needs to pre-sign before the vault can be activated on Bitcoin.\n */\n async requestDepositorPresignTransactions(\n params: RequestDepositorPresignTransactionsParams,\n signal?: AbortSignal,\n ): Promise<RequestDepositorPresignTransactionsResponse> {\n const response = await this.client.call<\n RequestDepositorPresignTransactionsParams,\n unknown\n >(\"vaultProvider_requestDepositorPresignTransactions\", params, signal);\n validateRequestDepositorPresignTransactionsResponse(response);\n return response;\n }\n\n /**\n * Submit the depositor's pre-signatures for the payout transactions\n * and the depositor-as-claimer graph.\n */\n async submitDepositorPresignatures(\n params: SubmitDepositorPresignaturesParams,\n signal?: AbortSignal,\n ): Promise<void> {\n return this.client.call<SubmitDepositorPresignaturesParams, void>(\n \"vaultProvider_submitDepositorPresignatures\",\n params,\n signal,\n );\n }\n\n /**\n * Submit the depositor's WOTS public key to the vault provider.\n * Called after the pegin is finalized on Ethereum, when the VP is in\n * `PendingDepositorWotsPK` status.\n */\n async submitDepositorWotsKey(\n params: SubmitDepositorWotsKeyParams,\n signal?: AbortSignal,\n ): Promise<void> {\n return this.client.call<SubmitDepositorWotsKeyParams, void>(\n \"vaultProvider_submitDepositorWotsKey\",\n params,\n signal,\n );\n }\n\n /**\n * Request the BaBe DecryptorArtifacts needed for the depositor to\n * independently evaluate garbled circuits during a challenge.\n */\n async requestDepositorClaimerArtifacts(\n params: RequestDepositorClaimerArtifactsParams,\n signal?: AbortSignal,\n ): Promise<RequestDepositorClaimerArtifactsResponse> {\n const response = await this.client.call<\n RequestDepositorClaimerArtifactsParams,\n unknown\n >(\"vaultProvider_requestDepositorClaimerArtifacts\", params, signal);\n validateRequestDepositorClaimerArtifactsResponse(response);\n return response;\n }\n\n /** Get the current pegin status from the vault provider daemon. */\n async getPeginStatus(\n params: GetPeginStatusParams,\n signal?: AbortSignal,\n ): Promise<GetPeginStatusResponse> {\n const response = await this.client.call<GetPeginStatusParams, unknown>(\n \"vaultProvider_getPeginStatus\",\n params,\n signal,\n );\n validateGetPeginStatusResponse(response);\n return response;\n }\n\n /** Get the current pegout status from the vault provider daemon. */\n async getPegoutStatus(\n params: GetPegoutStatusParams,\n signal?: AbortSignal,\n ): Promise<GetPegoutStatusResponse> {\n const response = await this.client.call<GetPegoutStatusParams, unknown>(\n \"vaultProvider_getPegoutStatus\",\n params,\n signal,\n );\n validateGetPegoutStatusResponse(response);\n return response;\n }\n}\n","/**\n * Concrete BTCVaultRegistry reader using viem's readContract.\n *\n * This is an optional utility — callers can use their own implementation\n * of the VaultRegistryReader interface.\n */\n\nimport type { Address, Hex, PublicClient } from \"viem\";\n\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport type {\n VaultBasicInfo,\n VaultData,\n VaultProtocolInfo,\n VaultRegistryReader,\n} from \"./types\";\n\n/**\n * Concrete vault registry reader using viem.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultRegistryReader(publicClient, registryAddress);\n * const data = await reader.getVaultData(vaultId);\n * ```\n */\nexport class ViemVaultRegistryReader implements VaultRegistryReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n async getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as readonly [Address, Hex, bigint, Address, number, Address, bigint];\n\n return {\n depositor: result[0],\n depositorBtcPubKey: result[1],\n amount: result[2],\n vaultProvider: result[3],\n status: result[4],\n applicationEntryPoint: result[5],\n createdAt: result[6],\n };\n }\n\n async getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as readonly [\n Hex,\n number,\n number,\n number,\n bigint,\n Hex,\n Hex,\n number,\n Hex,\n Hex,\n number,\n ];\n\n return {\n depositorSignedPeginTx: result[0],\n universalChallengersVersion: result[1],\n appVaultKeepersVersion: result[2],\n offchainParamsVersion: result[3],\n verifiedAt: result[4],\n depositorWotsPkHash: result[5],\n hashlock: result[6],\n htlcVout: result[7],\n depositorPopSignature: result[8],\n prePeginTxHash: result[9],\n vaultProviderCommissionBps: result[10],\n };\n }\n\n async getVaultData(vaultId: Hex): Promise<VaultData> {\n const [basic, protocol] = await Promise.all([\n this.getVaultBasicInfo(vaultId),\n this.getVaultProtocolInfo(vaultId),\n ]);\n\n if (\n !protocol.depositorSignedPeginTx ||\n protocol.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultId} not found on-chain or has no pegin transaction`,\n );\n }\n\n return { basic, protocol };\n }\n}\n"],"names":["MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","error","MAX_FEE_RATE","isValidSatoshiValue","value","isValidFeeRate","isValidVout","vout","outputCount","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","getTxInfo","txid","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","address","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","data","feeFields","field","BTCVaultRegistryABI","DAEMON_STATUS_VALUES","DaemonStatus","VP_ERROR_PREVIEW_MAX_LEN","preview","_a","VP_VALIDATION_USER_MESSAGE","VpResponseValidationError","detail","__publicField","HEX_RE","X_ONLY_PUBKEY_HEX_LEN","COMPRESSED_PUBKEY_HEX_LEN","TXID_HEX_LEN","isNonEmptyHex","isNonEmptyString","assertNonEmptyHex","assertNonEmptyString","assertBtcPubkey","validatePresigningProgressFields","progress","presigning","p","validateGetPeginStatusResponse","r","validateRequestDepositorPresignTransactionsResponse","i","validateClaimerTransactions","validateDepositorGraphTransactions","validateTransactionData","tx","validateChallengeAssertConnectorData","c","validatePresignDataPerChallenger","d","validateRequestDepositorClaimerArtifactsResponse","key","session","s","validateGetPegoutStatusResponse","claimer","challenger","graph","DEFAULT_TIMEOUT_MS","VaultProviderRpcClient","baseUrl","config","JsonRpcClient","params","signal","ViemVaultRegistryReader","publicClient","contractAddress","vaultId","result","basic","protocol"],"mappings":";;;;AAYA,MAAMA,IAAe,OAAa,KAG5BC,IAA6B;AAMnC,eAAeC,EACbC,GACAC,GACmB;AACnB,QAAMC,IAAa,IAAI,gBAAA,GACjBC,IAAY;AAAA,IAChB,MAAMD,EAAW,MAAA;AAAA,IACjBJ;AAAA,EAAA,GAIIM,IAAU,CAACF,EAAW,QAAQD,KAAA,gBAAAA,EAAS,MAAM,EAAE;AAAA,IACnD;AAAA,EAAA;AAGF,MAAI;AAEF,WAAO,MAAM,MAAMD,GAAK;AAAA,MACtB,GAAGC;AAAA,MACH,QAAQ,YAAY,IAAIG,CAAO;AAAA,IAAA,CAChC;AAAA,EACH,SAASC,GAAO;AAEd,UADA,aAAaF,CAAS,GAEpBE,KAAS,QACT,OAAOA,KAAU,YACjB,UAAUA,KACVA,EAAM,SAAS,eAET,IAAI;AAAA,MACR,uCAAuCP,CAA0B,OAAOE,CAAG;AAAA,IAAA,IAGzEK;AAAA,EACR;AACF;AAMA,MAAMC,IAAe;AAErB,SAASC,EAAoBC,GAAwB;AACnD,SAAO,OAAO,UAAU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