@secondlayer/stacks 6.0.0 → 6.1.1

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 (217) hide show
  1. package/dist/shared/stacks-esm-0pc6tmf0.js +50 -0
  2. package/dist/shared/{stacks-qex691bh.js.map → stacks-esm-0pc6tmf0.js.map} +2 -2
  3. package/dist/shared/{stacks-qt8ehebn.js → stacks-esm-16d82wyc.js} +10 -10
  4. package/dist/shared/{stacks-qt8ehebn.js.map → stacks-esm-16d82wyc.js.map} +2 -2
  5. package/dist/shared/{stacks-qs5fzts5.js → stacks-esm-7a0ehykf.js} +43 -43
  6. package/dist/shared/{stacks-qs5fzts5.js.map → stacks-esm-7a0ehykf.js.map} +2 -2
  7. package/dist/shared/{stacks-4hs8r4q2.js → stacks-esm-7v18h5dk.js} +4 -4
  8. package/dist/shared/{stacks-xjkn3en1.cjs.map → stacks-esm-7v18h5dk.js.map} +2 -2
  9. package/dist/shared/{stacks-71k0vmct.js → stacks-esm-8f5catbf.js} +126 -126
  10. package/dist/shared/{stacks-71k0vmct.js.map → stacks-esm-8f5catbf.js.map} +2 -2
  11. package/dist/shared/{stacks-wxfd6r4b.js → stacks-esm-8jt6k8p3.js} +13 -13
  12. package/dist/shared/{stacks-wxfd6r4b.js.map → stacks-esm-8jt6k8p3.js.map} +2 -2
  13. package/dist/shared/{stacks-x0qqwrev.js → stacks-esm-a20wyky3.js} +92 -92
  14. package/dist/shared/{stacks-agk106zs.cjs.map → stacks-esm-a20wyky3.js.map} +2 -2
  15. package/dist/shared/{stacks-gjz26k6b.js → stacks-esm-b54n1jdx.js} +102 -58
  16. package/dist/shared/stacks-esm-b54n1jdx.js.map +12 -0
  17. package/dist/shared/{stacks-9c1yam8b.js → stacks-esm-cmtj5vky.js} +162 -162
  18. package/dist/shared/{stacks-9c1yam8b.js.map → stacks-esm-cmtj5vky.js.map} +2 -2
  19. package/dist/shared/{stacks-z90xdr1x.js → stacks-esm-e2qhfgke.js} +36 -36
  20. package/dist/shared/{stacks-z90xdr1x.js.map → stacks-esm-e2qhfgke.js.map} +2 -2
  21. package/dist/shared/{stacks-v03zef3g.js → stacks-esm-ea4m4bk7.js} +117 -117
  22. package/dist/shared/{stacks-v03zef3g.js.map → stacks-esm-ea4m4bk7.js.map} +2 -2
  23. package/dist/shared/{stacks-69nq48jp.js → stacks-esm-hkw1kvd4.js} +140 -140
  24. package/dist/shared/{stacks-69nq48jp.js.map → stacks-esm-hkw1kvd4.js.map} +2 -2
  25. package/dist/shared/{stacks-qcae5852.js → stacks-esm-k108pemv.js} +4 -4
  26. package/dist/shared/{stacks-qcae5852.js.map → stacks-esm-k108pemv.js.map} +2 -2
  27. package/dist/shared/stacks-esm-kbz5s6v8.js +84 -0
  28. package/dist/shared/{stacks-4d7c3x27.js.map → stacks-esm-kbz5s6v8.js.map} +2 -2
  29. package/dist/shared/{stacks-kg1npstf.js → stacks-esm-mt1thm7k.js} +9 -9
  30. package/dist/shared/{stacks-kg1npstf.js.map → stacks-esm-mt1thm7k.js.map} +2 -2
  31. package/dist/shared/{stacks-yvb7rvwk.js → stacks-esm-n1mekwnb.js} +9 -9
  32. package/dist/shared/{stacks-8vzxax5e.cjs.map → stacks-esm-n1mekwnb.js.map} +2 -2
  33. package/dist/shared/{stacks-mftyrc60.js → stacks-esm-nt5hf8ht.js} +34 -34
  34. package/dist/shared/{stacks-mftyrc60.js.map → stacks-esm-nt5hf8ht.js.map} +2 -2
  35. package/dist/shared/{stacks-51ybf135.js → stacks-esm-phgy8yqf.js} +210 -210
  36. package/dist/shared/{stacks-51ybf135.js.map → stacks-esm-phgy8yqf.js.map} +2 -2
  37. package/dist/shared/{stacks-mbt36bzt.js → stacks-esm-pxv6ny92.js} +116 -116
  38. package/dist/shared/{stacks-mbt36bzt.js.map → stacks-esm-pxv6ny92.js.map} +2 -2
  39. package/dist/shared/{stacks-8brgfvqx.js → stacks-esm-qfzxhdqz.js} +19 -19
  40. package/dist/shared/{stacks-8brgfvqx.js.map → stacks-esm-qfzxhdqz.js.map} +2 -2
  41. package/dist/shared/{stacks-fd4rx56e.js → stacks-esm-snj9s2q8.js} +43 -43
  42. package/dist/shared/{stacks-fd4rx56e.js.map → stacks-esm-snj9s2q8.js.map} +2 -2
  43. package/dist/shared/{stacks-yajyej2y.js → stacks-esm-ss9ap75h.js} +28 -28
  44. package/dist/shared/{stacks-yajyej2y.js.map → stacks-esm-ss9ap75h.js.map} +2 -2
  45. package/dist/shared/{stacks-1m3m1agc.js → stacks-esm-t88hc019.js} +18 -18
  46. package/dist/shared/{stacks-1m3m1agc.js.map → stacks-esm-t88hc019.js.map} +2 -2
  47. package/dist/shared/stacks-esm-tdrdye4y.js +48 -0
  48. package/dist/shared/{stacks-enpj9krt.cjs.map → stacks-esm-tdrdye4y.js.map} +2 -2
  49. package/dist/src/accounts/index.cjs +565 -9
  50. package/dist/src/accounts/index.cjs.map +10 -4
  51. package/dist/src/accounts/index.d.cts +1 -1
  52. package/dist/src/accounts/index.d.ts +1 -1
  53. package/dist/src/accounts/index.js +26 -26
  54. package/dist/src/accounts/index.js.map +2 -2
  55. package/dist/src/actions/index.cjs +3860 -44
  56. package/dist/src/actions/index.cjs.map +65 -3
  57. package/dist/src/actions/index.d.cts +1 -1
  58. package/dist/src/actions/index.d.ts +1 -1
  59. package/dist/src/actions/index.js +102 -103
  60. package/dist/src/actions/index.js.map +1 -1
  61. package/dist/src/bitcoin/index.cjs +2506 -31
  62. package/dist/src/bitcoin/index.cjs.map +31 -3
  63. package/dist/src/bitcoin/index.d.cts +92 -92
  64. package/dist/src/bitcoin/index.d.ts +92 -92
  65. package/dist/src/bitcoin/index.js +88 -90
  66. package/dist/src/bitcoin/index.js.map +2 -2
  67. package/dist/src/bns/index.cjs +4435 -10
  68. package/dist/src/bns/index.cjs.map +50 -3
  69. package/dist/src/bns/index.d.cts +1 -1
  70. package/dist/src/bns/index.d.ts +1 -1
  71. package/dist/src/bns/index.js +39 -41
  72. package/dist/src/bns/index.js.map +2 -2
  73. package/dist/src/chains/index.cjs +141 -5
  74. package/dist/src/chains/index.cjs.map +5 -3
  75. package/dist/src/chains/index.d.cts +1 -1
  76. package/dist/src/chains/index.d.ts +1 -1
  77. package/dist/src/chains/index.js +12 -12
  78. package/dist/src/chains/index.js.map +1 -1
  79. package/dist/src/clarity/index.cjs +2021 -1
  80. package/dist/src/clarity/index.cjs.map +24 -3
  81. package/dist/src/clarity/index.d.cts +1 -1
  82. package/dist/src/clarity/index.d.ts +1 -1
  83. package/dist/src/clarity/index.js +170 -171
  84. package/dist/src/clarity/index.js.map +1 -1
  85. package/dist/src/connect/index.cjs +19 -19
  86. package/dist/src/connect/index.cjs.map +2 -2
  87. package/dist/src/connect/index.d.cts +1 -1
  88. package/dist/src/connect/index.d.ts +1 -1
  89. package/dist/src/connect/index.js +19 -19
  90. package/dist/src/connect/index.js.map +2 -2
  91. package/dist/src/connect/walletconnect/index.cjs +6 -46
  92. package/dist/src/connect/walletconnect/index.cjs.map +3 -4
  93. package/dist/src/connect/walletconnect/index.d.cts +1 -1
  94. package/dist/src/connect/walletconnect/index.d.ts +1 -1
  95. package/dist/src/connect/walletconnect/index.js +6 -46
  96. package/dist/src/connect/walletconnect/index.js.map +3 -4
  97. package/dist/src/filters/index.cjs +727 -1
  98. package/dist/src/filters/index.cjs.map +11 -3
  99. package/dist/src/filters/index.d.cts +76 -13
  100. package/dist/src/filters/index.d.ts +76 -13
  101. package/dist/src/filters/index.js +30 -26
  102. package/dist/src/filters/index.js.map +1 -1
  103. package/dist/src/index.cjs +4000 -126
  104. package/dist/src/index.cjs.map +69 -4
  105. package/dist/src/index.d.cts +658 -607
  106. package/dist/src/index.d.ts +658 -607
  107. package/dist/src/index.js +219 -219
  108. package/dist/src/index.js.map +2 -2
  109. package/dist/src/postconditions/index.cjs +1728 -1
  110. package/dist/src/postconditions/index.cjs.map +20 -3
  111. package/dist/src/postconditions/index.d.cts +1 -1
  112. package/dist/src/postconditions/index.d.ts +1 -1
  113. package/dist/src/postconditions/index.js +16 -17
  114. package/dist/src/postconditions/index.js.map +1 -1
  115. package/dist/src/pox/index.cjs +3866 -11
  116. package/dist/src/pox/index.cjs.map +48 -3
  117. package/dist/src/pox/index.d.cts +1 -1
  118. package/dist/src/pox/index.d.ts +1 -1
  119. package/dist/src/pox/index.js +40 -41
  120. package/dist/src/pox/index.js.map +2 -2
  121. package/dist/src/pox5/index.cjs +4124 -95
  122. package/dist/src/pox5/index.cjs.map +55 -4
  123. package/dist/src/pox5/index.d.cts +9 -1
  124. package/dist/src/pox5/index.d.ts +9 -1
  125. package/dist/src/pox5/index.js +210 -209
  126. package/dist/src/pox5/index.js.map +3 -3
  127. package/dist/src/sbtc/index.cjs +3719 -16
  128. package/dist/src/sbtc/index.cjs.map +47 -3
  129. package/dist/src/sbtc/index.d.cts +1 -1
  130. package/dist/src/sbtc/index.d.ts +1 -1
  131. package/dist/src/sbtc/index.js +39 -40
  132. package/dist/src/sbtc/index.js.map +2 -2
  133. package/dist/src/simnet/index.cjs +16 -16
  134. package/dist/src/simnet/index.cjs.map +2 -2
  135. package/dist/src/simnet/index.d.cts +1 -1
  136. package/dist/src/simnet/index.d.ts +1 -1
  137. package/dist/src/simnet/index.js +16 -16
  138. package/dist/src/simnet/index.js.map +2 -2
  139. package/dist/src/stackingdao/index.cjs +3747 -3
  140. package/dist/src/stackingdao/index.cjs.map +45 -3
  141. package/dist/src/stackingdao/index.d.cts +1 -1
  142. package/dist/src/stackingdao/index.d.ts +1 -1
  143. package/dist/src/stackingdao/index.js +26 -27
  144. package/dist/src/stackingdao/index.js.map +2 -2
  145. package/dist/src/subscriptions/index.cjs +160 -6
  146. package/dist/src/subscriptions/index.cjs.map +6 -3
  147. package/dist/src/subscriptions/index.d.cts +1 -1
  148. package/dist/src/subscriptions/index.d.ts +1 -1
  149. package/dist/src/subscriptions/index.js +14 -15
  150. package/dist/src/subscriptions/index.js.map +1 -1
  151. package/dist/src/transactions/index.cjs +2189 -49
  152. package/dist/src/transactions/index.cjs.map +23 -3
  153. package/dist/src/transactions/index.d.cts +1 -1
  154. package/dist/src/transactions/index.d.ts +1 -1
  155. package/dist/src/transactions/index.js +104 -105
  156. package/dist/src/transactions/index.js.map +1 -1
  157. package/dist/src/utils/index.cjs +503 -69
  158. package/dist/src/utils/index.cjs.map +9 -3
  159. package/dist/src/utils/index.d.cts +1 -1
  160. package/dist/src/utils/index.d.ts +1 -1
  161. package/dist/src/utils/index.js +131 -131
  162. package/dist/src/utils/index.js.map +2 -2
  163. package/package.json +1 -1
  164. package/dist/shared/stacks-02actsrx.cjs +0 -17
  165. package/dist/shared/stacks-02actsrx.cjs.map +0 -10
  166. package/dist/shared/stacks-03vfm21t.cjs +0 -222
  167. package/dist/shared/stacks-03vfm21t.cjs.map +0 -12
  168. package/dist/shared/stacks-24h5k94q.cjs +0 -74
  169. package/dist/shared/stacks-24h5k94q.cjs.map +0 -11
  170. package/dist/shared/stacks-37kz5t9f.cjs +0 -764
  171. package/dist/shared/stacks-37kz5t9f.cjs.map +0 -23
  172. package/dist/shared/stacks-3mt2q2na.cjs +0 -65
  173. package/dist/shared/stacks-3mt2q2na.cjs.map +0 -9
  174. package/dist/shared/stacks-4d7c3x27.js +0 -84
  175. package/dist/shared/stacks-4hs8r4q2.js.map +0 -10
  176. package/dist/shared/stacks-8vzxax5e.cjs +0 -45
  177. package/dist/shared/stacks-agk106zs.cjs +0 -267
  178. package/dist/shared/stacks-bdgh9n83.cjs +0 -212
  179. package/dist/shared/stacks-bdgh9n83.cjs.map +0 -11
  180. package/dist/shared/stacks-dpxnxhqb.cjs +0 -51
  181. package/dist/shared/stacks-dpxnxhqb.cjs.map +0 -11
  182. package/dist/shared/stacks-ee53k9j2.cjs +0 -651
  183. package/dist/shared/stacks-ee53k9j2.cjs.map +0 -13
  184. package/dist/shared/stacks-enpj9krt.cjs +0 -38
  185. package/dist/shared/stacks-f35mnrmg.cjs +0 -164
  186. package/dist/shared/stacks-f35mnrmg.cjs.map +0 -10
  187. package/dist/shared/stacks-fhzwsn5d.cjs +0 -261
  188. package/dist/shared/stacks-fhzwsn5d.cjs.map +0 -12
  189. package/dist/shared/stacks-gjz26k6b.js.map +0 -12
  190. package/dist/shared/stacks-gza2n1zs.cjs +0 -73
  191. package/dist/shared/stacks-gza2n1zs.cjs.map +0 -11
  192. package/dist/shared/stacks-kem68d80.cjs +0 -156
  193. package/dist/shared/stacks-kem68d80.cjs.map +0 -10
  194. package/dist/shared/stacks-n98w7g57.cjs +0 -234
  195. package/dist/shared/stacks-n98w7g57.cjs.map +0 -10
  196. package/dist/shared/stacks-p337hp6m.cjs +0 -336
  197. package/dist/shared/stacks-p337hp6m.cjs.map +0 -25
  198. package/dist/shared/stacks-q34k4vnc.cjs +0 -286
  199. package/dist/shared/stacks-q34k4vnc.cjs.map +0 -12
  200. package/dist/shared/stacks-qex691bh.js +0 -50
  201. package/dist/shared/stacks-rryme9bv.cjs +0 -569
  202. package/dist/shared/stacks-rryme9bv.cjs.map +0 -13
  203. package/dist/shared/stacks-s5vej5z6.cjs +0 -410
  204. package/dist/shared/stacks-s5vej5z6.cjs.map +0 -15
  205. package/dist/shared/stacks-sdqkapct.cjs +0 -67
  206. package/dist/shared/stacks-sdqkapct.cjs.map +0 -12
  207. package/dist/shared/stacks-v2rfr46a.js +0 -48
  208. package/dist/shared/stacks-v2rfr46a.js.map +0 -10
  209. package/dist/shared/stacks-vea7nde7.cjs +0 -731
  210. package/dist/shared/stacks-vea7nde7.cjs.map +0 -13
  211. package/dist/shared/stacks-wk8yp13j.cjs +0 -33
  212. package/dist/shared/stacks-wk8yp13j.cjs.map +0 -11
  213. package/dist/shared/stacks-x0qqwrev.js.map +0 -12
  214. package/dist/shared/stacks-xjkn3en1.cjs +0 -42
  215. package/dist/shared/stacks-xnrywjf1.cjs +0 -131
  216. package/dist/shared/stacks-xnrywjf1.cjs.map +0 -11
  217. package/dist/shared/stacks-yvb7rvwk.js.map +0 -10
@@ -1,75 +1,144 @@
1
+ var import_node_module = require("node:module");
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ function __accessProp(key) {
9
+ return this[key];
10
+ }
11
+ var __toESMCache_node;
12
+ var __toESMCache_esm;
13
+ var __toESM = (mod, isNodeMode, target) => {
14
+ var canCache = mod != null && typeof mod === "object";
15
+ if (canCache) {
16
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
17
+ var cached = cache.get(mod);
18
+ if (cached)
19
+ return cached;
20
+ }
21
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
22
+ const to = isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
23
+ if (mod && typeof mod === "object" || typeof mod === "function") {
24
+ for (let key of __getOwnPropNames(mod))
25
+ if (!__hasOwnProp.call(to, key))
26
+ __defProp(to, key, {
27
+ get: __accessProp.bind(mod, key),
28
+ enumerable: true
29
+ });
30
+ }
31
+ if (canCache)
32
+ cache.set(mod, to);
33
+ return to;
34
+ };
35
+ var __toCommonJS = (from) => {
36
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
37
+ if (entry)
38
+ return entry;
39
+ entry = __defProp({}, "__esModule", { value: true });
40
+ if (from && typeof from === "object" || typeof from === "function") {
41
+ for (var key of __getOwnPropNames(from))
42
+ if (!__hasOwnProp.call(entry, key))
43
+ __defProp(entry, key, {
44
+ get: __accessProp.bind(from, key),
45
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
46
+ });
47
+ }
48
+ __moduleCache.set(from, entry);
49
+ return entry;
50
+ };
51
+ var __moduleCache;
52
+ var __returnValue = (v) => v;
53
+ function __exportSetter(name, newValue) {
54
+ this[name] = __returnValue.bind(null, newValue);
55
+ }
56
+ var __export = (target, all) => {
57
+ for (var name in all)
58
+ __defProp(target, name, {
59
+ get: all[name],
60
+ enumerable: true,
61
+ configurable: true,
62
+ set: __exportSetter.bind(all, name)
63
+ });
64
+ };
65
+
1
66
  // src/pox5/index.ts
2
67
  var exports_pox5 = {};
3
68
  __export(exports_pox5, {
4
- verifySignerGrant: () => verifySignerGrant,
5
- stringifyBtcAddress: () => stringifyBtcAddress,
6
- stakerPreimage: () => stakerPreimage,
7
- stakerConsensusBuff: () => stakerConsensusBuff,
8
- spvProofToL1LockupOutput: () => spvProofToL1LockupOutput,
9
- signSignerGrant: () => signSignerGrant,
10
- signReclaim: () => signReclaim,
11
- serializeCScriptNum: () => serializeCScriptNum,
12
- rewardCycleToBurnHeight: () => rewardCycleToBurnHeight,
13
- reclaim: () => reclaim,
14
- pushScriptBytes: () => pushScriptBytes,
15
- pushCScriptNum: () => pushCScriptNum,
16
- pox5ContractId: () => pox5ContractId,
17
- pox5: () => pox5,
18
- parseSignerCalldata: () => parseSignerCalldata,
19
- parsePox5Error: () => parsePox5Error,
20
- parseBtcAddress: () => parseBtcAddress,
21
- isPox5Active: () => isPox5Active,
22
- isInPreparePhase: () => isInPreparePhase,
23
- getPoxInfo: () => getPoxInfo,
24
- getPox5Activation: () => getPox5Activation,
25
- finalizeReclaim: () => finalizeReclaim,
26
- eligibleUnstakeSbtc: () => eligibleUnstakeSbtc,
27
- eligibleUnstake: () => eligibleUnstake,
28
- eligibleStake: () => eligibleStake,
29
- eligibleSetBondAdmin: () => eligibleSetBondAdmin,
30
- eligibleRegisterForBond: () => eligibleRegisterForBond,
31
- eligiblePauseRewards: () => eligiblePauseRewards,
32
- eligibleGrantSignerKey: () => eligibleGrantSignerKey,
33
- eligibleClaimRewards: () => eligibleClaimRewards,
34
- distributionCycleToBurnHeight: () => distributionCycleToBurnHeight,
35
- describePox5Error: () => describePox5Error,
36
- currentDistributionCycle: () => currentDistributionCycle,
37
- computeSignerGrantHash: () => computeSignerGrantHash,
38
- computeReclaimSighash: () => computeReclaimSighash,
39
- computeBondUnlockHeight: () => computeBondUnlockHeight,
40
- burnHeightToRewardCycle: () => burnHeightToRewardCycle,
41
- burnHeightToDistributionIndex: () => burnHeightToDistributionIndex,
42
- buildSignerCalldata: () => buildSignerCalldata,
43
- buildRegisterMetadata: () => buildRegisterMetadata,
44
- buildReclaim: () => buildReclaim,
45
- buildPox5LockProof: () => buildPox5LockProof,
46
- buildLockupScript: () => buildLockupScript,
47
- buildLockupOutputScript: () => buildLockupOutputScript,
48
- buildLockupAddress: () => buildLockupAddress,
49
- buildDefaultStakerUnlockBytes: () => buildDefaultStakerUnlockBytes,
50
- bondUnlockCycle: () => bondUnlockCycle,
51
- bondStatusAtHeight: () => bondStatusAtHeight,
52
- bondPhaseAtHeight: () => bondPhaseAtHeight,
53
- bondPeriodToRewardCycle: () => bondPeriodToRewardCycle,
54
- bondPeriodToBurnHeight: () => bondPeriodToBurnHeight,
55
- assertPox5Active: () => assertPox5Active,
56
- Pox5ErrorCode: () => Pox5ErrorCode,
57
- POX5_SIGNER_DOMAIN: () => POX5_SIGNER_DOMAIN,
58
- POX5_EVENT_TOPICS: () => POX5_EVENT_TOPICS,
59
- POX5_ERROR_NAMES: () => POX5_ERROR_NAMES,
60
- POX5_CONTRACT_NAME: () => POX5_CONTRACT_NAME,
61
- POX5_CONTRACT_ID_MAINNET: () => POX5_CONTRACT_ID_MAINNET,
62
- POX5_ACTIVATION_BURN_HEIGHT_MAINNET: () => POX5_ACTIVATION_BURN_HEIGHT_MAINNET,
63
- POX5_ABI: () => POX5_ABI,
64
- MAX_NUM_CYCLES: () => MAX_NUM_CYCLES,
65
- C_SCRIPT_NUM_MAX: () => C_SCRIPT_NUM_MAX,
66
- BtcAddress: () => BtcAddress,
67
- BOND_LENGTH_CYCLES: () => BOND_LENGTH_CYCLES,
69
+ BITCOIN_LOCKTIME_THRESHOLD: () => BITCOIN_LOCKTIME_THRESHOLD,
68
70
  BOND_GAP_CYCLES: () => BOND_GAP_CYCLES,
69
- BITCOIN_LOCKTIME_THRESHOLD: () => BITCOIN_LOCKTIME_THRESHOLD
71
+ BOND_LENGTH_CYCLES: () => BOND_LENGTH_CYCLES,
72
+ BtcAddress: () => BtcAddress,
73
+ C_SCRIPT_NUM_MAX: () => C_SCRIPT_NUM_MAX,
74
+ MAINNET_PREPARE_CYCLE_LENGTH: () => MAINNET_PREPARE_CYCLE_LENGTH,
75
+ MAX_NUM_CYCLES: () => MAX_NUM_CYCLES,
76
+ POX5_ABI: () => POX5_ABI,
77
+ POX5_ACTIVATION_BURN_HEIGHT_MAINNET: () => POX5_ACTIVATION_BURN_HEIGHT_MAINNET,
78
+ POX5_CONTRACT_ID_MAINNET: () => POX5_CONTRACT_ID_MAINNET,
79
+ POX5_CONTRACT_NAME: () => POX5_CONTRACT_NAME,
80
+ POX5_ERROR_NAMES: () => POX5_ERROR_NAMES,
81
+ POX5_EVENT_TOPICS: () => POX5_EVENT_TOPICS,
82
+ POX5_SIGNER_DOMAIN: () => POX5_SIGNER_DOMAIN,
83
+ Pox5ErrorCode: () => Pox5ErrorCode,
84
+ assertPox5Active: () => assertPox5Active,
85
+ bondPeriodToBurnHeight: () => bondPeriodToBurnHeight,
86
+ bondPeriodToRewardCycle: () => bondPeriodToRewardCycle,
87
+ bondPhaseAtHeight: () => bondPhaseAtHeight,
88
+ bondStatusAtHeight: () => bondStatusAtHeight,
89
+ bondUnlockCycle: () => bondUnlockCycle,
90
+ buildDefaultStakerUnlockBytes: () => buildDefaultStakerUnlockBytes,
91
+ buildLockupAddress: () => buildLockupAddress,
92
+ buildLockupOutputScript: () => buildLockupOutputScript,
93
+ buildLockupScript: () => buildLockupScript,
94
+ buildPox5LockProof: () => buildPox5LockProof,
95
+ buildReclaim: () => buildReclaim,
96
+ buildRegisterMetadata: () => buildRegisterMetadata,
97
+ buildSignerCalldata: () => buildSignerCalldata,
98
+ burnHeightToDistributionIndex: () => burnHeightToDistributionIndex,
99
+ burnHeightToRewardCycle: () => burnHeightToRewardCycle,
100
+ computeBondUnlockHeight: () => computeBondUnlockHeight,
101
+ computeReclaimSighash: () => computeReclaimSighash,
102
+ computeSignerGrantHash: () => computeSignerGrantHash,
103
+ currentDistributionCycle: () => currentDistributionCycle,
104
+ describePox5Error: () => describePox5Error,
105
+ distributionCycleToBurnHeight: () => distributionCycleToBurnHeight,
106
+ eligibleClaimRewards: () => eligibleClaimRewards,
107
+ eligibleGrantSignerKey: () => eligibleGrantSignerKey,
108
+ eligiblePauseRewards: () => eligiblePauseRewards,
109
+ eligibleRegisterForBond: () => eligibleRegisterForBond,
110
+ eligibleSetBondAdmin: () => eligibleSetBondAdmin,
111
+ eligibleStake: () => eligibleStake,
112
+ eligibleUnstake: () => eligibleUnstake,
113
+ eligibleUnstakeSbtc: () => eligibleUnstakeSbtc,
114
+ finalizeReclaim: () => finalizeReclaim,
115
+ getPox5Activation: () => getPox5Activation,
116
+ getPoxInfo: () => getPoxInfo,
117
+ isInPreparePhase: () => isInPreparePhase,
118
+ isPox5Active: () => isPox5Active,
119
+ parseBtcAddress: () => parseBtcAddress,
120
+ parsePox5Error: () => parsePox5Error,
121
+ parseSignerCalldata: () => parseSignerCalldata,
122
+ pox5: () => pox5,
123
+ pox5ContractId: () => pox5ContractId,
124
+ pushCScriptNum: () => pushCScriptNum,
125
+ pushScriptBytes: () => pushScriptBytes,
126
+ reclaim: () => reclaim,
127
+ rewardCycleToBurnHeight: () => rewardCycleToBurnHeight,
128
+ serializeCScriptNum: () => serializeCScriptNum,
129
+ signReclaim: () => signReclaim,
130
+ signSignerGrant: () => signSignerGrant,
131
+ spvProofToL1LockupOutput: () => spvProofToL1LockupOutput,
132
+ stakerConsensusBuff: () => stakerConsensusBuff,
133
+ stakerPreimage: () => stakerPreimage,
134
+ stringifyBtcAddress: () => stringifyBtcAddress,
135
+ verifySignerGrant: () => verifySignerGrant
70
136
  });
71
137
  module.exports = __toCommonJS(exports_pox5);
72
138
 
139
+ // src/epochs.ts
140
+ var EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET = 960230;
141
+
73
142
  // src/pox5/constants.ts
74
143
  var POX5_CONTRACT_NAME = "pox-5";
75
144
  var POX5_CONTRACT_ID_MAINNET = `SP000000000000000000002Q6VF78.${POX5_CONTRACT_NAME}`;
@@ -95,6 +164,7 @@ var POX5_EVENT_TOPICS = [
95
164
  "revoke-signer-grant"
96
165
  ];
97
166
  var POX5_ACTIVATION_BURN_HEIGHT_MAINNET = EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET;
167
+ var MAINNET_PREPARE_CYCLE_LENGTH = 100;
98
168
  var BOND_LENGTH_CYCLES = 12;
99
169
  var BOND_GAP_CYCLES = 2;
100
170
  var MAX_NUM_CYCLES = 96;
@@ -298,21 +368,3337 @@ var POX5_ERROR_DESCRIPTIONS = {
298
368
  function parsePox5Error(result) {
299
369
  if (result == null)
300
370
  return;
301
- if (typeof result === "string") {
302
- const match = result.trim().match(/^\(err u(\d+)\)$/);
303
- return match ? Number(match[1]) : undefined;
371
+ if (typeof result === "string") {
372
+ const match = result.trim().match(/^\(err u(\d+)\)$/);
373
+ return match ? Number(match[1]) : undefined;
374
+ }
375
+ if (result.type !== "err")
376
+ return;
377
+ return result.value.type === "uint" ? Number(result.value.value) : undefined;
378
+ }
379
+ function describePox5Error(code) {
380
+ const n = Number(code);
381
+ const name = POX5_ERROR_NAMES[n];
382
+ if (!name)
383
+ return;
384
+ return { code: n, name, description: POX5_ERROR_DESCRIPTIONS[n] };
385
+ }
386
+ // src/errors/base.ts
387
+ function codeFromName(name) {
388
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toUpperCase();
389
+ }
390
+
391
+ class BaseError extends Error {
392
+ name = "StacksError";
393
+ #code;
394
+ shortMessage;
395
+ details;
396
+ constructor(shortMessage, options) {
397
+ const message = [
398
+ shortMessage,
399
+ options?.details ? `
400
+ ${options.details}` : ""
401
+ ].join("");
402
+ super(message, { cause: options?.cause });
403
+ if (options?.code !== undefined)
404
+ this.#code = options.code;
405
+ this.shortMessage = shortMessage;
406
+ this.details = options?.details;
407
+ }
408
+ get code() {
409
+ return this.#code ?? codeFromName(this.name);
410
+ }
411
+ set code(value) {
412
+ this.#code = value;
413
+ }
414
+ toJSON() {
415
+ return {
416
+ name: this.name,
417
+ code: this.code,
418
+ message: this.message,
419
+ shortMessage: this.shortMessage,
420
+ details: this.details,
421
+ cause: this.cause instanceof Error ? this.cause.message : undefined
422
+ };
423
+ }
424
+ }
425
+
426
+ // src/errors/response.ts
427
+ class MalformedResponseError extends BaseError {
428
+ name = "MalformedResponseError";
429
+ }
430
+
431
+ class ReadContractError extends BaseError {
432
+ name = "ReadContractError";
433
+ }
434
+
435
+ // src/actions/public/getBalance.ts
436
+ async function getBalance(client, params) {
437
+ const data = await client.request(`/v2/accounts/${encodeURIComponent(params.address)}`, {
438
+ method: "GET"
439
+ });
440
+ const balance = data?.balance;
441
+ if (typeof balance !== "string" && typeof balance !== "number") {
442
+ throw new MalformedResponseError(`getBalance: /v2/accounts/${params.address} response is missing "balance"`);
443
+ }
444
+ return BigInt(balance);
445
+ }
446
+
447
+ // src/errors/transaction.ts
448
+ class TransactionError extends BaseError {
449
+ name = "TransactionError";
450
+ }
451
+
452
+ class BroadcastError extends BaseError {
453
+ name = "BroadcastError";
454
+ txid;
455
+ reason;
456
+ reasonData;
457
+ constructor(message, options) {
458
+ super(message, options);
459
+ this.txid = options?.txid;
460
+ this.reason = options?.reason;
461
+ this.reasonData = options?.reasonData;
462
+ }
463
+ }
464
+
465
+ class TransactionAbortedError extends BaseError {
466
+ name = "TransactionAbortedError";
467
+ receipt;
468
+ constructor(message, options) {
469
+ super(message, options);
470
+ this.receipt = options.receipt;
471
+ }
472
+ }
473
+
474
+ class TransactionDroppedError extends BaseError {
475
+ name = "TransactionDroppedError";
476
+ txid;
477
+ constructor(message, options) {
478
+ super(message, options);
479
+ this.txid = options.txid;
480
+ }
481
+ }
482
+
483
+ class WaitForTransactionTimeoutError extends BaseError {
484
+ name = "WaitForTransactionTimeoutError";
485
+ txid;
486
+ constructor(message, options) {
487
+ super(message, options);
488
+ this.txid = options.txid;
489
+ }
490
+ }
491
+
492
+ class SerializationError extends BaseError {
493
+ name = "SerializationError";
494
+ }
495
+
496
+ class SigningError extends BaseError {
497
+ name = "SigningError";
498
+ }
499
+
500
+ // src/utils/encoding.ts
501
+ var hexes = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
502
+ function bytesToHex(bytes) {
503
+ let hex = "";
504
+ for (const b of bytes) {
505
+ hex += hexes[b];
506
+ }
507
+ return hex;
508
+ }
509
+ function hexToBytes(hex) {
510
+ let h = without0x(hex);
511
+ if (h.length % 2)
512
+ h = `0${h}`;
513
+ const array = new Uint8Array(h.length / 2);
514
+ for (let i = 0;i < array.length; i++) {
515
+ const j = i * 2;
516
+ const byte = Number.parseInt(h.slice(j, j + 2), 16);
517
+ if (Number.isNaN(byte) || byte < 0)
518
+ throw new Error("Invalid byte sequence");
519
+ array[i] = byte;
520
+ }
521
+ return array;
522
+ }
523
+ function with0x(value) {
524
+ return /^0x/i.test(value) ? value : `0x${value}`;
525
+ }
526
+ function without0x(value) {
527
+ return /^0x/i.test(value) ? value.slice(2) : value;
528
+ }
529
+ function utf8ToBytes(str) {
530
+ return new TextEncoder().encode(str);
531
+ }
532
+ function bytesToUtf8(bytes) {
533
+ return new TextDecoder().decode(bytes);
534
+ }
535
+ function asciiToBytes(str) {
536
+ const bytes = new Uint8Array(str.length);
537
+ for (let i = 0;i < str.length; i++) {
538
+ bytes[i] = str.charCodeAt(i) & 255;
539
+ }
540
+ return bytes;
541
+ }
542
+ function bytesToAscii(bytes) {
543
+ return String.fromCharCode(...bytes);
544
+ }
545
+ function concatBytes(...arrays) {
546
+ if (arrays.length === 1)
547
+ return arrays[0];
548
+ const length = arrays.reduce((a, arr) => a + arr.length, 0);
549
+ const result = new Uint8Array(length);
550
+ let pad = 0;
551
+ for (const arr of arrays) {
552
+ result.set(arr, pad);
553
+ pad += arr.length;
554
+ }
555
+ return result;
556
+ }
557
+ function intToBigInt(value) {
558
+ if (typeof value === "bigint")
559
+ return value;
560
+ if (typeof value === "string")
561
+ return BigInt(value);
562
+ if (typeof value === "number") {
563
+ if (!Number.isInteger(value))
564
+ throw new RangeError("Values of type 'number' must be an integer.");
565
+ if (value > Number.MAX_SAFE_INTEGER)
566
+ throw new RangeError(`Values of type 'number' must be <= ${Number.MAX_SAFE_INTEGER}. Use BigInt instead.`);
567
+ return BigInt(value);
568
+ }
569
+ if (value instanceof Uint8Array)
570
+ return BigInt(`0x${bytesToHex(value)}`);
571
+ throw new TypeError("Must be a number, bigint, string, or Uint8Array.");
572
+ }
573
+ function intToBytes(value, byteLength) {
574
+ return bigIntToBytes(intToBigInt(value), byteLength);
575
+ }
576
+ function bigIntToBytes(value, length = 16) {
577
+ const hex = value.toString(16).padStart(length * 2, "0");
578
+ return hexToBytes(hex);
579
+ }
580
+ function intToHex(integer, byteLength = 8) {
581
+ const value = typeof integer === "bigint" ? integer : intToBigInt(integer);
582
+ return value.toString(16).padStart(byteLength * 2, "0");
583
+ }
584
+ function toTwos(value, width) {
585
+ const limit = BigInt(1) << width - BigInt(1);
586
+ if (value < -limit || value > limit - BigInt(1)) {
587
+ throw new Error(`Unable to represent integer in width: ${width}`);
588
+ }
589
+ if (value >= BigInt(0))
590
+ return value;
591
+ return value + (BigInt(1) << width);
592
+ }
593
+ function fromTwos(value, width) {
594
+ if (value & BigInt(1) << width - BigInt(1)) {
595
+ return value - (BigInt(1) << width);
596
+ }
597
+ return value;
598
+ }
599
+ function bytesToTwosBigInt(bytes) {
600
+ if (bytes.length === 0)
601
+ return 0n;
602
+ const hex = bytesToHex(bytes);
603
+ if (hex.length === 0)
604
+ return 0n;
605
+ return fromTwos(BigInt(`0x${hex}`), BigInt(bytes.byteLength * 8));
606
+ }
607
+ function writeUInt32BE(value) {
608
+ const buf = new Uint8Array(4);
609
+ buf[0] = value >>> 24 & 255;
610
+ buf[1] = value >>> 16 & 255;
611
+ buf[2] = value >>> 8 & 255;
612
+ buf[3] = value & 255;
613
+ return buf;
614
+ }
615
+ function readUInt32BE(bytes, offset = 0) {
616
+ return (bytes[offset] << 24 | bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3]) >>> 0;
617
+ }
618
+ function writeUInt16BE(value) {
619
+ const buf = new Uint8Array(2);
620
+ buf[0] = value >>> 8 & 255;
621
+ buf[1] = value & 255;
622
+ return buf;
623
+ }
624
+ function readUInt16BE(bytes, offset = 0) {
625
+ return (bytes[offset] << 8 | bytes[offset + 1]) >>> 0;
626
+ }
627
+ function writeUInt8(value) {
628
+ return new Uint8Array([value & 255]);
629
+ }
630
+
631
+ // src/utils/bytes-reader.ts
632
+ class BytesReader {
633
+ data;
634
+ offset = 0;
635
+ constructor(data) {
636
+ this.data = data;
637
+ }
638
+ remaining() {
639
+ return this.data.length - this.offset;
640
+ }
641
+ ensure(length) {
642
+ if (this.offset + length > this.data.length) {
643
+ throw new SerializationError(`Buffer underflow: need ${length} bytes at offset ${this.offset}, have ${this.data.length}`);
644
+ }
645
+ }
646
+ readUInt8() {
647
+ this.ensure(1);
648
+ return this.data[this.offset++];
649
+ }
650
+ readUInt16BE() {
651
+ this.ensure(2);
652
+ const val = (this.data[this.offset] << 8 | this.data[this.offset + 1]) >>> 0;
653
+ this.offset += 2;
654
+ return val;
655
+ }
656
+ readUInt32BE() {
657
+ this.ensure(4);
658
+ const val = (this.data[this.offset] << 24 | this.data[this.offset + 1] << 16 | this.data[this.offset + 2] << 8 | this.data[this.offset + 3]) >>> 0;
659
+ this.offset += 4;
660
+ return val;
661
+ }
662
+ readBytes(length) {
663
+ this.ensure(length);
664
+ const slice = this.data.slice(this.offset, this.offset + length);
665
+ this.offset += length;
666
+ return slice;
667
+ }
668
+ readBigUInt64BE() {
669
+ const hex = bytesToHex(this.readBytes(8));
670
+ return hex.length > 0 ? BigInt(`0x${hex}`) : 0n;
671
+ }
672
+ }
673
+
674
+ // src/utils/c32.ts
675
+ var import_sha2 = require("@noble/hashes/sha2.js");
676
+ var C32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
677
+ var HEX = "0123456789abcdef";
678
+ function c32normalize(input) {
679
+ return input.toUpperCase().replace(/O/g, "0").replace(/L|I/g, "1");
680
+ }
681
+ function c32encode(inputHex) {
682
+ let hex = inputHex;
683
+ if (hex.length % 2 !== 0)
684
+ hex = `0${hex}`;
685
+ hex = hex.toLowerCase();
686
+ const res = [];
687
+ let carry = 0;
688
+ for (let i = hex.length - 1;i >= 0; i--) {
689
+ if (carry < 4) {
690
+ const currentCode = HEX.indexOf(hex[i]) >> carry;
691
+ const nextCode = i !== 0 ? HEX.indexOf(hex[i - 1]) : 0;
692
+ const nextBits = 1 + carry;
693
+ const nextLowBits = nextCode % (1 << nextBits) << 5 - nextBits;
694
+ res.unshift(C32[currentCode + nextLowBits]);
695
+ carry = nextBits;
696
+ } else {
697
+ carry = 0;
698
+ }
699
+ }
700
+ let leadingZeros = 0;
701
+ while (leadingZeros < res.length && res[leadingZeros] === "0")
702
+ leadingZeros++;
703
+ const stripped = res.slice(leadingZeros);
704
+ const bytes = hexToBytes(hex);
705
+ let zeroBytesCount = 0;
706
+ while (zeroBytesCount < bytes.length && bytes[zeroBytesCount] === 0)
707
+ zeroBytesCount++;
708
+ const prefix = Array(zeroBytesCount).fill(C32[0]);
709
+ return [...prefix, ...stripped].join("");
710
+ }
711
+ function c32decode(c32input) {
712
+ const input = c32normalize(c32input);
713
+ if (!input.match(`^[${C32}]*$`))
714
+ throw new Error("Not a c32-encoded string");
715
+ const zeroPrefix = input.match(`^${C32[0]}*`);
716
+ const numLeadingZeroBytes = zeroPrefix ? zeroPrefix[0]?.length : 0;
717
+ const res = [];
718
+ let carry = 0;
719
+ let carryBits = 0;
720
+ for (let i = input.length - 1;i >= 0; i--) {
721
+ if (carryBits === 4) {
722
+ res.unshift(HEX[carry]);
723
+ carryBits = 0;
724
+ carry = 0;
725
+ }
726
+ const currentValue = (C32.indexOf(input[i]) << carryBits) + carry;
727
+ res.unshift(HEX[currentValue % 16]);
728
+ carryBits += 1;
729
+ carry = currentValue >> 4;
730
+ if (carry > 1 << carryBits)
731
+ throw new Error("Panic error in c32 decoding");
732
+ }
733
+ res.unshift(HEX[carry]);
734
+ if (res.length % 2 === 1)
735
+ res.unshift("0");
736
+ let hexLeadingZeros = 0;
737
+ while (hexLeadingZeros < res.length && res[hexLeadingZeros] === "0")
738
+ hexLeadingZeros++;
739
+ let hexStr = res.slice(hexLeadingZeros - hexLeadingZeros % 2).join("");
740
+ for (let i = 0;i < numLeadingZeroBytes; i++)
741
+ hexStr = `00${hexStr}`;
742
+ return hexStr;
743
+ }
744
+ function c32checksum(dataHex) {
745
+ return bytesToHex(import_sha2.sha256(import_sha2.sha256(hexToBytes(dataHex))).slice(0, 4));
746
+ }
747
+ function c32checkEncode(version, data) {
748
+ if (version < 0 || version >= 32)
749
+ throw new Error("Invalid version (must be between 0 and 31)");
750
+ if (!data.match(/^[0-9a-fA-F]*$/))
751
+ throw new Error("Invalid data (not a hex string)");
752
+ let d = data.toLowerCase();
753
+ if (d.length % 2 !== 0)
754
+ d = `0${d}`;
755
+ let versionHex = version.toString(16);
756
+ if (versionHex.length === 1)
757
+ versionHex = `0${versionHex}`;
758
+ const checksumHex = c32checksum(`${versionHex}${d}`);
759
+ return `${C32[version]}${c32encode(`${d}${checksumHex}`)}`;
760
+ }
761
+ function c32checkDecode(c32data) {
762
+ const normalized = c32normalize(c32data);
763
+ const dataHex = c32decode(normalized.slice(1));
764
+ const version = C32.indexOf(normalized[0]);
765
+ const checksum = dataHex.slice(-8);
766
+ let versionHex = version.toString(16);
767
+ if (versionHex.length === 1)
768
+ versionHex = `0${versionHex}`;
769
+ if (c32checksum(`${versionHex}${dataHex.substring(0, dataHex.length - 8)}`) !== checksum) {
770
+ throw new Error("Invalid c32check string: checksum mismatch");
771
+ }
772
+ return [version, dataHex.substring(0, dataHex.length - 8)];
773
+ }
774
+ function c32address(version, hash160hex) {
775
+ if (!hash160hex.match(/^[0-9a-fA-F]{40}$/)) {
776
+ throw new Error("Invalid argument: not a hash160 hex string");
777
+ }
778
+ return `S${c32checkEncode(version, hash160hex)}`;
779
+ }
780
+ function c32addressDecode(c32addr) {
781
+ if (c32addr.length <= 5)
782
+ throw new Error("Invalid c32 address: invalid length");
783
+ if (c32addr[0] !== "S")
784
+ throw new Error('Invalid c32 address: must start with "S"');
785
+ return c32checkDecode(c32addr.slice(1));
786
+ }
787
+
788
+ // src/clarity/types.ts
789
+ var ClarityWireType = {
790
+ int: 0,
791
+ uint: 1,
792
+ buffer: 2,
793
+ true: 3,
794
+ false: 4,
795
+ address: 5,
796
+ contract: 6,
797
+ ok: 7,
798
+ err: 8,
799
+ none: 9,
800
+ some: 10,
801
+ list: 11,
802
+ tuple: 12,
803
+ ascii: 13,
804
+ utf8: 14
805
+ };
806
+ var wireTypeToClarity = Object.fromEntries(Object.entries(ClarityWireType).map(([k, v]) => [v, k]));
807
+ function clarityTypeFromByte(byte) {
808
+ const type = wireTypeToClarity[byte];
809
+ if (!type)
810
+ throw new Error(`Unknown clarity wire type: ${byte}`);
811
+ return type;
812
+ }
813
+
814
+ // src/utils/constants.ts
815
+ var MAX_U128 = (1n << 128n) - 1n;
816
+ var MAX_I128 = (1n << 127n) - 1n;
817
+ var MIN_I128 = -(1n << 127n);
818
+ var AddressVersion = {
819
+ MainnetSingleSig: 22,
820
+ MainnetMultiSig: 20,
821
+ TestnetSingleSig: 26,
822
+ TestnetMultiSig: 21
823
+ };
824
+ var ZERO_ADDRESS = "SP000000000000000000002Q6VF78";
825
+ var TESTNET_ZERO_ADDRESS = "ST000000000000000000002AMW42H";
826
+ var MICROSTX_PER_STX = 1000000n;
827
+
828
+ // src/utils/hash.ts
829
+ var import_legacy = require("@noble/hashes/legacy.js");
830
+ var import_sha22 = require("@noble/hashes/sha2.js");
831
+ var import_sha23 = require("@noble/hashes/sha2.js");
832
+ function hash160(input) {
833
+ return import_legacy.ripemd160(import_sha22.sha256(input));
834
+ }
835
+ function txidFromBytes(data) {
836
+ return bytesToHex(import_sha23.sha512_256(data));
837
+ }
838
+ function hashP2PKH(input) {
839
+ return bytesToHex(hash160(input));
840
+ }
841
+
842
+ // src/utils/address.ts
843
+ function publicKeyToAddress(publicKey, network = "mainnet") {
844
+ const bytes = typeof publicKey === "string" ? hexToBytes(without0x(publicKey)) : publicKey;
845
+ const version = network === "mainnet" ? AddressVersion.MainnetSingleSig : AddressVersion.TestnetSingleSig;
846
+ return c32address(version, bytesToHex(hash160(bytes)));
847
+ }
848
+ var CONTRACT_NAME_REGEX = /^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/;
849
+ function validateStacksAddress(address) {
850
+ try {
851
+ c32addressDecode(address);
852
+ return true;
853
+ } catch {
854
+ return false;
855
+ }
856
+ }
857
+ var isValidAddress = validateStacksAddress;
858
+ function parsePrincipal(value) {
859
+ const parts = value.split(".");
860
+ if (parts.length > 2)
861
+ return null;
862
+ const [address, contractName] = parts;
863
+ if (!validateStacksAddress(address))
864
+ return null;
865
+ if (contractName === undefined)
866
+ return { address };
867
+ if (!CONTRACT_NAME_REGEX.test(contractName))
868
+ return null;
869
+ return { address, contractName };
870
+ }
871
+ function parseContractId(contractId) {
872
+ const parsed = parsePrincipal(contractId);
873
+ if (!parsed?.contractName)
874
+ throw new Error(`Invalid contract identifier: ${contractId}`);
875
+ return [parsed.address, parsed.contractName];
876
+ }
877
+ function isClarityName(name) {
878
+ const regex = /^[a-zA-Z]([a-zA-Z0-9]|[-_!?+<>=/*])*$|^[-+=/*]$|^[<>]=?$/;
879
+ return regex.test(name) && name.length < 128;
880
+ }
881
+ function isAddressEqual(a, b) {
882
+ const [versionA, hashA] = c32addressDecode(a);
883
+ const [versionB, hashB] = c32addressDecode(b);
884
+ return versionA === versionB && hashA.toLowerCase() === hashB.toLowerCase();
885
+ }
886
+ function addressToVersion(address) {
887
+ return c32addressDecode(address)[0];
888
+ }
889
+ function getContractAddress(deployer, contractName) {
890
+ if (!validateStacksAddress(deployer)) {
891
+ throw new Error(`Invalid deployer address: ${deployer}`);
892
+ }
893
+ if (!isClarityName(contractName)) {
894
+ throw new Error(`Invalid contract name: ${contractName}`);
895
+ }
896
+ return `${deployer}.${contractName}`;
897
+ }
898
+
899
+ // src/clarity/serialize.ts
900
+ var CLARITY_INT_SIZE = 128n;
901
+ var CLARITY_INT_BYTE_SIZE = 16;
902
+ function typeIdByte(type) {
903
+ return ClarityWireType[type];
904
+ }
905
+ function withTypeId(type, bytes) {
906
+ return concatBytes(new Uint8Array([typeIdByte(type)]), bytes);
907
+ }
908
+ function serializeAddress(c32Address) {
909
+ const [version, hash160] = c32addressDecode(c32Address);
910
+ return concatBytes(new Uint8Array([version]), hexToBytes(hash160));
911
+ }
912
+ function serializeLPString(str, prefixBytes = 1) {
913
+ const content = utf8ToBytes(str);
914
+ const lengthPrefix = hexToBytes(intToHex(content.byteLength, prefixBytes));
915
+ return concatBytes(lengthPrefix, content);
916
+ }
917
+ function serializeCVBytes(value) {
918
+ switch (value.type) {
919
+ case "true":
920
+ case "false":
921
+ return new Uint8Array([typeIdByte(value.type)]);
922
+ case "int": {
923
+ const bytes = bigIntToBytes(toTwos(BigInt(value.value), CLARITY_INT_SIZE), CLARITY_INT_BYTE_SIZE);
924
+ return withTypeId(value.type, bytes);
925
+ }
926
+ case "uint": {
927
+ const bytes = bigIntToBytes(BigInt(value.value), CLARITY_INT_BYTE_SIZE);
928
+ return withTypeId(value.type, bytes);
929
+ }
930
+ case "buffer": {
931
+ const bufBytes = hexToBytes(value.value);
932
+ return withTypeId(value.type, concatBytes(writeUInt32BE(bufBytes.length), bufBytes));
933
+ }
934
+ case "none":
935
+ return new Uint8Array([typeIdByte(value.type)]);
936
+ case "some":
937
+ return withTypeId(value.type, serializeCVBytes(value.value));
938
+ case "ok":
939
+ case "err":
940
+ return withTypeId(value.type, serializeCVBytes(value.value));
941
+ case "address":
942
+ return withTypeId(value.type, serializeAddress(value.value));
943
+ case "contract": {
944
+ const [addr, name] = value.value.split(".");
945
+ if (!addr || !name)
946
+ throw new Error(`Invalid contract principal: ${value.value}`);
947
+ return withTypeId(value.type, concatBytes(serializeAddress(addr), serializeLPString(name)));
948
+ }
949
+ case "list": {
950
+ const parts = [writeUInt32BE(value.value.length)];
951
+ for (const item of value.value) {
952
+ parts.push(serializeCVBytes(item));
953
+ }
954
+ return withTypeId(value.type, concatBytes(...parts));
955
+ }
956
+ case "tuple": {
957
+ const keys = Object.keys(value.value).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
958
+ const parts = [writeUInt32BE(keys.length)];
959
+ for (const key of keys) {
960
+ parts.push(serializeLPString(key));
961
+ parts.push(serializeCVBytes(value.value[key]));
962
+ }
963
+ return withTypeId(value.type, concatBytes(...parts));
964
+ }
965
+ case "ascii": {
966
+ const strBytes = asciiToBytes(value.value);
967
+ return withTypeId(value.type, concatBytes(writeUInt32BE(strBytes.length), strBytes));
968
+ }
969
+ case "utf8": {
970
+ const strBytes = utf8ToBytes(value.value);
971
+ return withTypeId(value.type, concatBytes(writeUInt32BE(strBytes.length), strBytes));
972
+ }
973
+ default:
974
+ throw new Error("Cannot serialize unknown clarity type");
975
+ }
976
+ }
977
+ function serializeCV(value) {
978
+ return bytesToHex(serializeCVBytes(value));
979
+ }
980
+
981
+ // src/clarity/values.ts
982
+ var MAX_U1282 = BigInt("0xffffffffffffffffffffffffffffffff");
983
+ var MIN_I1282 = BigInt("-170141183460469231731687303715884105728");
984
+ var MAX_I1282 = BigInt("0x7fffffffffffffffffffffffffffffff");
985
+ function intCV(value) {
986
+ let v = value;
987
+ if (typeof v === "string" && v.toLowerCase().startsWith("0x")) {
988
+ v = bytesToTwosBigInt(hexToBytes(v));
989
+ }
990
+ if (v instanceof Uint8Array)
991
+ v = bytesToTwosBigInt(v);
992
+ const n = intToBigInt(v);
993
+ if (n > MAX_I1282)
994
+ throw new RangeError(`Int exceeds max i128: ${MAX_I1282}`);
995
+ if (n < MIN_I1282)
996
+ throw new RangeError(`Int below min i128: ${MIN_I1282}`);
997
+ return { type: "int", value: n };
998
+ }
999
+ function uintCV(value) {
1000
+ const n = intToBigInt(value);
1001
+ if (n < 0n)
1002
+ throw new RangeError("Cannot construct unsigned int from negative value");
1003
+ if (n > MAX_U1282)
1004
+ throw new RangeError(`UInt exceeds max u128: ${MAX_U1282}`);
1005
+ return { type: "uint", value: n };
1006
+ }
1007
+ var trueCV = () => ({ type: "true" });
1008
+ var falseCV = () => ({ type: "false" });
1009
+ var boolCV = (v) => v ? trueCV() : falseCV();
1010
+ function bufferCV(buffer) {
1011
+ if (buffer.byteLength > 1048576) {
1012
+ throw new Error("Buffer exceeds max size of 1MB");
1013
+ }
1014
+ return { type: "buffer", value: bytesToHex(buffer) };
1015
+ }
1016
+ function standardPrincipalCV(address) {
1017
+ const [version, hash160] = c32addressDecode(address);
1018
+ const normalized = c32address(version, hash160);
1019
+ return { type: "address", value: normalized };
1020
+ }
1021
+ function contractPrincipalCV(address, contractName) {
1022
+ const [version, hash160] = c32addressDecode(address);
1023
+ const normalized = c32address(version, hash160);
1024
+ if (utf8ToBytes(contractName).byteLength >= 128) {
1025
+ throw new Error("Contract name must be less than 128 bytes");
1026
+ }
1027
+ return { type: "contract", value: `${normalized}.${contractName}` };
1028
+ }
1029
+ function noneCV() {
1030
+ return { type: "none" };
1031
+ }
1032
+ function someCV(value) {
1033
+ return { type: "some", value };
1034
+ }
1035
+ function responseOkCV(value) {
1036
+ return { type: "ok", value };
1037
+ }
1038
+ function responseErrorCV(value) {
1039
+ return { type: "err", value };
1040
+ }
1041
+ function listCV(values) {
1042
+ return { type: "list", value: values };
1043
+ }
1044
+ function tupleCV(data) {
1045
+ for (const key in data) {
1046
+ if (!isClarityName(key)) {
1047
+ throw new Error(`"${key}" is not a valid Clarity name`);
1048
+ }
1049
+ }
1050
+ return { type: "tuple", value: data };
1051
+ }
1052
+ function stringAsciiCV(value) {
1053
+ return { type: "ascii", value };
1054
+ }
1055
+ function stringUtf8CV(value) {
1056
+ return { type: "utf8", value };
1057
+ }
1058
+ var Cl = {
1059
+ int: intCV,
1060
+ uint: uintCV,
1061
+ bool: boolCV,
1062
+ principal(address) {
1063
+ const parsed = parsePrincipal(address);
1064
+ if (!parsed)
1065
+ throw new Error(`Invalid principal: ${address}`);
1066
+ return parsed.contractName ? contractPrincipalCV(parsed.address, parsed.contractName) : standardPrincipalCV(parsed.address);
1067
+ },
1068
+ address(address) {
1069
+ return Cl.principal(address);
1070
+ },
1071
+ contractPrincipal: contractPrincipalCV,
1072
+ standardPrincipal: standardPrincipalCV,
1073
+ buffer: bufferCV,
1074
+ bufferFromHex: (hex) => bufferCV(hexToBytes(hex)),
1075
+ bufferFromAscii: (ascii) => bufferCV(asciiToBytes(ascii)),
1076
+ bufferFromUtf8: (utf8) => bufferCV(utf8ToBytes(utf8)),
1077
+ none: noneCV,
1078
+ some: someCV,
1079
+ ok: responseOkCV,
1080
+ error: responseErrorCV,
1081
+ list: listCV,
1082
+ tuple: tupleCV,
1083
+ stringAscii: stringAsciiCV,
1084
+ stringUtf8: stringUtf8CV,
1085
+ serialize(value) {
1086
+ return bytesToHex(serializeCVBytes(value));
1087
+ },
1088
+ deserialize: deserializeCVBytes
1089
+ };
1090
+
1091
+ // src/clarity/deserialize.ts
1092
+ function readAddress(reader) {
1093
+ const version = reader.readUInt8();
1094
+ const hash160 = bytesToHex(reader.readBytes(20));
1095
+ return c32address(version, hash160);
1096
+ }
1097
+ function readLPString(reader, prefixBytes = 1) {
1098
+ let length = 0;
1099
+ for (let i = 0;i < prefixBytes; i++) {
1100
+ length = length << 8 | reader.readUInt8();
1101
+ }
1102
+ return bytesToUtf8(reader.readBytes(length));
1103
+ }
1104
+ var MAX_CV_DEPTH = 64;
1105
+ var MIN_LIST_ITEM_BYTES = 1;
1106
+ var MIN_TUPLE_ENTRY_BYTES = 2;
1107
+ function checkCount(reader, count, minBytes) {
1108
+ if (count * minBytes > reader.remaining()) {
1109
+ throw new SerializationError(`Clarity value declares ${count} elements but only ${reader.remaining()} bytes remain`);
1110
+ }
1111
+ }
1112
+ function readCV(reader, depth = 0) {
1113
+ if (depth > MAX_CV_DEPTH) {
1114
+ throw new SerializationError(`Clarity value nests deeper than ${MAX_CV_DEPTH} levels`);
1115
+ }
1116
+ const typeByte = reader.readUInt8();
1117
+ const type = clarityTypeFromByte(typeByte);
1118
+ switch (type) {
1119
+ case "int":
1120
+ return intCV(bytesToTwosBigInt(reader.readBytes(16)));
1121
+ case "uint":
1122
+ return uintCV(reader.readBytes(16));
1123
+ case "true":
1124
+ return trueCV();
1125
+ case "false":
1126
+ return falseCV();
1127
+ case "buffer": {
1128
+ const len = reader.readUInt32BE();
1129
+ return bufferCV(reader.readBytes(len));
1130
+ }
1131
+ case "none":
1132
+ return noneCV();
1133
+ case "some":
1134
+ return someCV(readCV(reader, depth + 1));
1135
+ case "ok":
1136
+ return responseOkCV(readCV(reader, depth + 1));
1137
+ case "err":
1138
+ return responseErrorCV(readCV(reader, depth + 1));
1139
+ case "address":
1140
+ return standardPrincipalCV(readAddress(reader));
1141
+ case "contract": {
1142
+ const addr = readAddress(reader);
1143
+ const name = readLPString(reader);
1144
+ return contractPrincipalCV(addr, name);
1145
+ }
1146
+ case "list": {
1147
+ const len = reader.readUInt32BE();
1148
+ checkCount(reader, len, MIN_LIST_ITEM_BYTES);
1149
+ const items = [];
1150
+ for (let i = 0;i < len; i++) {
1151
+ items.push(readCV(reader, depth + 1));
1152
+ }
1153
+ return listCV(items);
1154
+ }
1155
+ case "tuple": {
1156
+ const len = reader.readUInt32BE();
1157
+ checkCount(reader, len, MIN_TUPLE_ENTRY_BYTES);
1158
+ const data = {};
1159
+ for (let i = 0;i < len; i++) {
1160
+ const key = readLPString(reader);
1161
+ data[key] = readCV(reader, depth + 1);
1162
+ }
1163
+ return tupleCV(data);
1164
+ }
1165
+ case "ascii": {
1166
+ const len = reader.readUInt32BE();
1167
+ return stringAsciiCV(bytesToAscii(reader.readBytes(len)));
1168
+ }
1169
+ case "utf8": {
1170
+ const len = reader.readUInt32BE();
1171
+ return stringUtf8CV(bytesToUtf8(reader.readBytes(len)));
1172
+ }
1173
+ default:
1174
+ throw new SerializationError(`Cannot deserialize unknown clarity type: ${type}`);
1175
+ }
1176
+ }
1177
+ function deserializeCVBytes(input) {
1178
+ const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
1179
+ return readCV(new BytesReader(bytes));
1180
+ }
1181
+ function deserializeCV(input) {
1182
+ return deserializeCVBytes(input);
1183
+ }
1184
+
1185
+ // src/actions/public/getDataVar.ts
1186
+ async function getDataVar(client, params) {
1187
+ const [address, name] = parseContractId(params.contract);
1188
+ const path = `/v2/data_var/${address}/${name}/${params.varName}?proof=0`;
1189
+ const data = await client.request(path, { method: "GET" });
1190
+ if (typeof data?.data !== "string") {
1191
+ throw new MalformedResponseError(`getDataVar: /v2/data_var/${address}/${name}/${params.varName} response is missing "data"`);
1192
+ }
1193
+ return deserializeCVBytes(data.data);
1194
+ }
1195
+
1196
+ // src/actions/public/getMapEntry.ts
1197
+ async function getMapEntry(client, params) {
1198
+ const [address, name] = parseContractId(params.contract);
1199
+ const serializedKey = with0x(bytesToHex(serializeCVBytes(params.key)));
1200
+ const data = await client.request(`/v2/map_entry/${address}/${name}/${params.mapName}`, {
1201
+ method: "POST",
1202
+ body: serializedKey
1203
+ });
1204
+ if (typeof data?.data !== "string") {
1205
+ throw new MalformedResponseError(`getMapEntry: /v2/map_entry/${address}/${name}/${params.mapName} response is missing "data"`);
1206
+ }
1207
+ return deserializeCVBytes(data.data);
1208
+ }
1209
+
1210
+ // src/clarity/abi/utils.ts
1211
+ function toCamelCase(str) {
1212
+ return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/-([A-Z])/g, (_, letter) => letter).replace(/-(\d)/g, (_, digit) => digit).replace(/-/g, "").replace(/^\d/, "_$&");
1213
+ }
1214
+ // src/clarity/abi/guards.ts
1215
+ function isUint128(value) {
1216
+ return typeof value === "bigint" && value >= 0n && value <= MAX_U128;
1217
+ }
1218
+ function isInt128(value) {
1219
+ return typeof value === "bigint" && value >= MIN_I128 && value <= MAX_I128;
1220
+ }
1221
+ function isBool(value) {
1222
+ return typeof value === "boolean";
1223
+ }
1224
+ function isPrincipal(value) {
1225
+ return typeof value === "string" && parsePrincipal(value) !== null;
1226
+ }
1227
+ function isStandardPrincipal(value) {
1228
+ if (typeof value !== "string")
1229
+ return false;
1230
+ const parsed = parsePrincipal(value);
1231
+ return parsed !== null && parsed.contractName === undefined;
1232
+ }
1233
+ function isContractPrincipal(value) {
1234
+ if (typeof value !== "string")
1235
+ return false;
1236
+ const parsed = parsePrincipal(value);
1237
+ return parsed !== null && parsed.contractName !== undefined;
1238
+ }
1239
+ function isTraitReference(value) {
1240
+ return isContractPrincipal(value);
1241
+ }
1242
+ function isString(value) {
1243
+ return typeof value === "string";
1244
+ }
1245
+ function isUint8Array(value) {
1246
+ return value instanceof Uint8Array;
1247
+ }
1248
+ function isArray(value, itemGuard) {
1249
+ return Array.isArray(value) && value.every(itemGuard);
1250
+ }
1251
+ function isOptional(value, guard) {
1252
+ return value === null || guard(value);
1253
+ }
1254
+ function isOkResponse(response) {
1255
+ return "ok" in response && !("err" in response);
1256
+ }
1257
+ function isErrResponse(response) {
1258
+ return "err" in response && !("ok" in response);
1259
+ }
1260
+ function isResponse(value, okGuard, errGuard) {
1261
+ if (typeof value !== "object" || value === null)
1262
+ return false;
1263
+ const obj = value;
1264
+ if ("ok" in value && !("err" in value))
1265
+ return okGuard(obj.ok);
1266
+ if ("err" in value && !("ok" in value))
1267
+ return errGuard(obj.err);
1268
+ return false;
1269
+ }
1270
+ function isAbiList(type) {
1271
+ return typeof type === "object" && type !== null && "list" in type;
1272
+ }
1273
+ function isAbiTuple(type) {
1274
+ return typeof type === "object" && type !== null && "tuple" in type;
1275
+ }
1276
+ function isAbiOptional(type) {
1277
+ return typeof type === "object" && type !== null && "optional" in type;
1278
+ }
1279
+ function isAbiResponse(type) {
1280
+ return typeof type === "object" && type !== null && "response" in type;
1281
+ }
1282
+ function isAbiBuffer(type) {
1283
+ return typeof type === "object" && type !== null && "buff" in type;
1284
+ }
1285
+ function isAbiStringAscii(type) {
1286
+ return typeof type === "object" && type !== null && "string-ascii" in type;
1287
+ }
1288
+ function isAbiStringUtf8(type) {
1289
+ return typeof type === "object" && type !== null && "string-utf8" in type;
1290
+ }
1291
+ function isAbiTraitReference(type) {
1292
+ return type === "trait_reference";
1293
+ }
1294
+
1295
+ // src/clarity/bridge.ts
1296
+ var CV_TYPE_TAGS = new Set([
1297
+ "int",
1298
+ "uint",
1299
+ "true",
1300
+ "false",
1301
+ "address",
1302
+ "contract",
1303
+ "ascii",
1304
+ "utf8",
1305
+ "buffer",
1306
+ "list",
1307
+ "tuple",
1308
+ "none",
1309
+ "some",
1310
+ "ok",
1311
+ "err"
1312
+ ]);
1313
+ function isClarityValue(value) {
1314
+ if (typeof value !== "object" || value === null)
1315
+ return false;
1316
+ const type = value.type;
1317
+ if (typeof type !== "string" || !CV_TYPE_TAGS.has(type))
1318
+ return false;
1319
+ if (type === "true" || type === "false" || type === "none")
1320
+ return true;
1321
+ return "value" in value;
1322
+ }
1323
+ var HEX_PAIRS_REGEX = /^(?:[0-9a-fA-F]{2})+$/;
1324
+ function coerceBuffer(value) {
1325
+ if (value instanceof Uint8Array)
1326
+ return bufferCV(value);
1327
+ if (typeof value === "object" && value !== null && "type" in value) {
1328
+ const tagged = value;
1329
+ if (tagged.type === "buffer" && isClarityValue(value))
1330
+ return value;
1331
+ if (typeof tagged.value === "string") {
1332
+ if (tagged.type === "ascii")
1333
+ return Cl.bufferFromAscii(tagged.value);
1334
+ if (tagged.type === "utf8")
1335
+ return Cl.bufferFromUtf8(tagged.value);
1336
+ if (tagged.type === "hex")
1337
+ return Cl.bufferFromHex(tagged.value);
1338
+ }
1339
+ throw new Error(`Unsupported buffer input: ${JSON.stringify(value)}`);
1340
+ }
1341
+ if (typeof value === "string") {
1342
+ const hex = value.startsWith("0x") ? value.slice(2) : value;
1343
+ if (HEX_PAIRS_REGEX.test(hex))
1344
+ return Cl.bufferFromHex(hex);
1345
+ return Cl.bufferFromUtf8(value);
1346
+ }
1347
+ throw new Error("buffer arg expects Uint8Array, hex string, { type, value }, or BufferCV");
1348
+ }
1349
+ function jsToClarityValue(abiType, value) {
1350
+ if (isAbiBuffer(abiType))
1351
+ return coerceBuffer(value);
1352
+ if (isClarityValue(value))
1353
+ return value;
1354
+ if (abiType === "uint128")
1355
+ return uintCV(value);
1356
+ if (abiType === "int128")
1357
+ return intCV(value);
1358
+ if (abiType === "bool")
1359
+ return boolCV(value);
1360
+ if (abiType === "principal" || abiType === "trait_reference")
1361
+ return Cl.principal(value);
1362
+ if (isAbiStringAscii(abiType))
1363
+ return stringAsciiCV(value);
1364
+ if (isAbiStringUtf8(abiType))
1365
+ return stringUtf8CV(value);
1366
+ if (isAbiList(abiType)) {
1367
+ const arr = value;
1368
+ return listCV(arr.map((item) => jsToClarityValue(abiType.list.type, item)));
1369
+ }
1370
+ if (isAbiTuple(abiType)) {
1371
+ const obj = value;
1372
+ const data = {};
1373
+ for (const field of abiType.tuple) {
1374
+ const camelKey = toCamelCase(field.name);
1375
+ const hasOriginal = field.name in obj;
1376
+ const hasCamel = camelKey in obj;
1377
+ const fieldValue = hasOriginal ? obj[field.name] : hasCamel ? obj[camelKey] : undefined;
1378
+ if (fieldValue === undefined && !isAbiOptional(field.type)) {
1379
+ throw new Error(`Missing tuple field: ${field.name}`);
1380
+ }
1381
+ data[field.name] = jsToClarityValue(field.type, fieldValue);
1382
+ }
1383
+ return tupleCV(data);
1384
+ }
1385
+ if (isAbiOptional(abiType)) {
1386
+ if (value === null || value === undefined)
1387
+ return noneCV();
1388
+ return someCV(jsToClarityValue(abiType.optional, value));
1389
+ }
1390
+ if (isAbiResponse(abiType)) {
1391
+ const obj = value;
1392
+ if ("ok" in obj && !("err" in obj))
1393
+ return responseOkCV(jsToClarityValue(abiType.response.ok, obj.ok));
1394
+ if ("err" in obj && !("ok" in obj))
1395
+ return responseErrorCV(jsToClarityValue(abiType.response.error, obj.err));
1396
+ throw new Error("Response must have exactly 'ok' or 'err' property");
1397
+ }
1398
+ throw new Error(`Unknown ABI type: ${JSON.stringify(abiType)}`);
1399
+ }
1400
+ function clarityValueToJS(abiType, cv) {
1401
+ return clarityValueToJSInner(abiType, cv);
1402
+ }
1403
+ function clarityValueToJSUntyped(abiType, cv) {
1404
+ return clarityValueToJSInner(abiType, cv);
1405
+ }
1406
+ function clarityValueToJSInner(abiType, cv) {
1407
+ if (abiType === "uint128" || abiType === "int128") {
1408
+ if (cv.type !== "int" && cv.type !== "uint")
1409
+ throw new Error(`Expected int/uint CV, got ${cv.type}`);
1410
+ return cv.value;
1411
+ }
1412
+ if (abiType === "bool") {
1413
+ if (cv.type === "true")
1414
+ return true;
1415
+ if (cv.type === "false")
1416
+ return false;
1417
+ throw new Error(`Expected bool CV, got ${cv.type}`);
1418
+ }
1419
+ if (abiType === "principal" || abiType === "trait_reference") {
1420
+ if (cv.type !== "address" && cv.type !== "contract")
1421
+ throw new Error(`Expected principal CV, got ${cv.type}`);
1422
+ return cv.value;
1423
+ }
1424
+ if (isAbiStringAscii(abiType) || isAbiStringUtf8(abiType)) {
1425
+ if (cv.type !== "ascii" && cv.type !== "utf8")
1426
+ throw new Error(`Expected string CV, got ${cv.type}`);
1427
+ return cv.value;
1428
+ }
1429
+ if (isAbiBuffer(abiType)) {
1430
+ if (cv.type !== "buffer")
1431
+ throw new Error(`Expected buffer CV, got ${cv.type}`);
1432
+ const hex = cv.value;
1433
+ const bytes = new Uint8Array(hex.length / 2);
1434
+ for (let i = 0;i < bytes.length; i++) {
1435
+ bytes[i] = Number.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
1436
+ }
1437
+ return bytes;
1438
+ }
1439
+ if (isAbiList(abiType)) {
1440
+ if (cv.type !== "list")
1441
+ throw new Error(`Expected list CV, got ${cv.type}`);
1442
+ return cv.value.map((item) => clarityValueToJSInner(abiType.list.type, item));
1443
+ }
1444
+ if (isAbiTuple(abiType)) {
1445
+ if (cv.type !== "tuple")
1446
+ throw new Error(`Expected tuple CV, got ${cv.type}`);
1447
+ const result = {};
1448
+ for (const field of abiType.tuple) {
1449
+ const fieldCV = cv.value[field.name];
1450
+ if (!fieldCV)
1451
+ throw new Error(`Missing tuple field in CV: ${field.name}`);
1452
+ const camelKey = toCamelCase(field.name);
1453
+ result[camelKey] = clarityValueToJSInner(field.type, fieldCV);
1454
+ }
1455
+ return result;
1456
+ }
1457
+ if (isAbiOptional(abiType)) {
1458
+ if (cv.type === "none")
1459
+ return null;
1460
+ if (cv.type === "some")
1461
+ return clarityValueToJSInner(abiType.optional, cv.value);
1462
+ throw new Error(`Expected optional CV, got ${cv.type}`);
1463
+ }
1464
+ if (isAbiResponse(abiType)) {
1465
+ if (cv.type === "ok")
1466
+ return { ok: clarityValueToJSInner(abiType.response.ok, cv.value) };
1467
+ if (cv.type === "err")
1468
+ return { err: clarityValueToJSInner(abiType.response.error, cv.value) };
1469
+ throw new Error(`Expected response CV, got ${cv.type}`);
1470
+ }
1471
+ throw new Error(`Unknown ABI type: ${JSON.stringify(abiType)}`);
1472
+ }
1473
+
1474
+ // src/transactions/types.ts
1475
+ var AuthType = {
1476
+ Standard: 4,
1477
+ Sponsored: 5
1478
+ };
1479
+ var PayloadType = {
1480
+ TokenTransfer: 0,
1481
+ SmartContract: 1,
1482
+ ContractCall: 2,
1483
+ PoisonMicroblock: 3,
1484
+ Coinbase: 4,
1485
+ CoinbaseToAltRecipient: 5,
1486
+ VersionedSmartContract: 6,
1487
+ TenureChange: 7,
1488
+ NakamotoCoinbase: 8
1489
+ };
1490
+ var ClarityVersion = {
1491
+ Clarity1: 1,
1492
+ Clarity2: 2,
1493
+ Clarity3: 3,
1494
+ Clarity4: 4,
1495
+ Clarity5: 5,
1496
+ Clarity6: 6
1497
+ };
1498
+ var AnchorMode = {
1499
+ OnChainOnly: 1,
1500
+ OffChainOnly: 2,
1501
+ Any: 3
1502
+ };
1503
+ var PostConditionModeWire = {
1504
+ Allow: 1,
1505
+ Deny: 2,
1506
+ Originator: 3
1507
+ };
1508
+ var AddressHashMode = {
1509
+ P2PKH: 0,
1510
+ P2SH: 1,
1511
+ P2WPKH: 2,
1512
+ P2WSH: 3,
1513
+ P2SH_NonSequential: 5,
1514
+ P2WSH_P2SH_NonSequential: 7
1515
+ };
1516
+ var PubKeyEncoding = {
1517
+ Compressed: 0,
1518
+ Uncompressed: 1
1519
+ };
1520
+ var FungibleConditionCode = {
1521
+ Equal: 1,
1522
+ Greater: 2,
1523
+ GreaterEqual: 3,
1524
+ Less: 4,
1525
+ LessEqual: 5
1526
+ };
1527
+ var NonFungibleConditionCode = {
1528
+ Sends: 16,
1529
+ DoesNotSend: 17,
1530
+ MaybeSent: 18
1531
+ };
1532
+ var PoxConditionCode = {
1533
+ WillNotPerform: 48,
1534
+ MayPerform: 49,
1535
+ WillPerform: 50
1536
+ };
1537
+ var PostConditionPrincipalId = {
1538
+ Origin: 1,
1539
+ Standard: 2,
1540
+ Contract: 3
1541
+ };
1542
+ var AssetType = {
1543
+ STX: 0,
1544
+ Fungible: 1,
1545
+ NonFungible: 2,
1546
+ Staking: 3,
1547
+ Pox: 4
1548
+ };
1549
+ var AuthFieldType = {
1550
+ PublicKeyCompressed: 0,
1551
+ PublicKeyUncompressed: 1,
1552
+ SignatureCompressed: 2,
1553
+ SignatureUncompressed: 3
1554
+ };
1555
+ var RECOVERABLE_ECDSA_SIG_LENGTH_BYTES = 65;
1556
+ var MEMO_MAX_LENGTH_BYTES = 34;
1557
+ var MAX_STRING_LENGTH_BYTES = 128;
1558
+ var COINBASE_BYTES_LENGTH = 32;
1559
+ var VRF_PROOF_BYTES_LENGTH = 80;
1560
+ var MICROBLOCK_HEADER_BYTES_LENGTH = 132;
1561
+ var TenureChangeCause = {
1562
+ BlockFound: 0,
1563
+ Extended: 1,
1564
+ ExtendedRuntime: 2,
1565
+ ExtendedReadCount: 3,
1566
+ ExtendedReadLength: 4,
1567
+ ExtendedWriteCount: 5,
1568
+ ExtendedWriteLength: 6
1569
+ };
1570
+
1571
+ // src/transactions/wire/deserialize.ts
1572
+ function readSpendingCondition(r) {
1573
+ const hashMode = r.readUInt8();
1574
+ const signer = bytesToHex(r.readBytes(20));
1575
+ const nonce = r.readBigUInt64BE();
1576
+ const fee = r.readBigUInt64BE();
1577
+ if (hashMode === AddressHashMode.P2PKH || hashMode === AddressHashMode.P2WPKH) {
1578
+ const keyEncoding = r.readUInt8();
1579
+ const signature = bytesToHex(r.readBytes(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES));
1580
+ return {
1581
+ hashMode,
1582
+ signer,
1583
+ nonce,
1584
+ fee,
1585
+ keyEncoding,
1586
+ signature
1587
+ };
1588
+ }
1589
+ const fieldCount = r.readUInt32BE();
1590
+ const fields = [];
1591
+ for (let i = 0;i < fieldCount; i++) {
1592
+ const fieldType = r.readUInt8();
1593
+ if (fieldType <= 1) {
1594
+ const keyLen = fieldType === 0 ? 33 : 65;
1595
+ fields.push({
1596
+ type: "publicKey",
1597
+ pubKeyEncoding: fieldType,
1598
+ data: bytesToHex(r.readBytes(keyLen))
1599
+ });
1600
+ } else {
1601
+ fields.push({
1602
+ type: "signature",
1603
+ pubKeyEncoding: fieldType === 2 ? 0 : 1,
1604
+ data: bytesToHex(r.readBytes(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES))
1605
+ });
1606
+ }
1607
+ }
1608
+ const signaturesRequired = r.readUInt16BE();
1609
+ return {
1610
+ hashMode,
1611
+ signer,
1612
+ nonce,
1613
+ fee,
1614
+ fields,
1615
+ signaturesRequired
1616
+ };
1617
+ }
1618
+ function readAuthorization(r) {
1619
+ const authType = r.readUInt8();
1620
+ const spendingCondition = readSpendingCondition(r);
1621
+ if (authType === AuthType.Standard) {
1622
+ return { authType: AuthType.Standard, spendingCondition };
1623
+ }
1624
+ const sponsorSpendingCondition = readSpendingCondition(r);
1625
+ return {
1626
+ authType: AuthType.Sponsored,
1627
+ spendingCondition,
1628
+ sponsorSpendingCondition
1629
+ };
1630
+ }
1631
+ function readAssetInfo(r) {
1632
+ return {
1633
+ address: readAddress(r),
1634
+ contractName: readLPString(r),
1635
+ assetName: readLPString(r)
1636
+ };
1637
+ }
1638
+ function readPostConditionPrincipal(r) {
1639
+ const type = r.readUInt8();
1640
+ switch (type) {
1641
+ case PostConditionPrincipalId.Origin:
1642
+ return { type: "origin" };
1643
+ case PostConditionPrincipalId.Standard:
1644
+ return { type: "standard", address: readAddress(r) };
1645
+ case PostConditionPrincipalId.Contract:
1646
+ return {
1647
+ type: "contract",
1648
+ address: readAddress(r),
1649
+ contractName: readLPString(r)
1650
+ };
1651
+ default:
1652
+ return { type: "origin" };
1653
+ }
1654
+ }
1655
+ function readPostCondition(r) {
1656
+ const assetType = r.readUInt8();
1657
+ const principal = readPostConditionPrincipal(r);
1658
+ switch (assetType) {
1659
+ case AssetType.STX:
1660
+ return {
1661
+ type: "stx",
1662
+ principal,
1663
+ conditionCode: r.readUInt8(),
1664
+ amount: r.readBigUInt64BE()
1665
+ };
1666
+ case AssetType.Fungible:
1667
+ return {
1668
+ type: "ft",
1669
+ principal,
1670
+ asset: readAssetInfo(r),
1671
+ conditionCode: r.readUInt8(),
1672
+ amount: r.readBigUInt64BE()
1673
+ };
1674
+ case AssetType.NonFungible:
1675
+ return {
1676
+ type: "nft",
1677
+ principal,
1678
+ asset: readAssetInfo(r),
1679
+ assetId: readCV(r),
1680
+ conditionCode: r.readUInt8()
1681
+ };
1682
+ case AssetType.Staking:
1683
+ return {
1684
+ type: "staking",
1685
+ principal,
1686
+ conditionCode: r.readUInt8(),
1687
+ amount: r.readBigUInt64BE()
1688
+ };
1689
+ case AssetType.Pox:
1690
+ return {
1691
+ type: "pox",
1692
+ principal,
1693
+ conditionCode: r.readUInt8()
1694
+ };
1695
+ default:
1696
+ throw new Error(`Unknown post-condition asset type: 0x${assetType.toString(16).padStart(2, "0")}`);
1697
+ }
1698
+ }
1699
+ function readPostConditions(r) {
1700
+ const count = r.readUInt32BE();
1701
+ const pcs = [];
1702
+ for (let i = 0;i < count; i++) {
1703
+ try {
1704
+ pcs.push(readPostCondition(r));
1705
+ } catch (e) {
1706
+ if (e instanceof Error && e.message.startsWith("Unknown post-condition asset type:")) {
1707
+ throw new Error(`${e.message} (post-condition ${i + 1}/${count})`);
1708
+ }
1709
+ throw e;
1710
+ }
1711
+ }
1712
+ return pcs;
1713
+ }
1714
+ function readPayload(r) {
1715
+ const payloadType = r.readUInt8();
1716
+ switch (payloadType) {
1717
+ case PayloadType.TokenTransfer: {
1718
+ const recipient = readCV(r);
1719
+ const amount = r.readBigUInt64BE();
1720
+ const memoBytes = r.readBytes(MEMO_MAX_LENGTH_BYTES);
1721
+ const memo = bytesToAscii(memoBytes).replace(/\0+$/, "");
1722
+ return {
1723
+ payloadType: PayloadType.TokenTransfer,
1724
+ recipient,
1725
+ amount,
1726
+ memo
1727
+ };
1728
+ }
1729
+ case PayloadType.ContractCall: {
1730
+ const contractAddress = readAddress(r);
1731
+ const contractName = readLPString(r);
1732
+ const functionName = readLPString(r);
1733
+ const numArgs = r.readUInt32BE();
1734
+ const functionArgs = [];
1735
+ for (let i = 0;i < numArgs; i++)
1736
+ functionArgs.push(readCV(r));
1737
+ return {
1738
+ payloadType: PayloadType.ContractCall,
1739
+ contractAddress,
1740
+ contractName,
1741
+ functionName,
1742
+ functionArgs
1743
+ };
1744
+ }
1745
+ case PayloadType.SmartContract: {
1746
+ const contractName = readLPString(r);
1747
+ const codeBody = readLPString(r, 4);
1748
+ return { payloadType: PayloadType.SmartContract, contractName, codeBody };
1749
+ }
1750
+ case PayloadType.VersionedSmartContract: {
1751
+ const clarityVersion = r.readUInt8();
1752
+ const contractName = readLPString(r);
1753
+ const codeBody = readLPString(r, 4);
1754
+ return {
1755
+ payloadType: PayloadType.VersionedSmartContract,
1756
+ clarityVersion,
1757
+ contractName,
1758
+ codeBody
1759
+ };
1760
+ }
1761
+ case PayloadType.Coinbase: {
1762
+ const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
1763
+ return { payloadType: PayloadType.Coinbase, coinbaseBuffer };
1764
+ }
1765
+ case PayloadType.CoinbaseToAltRecipient: {
1766
+ const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
1767
+ const recipient = readCV(r);
1768
+ return {
1769
+ payloadType: PayloadType.CoinbaseToAltRecipient,
1770
+ coinbaseBuffer,
1771
+ recipient
1772
+ };
1773
+ }
1774
+ case PayloadType.PoisonMicroblock: {
1775
+ const header1 = bytesToHex(r.readBytes(MICROBLOCK_HEADER_BYTES_LENGTH));
1776
+ const header2 = bytesToHex(r.readBytes(MICROBLOCK_HEADER_BYTES_LENGTH));
1777
+ return { payloadType: PayloadType.PoisonMicroblock, header1, header2 };
1778
+ }
1779
+ case PayloadType.TenureChange: {
1780
+ const tenureConsensusHash = bytesToHex(r.readBytes(20));
1781
+ const prevTenureConsensusHash = bytesToHex(r.readBytes(20));
1782
+ const burnViewConsensusHash = bytesToHex(r.readBytes(20));
1783
+ const previousTenureEnd = bytesToHex(r.readBytes(32));
1784
+ const previousTenureBlocks = r.readUInt32BE();
1785
+ const cause = r.readUInt8();
1786
+ const pubkeyHash = bytesToHex(r.readBytes(20));
1787
+ return {
1788
+ payloadType: PayloadType.TenureChange,
1789
+ tenureConsensusHash,
1790
+ prevTenureConsensusHash,
1791
+ burnViewConsensusHash,
1792
+ previousTenureEnd,
1793
+ previousTenureBlocks,
1794
+ cause,
1795
+ pubkeyHash
1796
+ };
1797
+ }
1798
+ case PayloadType.NakamotoCoinbase: {
1799
+ const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
1800
+ const optionalCV = readCV(r);
1801
+ const recipient = optionalCV.type === "none" ? null : optionalCV.type === "some" ? optionalCV.value : optionalCV;
1802
+ const vrfProof = bytesToHex(r.readBytes(VRF_PROOF_BYTES_LENGTH));
1803
+ return {
1804
+ payloadType: PayloadType.NakamotoCoinbase,
1805
+ coinbaseBuffer,
1806
+ recipient,
1807
+ vrfProof
1808
+ };
1809
+ }
1810
+ default:
1811
+ throw new Error(`Unknown payload type: ${payloadType}`);
1812
+ }
1813
+ }
1814
+ function deserializePostConditionWire(input) {
1815
+ const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
1816
+ return readPostCondition(new BytesReader(bytes));
1817
+ }
1818
+ function deserializeTransaction(input, meta) {
1819
+ const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
1820
+ const r = new BytesReader(bytes);
1821
+ const tx = {
1822
+ version: r.readUInt8(),
1823
+ chainId: r.readUInt32BE(),
1824
+ auth: readAuthorization(r),
1825
+ anchorMode: r.readUInt8(),
1826
+ postConditionMode: r.readUInt8(),
1827
+ postConditions: readPostConditions(r),
1828
+ payload: readPayload(r)
1829
+ };
1830
+ if (meta?._multisig) {
1831
+ tx._multisig = meta._multisig;
1832
+ }
1833
+ return tx;
1834
+ }
1835
+
1836
+ // src/transactions/wire/serialize.ts
1837
+ function serializeAddress2(c32Address) {
1838
+ const [version, hash160] = c32addressDecode(c32Address);
1839
+ return concatBytes(new Uint8Array([version]), hexToBytes(hash160));
1840
+ }
1841
+ function serializeLPString2(str, prefixBytes = 1) {
1842
+ const content = utf8ToBytes(str);
1843
+ const prefix = hexToBytes(intToHex(content.byteLength, prefixBytes));
1844
+ return concatBytes(prefix, content);
1845
+ }
1846
+ function serializeLPStringLong(str) {
1847
+ return serializeLPString2(str, 4);
1848
+ }
1849
+ function serializeMemo(memo) {
1850
+ const content = asciiToBytes(memo);
1851
+ const padded = new Uint8Array(MEMO_MAX_LENGTH_BYTES);
1852
+ padded.set(content.slice(0, MEMO_MAX_LENGTH_BYTES));
1853
+ return padded;
1854
+ }
1855
+ function serializeSpendingCondition(condition) {
1856
+ const parts = [
1857
+ writeUInt8(condition.hashMode),
1858
+ hexToBytes(condition.signer),
1859
+ intToBytes(condition.nonce, 8),
1860
+ intToBytes(condition.fee, 8)
1861
+ ];
1862
+ if ("signature" in condition) {
1863
+ const sc = condition;
1864
+ parts.push(writeUInt8(sc.keyEncoding));
1865
+ parts.push(hexToBytes(sc.signature));
1866
+ } else {
1867
+ const mc = condition;
1868
+ parts.push(writeUInt32BE(mc.fields.length));
1869
+ for (const field of mc.fields) {
1870
+ parts.push(serializeAuthField(field));
1871
+ }
1872
+ parts.push(writeUInt16BE(mc.signaturesRequired));
1873
+ }
1874
+ return concatBytes(...parts);
1875
+ }
1876
+ function serializeAuthField(field) {
1877
+ if (field.type === "publicKey") {
1878
+ const typeId = field.pubKeyEncoding === 0 ? 0 : 1;
1879
+ return concatBytes(writeUInt8(typeId), hexToBytes(field.data));
1880
+ }
1881
+ const typeId = field.pubKeyEncoding === 0 ? 2 : 3;
1882
+ return concatBytes(writeUInt8(typeId), hexToBytes(field.data));
1883
+ }
1884
+ function serializeAuthorization(auth) {
1885
+ const parts = [writeUInt8(auth.authType)];
1886
+ parts.push(serializeSpendingCondition(auth.spendingCondition));
1887
+ if (auth.authType === AuthType.Sponsored) {
1888
+ parts.push(serializeSpendingCondition(auth.sponsorSpendingCondition));
1889
+ }
1890
+ return concatBytes(...parts);
1891
+ }
1892
+ function serializePrincipal(principal) {
1893
+ switch (principal.type) {
1894
+ case "origin":
1895
+ return writeUInt8(PostConditionPrincipalId.Origin);
1896
+ case "standard":
1897
+ return concatBytes(writeUInt8(PostConditionPrincipalId.Standard), serializeAddress2(principal.address));
1898
+ case "contract":
1899
+ return concatBytes(writeUInt8(PostConditionPrincipalId.Contract), serializeAddress2(principal.address), serializeLPString2(principal.contractName));
1900
+ }
1901
+ }
1902
+ function serializeAssetInfo(asset) {
1903
+ return concatBytes(serializeAddress2(asset.address), serializeLPString2(asset.contractName), serializeLPString2(asset.assetName));
1904
+ }
1905
+ function serializePostConditionWire(pc) {
1906
+ const parts = [];
1907
+ switch (pc.type) {
1908
+ case "stx":
1909
+ parts.push(writeUInt8(AssetType.STX));
1910
+ parts.push(serializePrincipal(pc.principal));
1911
+ parts.push(writeUInt8(pc.conditionCode));
1912
+ parts.push(intToBytes(pc.amount, 8));
1913
+ break;
1914
+ case "ft":
1915
+ parts.push(writeUInt8(AssetType.Fungible));
1916
+ parts.push(serializePrincipal(pc.principal));
1917
+ parts.push(serializeAssetInfo(pc.asset));
1918
+ parts.push(writeUInt8(pc.conditionCode));
1919
+ parts.push(intToBytes(pc.amount, 8));
1920
+ break;
1921
+ case "nft":
1922
+ parts.push(writeUInt8(AssetType.NonFungible));
1923
+ parts.push(serializePrincipal(pc.principal));
1924
+ parts.push(serializeAssetInfo(pc.asset));
1925
+ parts.push(serializeCVBytes(pc.assetId));
1926
+ parts.push(writeUInt8(pc.conditionCode));
1927
+ break;
1928
+ case "staking":
1929
+ parts.push(writeUInt8(AssetType.Staking));
1930
+ parts.push(serializePrincipal(pc.principal));
1931
+ parts.push(writeUInt8(pc.conditionCode));
1932
+ parts.push(intToBytes(pc.amount, 8));
1933
+ break;
1934
+ case "pox":
1935
+ parts.push(writeUInt8(AssetType.Pox));
1936
+ parts.push(serializePrincipal(pc.principal));
1937
+ parts.push(writeUInt8(pc.conditionCode));
1938
+ break;
1939
+ }
1940
+ return concatBytes(...parts);
1941
+ }
1942
+ function serializePostConditions(pcs) {
1943
+ const parts = [writeUInt32BE(pcs.length)];
1944
+ for (const pc of pcs)
1945
+ parts.push(serializePostConditionWire(pc));
1946
+ return concatBytes(...parts);
1947
+ }
1948
+ function serializePayload(payload) {
1949
+ const parts = [writeUInt8(payload.payloadType)];
1950
+ switch (payload.payloadType) {
1951
+ case PayloadType.TokenTransfer:
1952
+ parts.push(serializeCVBytes(payload.recipient));
1953
+ parts.push(intToBytes(payload.amount, 8));
1954
+ parts.push(serializeMemo(payload.memo));
1955
+ break;
1956
+ case PayloadType.ContractCall:
1957
+ parts.push(serializeAddress2(payload.contractAddress));
1958
+ parts.push(serializeLPString2(payload.contractName));
1959
+ parts.push(serializeLPString2(payload.functionName));
1960
+ parts.push(writeUInt32BE(payload.functionArgs.length));
1961
+ for (const arg of payload.functionArgs) {
1962
+ parts.push(serializeCVBytes(arg));
1963
+ }
1964
+ break;
1965
+ case PayloadType.SmartContract:
1966
+ parts.push(serializeLPString2(payload.contractName));
1967
+ parts.push(serializeLPStringLong(payload.codeBody));
1968
+ break;
1969
+ case PayloadType.VersionedSmartContract:
1970
+ parts.push(writeUInt8(payload.clarityVersion ?? 2));
1971
+ parts.push(serializeLPString2(payload.contractName));
1972
+ parts.push(serializeLPStringLong(payload.codeBody));
1973
+ break;
1974
+ case PayloadType.Coinbase:
1975
+ parts.push(hexToBytes(payload.coinbaseBuffer));
1976
+ break;
1977
+ case PayloadType.CoinbaseToAltRecipient: {
1978
+ const cbAlt = payload;
1979
+ parts.push(hexToBytes(cbAlt.coinbaseBuffer));
1980
+ parts.push(serializeCVBytes(cbAlt.recipient));
1981
+ break;
1982
+ }
1983
+ case PayloadType.PoisonMicroblock: {
1984
+ const pm = payload;
1985
+ parts.push(hexToBytes(pm.header1));
1986
+ parts.push(hexToBytes(pm.header2));
1987
+ break;
1988
+ }
1989
+ case PayloadType.TenureChange: {
1990
+ const tc = payload;
1991
+ parts.push(hexToBytes(tc.tenureConsensusHash));
1992
+ parts.push(hexToBytes(tc.prevTenureConsensusHash));
1993
+ parts.push(hexToBytes(tc.burnViewConsensusHash));
1994
+ parts.push(hexToBytes(tc.previousTenureEnd));
1995
+ parts.push(writeUInt32BE(tc.previousTenureBlocks));
1996
+ parts.push(writeUInt8(tc.cause));
1997
+ parts.push(hexToBytes(tc.pubkeyHash));
1998
+ break;
1999
+ }
2000
+ case PayloadType.NakamotoCoinbase: {
2001
+ const nc = payload;
2002
+ parts.push(hexToBytes(nc.coinbaseBuffer));
2003
+ if (nc.recipient) {
2004
+ parts.push(serializeCVBytes({ type: "some", value: nc.recipient }));
2005
+ } else {
2006
+ parts.push(serializeCVBytes({ type: "none" }));
2007
+ }
2008
+ parts.push(hexToBytes(nc.vrfProof));
2009
+ break;
2010
+ }
2011
+ }
2012
+ return concatBytes(...parts);
2013
+ }
2014
+ var _txCache = new WeakMap;
2015
+ function clearTxCache(tx) {
2016
+ _txCache.delete(tx);
2017
+ }
2018
+ function serializeTransaction(tx) {
2019
+ const cached = _txCache.get(tx);
2020
+ if (cached)
2021
+ return cached;
2022
+ const bytes = concatBytes(writeUInt8(tx.version), writeUInt32BE(tx.chainId), serializeAuthorization(tx.auth), writeUInt8(tx.anchorMode), writeUInt8(tx.postConditionMode), serializePostConditions(tx.postConditions), serializePayload(tx.payload));
2023
+ _txCache.set(tx, bytes);
2024
+ return bytes;
2025
+ }
2026
+ function serializeTransactionHex(tx) {
2027
+ return bytesToHex(serializeTransaction(tx));
2028
+ }
2029
+
2030
+ // src/postconditions/convert.ts
2031
+ var MAX_U64 = 18446744073709551615n;
2032
+ function parsePostConditionAmount(amount) {
2033
+ const value = intToBigInt(amount);
2034
+ if (value < 0n || value > MAX_U64) {
2035
+ throw new RangeError(`Post-condition amount must be between 0 and ${MAX_U64} (u64 max), received: ${value}`);
2036
+ }
2037
+ return value;
2038
+ }
2039
+ var FUNGIBLE_CODE_MAP = {
2040
+ eq: FungibleConditionCode.Equal,
2041
+ gt: FungibleConditionCode.Greater,
2042
+ gte: FungibleConditionCode.GreaterEqual,
2043
+ lt: FungibleConditionCode.Less,
2044
+ lte: FungibleConditionCode.LessEqual
2045
+ };
2046
+ var FUNGIBLE_CODE_REVERSE = {
2047
+ [FungibleConditionCode.Equal]: "eq",
2048
+ [FungibleConditionCode.Greater]: "gt",
2049
+ [FungibleConditionCode.GreaterEqual]: "gte",
2050
+ [FungibleConditionCode.Less]: "lt",
2051
+ [FungibleConditionCode.LessEqual]: "lte"
2052
+ };
2053
+ var NFT_CODE_MAP = {
2054
+ sent: NonFungibleConditionCode.Sends,
2055
+ "not-sent": NonFungibleConditionCode.DoesNotSend,
2056
+ "maybe-sent": NonFungibleConditionCode.MaybeSent
2057
+ };
2058
+ var NFT_CODE_REVERSE = {
2059
+ [NonFungibleConditionCode.Sends]: "sent",
2060
+ [NonFungibleConditionCode.DoesNotSend]: "not-sent",
2061
+ [NonFungibleConditionCode.MaybeSent]: "maybe-sent"
2062
+ };
2063
+ var POX_CODE_MAP = {
2064
+ "will-not-perform": PoxConditionCode.WillNotPerform,
2065
+ "may-perform": PoxConditionCode.MayPerform,
2066
+ "will-perform": PoxConditionCode.WillPerform
2067
+ };
2068
+ var POX_CODE_REVERSE = {
2069
+ [PoxConditionCode.WillNotPerform]: "will-not-perform",
2070
+ [PoxConditionCode.MayPerform]: "may-perform",
2071
+ [PoxConditionCode.WillPerform]: "will-perform"
2072
+ };
2073
+ function resolvePrincipal(address) {
2074
+ if (address === "origin")
2075
+ return { type: "origin" };
2076
+ const [addr, name] = address.split(".");
2077
+ if (name) {
2078
+ return { type: "contract", address: addr, contractName: name };
2079
+ }
2080
+ return { type: "standard", address: addr };
2081
+ }
2082
+ function principalToString(principal) {
2083
+ if (principal.type === "origin")
2084
+ return "origin";
2085
+ if (principal.type === "contract") {
2086
+ return `${principal.address}.${principal.contractName}`;
2087
+ }
2088
+ return principal.address;
2089
+ }
2090
+ function assetToString(asset) {
2091
+ return `${asset.address}.${asset.contractName}::${asset.assetName}`;
2092
+ }
2093
+ function parseAsset(asset) {
2094
+ const [contractId, tokenName] = asset.split("::");
2095
+ const [addr, name] = parseContractId(contractId);
2096
+ return { address: addr, contractName: name, assetName: tokenName };
2097
+ }
2098
+ function convertPostCondition(pc) {
2099
+ switch (pc.type) {
2100
+ case "stx-postcondition":
2101
+ return {
2102
+ type: "stx",
2103
+ principal: resolvePrincipal(pc.address),
2104
+ conditionCode: FUNGIBLE_CODE_MAP[pc.condition],
2105
+ amount: parsePostConditionAmount(pc.amount)
2106
+ };
2107
+ case "ft-postcondition":
2108
+ return {
2109
+ type: "ft",
2110
+ principal: resolvePrincipal(pc.address),
2111
+ asset: parseAsset(pc.asset),
2112
+ conditionCode: FUNGIBLE_CODE_MAP[pc.condition],
2113
+ amount: parsePostConditionAmount(pc.amount)
2114
+ };
2115
+ case "nft-postcondition":
2116
+ return {
2117
+ type: "nft",
2118
+ principal: resolvePrincipal(pc.address),
2119
+ asset: parseAsset(pc.asset),
2120
+ conditionCode: NFT_CODE_MAP[pc.condition],
2121
+ assetId: pc.assetId
2122
+ };
2123
+ case "staking-postcondition":
2124
+ return {
2125
+ type: "staking",
2126
+ principal: resolvePrincipal(pc.address),
2127
+ conditionCode: FUNGIBLE_CODE_MAP[pc.condition],
2128
+ amount: parsePostConditionAmount(pc.amount)
2129
+ };
2130
+ case "pox-postcondition":
2131
+ return {
2132
+ type: "pox",
2133
+ principal: resolvePrincipal(pc.address),
2134
+ conditionCode: POX_CODE_MAP[pc.condition]
2135
+ };
2136
+ }
2137
+ }
2138
+ function wireToPostCondition(wire) {
2139
+ switch (wire.type) {
2140
+ case "stx":
2141
+ return {
2142
+ type: "stx-postcondition",
2143
+ address: principalToString(wire.principal),
2144
+ condition: fungibleName(wire.conditionCode),
2145
+ amount: wire.amount.toString()
2146
+ };
2147
+ case "ft":
2148
+ return {
2149
+ type: "ft-postcondition",
2150
+ address: principalToString(wire.principal),
2151
+ condition: fungibleName(wire.conditionCode),
2152
+ amount: wire.amount.toString(),
2153
+ asset: assetToString(wire.asset)
2154
+ };
2155
+ case "nft":
2156
+ return {
2157
+ type: "nft-postcondition",
2158
+ address: principalToString(wire.principal),
2159
+ condition: nftName(wire.conditionCode),
2160
+ asset: assetToString(wire.asset),
2161
+ assetId: wire.assetId
2162
+ };
2163
+ case "staking":
2164
+ return {
2165
+ type: "staking-postcondition",
2166
+ address: principalToString(wire.principal),
2167
+ condition: fungibleName(wire.conditionCode),
2168
+ amount: wire.amount.toString()
2169
+ };
2170
+ case "pox":
2171
+ return {
2172
+ type: "pox-postcondition",
2173
+ address: principalToString(wire.principal),
2174
+ condition: poxName(wire.conditionCode)
2175
+ };
2176
+ }
2177
+ }
2178
+ function fungibleName(code) {
2179
+ const name = FUNGIBLE_CODE_REVERSE[code];
2180
+ if (!name)
2181
+ throw new Error(`Unknown fungible post-condition code: ${code}`);
2182
+ return name;
2183
+ }
2184
+ function nftName(code) {
2185
+ const name = NFT_CODE_REVERSE[code];
2186
+ if (!name)
2187
+ throw new Error(`Unknown nft post-condition code: ${code}`);
2188
+ return name;
2189
+ }
2190
+ function poxName(code) {
2191
+ const name = POX_CODE_REVERSE[code];
2192
+ if (!name)
2193
+ throw new Error(`Unknown pox post-condition code: ${code}`);
2194
+ return name;
2195
+ }
2196
+ function fromHex(hex) {
2197
+ return wireToPostCondition(deserializePostConditionWire(hex));
2198
+ }
2199
+ function postConditionToHex(pc) {
2200
+ return bytesToHex(serializePostConditionWire(convertPostCondition(pc)));
2201
+ }
2202
+
2203
+ // src/transactions/authorization.ts
2204
+ var import_hmac = require("@noble/hashes/hmac.js");
2205
+ var import_sha24 = require("@noble/hashes/sha2.js");
2206
+ var import_secp256k1 = require("@noble/secp256k1");
2207
+ import_secp256k1.etc.hmacSha256Sync = (key, ...msgs) => {
2208
+ const h = import_hmac.hmac.create(import_sha24.sha256, key);
2209
+ for (const msg of msgs)
2210
+ h.update(msg);
2211
+ return h.digest();
2212
+ };
2213
+ var EMPTY_SIG = bytesToHex(new Uint8Array(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES));
2214
+ function createSingleSigSpendingCondition(publicKey, nonce, fee) {
2215
+ const pubKeyBytes = hexToBytes(publicKey);
2216
+ const signer = hashP2PKH(pubKeyBytes);
2217
+ const isCompressed = pubKeyBytes.length === 33;
2218
+ return {
2219
+ hashMode: AddressHashMode.P2PKH,
2220
+ signer,
2221
+ nonce,
2222
+ fee,
2223
+ keyEncoding: isCompressed ? PubKeyEncoding.Compressed : PubKeyEncoding.Uncompressed,
2224
+ signature: EMPTY_SIG
2225
+ };
2226
+ }
2227
+ function createStandardAuth(spendingCondition) {
2228
+ return { authType: AuthType.Standard, spendingCondition };
2229
+ }
2230
+ function createSponsoredAuth(spendingCondition, sponsorSpendingCondition) {
2231
+ return {
2232
+ authType: AuthType.Sponsored,
2233
+ spendingCondition,
2234
+ sponsorSpendingCondition: sponsorSpendingCondition ?? createSingleSigSpendingCondition("0".repeat(66), 0n, 0n)
2235
+ };
2236
+ }
2237
+ function clearCondition(condition) {
2238
+ if ("signature" in condition) {
2239
+ return {
2240
+ ...condition,
2241
+ nonce: 0n,
2242
+ fee: 0n,
2243
+ signature: EMPTY_SIG
2244
+ };
2245
+ }
2246
+ return {
2247
+ ...condition,
2248
+ nonce: 0n,
2249
+ fee: 0n,
2250
+ fields: []
2251
+ };
2252
+ }
2253
+ function sponsorSigningSentinel() {
2254
+ return {
2255
+ hashMode: AddressHashMode.P2PKH,
2256
+ signer: "00".repeat(20),
2257
+ nonce: 0n,
2258
+ fee: 0n,
2259
+ keyEncoding: PubKeyEncoding.Compressed,
2260
+ signature: EMPTY_SIG
2261
+ };
2262
+ }
2263
+ function intoInitialSighashAuth(auth) {
2264
+ if (auth.authType === AuthType.Standard) {
2265
+ return createStandardAuth(clearCondition(auth.spendingCondition));
2266
+ }
2267
+ return createSponsoredAuth(clearCondition(auth.spendingCondition), sponsorSigningSentinel());
2268
+ }
2269
+ function sigHashPreSign(curSigHash, authType, fee, nonce) {
2270
+ const data = concatBytes(hexToBytes(curSigHash), new Uint8Array([authType]), intToBytes(fee, 8), intToBytes(nonce, 8));
2271
+ return txidFromBytes(data);
2272
+ }
2273
+ function sigHashPostSign(curSigHash, pubKeyEncoding, signature) {
2274
+ const data = concatBytes(hexToBytes(curSigHash), new Uint8Array([pubKeyEncoding]), hexToBytes(signature));
2275
+ return txidFromBytes(data);
2276
+ }
2277
+ function signWithKey(privateKey, messageHash) {
2278
+ const keyBytes = hexToBytes(privateKey).slice(0, 32);
2279
+ const sig = import_secp256k1.sign(messageHash, keyBytes, { lowS: true });
2280
+ const recoveryIdHex = intToHex(sig.recovery, 1);
2281
+ return recoveryIdHex + sig.toCompactHex();
2282
+ }
2283
+ function nextSignature(curSigHash, authType, fee, nonce, privateKey) {
2284
+ const sigHashPre = sigHashPreSign(curSigHash, authType, fee, nonce);
2285
+ const keyBytes = hexToBytes(privateKey).slice(0, 32);
2286
+ const pubKey = import_secp256k1.getPublicKey(keyBytes, true);
2287
+ const isCompressed = pubKey.length === 33;
2288
+ const pubKeyEncoding = isCompressed ? PubKeyEncoding.Compressed : PubKeyEncoding.Uncompressed;
2289
+ const nextSig = signWithKey(privateKey, sigHashPre);
2290
+ const nextSigHash = sigHashPostSign(sigHashPre, pubKeyEncoding, nextSig);
2291
+ return { nextSig, nextSigHash };
2292
+ }
2293
+
2294
+ // src/transactions/multisig.ts
2295
+ var import_secp256k12 = require("@noble/secp256k1");
2296
+ var OP_CHECKMULTISIG = 174;
2297
+ function isNonSequential(hashMode) {
2298
+ return (hashMode & 4) !== 0;
2299
+ }
2300
+ function makeRedeemScript(publicKeys, signaturesRequired) {
2301
+ const parts = [];
2302
+ parts.push(new Uint8Array([80 + signaturesRequired]));
2303
+ for (const pk of publicKeys) {
2304
+ const pkBytes = hexToBytes(pk);
2305
+ parts.push(new Uint8Array([pkBytes.length]));
2306
+ parts.push(pkBytes);
2307
+ }
2308
+ parts.push(new Uint8Array([80 + publicKeys.length]));
2309
+ parts.push(new Uint8Array([OP_CHECKMULTISIG]));
2310
+ return concatBytes(...parts);
2311
+ }
2312
+ function makeMultiSigAddress(publicKeys, signaturesRequired, chain) {
2313
+ if (signaturesRequired < 1 || signaturesRequired > publicKeys.length) {
2314
+ throw new Error(`signaturesRequired must be between 1 and ${publicKeys.length}`);
2315
+ }
2316
+ const redeemScript = makeRedeemScript(publicKeys, signaturesRequired);
2317
+ const signer = hash160(redeemScript);
2318
+ const version = chain?.addressVersion?.multiSig ?? 20;
2319
+ return c32address(version, bytesToHex(signer));
2320
+ }
2321
+ function createMultiSigSpendingCondition(publicKeys, signaturesRequired, nonce, fee, hashMode = AddressHashMode.P2SH) {
2322
+ const redeemScript = makeRedeemScript(publicKeys, signaturesRequired);
2323
+ const signer = bytesToHex(hash160(redeemScript));
2324
+ return {
2325
+ hashMode,
2326
+ signer,
2327
+ nonce,
2328
+ fee,
2329
+ fields: [],
2330
+ signaturesRequired
2331
+ };
2332
+ }
2333
+ function initialSigHash(tx) {
2334
+ const cleared = {
2335
+ ...tx,
2336
+ auth: intoInitialSighashAuth(tx.auth)
2337
+ };
2338
+ return txidFromBytes(serializeTransaction(cleared));
2339
+ }
2340
+ function nonSequentialPreSignHash(tx) {
2341
+ const condition = tx.auth.spendingCondition;
2342
+ const initHash = initialSigHash(tx);
2343
+ return sigHashPreSign(initHash, AuthType.Standard, condition.fee, condition.nonce);
2344
+ }
2345
+ function replayMultiSigSigHash(tx) {
2346
+ const condition = tx.auth.spendingCondition;
2347
+ if (isNonSequential(condition.hashMode)) {
2348
+ const preSign = nonSequentialPreSignHash(tx);
2349
+ let curSigHash = preSign;
2350
+ for (const field of condition.fields) {
2351
+ curSigHash = sigHashPostSign(curSigHash, field.pubKeyEncoding, field.data);
2352
+ }
2353
+ return curSigHash;
2354
+ }
2355
+ let curSigHash = initialSigHash(tx);
2356
+ for (const field of condition.fields) {
2357
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2358
+ curSigHash = sigHashPostSign(preSign, field.pubKeyEncoding, field.data);
2359
+ }
2360
+ return curSigHash;
2361
+ }
2362
+ function signMultiSig(tx, privateKey, publicKeys) {
2363
+ const keyBytes = hexToBytes(privateKey).slice(0, 32);
2364
+ const signerPubKey = bytesToHex(import_secp256k12.getPublicKey(keyBytes, true));
2365
+ const signerIndex = publicKeys.findIndex((pk) => pk === signerPubKey);
2366
+ if (signerIndex === -1) {
2367
+ throw new Error("Private key does not correspond to any signer in the multi-sig");
2368
+ }
2369
+ const condition = {
2370
+ ...tx.auth.spendingCondition
2371
+ };
2372
+ if (isNonSequential(condition.hashMode)) {
2373
+ return signNonSequential(tx, condition, privateKey);
2374
+ }
2375
+ return signSequential(tx, condition, privateKey, publicKeys, signerIndex);
2376
+ }
2377
+ function signNonSequential(tx, condition, privateKey) {
2378
+ const fields = [...condition.fields];
2379
+ const preSignHash = nonSequentialPreSignHash(tx);
2380
+ const keyBytes = hexToBytes(privateKey).slice(0, 32);
2381
+ const sig = import_secp256k12.sign(preSignHash, keyBytes, { lowS: true });
2382
+ const recoveryIdHex = intToHex(sig.recovery, 1);
2383
+ const nextSig = recoveryIdHex + sig.toCompactHex();
2384
+ fields.push({
2385
+ type: "signature",
2386
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2387
+ data: nextSig
2388
+ });
2389
+ const newCondition = { ...condition, fields };
2390
+ const sigCount = fields.filter((f) => f.type === "signature").length;
2391
+ if (sigCount >= condition.signaturesRequired) {
2392
+ return {
2393
+ ...tx,
2394
+ auth: { ...tx.auth, spendingCondition: newCondition }
2395
+ };
2396
+ }
2397
+ return {
2398
+ ...tx,
2399
+ auth: { ...tx.auth, spendingCondition: newCondition }
2400
+ };
2401
+ }
2402
+ function signSequential(tx, condition, privateKey, publicKeys, signerIndex) {
2403
+ const fields = [...condition.fields];
2404
+ let curSigHash = initialSigHash(tx);
2405
+ for (const field of fields) {
2406
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2407
+ curSigHash = sigHashPostSign(preSign, field.pubKeyEncoding, field.data);
2408
+ }
2409
+ for (let i = fields.length;i < signerIndex; i++) {
2410
+ const pubKeyField = {
2411
+ type: "publicKey",
2412
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2413
+ data: publicKeys[i]
2414
+ };
2415
+ fields.push(pubKeyField);
2416
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2417
+ curSigHash = sigHashPostSign(preSign, pubKeyField.pubKeyEncoding, pubKeyField.data);
2418
+ }
2419
+ const { nextSig, nextSigHash } = nextSignature(curSigHash, AuthType.Standard, condition.fee, condition.nonce, privateKey);
2420
+ fields.push({
2421
+ type: "signature",
2422
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2423
+ data: nextSig
2424
+ });
2425
+ curSigHash = nextSigHash;
2426
+ const newCondition = { ...condition, fields };
2427
+ const sigCount = fields.filter((f) => f.type === "signature").length;
2428
+ let finalCondition = newCondition;
2429
+ if (sigCount >= condition.signaturesRequired) {
2430
+ finalCondition = finalizeMultiSigCondition(newCondition, publicKeys, curSigHash);
2431
+ }
2432
+ return {
2433
+ ...tx,
2434
+ auth: {
2435
+ ...tx.auth,
2436
+ spendingCondition: finalCondition
2437
+ }
2438
+ };
2439
+ }
2440
+ async function signMultiSigWithAccount(tx, account, publicKeys) {
2441
+ const signerPubKey = account.publicKey;
2442
+ const signerIndex = publicKeys.findIndex((pk) => pk === signerPubKey);
2443
+ if (signerIndex === -1) {
2444
+ throw new Error("Account does not correspond to any signer in the multi-sig");
2445
+ }
2446
+ const condition = {
2447
+ ...tx.auth.spendingCondition
2448
+ };
2449
+ if (isNonSequential(condition.hashMode)) {
2450
+ return signNonSequentialWithAccount(tx, condition, account);
2451
+ }
2452
+ return signSequentialWithAccount(tx, condition, account, publicKeys, signerIndex);
2453
+ }
2454
+ async function signNonSequentialWithAccount(tx, condition, account) {
2455
+ const fields = [...condition.fields];
2456
+ const preSignHash = nonSequentialPreSignHash(tx);
2457
+ const sigBytes = await account.sign(hexToBytes(preSignHash));
2458
+ const nextSig = bytesToHex(sigBytes);
2459
+ fields.push({
2460
+ type: "signature",
2461
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2462
+ data: nextSig
2463
+ });
2464
+ const newCondition = { ...condition, fields };
2465
+ return {
2466
+ ...tx,
2467
+ auth: { ...tx.auth, spendingCondition: newCondition }
2468
+ };
2469
+ }
2470
+ async function signSequentialWithAccount(tx, condition, account, publicKeys, signerIndex) {
2471
+ const fields = [...condition.fields];
2472
+ let curSigHash = initialSigHash(tx);
2473
+ for (const field of fields) {
2474
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2475
+ curSigHash = sigHashPostSign(preSign, field.pubKeyEncoding, field.data);
2476
+ }
2477
+ for (let i = fields.length;i < signerIndex; i++) {
2478
+ const pubKeyField = {
2479
+ type: "publicKey",
2480
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2481
+ data: publicKeys[i]
2482
+ };
2483
+ fields.push(pubKeyField);
2484
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2485
+ curSigHash = sigHashPostSign(preSign, pubKeyField.pubKeyEncoding, pubKeyField.data);
2486
+ }
2487
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2488
+ const sigBytes = await account.sign(hexToBytes(preSign));
2489
+ const nextSig = bytesToHex(sigBytes);
2490
+ const nextSigHash = sigHashPostSign(preSign, PubKeyEncoding.Compressed, nextSig);
2491
+ fields.push({
2492
+ type: "signature",
2493
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2494
+ data: nextSig
2495
+ });
2496
+ curSigHash = nextSigHash;
2497
+ const newCondition = { ...condition, fields };
2498
+ const sigCount = fields.filter((f) => f.type === "signature").length;
2499
+ let finalCondition = newCondition;
2500
+ if (sigCount >= condition.signaturesRequired) {
2501
+ finalCondition = finalizeMultiSigCondition(newCondition, publicKeys, curSigHash);
2502
+ }
2503
+ return {
2504
+ ...tx,
2505
+ auth: {
2506
+ ...tx.auth,
2507
+ spendingCondition: finalCondition
2508
+ }
2509
+ };
2510
+ }
2511
+ function finalizeMultiSig(tx, publicKeys) {
2512
+ const condition = tx.auth.spendingCondition;
2513
+ if (isNonSequential(condition.hashMode)) {
2514
+ return tx;
2515
+ }
2516
+ const curSigHash = replayMultiSigSigHash(tx);
2517
+ const finalCondition = finalizeMultiSigCondition(condition, publicKeys, curSigHash);
2518
+ return {
2519
+ ...tx,
2520
+ auth: {
2521
+ ...tx.auth,
2522
+ spendingCondition: finalCondition
2523
+ }
2524
+ };
2525
+ }
2526
+ function finalizeMultiSigCondition(condition, publicKeys, curSigHash) {
2527
+ const fields = [...condition.fields];
2528
+ let sigHash = curSigHash;
2529
+ for (let i = fields.length;i < publicKeys.length; i++) {
2530
+ const pubKeyField = {
2531
+ type: "publicKey",
2532
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2533
+ data: publicKeys[i]
2534
+ };
2535
+ fields.push(pubKeyField);
2536
+ const preSign = sigHashPreSign(sigHash, AuthType.Standard, condition.fee, condition.nonce);
2537
+ sigHash = sigHashPostSign(preSign, pubKeyField.pubKeyEncoding, pubKeyField.data);
2538
+ }
2539
+ return { ...condition, fields };
2540
+ }
2541
+ function combineMultiSigSignatures(baseTx, signedTxs) {
2542
+ const condition = baseTx.auth.spendingCondition;
2543
+ if (!isNonSequential(condition.hashMode)) {
2544
+ throw new Error("combineMultiSigSignatures only works with non-sequential hash modes (SIP-027)");
2545
+ }
2546
+ const seenSigs = new Set;
2547
+ const signatures = [];
2548
+ for (const stx of signedTxs) {
2549
+ const stxCondition = stx.auth.spendingCondition;
2550
+ for (const field of stxCondition.fields) {
2551
+ if (field.type === "signature" && !seenSigs.has(field.data)) {
2552
+ seenSigs.add(field.data);
2553
+ signatures.push(field);
2554
+ }
2555
+ }
2556
+ }
2557
+ if (signatures.length === 0) {
2558
+ throw new Error("No signatures found in the provided transactions");
2559
+ }
2560
+ const newCondition = {
2561
+ ...condition,
2562
+ fields: signatures
2563
+ };
2564
+ return {
2565
+ ...baseTx,
2566
+ auth: { ...baseTx.auth, spendingCondition: newCondition }
2567
+ };
2568
+ }
2569
+
2570
+ // src/transactions/build.ts
2571
+ function resolvePcMode(mode) {
2572
+ if (mode === "allow")
2573
+ return PostConditionModeWire.Allow;
2574
+ if (mode === "originator")
2575
+ return PostConditionModeWire.Originator;
2576
+ return PostConditionModeWire.Deny;
2577
+ }
2578
+ function convertPostConditions(pcs) {
2579
+ if (!pcs || pcs.length === 0)
2580
+ return [];
2581
+ return pcs.map((pc) => convertPostCondition(typeof pc === "string" ? fromHex(pc) : pc));
2582
+ }
2583
+ function resolveSpendingCondition(opts, nonce, fee) {
2584
+ if (opts.publicKeys) {
2585
+ return createMultiSigSpendingCondition(opts.publicKeys, opts.signaturesRequired, nonce, fee, opts.hashMode);
2586
+ }
2587
+ return createSingleSigSpendingCondition(opts.publicKey, nonce, fee);
2588
+ }
2589
+ function resolveAuth(spendingCondition, sponsored) {
2590
+ return sponsored ? createSponsoredAuth(spendingCondition) : createStandardAuth(spendingCondition);
2591
+ }
2592
+ function resolveVersionAndChainId(chain) {
2593
+ if (!chain)
2594
+ return { version: 0, chainId: 1 };
2595
+ return { version: chain.transactionVersion, chainId: chain.id };
2596
+ }
2597
+ function buildTokenTransfer(options) {
2598
+ const { version, chainId } = resolveVersionAndChainId(options.chain);
2599
+ const fee = intToBigInt(options.fee);
2600
+ const nonce = intToBigInt(options.nonce);
2601
+ const spendingCondition = resolveSpendingCondition(options, nonce, fee);
2602
+ const recipient = Cl.principal(options.recipient);
2603
+ const tx = {
2604
+ version,
2605
+ chainId,
2606
+ auth: resolveAuth(spendingCondition, options.sponsored),
2607
+ anchorMode: AnchorMode.Any,
2608
+ postConditionMode: resolvePcMode(options.postConditionMode),
2609
+ postConditions: convertPostConditions(options.postConditions),
2610
+ payload: {
2611
+ payloadType: PayloadType.TokenTransfer,
2612
+ recipient,
2613
+ amount: intToBigInt(options.amount),
2614
+ memo: options.memo ?? ""
2615
+ }
2616
+ };
2617
+ if (options.publicKeys) {
2618
+ tx._multisig = { publicKeys: options.publicKeys };
2619
+ }
2620
+ return tx;
2621
+ }
2622
+ function buildContractCall(options) {
2623
+ const { version, chainId } = resolveVersionAndChainId(options.chain);
2624
+ const fee = intToBigInt(options.fee);
2625
+ const nonce = intToBigInt(options.nonce);
2626
+ const spendingCondition = resolveSpendingCondition(options, nonce, fee);
2627
+ const tx = {
2628
+ version,
2629
+ chainId,
2630
+ auth: resolveAuth(spendingCondition, options.sponsored),
2631
+ anchorMode: AnchorMode.Any,
2632
+ postConditionMode: resolvePcMode(options.postConditionMode),
2633
+ postConditions: convertPostConditions(options.postConditions),
2634
+ payload: {
2635
+ payloadType: PayloadType.ContractCall,
2636
+ contractAddress: options.contractAddress,
2637
+ contractName: options.contractName,
2638
+ functionName: options.functionName,
2639
+ functionArgs: options.functionArgs
2640
+ }
2641
+ };
2642
+ if (options.publicKeys) {
2643
+ tx._multisig = { publicKeys: options.publicKeys };
2644
+ }
2645
+ return tx;
2646
+ }
2647
+ function buildContractDeploy(options) {
2648
+ const { version, chainId } = resolveVersionAndChainId(options.chain);
2649
+ const fee = intToBigInt(options.fee);
2650
+ const nonce = intToBigInt(options.nonce);
2651
+ const spendingCondition = resolveSpendingCondition(options, nonce, fee);
2652
+ const clarityVersion = options.clarityVersion ?? ClarityVersion.Clarity4;
2653
+ const tx = {
2654
+ version,
2655
+ chainId,
2656
+ auth: resolveAuth(spendingCondition, options.sponsored),
2657
+ anchorMode: AnchorMode.Any,
2658
+ postConditionMode: resolvePcMode(options.postConditionMode),
2659
+ postConditions: convertPostConditions(options.postConditions),
2660
+ payload: {
2661
+ payloadType: PayloadType.VersionedSmartContract,
2662
+ clarityVersion,
2663
+ contractName: options.contractName,
2664
+ codeBody: options.codeBody
2665
+ }
2666
+ };
2667
+ if (options.publicKeys) {
2668
+ tx._multisig = { publicKeys: options.publicKeys };
2669
+ }
2670
+ return tx;
2671
+ }
2672
+
2673
+ // src/actions/public/getNonce.ts
2674
+ async function getNonce(client, params) {
2675
+ const data = await client.request(`/v2/accounts/${encodeURIComponent(params.address)}`, { method: "GET" });
2676
+ const nonce = data?.nonce;
2677
+ if (typeof nonce !== "number" && typeof nonce !== "string") {
2678
+ throw new MalformedResponseError(`getNonce: /v2/accounts/${params.address} response is missing "nonce"`);
2679
+ }
2680
+ return BigInt(nonce);
2681
+ }
2682
+
2683
+ // src/actions/public/readContract.ts
2684
+ async function readContract(client, params) {
2685
+ const [address, name] = parseContractId(params.contract);
2686
+ const sender = params.sender ?? address;
2687
+ const serializedArgs = (params.args ?? []).map((arg) => with0x(bytesToHex(serializeCVBytes(arg))));
2688
+ const path = `/v2/contracts/call-read/${encodeURIComponent(address)}/${encodeURIComponent(name)}/${encodeURIComponent(params.functionName)}`;
2689
+ const data = await client.request(params.tip ? `${path}?tip=${encodeURIComponent(params.tip)}` : path, {
2690
+ method: "POST",
2691
+ body: {
2692
+ sender,
2693
+ arguments: serializedArgs
2694
+ }
2695
+ });
2696
+ if (data.okay) {
2697
+ if (typeof data.result !== "string") {
2698
+ throw new MalformedResponseError(`readContract: /v2/contracts/call-read response is missing "result"`);
2699
+ }
2700
+ return deserializeCVBytes(data.result);
2701
+ }
2702
+ throw new ReadContractError(data.cause ?? "Read-only call failed");
2703
+ }
2704
+
2705
+ // src/transactions/signer.ts
2706
+ function txid(tx) {
2707
+ return txidFromBytes(serializeTransaction(tx));
2708
+ }
2709
+ function signBegin(tx) {
2710
+ const cleared = {
2711
+ ...tx,
2712
+ auth: intoInitialSighashAuth(tx.auth)
2713
+ };
2714
+ return txid(cleared);
2715
+ }
2716
+ function signTransaction(tx, privateKey) {
2717
+ const sigHash = signBegin(tx);
2718
+ const condition = tx.auth.spendingCondition;
2719
+ const { nextSig } = nextSignature(sigHash, AuthType.Standard, condition.fee, condition.nonce, privateKey);
2720
+ return {
2721
+ ...tx,
2722
+ auth: {
2723
+ ...tx.auth,
2724
+ spendingCondition: {
2725
+ ...condition,
2726
+ signature: nextSig
2727
+ }
2728
+ }
2729
+ };
2730
+ }
2731
+ async function signTransactionWithAccount(tx, account) {
2732
+ const sigHash = signBegin(tx);
2733
+ const condition = tx.auth.spendingCondition;
2734
+ const sigHashPre = sigHashPreSign(sigHash, AuthType.Standard, condition.fee, condition.nonce);
2735
+ const sigBytes = await account.sign(hexToBytes(sigHashPre));
2736
+ const nextSig = bytesToHex(sigBytes);
2737
+ return {
2738
+ ...tx,
2739
+ auth: {
2740
+ ...tx.auth,
2741
+ spendingCondition: {
2742
+ ...condition,
2743
+ signature: nextSig
2744
+ }
2745
+ }
2746
+ };
2747
+ }
2748
+ function getTransactionId(tx) {
2749
+ return txid(tx);
2750
+ }
2751
+ function getOriginSigHash(tx) {
2752
+ const condition = tx.auth.spendingCondition;
2753
+ if ("fields" in condition) {
2754
+ return replayMultiSigSigHash(tx);
2755
+ }
2756
+ const initialSigHash = signBegin(tx);
2757
+ const sc = condition;
2758
+ const preSign = sigHashPreSign(initialSigHash, AuthType.Standard, sc.fee, sc.nonce);
2759
+ return sigHashPostSign(preSign, sc.keyEncoding, sc.signature);
2760
+ }
2761
+ function signSponsor(tx, privateKey) {
2762
+ if (tx.auth.authType !== AuthType.Sponsored) {
2763
+ throw new Error("Transaction must be sponsored");
2764
+ }
2765
+ const auth = tx.auth;
2766
+ const sponsorCondition = auth.sponsorSpendingCondition;
2767
+ const originSigHash = getOriginSigHash(tx);
2768
+ const { nextSig } = nextSignature(originSigHash, AuthType.Sponsored, sponsorCondition.fee, sponsorCondition.nonce, privateKey);
2769
+ return {
2770
+ ...tx,
2771
+ auth: {
2772
+ ...auth,
2773
+ sponsorSpendingCondition: {
2774
+ ...sponsorCondition,
2775
+ signature: nextSig
2776
+ }
2777
+ }
2778
+ };
2779
+ }
2780
+ async function signSponsorWithAccount(tx, account) {
2781
+ if (tx.auth.authType !== AuthType.Sponsored) {
2782
+ throw new Error("Transaction must be sponsored");
2783
+ }
2784
+ const auth = tx.auth;
2785
+ const sponsorCondition = auth.sponsorSpendingCondition;
2786
+ const originSigHash = getOriginSigHash(tx);
2787
+ const sigHashPre = sigHashPreSign(originSigHash, AuthType.Sponsored, sponsorCondition.fee, sponsorCondition.nonce);
2788
+ const sigBytes = await account.sign(hexToBytes(sigHashPre));
2789
+ const nextSig = bytesToHex(sigBytes);
2790
+ return {
2791
+ ...tx,
2792
+ auth: {
2793
+ ...auth,
2794
+ sponsorSpendingCondition: {
2795
+ ...sponsorCondition,
2796
+ signature: nextSig
2797
+ }
2798
+ }
2799
+ };
2800
+ }
2801
+
2802
+ // src/errors/http.ts
2803
+ class HttpRequestError extends BaseError {
2804
+ name = "HttpRequestError";
2805
+ status;
2806
+ url;
2807
+ method;
2808
+ constructor(status, options) {
2809
+ const where = options?.url !== undefined ? ` (${options.method ?? "GET"} ${options.url})` : "";
2810
+ super(`HTTP request failed with status ${status}${where}`, options);
2811
+ this.status = status;
2812
+ this.url = options?.url;
2813
+ this.method = options?.method;
2814
+ }
2815
+ }
2816
+
2817
+ // src/errors/transport.ts
2818
+ class TimeoutError extends BaseError {
2819
+ name = "TimeoutError";
2820
+ method;
2821
+ url;
2822
+ timeout;
2823
+ attempt;
2824
+ constructor(params) {
2825
+ super(`${params.method} ${params.url} did not complete within ${params.timeout}ms (attempt ${params.attempt + 1})`);
2826
+ this.method = params.method;
2827
+ this.url = params.url;
2828
+ this.timeout = params.timeout;
2829
+ this.attempt = params.attempt;
2830
+ }
2831
+ }
2832
+
2833
+ // src/transports/createTransport.ts
2834
+ function createTransport(type, config) {
2835
+ const { request, apiKey: _apiKey, ...exposed } = config;
2836
+ return {
2837
+ type,
2838
+ request,
2839
+ config: exposed
2840
+ };
2841
+ }
2842
+ var MAX_ERROR_DETAILS_BYTES = 4096;
2843
+ function capDetails(body) {
2844
+ if (body === undefined)
2845
+ return;
2846
+ const bytes = new TextEncoder().encode(body);
2847
+ if (bytes.length <= MAX_ERROR_DETAILS_BYTES)
2848
+ return body;
2849
+ const head = new TextDecoder().decode(bytes.subarray(0, MAX_ERROR_DETAILS_BYTES));
2850
+ return `${head}... [truncated ${bytes.length - MAX_ERROR_DETAILS_BYTES} bytes]`;
2851
+ }
2852
+ function isRetryableStatus(status) {
2853
+ return status === 429 || status >= 500;
2854
+ }
2855
+ var MAX_RETRY_AFTER_MS = 60000;
2856
+ function retryAfterMs(response) {
2857
+ const value = response.headers.get("Retry-After");
2858
+ if (!value)
2859
+ return;
2860
+ const seconds = Number(value);
2861
+ const ms = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - Date.now();
2862
+ if (!Number.isFinite(ms) || ms < 0 || ms > MAX_RETRY_AFTER_MS)
2863
+ return;
2864
+ return ms;
2865
+ }
2866
+ function abortReason(signal) {
2867
+ const reason = signal.reason;
2868
+ if (reason instanceof Error)
2869
+ return reason;
2870
+ return new DOMException(typeof reason === "string" ? reason : "The operation was aborted", "AbortError");
2871
+ }
2872
+ function sleep(ms, signal) {
2873
+ return new Promise((resolve, reject) => {
2874
+ if (signal?.aborted)
2875
+ return reject(abortReason(signal));
2876
+ const onAbort = () => {
2877
+ clearTimeout(id);
2878
+ reject(abortReason(signal));
2879
+ };
2880
+ const id = setTimeout(() => {
2881
+ signal?.removeEventListener("abort", onAbort);
2882
+ resolve();
2883
+ }, ms);
2884
+ signal?.addEventListener("abort", onAbort, { once: true });
2885
+ });
2886
+ }
2887
+ async function fetchWithRetry(url, options, retryCount, retryDelay, timeout, extra = {}) {
2888
+ const { signal } = extra;
2889
+ const read = extra.read ?? (async (response) => response);
2890
+ const method = options.method ?? "GET";
2891
+ let lastError;
2892
+ for (let attempt = 0;attempt <= retryCount; attempt++) {
2893
+ if (signal?.aborted)
2894
+ throw abortReason(signal);
2895
+ const controller = new AbortController;
2896
+ let timedOut = false;
2897
+ const timeoutId = setTimeout(() => {
2898
+ timedOut = true;
2899
+ controller.abort(new TimeoutError({ method, url, timeout, attempt }));
2900
+ }, timeout);
2901
+ const onCallerAbort = () => controller.abort(abortReason(signal));
2902
+ signal?.addEventListener("abort", onCallerAbort, { once: true });
2903
+ const aborted = new Promise((_, reject) => {
2904
+ if (controller.signal.aborted)
2905
+ return reject(controller.signal.reason);
2906
+ controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
2907
+ });
2908
+ let response;
2909
+ try {
2910
+ try {
2911
+ response = await Promise.race([
2912
+ fetch(url, { ...options, signal: controller.signal }),
2913
+ aborted
2914
+ ]);
2915
+ } catch (error) {
2916
+ if (signal?.aborted)
2917
+ throw abortReason(signal);
2918
+ lastError = timedOut ? new TimeoutError({ method, url, timeout, attempt }) : error instanceof Error ? error : new Error(String(error));
2919
+ if (attempt < retryCount) {
2920
+ clearTimeout(timeoutId);
2921
+ await sleep(retryDelay * (attempt + 1), signal);
2922
+ continue;
2923
+ }
2924
+ throw lastError;
2925
+ }
2926
+ if (response.ok) {
2927
+ try {
2928
+ return await Promise.race([read(response), aborted]);
2929
+ } catch (error) {
2930
+ response.body?.cancel().catch(() => {});
2931
+ if (signal?.aborted)
2932
+ throw abortReason(signal);
2933
+ if (!timedOut)
2934
+ throw error;
2935
+ lastError = new TimeoutError({ method, url, timeout, attempt });
2936
+ if (attempt < retryCount) {
2937
+ clearTimeout(timeoutId);
2938
+ await sleep(retryDelay * (attempt + 1), signal);
2939
+ continue;
2940
+ }
2941
+ throw lastError;
2942
+ }
2943
+ }
2944
+ const retryable = isRetryableStatus(response.status);
2945
+ if (!retryable || attempt === retryCount) {
2946
+ const body = await Promise.race([
2947
+ response.text().catch(() => {
2948
+ return;
2949
+ }),
2950
+ aborted.catch(() => {
2951
+ return;
2952
+ })
2953
+ ]);
2954
+ throw new HttpRequestError(response.status, {
2955
+ details: capDetails(body),
2956
+ url,
2957
+ method
2958
+ });
2959
+ }
2960
+ lastError = new HttpRequestError(response.status, { url, method });
2961
+ const delay = retryAfterMs(response) ?? retryDelay * (attempt + 1);
2962
+ response.body?.cancel().catch(() => {});
2963
+ clearTimeout(timeoutId);
2964
+ await sleep(delay, signal);
2965
+ } finally {
2966
+ clearTimeout(timeoutId);
2967
+ signal?.removeEventListener("abort", onCallerAbort);
2968
+ }
2969
+ }
2970
+ throw lastError ?? new Error("Request failed");
2971
+ }
2972
+ async function readBody(response) {
2973
+ const contentType = response.headers.get("content-type") ?? "";
2974
+ if (contentType.includes("application/json")) {
2975
+ return response.json();
2976
+ }
2977
+ return response.text();
2978
+ }
2979
+ function buildRequestFn(baseUrl, config) {
2980
+ const {
2981
+ timeout = 30000,
2982
+ retryCount = 3,
2983
+ retryDelay = 150,
2984
+ fetchOptions = {},
2985
+ apiKey
2986
+ } = config;
2987
+ return async (path, options) => {
2988
+ const url = `${baseUrl.replace(/\/$/, "")}${path}`;
2989
+ const headers = {
2990
+ "Content-Type": "application/json",
2991
+ ...fetchOptions.headers,
2992
+ ...options?.headers
2993
+ };
2994
+ if (apiKey) {
2995
+ headers["x-api-key"] = apiKey;
2996
+ }
2997
+ const init = {
2998
+ ...fetchOptions,
2999
+ method: options?.method ?? "GET",
3000
+ headers
3001
+ };
3002
+ if (options?.body !== undefined) {
3003
+ init.body = JSON.stringify(options.body);
3004
+ }
3005
+ return fetchWithRetry(url, init, options?.retryCount ?? retryCount, retryDelay, timeout, { signal: options?.signal, read: readBody });
3006
+ };
3007
+ }
3008
+
3009
+ // src/actions/public/txSources.ts
3010
+ class IndexSourceConfigError extends Error {
3011
+ name = "IndexSourceConfigError";
3012
+ }
3013
+ function isHiroHost(url, client) {
3014
+ let hostname;
3015
+ try {
3016
+ hostname = new URL(url).hostname;
3017
+ } catch {
3018
+ return false;
3019
+ }
3020
+ if (hostname === "hiro.so" || hostname.endsWith(".hiro.so"))
3021
+ return true;
3022
+ const defaults = client.chain?.rpcUrls?.default?.http ?? [];
3023
+ return defaults.some((d) => {
3024
+ try {
3025
+ return new URL(d).hostname === hostname && hostname !== "localhost";
3026
+ } catch {
3027
+ return false;
3028
+ }
3029
+ });
3030
+ }
3031
+ function indexRequestFn(client, baseUrl, sourceName) {
3032
+ const transportUrl = client.transport.config.url?.replace(/\/$/, "");
3033
+ if (baseUrl === undefined) {
3034
+ if (!transportUrl) {
3035
+ throw new IndexSourceConfigError(`${sourceName} needs the URL of your Secondlayer instance: pass baseUrl, or use an http() transport pointed at the instance`);
3036
+ }
3037
+ if (isHiroHost(transportUrl, client)) {
3038
+ throw new IndexSourceConfigError(`${sourceName} reads /v1/index on a Secondlayer instance, and ${transportUrl} is a Hiro host: pass baseUrl with the URL of your instance`);
3039
+ }
3040
+ return client.request;
3041
+ }
3042
+ const target = baseUrl.replace(/\/$/, "");
3043
+ if (target === transportUrl)
3044
+ return client.request;
3045
+ const { timeout, retryCount, retryDelay } = client.transport.config;
3046
+ return buildRequestFn(target, { timeout, retryCount, retryDelay });
3047
+ }
3048
+ function indexNotFound(error, sourceName) {
3049
+ if (!(error instanceof HttpRequestError) || error.status !== 404) {
3050
+ return false;
3051
+ }
3052
+ const body = error.details;
3053
+ if (body !== undefined) {
3054
+ try {
3055
+ JSON.parse(body);
3056
+ } catch {
3057
+ throw new IndexSourceConfigError(`${sourceName} got a non-JSON 404 from ${error.url ?? "the transport host"}: it does not serve /v1/index, pass baseUrl with the URL of your Secondlayer instance`, { cause: error });
3058
+ }
3059
+ }
3060
+ return true;
3061
+ }
3062
+ function normalizeTxid(txid) {
3063
+ return txid.startsWith("0x") ? txid : `0x${txid}`;
3064
+ }
3065
+ function decodeResultHex(hex) {
3066
+ if (!hex)
3067
+ return {};
3068
+ try {
3069
+ return { result: deserializeCVBytes(hex), resultHex: hex };
3070
+ } catch {
3071
+ return { resultHex: hex };
3072
+ }
3073
+ }
3074
+ function normalizeStatus(txStatus) {
3075
+ switch (txStatus) {
3076
+ case "pending":
3077
+ case "success":
3078
+ case "abort_by_response":
3079
+ case "abort_by_post_condition":
3080
+ return txStatus;
3081
+ default:
3082
+ return txStatus.startsWith("dropped") ? "dropped" : undefined;
3083
+ }
3084
+ }
3085
+ function extendedApiSource() {
3086
+ return {
3087
+ async get({ client, txid }) {
3088
+ let data;
3089
+ try {
3090
+ data = await client.request(`/extended/v1/tx/${encodeURIComponent(normalizeTxid(txid))}`, { method: "GET" });
3091
+ } catch (error) {
3092
+ if (error instanceof HttpRequestError && error.status === 404) {
3093
+ return { receipt: null };
3094
+ }
3095
+ throw error;
3096
+ }
3097
+ const txStatus = typeof data?.tx_status === "string" ? data.tx_status : undefined;
3098
+ if (!txStatus)
3099
+ return { receipt: null };
3100
+ const status = normalizeStatus(txStatus);
3101
+ if (!status)
3102
+ return { receipt: null };
3103
+ return {
3104
+ receipt: {
3105
+ txid: normalizeTxid(txid),
3106
+ status,
3107
+ blockHeight: typeof data.block_height === "number" && data.block_height > 0 ? data.block_height : undefined,
3108
+ blockHash: data.block_hash ?? undefined,
3109
+ ...decodeResultHex(data.tx_result?.hex),
3110
+ events: Array.isArray(data.events) ? data.events : [],
3111
+ raw: data
3112
+ }
3113
+ };
3114
+ }
3115
+ };
3116
+ }
3117
+ function indexTxSource(params = {}) {
3118
+ const headers = params.apiKey ? { authorization: `Bearer ${params.apiKey}` } : undefined;
3119
+ return {
3120
+ canonicalOnly: true,
3121
+ async get({ client, txid }) {
3122
+ const request = indexRequestFn(client, params.baseUrl, "indexTxSource");
3123
+ let data;
3124
+ try {
3125
+ data = await request(`/v1/index/transactions/${normalizeTxid(txid)}`, {
3126
+ method: "GET",
3127
+ headers
3128
+ });
3129
+ } catch (error) {
3130
+ if (indexNotFound(error, "indexTxSource"))
3131
+ return { receipt: null };
3132
+ throw error;
3133
+ }
3134
+ const tx = data.transaction;
3135
+ const tip = data.tip?.block_height;
3136
+ if (!tx)
3137
+ return { receipt: null, tip };
3138
+ const status = normalizeStatus(tx.status) ?? "success";
3139
+ return {
3140
+ receipt: {
3141
+ txid: normalizeTxid(tx.tx_id),
3142
+ status,
3143
+ blockHeight: tx.block_height,
3144
+ ...decodeResultHex(tx.contract_call?.result_hex),
3145
+ events: [],
3146
+ raw: data
3147
+ },
3148
+ tip
3149
+ };
3150
+ }
3151
+ };
3152
+ }
3153
+
3154
+ // src/actions/public/getTransaction.ts
3155
+ async function getTransaction(client, params) {
3156
+ const source = params.source ?? extendedApiSource();
3157
+ const { receipt } = await source.get({ client, txid: params.txid });
3158
+ return receipt;
3159
+ }
3160
+
3161
+ // src/actions/public/getBlockHeight.ts
3162
+ async function getBlockHeight(client) {
3163
+ const data = await client.request("/v2/info", { method: "GET" });
3164
+ if (typeof data?.stacks_tip_height !== "number") {
3165
+ throw new MalformedResponseError('getBlockHeight: /v2/info response is missing "stacks_tip_height"');
3166
+ }
3167
+ return data.stacks_tip_height;
3168
+ }
3169
+
3170
+ // src/actions/public/waitForTransactionReceipt.ts
3171
+ var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
3172
+ async function waitForTransactionReceipt(client, params) {
3173
+ const {
3174
+ txid,
3175
+ confirmations = 1,
3176
+ timeout = 180000,
3177
+ pollingInterval = 3000
3178
+ } = params;
3179
+ const source = params.source ?? extendedApiSource();
3180
+ const droppedGracePeriod = params.droppedGracePeriod ?? (source.canonicalOnly ? timeout : 30000);
3181
+ const startedAt = Date.now();
3182
+ let unknownSince = null;
3183
+ let everPending = false;
3184
+ while (true) {
3185
+ const snapshot = await source.get({ client, txid });
3186
+ const receipt = snapshot.receipt;
3187
+ if (receipt === null) {
3188
+ unknownSince ??= Date.now();
3189
+ if (Date.now() - unknownSince >= droppedGracePeriod) {
3190
+ throw new TransactionDroppedError(everPending ? `Transaction ${txid} left the mempool without being mined` : `Transaction ${txid} was never observed by the status source`, { txid });
3191
+ }
3192
+ } else {
3193
+ unknownSince = null;
3194
+ switch (receipt.status) {
3195
+ case "dropped":
3196
+ throw new TransactionDroppedError(`Transaction ${txid} was dropped from the mempool`, { txid });
3197
+ case "abort_by_response":
3198
+ case "abort_by_post_condition":
3199
+ throw new TransactionAbortedError(`Transaction ${txid} aborted (${receipt.status})`, { receipt });
3200
+ case "pending":
3201
+ everPending = true;
3202
+ break;
3203
+ case "success": {
3204
+ if (confirmations <= 1)
3205
+ return receipt;
3206
+ if (receipt.blockHeight !== undefined) {
3207
+ const tip = snapshot.tip ?? await getBlockHeight(client);
3208
+ if (tip - receipt.blockHeight + 1 >= confirmations)
3209
+ return receipt;
3210
+ }
3211
+ break;
3212
+ }
3213
+ }
3214
+ }
3215
+ if (Date.now() - startedAt >= timeout) {
3216
+ throw new WaitForTransactionTimeoutError(`Timed out after ${timeout}ms waiting for transaction ${txid}`, { txid });
3217
+ }
3218
+ await sleep2(pollingInterval);
3219
+ }
3220
+ }
3221
+
3222
+ // src/actions/wallet/sendTransaction.ts
3223
+ async function sendTransaction(client, params) {
3224
+ const hex = bytesToHex(serializeTransaction(params.transaction));
3225
+ const body = { tx: hex };
3226
+ if (params.attachment) {
3227
+ body.attachment = typeof params.attachment === "string" ? params.attachment : bytesToHex(params.attachment);
3228
+ }
3229
+ let data;
3230
+ try {
3231
+ data = await client.request("/v2/transactions", {
3232
+ method: "POST",
3233
+ body,
3234
+ retryCount: 0
3235
+ });
3236
+ } catch (error) {
3237
+ if (error instanceof HttpRequestError && error.details) {
3238
+ try {
3239
+ data = JSON.parse(error.details);
3240
+ } catch {
3241
+ throw error;
3242
+ }
3243
+ } else if (error instanceof TimeoutError) {
3244
+ const txid = getTransactionId(params.transaction);
3245
+ const receipt = await getTransaction(client, { txid }).catch(() => null);
3246
+ if (receipt === null)
3247
+ throw error;
3248
+ data = { txid };
3249
+ } else {
3250
+ throw error;
3251
+ }
3252
+ }
3253
+ if (data.error) {
3254
+ throw new BroadcastError(data.reason ?? data.error, {
3255
+ reason: data.reason,
3256
+ reasonData: data.reason_data,
3257
+ txid: data.txid ?? getTransactionId(params.transaction)
3258
+ });
3259
+ }
3260
+ const txid = typeof data === "string" ? data.replace(/"/g, "") : data.txid ?? getTransactionId(params.transaction);
3261
+ if (params.wait) {
3262
+ const confirmations = params.wait === true ? 1 : params.wait;
3263
+ const receipt = await waitForTransactionReceipt(client, {
3264
+ txid,
3265
+ confirmations
3266
+ });
3267
+ return { txid, receipt };
3268
+ }
3269
+ return { txid };
3270
+ }
3271
+
3272
+ // src/actions/wallet/nonceManager.ts
3273
+ function jsonRpcSource() {
3274
+ return {
3275
+ get: ({ client, address }) => getNonce(client, { address })
3276
+ };
3277
+ }
3278
+ function memoryStore() {
3279
+ const next = new Map;
3280
+ const locks = new Map;
3281
+ function withLock(key, fn) {
3282
+ const prev = locks.get(key) ?? Promise.resolve();
3283
+ const run = prev.then(fn, fn);
3284
+ locks.set(key, run.catch(() => {}));
3285
+ return run;
3286
+ }
3287
+ return {
3288
+ reserve(key, getFloor) {
3289
+ return withLock(key, async () => {
3290
+ let current = next.get(key);
3291
+ if (current === undefined)
3292
+ current = await getFloor();
3293
+ next.set(key, current + 1n);
3294
+ return current;
3295
+ });
3296
+ },
3297
+ reset(key) {
3298
+ next.delete(key);
3299
+ },
3300
+ release(key, nonce) {
3301
+ return withLock(key, async () => {
3302
+ if (next.get(key) === nonce + 1n)
3303
+ next.set(key, nonce);
3304
+ });
3305
+ },
3306
+ peek(key) {
3307
+ return next.get(key);
3308
+ }
3309
+ };
3310
+ }
3311
+ function nonceKey(client, address) {
3312
+ return `${client.chain?.id ?? "stacks"}:${address}`;
3313
+ }
3314
+ function createNonceManager(params = {}) {
3315
+ const source = params.source ?? jsonRpcSource();
3316
+ const store = params.store ?? memoryStore();
3317
+ return {
3318
+ consume({ client, address }) {
3319
+ return store.reserve(nonceKey(client, address), () => source.get({ client, address }));
3320
+ },
3321
+ reset({ client, address }) {
3322
+ return store.reset(nonceKey(client, address));
3323
+ },
3324
+ release({ client, address, nonce }) {
3325
+ return store.release?.(nonceKey(client, address), nonce);
3326
+ },
3327
+ async peek({ client, address }) {
3328
+ return store.peek?.(nonceKey(client, address));
3329
+ }
3330
+ };
3331
+ }
3332
+ async function resolveNonce(client, address) {
3333
+ if (client.nonceManager)
3334
+ return client.nonceManager.consume({ client, address });
3335
+ return getNonce(client, { address });
3336
+ }
3337
+ async function releaseNonce(client, address, nonce) {
3338
+ if (!client.nonceManager)
3339
+ return;
3340
+ try {
3341
+ await client.nonceManager.release({ client, address, nonce });
3342
+ } catch {}
3343
+ }
3344
+ async function reconcileNonce(manager, params) {
3345
+ const { client, address, source } = params;
3346
+ const downward = params.downward ?? true;
3347
+ const authoritative = await source.get({ client, address });
3348
+ const tracked = await manager.peek({ client, address });
3349
+ if (tracked === undefined || authoritative === tracked) {
3350
+ return { reset: false, authoritative, tracked };
304
3351
  }
305
- if (result.type !== "err")
306
- return;
307
- return result.value.type === "uint" ? Number(result.value.value) : undefined;
3352
+ if (authoritative < tracked && !downward) {
3353
+ return { reset: false, authoritative, tracked };
3354
+ }
3355
+ await manager.reset({ client, address });
3356
+ return { reset: true, authoritative, tracked };
308
3357
  }
309
- function describePox5Error(code) {
310
- const n = Number(code);
311
- const name = POX5_ERROR_NAMES[n];
312
- if (!name)
313
- return;
314
- return { code: n, name, description: POX5_ERROR_DESCRIPTIONS[n] };
3358
+ function startNonceReconciler(manager, params) {
3359
+ const { client, addresses, source, clock } = params;
3360
+ const intervalMs = params.intervalMs ?? 60000;
3361
+ let running = true;
3362
+ const tick = async () => {
3363
+ if (!running)
3364
+ return;
3365
+ for (const address of addresses) {
3366
+ try {
3367
+ const result = await reconcileNonce(manager, {
3368
+ client,
3369
+ address,
3370
+ source,
3371
+ downward: params.downward
3372
+ });
3373
+ params.onReconcile?.(address, result);
3374
+ } catch (error) {
3375
+ try {
3376
+ params.onError?.(address, error);
3377
+ } catch {}
3378
+ }
3379
+ }
3380
+ if (running && clock) {
3381
+ await clock.advance(intervalMs);
3382
+ tick();
3383
+ }
3384
+ };
3385
+ if (clock) {
3386
+ tick();
3387
+ return {
3388
+ stop: () => {
3389
+ running = false;
3390
+ }
3391
+ };
3392
+ }
3393
+ const timer = setInterval(tick, intervalMs);
3394
+ timer.unref?.();
3395
+ return {
3396
+ stop: () => clearInterval(timer)
3397
+ };
3398
+ }
3399
+ function isNonceConflictError(error) {
3400
+ if (!(error instanceof BroadcastError))
3401
+ return false;
3402
+ if (error.reason === "ConflictingNonceInMempool" || error.reason === "BadNonce") {
3403
+ return true;
3404
+ }
3405
+ if (error.reason !== undefined)
3406
+ return false;
3407
+ return error.message.toLowerCase().includes("nonce");
3408
+ }
3409
+ async function broadcastWithNonceReset(client, params) {
3410
+ try {
3411
+ const result = await sendTransaction(client, {
3412
+ transaction: params.transaction
3413
+ });
3414
+ return result.txid;
3415
+ } catch (error) {
3416
+ if (client.nonceManager && isNonceConflictError(error)) {
3417
+ await client.nonceManager.reset({ client, address: params.address });
3418
+ }
3419
+ throw error;
3420
+ }
3421
+ }
3422
+
3423
+ // src/actions/public/estimateFee.ts
3424
+ function isValidEstimation(e) {
3425
+ return typeof e === "object" && e !== null && "fee_rate" in e && "fee" in e && (typeof e.fee_rate === "number" || typeof e.fee_rate === "string") && (typeof e.fee === "number" || typeof e.fee === "string");
3426
+ }
3427
+ async function estimateFee(client, params) {
3428
+ const payloadHex = bytesToHex(serializePayload(params.transaction.payload));
3429
+ const txHex = bytesToHex(serializeTransaction(params.transaction));
3430
+ const data = await client.request("/v2/fees/transaction", {
3431
+ method: "POST",
3432
+ body: {
3433
+ estimated_len: Math.ceil(txHex.length / 2),
3434
+ transaction_payload: `0x${payloadHex}`
3435
+ }
3436
+ });
3437
+ const raw = data?.estimations ?? [];
3438
+ return raw.map((e) => {
3439
+ if (!isValidEstimation(e)) {
3440
+ throw new MalformedResponseError("estimateFee: node response contains invalid fee estimation entry");
3441
+ }
3442
+ return {
3443
+ feeRate: Number(e.fee_rate),
3444
+ fee: Number(e.fee)
3445
+ };
3446
+ });
3447
+ }
3448
+
3449
+ // src/actions/wallet/utils.ts
3450
+ function isProviderAccount(account) {
3451
+ return account.type === "provider";
3452
+ }
3453
+ var FEE_TIERS = ["min", "low", "mid", "high"];
3454
+ var TIER_INDEX = { low: 0, mid: 1, high: 2 };
3455
+ function isFeeTier(fee) {
3456
+ return typeof fee === "string" && FEE_TIERS.includes(fee);
3457
+ }
3458
+ function minimumFee(transaction) {
3459
+ return BigInt(serializeTransaction(transaction).length);
3460
+ }
3461
+ function isNoEstimateAvailable(error) {
3462
+ return error instanceof HttpRequestError && error.status === 400 && (error.details?.includes("NoEstimateAvailable") ?? false);
3463
+ }
3464
+ async function resolveFee(client, transaction, fee) {
3465
+ if (fee !== undefined && !isFeeTier(fee))
3466
+ return { fee: intToBigInt(fee) };
3467
+ const tier = fee ?? "mid";
3468
+ if (tier === "min")
3469
+ return { fee: minimumFee(transaction), tier };
3470
+ let estimates;
3471
+ try {
3472
+ estimates = await estimateFee(client, { transaction });
3473
+ } catch (error) {
3474
+ if (!isNoEstimateAvailable(error))
3475
+ throw error;
3476
+ return { fee: minimumFee(transaction), tier: "min" };
3477
+ }
3478
+ const pick = estimates[TIER_INDEX[tier]] ?? estimates[estimates.length - 1];
3479
+ if (pick)
3480
+ return { fee: BigInt(pick.fee), tier };
3481
+ return { fee: minimumFee(transaction), tier: "min" };
3482
+ }
3483
+ function setUnsignedFee(transaction, fee) {
3484
+ transaction.auth.spendingCondition.fee = fee;
3485
+ clearTxCache(transaction);
3486
+ }
3487
+ function assertNoFeeTierForProvider(fee) {
3488
+ if (isFeeTier(fee)) {
3489
+ throw new Error(`Fee tier '${fee}' requires local signing; provider (wallet) accounts set their own fee`);
3490
+ }
3491
+ }
3492
+
3493
+ // src/actions/wallet/callContract.ts
3494
+ async function callContract(client, params) {
3495
+ const account = client.account;
3496
+ if (!account)
3497
+ throw new Error("Account required");
3498
+ const [contractAddress, contractName] = parseContractId(params.contract);
3499
+ if (isProviderAccount(account)) {
3500
+ assertNoFeeTierForProvider(params.fee);
3501
+ const result = await account.provider.request("stx_callContract", {
3502
+ contract: params.contract,
3503
+ functionName: params.functionName,
3504
+ functionArgs: params.functionArgs ?? []
3505
+ });
3506
+ return result.txid;
3507
+ }
3508
+ const managed = params.nonce === undefined && client.nonceManager !== undefined;
3509
+ const nonce = params.nonce ?? await resolveNonce(client, account.address);
3510
+ try {
3511
+ const needsFeeResolution = params.fee === undefined || isFeeTier(params.fee);
3512
+ const unsigned = buildContractCall({
3513
+ contractAddress,
3514
+ contractName,
3515
+ functionName: params.functionName,
3516
+ functionArgs: params.functionArgs ?? [],
3517
+ fee: needsFeeResolution ? 0n : params.fee,
3518
+ nonce,
3519
+ publicKey: account.publicKey,
3520
+ chain: client.chain,
3521
+ postConditionMode: params.postConditionMode,
3522
+ postConditions: params.postConditions
3523
+ });
3524
+ if (needsFeeResolution) {
3525
+ const { fee } = await resolveFee(client, unsigned, params.fee);
3526
+ setUnsignedFee(unsigned, fee);
3527
+ }
3528
+ const signed = await signTransactionWithAccount(unsigned, account);
3529
+ return await broadcastWithNonceReset(client, {
3530
+ transaction: signed,
3531
+ address: account.address
3532
+ });
3533
+ } catch (error) {
3534
+ if (managed)
3535
+ await releaseNonce(client, account.address, nonce);
3536
+ throw error;
3537
+ }
3538
+ }
3539
+
3540
+ // src/actions/getContract.ts
3541
+ function getContract(params) {
3542
+ const { client, address, name: contractName, abi } = params;
3543
+ const contractId = `${address}.${contractName}`;
3544
+ const fnByName = new Map;
3545
+ for (const fn of abi.functions) {
3546
+ fnByName.set(fn.name, fn);
3547
+ }
3548
+ const mapByName = new Map;
3549
+ if (abi.maps) {
3550
+ for (const m of abi.maps) {
3551
+ mapByName.set(m.name, m);
3552
+ }
3553
+ }
3554
+ const camelToKebab = new Map;
3555
+ for (const fn of abi.functions) {
3556
+ camelToKebab.set(toCamelCase(fn.name), fn.name);
3557
+ }
3558
+ if (abi.maps) {
3559
+ for (const m of abi.maps) {
3560
+ camelToKebab.set(toCamelCase(m.name), m.name);
3561
+ }
3562
+ }
3563
+ const read = new Proxy({}, {
3564
+ get(_target, prop) {
3565
+ const fnName = camelToKebab.get(prop) ?? prop;
3566
+ const fn = fnByName.get(fnName);
3567
+ if (!fn || fn.access !== "read-only")
3568
+ return;
3569
+ return async (args = {}) => {
3570
+ const clarityArgs = buildFunctionArgs(fn, args);
3571
+ const result = await readContract(client, {
3572
+ contract: contractId,
3573
+ functionName: fn.name,
3574
+ args: clarityArgs
3575
+ });
3576
+ const jsValue = clarityValueToJSUntyped(fn.outputs, result);
3577
+ if (isResponseOutput(fn.outputs)) {
3578
+ const resp = jsValue;
3579
+ if ("ok" in resp)
3580
+ return resp.ok;
3581
+ throw new ContractResponseError(`${contractId}::${fn.name} returned (err ${formatErrValue(resp.err)})`, resp.err);
3582
+ }
3583
+ return jsValue;
3584
+ };
3585
+ }
3586
+ });
3587
+ const call = new Proxy({}, {
3588
+ get(_target, prop) {
3589
+ const fnName = camelToKebab.get(prop) ?? prop;
3590
+ const fn = fnByName.get(fnName);
3591
+ if (!fn || fn.access !== "public")
3592
+ return;
3593
+ return async (args = {}, options) => {
3594
+ const clarityArgs = buildFunctionArgs(fn, args);
3595
+ return callContract(client, {
3596
+ contract: contractId,
3597
+ functionName: fn.name,
3598
+ functionArgs: clarityArgs,
3599
+ ...options
3600
+ });
3601
+ };
3602
+ }
3603
+ });
3604
+ const buildCall = new Proxy({}, {
3605
+ get(_target, prop) {
3606
+ const fnName = camelToKebab.get(prop) ?? prop;
3607
+ const fn = fnByName.get(fnName);
3608
+ if (!fn || fn.access !== "public")
3609
+ return;
3610
+ return async (args = {}, options) => {
3611
+ const publicKey = options?.publicKey ?? client.account?.publicKey;
3612
+ if (!publicKey) {
3613
+ throw new Error("buildCall requires a publicKey (pass options.publicKey or configure a client account)");
3614
+ }
3615
+ const functionArgs = buildFunctionArgs(fn, args);
3616
+ const network = client.chain?.network ?? "mainnet";
3617
+ const nonce = options?.nonce ?? await getNonce(client, {
3618
+ address: publicKeyToAddress(publicKey, network)
3619
+ });
3620
+ const unsigned = buildContractCall({
3621
+ contractAddress: address,
3622
+ contractName,
3623
+ functionName: fn.name,
3624
+ functionArgs,
3625
+ fee: options?.fee ?? 0n,
3626
+ nonce,
3627
+ publicKey,
3628
+ chain: client.chain,
3629
+ postConditionMode: options?.postConditionMode,
3630
+ postConditions: options?.postConditions,
3631
+ sponsored: options?.sponsored
3632
+ });
3633
+ if (options?.fee === undefined) {
3634
+ const { fee } = await resolveFee(client, unsigned, undefined);
3635
+ setUnsignedFee(unsigned, fee);
3636
+ }
3637
+ return unsigned;
3638
+ };
3639
+ }
3640
+ });
3641
+ const maps = new Proxy({}, {
3642
+ get(_target, prop) {
3643
+ const mapName = camelToKebab.get(prop) ?? prop;
3644
+ const map = mapByName.get(mapName);
3645
+ if (!map)
3646
+ return;
3647
+ return async (key) => {
3648
+ const clarityKey = jsToClarityValue(map.key, key);
3649
+ const result = await getMapEntry(client, {
3650
+ contract: contractId,
3651
+ mapName: map.name,
3652
+ key: clarityKey
3653
+ });
3654
+ if (result.type === "none")
3655
+ return null;
3656
+ if (result.type === "some") {
3657
+ return clarityValueToJSUntyped(map.value, result.value);
3658
+ }
3659
+ return clarityValueToJSUntyped(map.value, result);
3660
+ };
3661
+ }
3662
+ });
3663
+ return { read, call, buildCall, maps };
3664
+ }
3665
+ function resolveNetworkContract(client, contracts) {
3666
+ if (!client.chain) {
3667
+ throw new Error("Client must have a chain configured");
3668
+ }
3669
+ return contracts[client.chain.network];
3670
+ }
3671
+ function buildFunctionArgs(fn, args = {}) {
3672
+ return fn.args.map((arg) => {
3673
+ const camelKey = toCamelCase(arg.name);
3674
+ const hasOriginal = arg.name in args;
3675
+ const hasCamel = camelKey in args;
3676
+ const value = hasOriginal ? args[arg.name] : hasCamel ? args[camelKey] : undefined;
3677
+ if (value === undefined)
3678
+ throw new Error(`Missing argument: ${arg.name}`);
3679
+ return jsToClarityValue(arg.type, value);
3680
+ });
3681
+ }
3682
+ function isResponseOutput(type) {
3683
+ return typeof type === "object" && type !== null && "response" in type;
3684
+ }
3685
+ function formatErrValue(value) {
3686
+ if (typeof value === "bigint")
3687
+ return value.toString();
3688
+ if (typeof value === "string")
3689
+ return `"${value}"`;
3690
+ return String(value);
3691
+ }
3692
+
3693
+ class ContractResponseError extends Error {
3694
+ errorValue;
3695
+ name = "ContractResponseError";
3696
+ constructor(message, errorValue) {
3697
+ super(message);
3698
+ this.errorValue = errorValue;
3699
+ }
315
3700
  }
3701
+
316
3702
  // src/pox5/abi.ts
317
3703
  var POX5_ABI = {
318
3704
  functions: [
@@ -1603,8 +4989,222 @@ async function eligiblePauseRewards(client, params) {
1603
4989
  return { ok: true };
1604
4990
  }
1605
4991
  // src/pox5/script.ts
1606
- var import_sha2 = require("@noble/hashes/sha2.js");
1607
- var import_base = require("@scure/base");
4992
+ var import_sha25 = require("@noble/hashes/sha2.js");
4993
+ var import_base6 = require("@scure/base");
4994
+
4995
+ // src/bitcoin/address.ts
4996
+ var import_secp256k13 = require("@noble/curves/secp256k1.js");
4997
+ var import_base5 = require("@scure/base");
4998
+
4999
+ // src/bitcoin/serialize.ts
5000
+ function doubleSha256(bytes) {
5001
+ return import_sha22.sha256(import_sha22.sha256(bytes));
5002
+ }
5003
+ function reverseBytes(bytes) {
5004
+ const out = new Uint8Array(bytes.length);
5005
+ for (let i = 0;i < bytes.length; i++) {
5006
+ out[i] = bytes[bytes.length - 1 - i];
5007
+ }
5008
+ return out;
5009
+ }
5010
+
5011
+ class BtcReader {
5012
+ data;
5013
+ view;
5014
+ offset = 0;
5015
+ constructor(data) {
5016
+ this.data = data;
5017
+ this.view = new DataView(data.buffer, data.byteOffset, data.byteLength);
5018
+ }
5019
+ get length() {
5020
+ return this.data.length;
5021
+ }
5022
+ readUInt8() {
5023
+ const v = this.view.getUint8(this.offset);
5024
+ this.offset += 1;
5025
+ return v;
5026
+ }
5027
+ peekUInt8() {
5028
+ return this.view.getUint8(this.offset);
5029
+ }
5030
+ readUInt32LE() {
5031
+ const v = this.view.getUint32(this.offset, true);
5032
+ this.offset += 4;
5033
+ return v;
5034
+ }
5035
+ readUInt64LE() {
5036
+ const v = this.view.getBigUint64(this.offset, true);
5037
+ this.offset += 8;
5038
+ return v;
5039
+ }
5040
+ readBytes(n) {
5041
+ if (this.offset + n > this.data.length) {
5042
+ throw new Error(`Bitcoin tx underflow: need ${n} bytes at offset ${this.offset}, have ${this.data.length}`);
5043
+ }
5044
+ const slice = this.data.slice(this.offset, this.offset + n);
5045
+ this.offset += n;
5046
+ return slice;
5047
+ }
5048
+ readVarInt() {
5049
+ const first = this.readUInt8();
5050
+ if (first < 253)
5051
+ return first;
5052
+ if (first === 253) {
5053
+ const v = this.view.getUint16(this.offset, true);
5054
+ this.offset += 2;
5055
+ return v;
5056
+ }
5057
+ if (first === 254) {
5058
+ return this.readUInt32LE();
5059
+ }
5060
+ const big = this.readUInt64LE();
5061
+ if (big > BigInt(Number.MAX_SAFE_INTEGER)) {
5062
+ throw new Error("Bitcoin varint exceeds safe integer range");
5063
+ }
5064
+ return Number(big);
5065
+ }
5066
+ }
5067
+ function scanTx(rawTx) {
5068
+ const r = new BtcReader(rawTx);
5069
+ const version = r.readUInt32LE();
5070
+ let hasWitness = false;
5071
+ if (r.peekUInt8() === 0) {
5072
+ r.readUInt8();
5073
+ const flag = r.readUInt8();
5074
+ if (flag !== 1) {
5075
+ throw new Error(`Unexpected SegWit flag 0x${flag.toString(16)}`);
5076
+ }
5077
+ hasWitness = true;
5078
+ }
5079
+ const bodyStart = r.offset;
5080
+ const inputCount = r.readVarInt();
5081
+ const inputs = [];
5082
+ for (let i = 0;i < inputCount; i++) {
5083
+ const prevTxid = r.readBytes(32);
5084
+ const vout = r.readUInt32LE();
5085
+ const scriptSig = r.readBytes(r.readVarInt());
5086
+ const sequence = r.readUInt32LE();
5087
+ inputs.push({ prevTxid, vout, scriptSig, sequence });
5088
+ }
5089
+ const outputCount = r.readVarInt();
5090
+ const outputs = [];
5091
+ for (let i = 0;i < outputCount; i++) {
5092
+ const value = r.readUInt64LE();
5093
+ const scriptPubKey = r.readBytes(r.readVarInt());
5094
+ outputs.push({ value, scriptPubKey });
5095
+ }
5096
+ const bodyEnd = r.offset;
5097
+ if (hasWitness) {
5098
+ for (let i = 0;i < inputCount; i++) {
5099
+ const itemCount = r.readVarInt();
5100
+ for (let j = 0;j < itemCount; j++) {
5101
+ r.readBytes(r.readVarInt());
5102
+ }
5103
+ }
5104
+ }
5105
+ const locktime = r.readUInt32LE();
5106
+ const legacy = concatBytes(rawTx.slice(0, 4), rawTx.slice(bodyStart, bodyEnd), rawTx.slice(r.offset - 4, r.offset));
5107
+ return { version, hasWitness, inputs, outputs, locktime, legacy };
5108
+ }
5109
+ function parseBitcoinTx(rawTx) {
5110
+ const s = scanTx(rawTx);
5111
+ return {
5112
+ version: s.version,
5113
+ hasWitness: s.hasWitness,
5114
+ inputs: s.inputs,
5115
+ outputs: s.outputs,
5116
+ locktime: s.locktime,
5117
+ txidInternal: doubleSha256(s.legacy)
5118
+ };
5119
+ }
5120
+ function stripWitness(rawTx) {
5121
+ return scanTx(rawTx).legacy;
5122
+ }
5123
+ function bitcoinTxid(rawTx, { display = false } = {}) {
5124
+ const txid = doubleSha256(scanTx(rawTx).legacy);
5125
+ return display ? reverseBytes(txid) : txid;
5126
+ }
5127
+ function parseBlockHeader(header) {
5128
+ if (header.length !== 80) {
5129
+ throw new Error(`Bitcoin block header must be 80 bytes, got ${header.length}`);
5130
+ }
5131
+ const r = new BtcReader(header);
5132
+ const version = r.readUInt32LE();
5133
+ const prevBlock = r.readBytes(32);
5134
+ const merkleRoot = r.readBytes(32);
5135
+ const timestamp = r.readUInt32LE();
5136
+ const bits = r.readUInt32LE();
5137
+ const nonce = r.readUInt32LE();
5138
+ return { version, prevBlock, merkleRoot, timestamp, bits, nonce };
5139
+ }
5140
+ function blockHash(header, { display = false } = {}) {
5141
+ const hash = doubleSha256(header);
5142
+ return display ? reverseBytes(hash) : hash;
5143
+ }
5144
+
5145
+ // src/bitcoin/address.ts
5146
+ var BITCOIN_NETWORK_PARAMS = {
5147
+ mainnet: { p2pkh: 0, p2sh: 5, hrp: "bc" },
5148
+ testnet: { p2pkh: 111, p2sh: 196, hrp: "tb" },
5149
+ regtest: { p2pkh: 111, p2sh: 196, hrp: "bcrt" }
5150
+ };
5151
+ var NETWORK_PARAMS = BITCOIN_NETWORK_PARAMS;
5152
+ function base58CheckEncode(version, payload) {
5153
+ const data = concatBytes(Uint8Array.of(version), payload);
5154
+ const checksum = doubleSha256(data).slice(0, 4);
5155
+ return import_base5.base58.encode(concatBytes(data, checksum));
5156
+ }
5157
+ function formatBitcoinAddress(parsed, network = "mainnet") {
5158
+ const params = NETWORK_PARAMS[network];
5159
+ const hash = parsed.hash;
5160
+ if (!hash)
5161
+ return;
5162
+ switch (parsed.type) {
5163
+ case "p2pkh":
5164
+ return base58CheckEncode(params.p2pkh, hash);
5165
+ case "p2sh":
5166
+ return base58CheckEncode(params.p2sh, hash);
5167
+ case "p2wpkh":
5168
+ case "p2wsh":
5169
+ return import_base5.bech32.encode(params.hrp, [0, ...import_base5.bech32.toWords(hash)]);
5170
+ case "p2tr":
5171
+ return import_base5.bech32m.encode(params.hrp, [1, ...import_base5.bech32m.toWords(hash)]);
5172
+ default:
5173
+ return;
5174
+ }
5175
+ }
5176
+ function toPubkeyBytes(publicKey) {
5177
+ return typeof publicKey === "string" ? hexToBytes(publicKey) : publicKey;
5178
+ }
5179
+ function taprootTweakPubkey(xonly) {
5180
+ if (xonly.length !== 32)
5181
+ throw new Error(`Expected 32-byte x-only pubkey, got ${xonly.length}`);
5182
+ const tweak = import_secp256k13.schnorr.utils.taggedHash("TapTweak", xonly);
5183
+ const t = BigInt(`0x${Array.from(tweak, (b) => b.toString(16).padStart(2, "0")).join("")}`);
5184
+ if (t >= import_secp256k13.secp256k1.Point.Fn.ORDER)
5185
+ throw new Error("Invalid tap tweak (exceeds curve order)");
5186
+ const internal = import_secp256k13.secp256k1.Point.fromBytes(concatBytes(Uint8Array.of(2), xonly));
5187
+ const output = internal.add(import_secp256k13.secp256k1.Point.BASE.multiply(t));
5188
+ return output.toBytes(true).slice(1);
5189
+ }
5190
+ function publicKeyToP2wpkhAddress(publicKey, network = "mainnet") {
5191
+ const pubkey = toPubkeyBytes(publicKey);
5192
+ if (pubkey.length !== 33)
5193
+ throw new Error(`Expected 33-byte compressed pubkey, got ${pubkey.length}`);
5194
+ const params = NETWORK_PARAMS[network];
5195
+ return import_base5.bech32.encode(params.hrp, [0, ...import_base5.bech32.toWords(hash160(pubkey))]);
5196
+ }
5197
+ function publicKeyToP2trAddress(publicKey, network = "mainnet") {
5198
+ const pubkey = toPubkeyBytes(publicKey);
5199
+ const xonly = pubkey.length === 33 ? pubkey.slice(1) : pubkey.length === 32 ? pubkey : undefined;
5200
+ if (!xonly)
5201
+ throw new Error(`Expected 33-byte compressed or 32-byte x-only pubkey, got ${pubkey.length}`);
5202
+ const params = NETWORK_PARAMS[network];
5203
+ const outputKey = taprootTweakPubkey(xonly);
5204
+ return import_base5.bech32m.encode(params.hrp, [1, ...import_base5.bech32m.toWords(outputKey)]);
5205
+ }
5206
+
5207
+ // src/pox5/script.ts
1608
5208
  function serializeCScriptNum(n) {
1609
5209
  const big = typeof n === "bigint" ? n : BigInt(n);
1610
5210
  if (big < 0n)
@@ -1649,7 +5249,7 @@ function stakerConsensusBuff(stxAddress) {
1649
5249
  return serializeCVBytes(Cl.principal(stxAddress));
1650
5250
  }
1651
5251
  function stakerPreimage(stxAddress) {
1652
- return import_sha2.sha256(stakerConsensusBuff(stxAddress));
5252
+ return import_sha25.sha256(stakerConsensusBuff(stxAddress));
1653
5253
  }
1654
5254
  function toBytes3(input) {
1655
5255
  return typeof input === "string" ? hexToBytes(input) : input;
@@ -1662,17 +5262,17 @@ function buildLockupScript(opts) {
1662
5262
  if (height >= BITCOIN_LOCKTIME_THRESHOLD) {
1663
5263
  throw new Error("unlockBurnHeight >= 500,000,000 would be read by Bitcoin as a timestamp (contract rejects it)");
1664
5264
  }
1665
- const stakerHash = import_sha2.sha256(stakerPreimage(opts.stxAddress));
5265
+ const stakerHash = import_sha25.sha256(stakerPreimage(opts.stxAddress));
1666
5266
  return concatBytes(Uint8Array.of(99), pushCScriptNum(height), Uint8Array.of(177, 103), hexToBytes("82012088a820"), stakerHash, Uint8Array.of(136), toBytes3(opts.earlyUnlockBytes), Uint8Array.of(104, 105), toBytes3(opts.stakerUnlockBytes));
1667
5267
  }
1668
5268
  function buildLockupOutputScript(opts) {
1669
- return concatBytes(Uint8Array.of(0, 32), import_sha2.sha256(buildLockupScript(opts)));
5269
+ return concatBytes(Uint8Array.of(0, 32), import_sha25.sha256(buildLockupScript(opts)));
1670
5270
  }
1671
5271
  function buildLockupAddress(opts, network = "mainnet") {
1672
- const hash = import_sha2.sha256(buildLockupScript(opts));
1673
- return import_base.bech32.encode(BITCOIN_NETWORK_PARAMS[network].hrp, [
5272
+ const hash = import_sha25.sha256(buildLockupScript(opts));
5273
+ return import_base6.bech32.encode(BITCOIN_NETWORK_PARAMS[network].hrp, [
1674
5274
  0,
1675
- ...import_base.bech32.toWords(hash)
5275
+ ...import_base6.bech32.toWords(hash)
1676
5276
  ]);
1677
5277
  }
1678
5278
  function buildDefaultStakerUnlockBytes(publicKey) {
@@ -1703,7 +5303,45 @@ function buildRegisterMetadata(opts) {
1703
5303
  };
1704
5304
  }
1705
5305
  // src/pox5/grants.ts
1706
- var import_secp256k1 = require("@noble/curves/secp256k1.js");
5306
+ var import_secp256k14 = require("@noble/curves/secp256k1.js");
5307
+
5308
+ // src/clarity/structuredData.ts
5309
+ var import_sha26 = require("@noble/hashes/sha2.js");
5310
+ var SIP018_PREFIX = new Uint8Array([
5311
+ 83,
5312
+ 73,
5313
+ 80,
5314
+ 48,
5315
+ 49,
5316
+ 56
5317
+ ]);
5318
+ function hashStructuredData(structuredData) {
5319
+ return import_sha26.sha256(serializeCVBytes(structuredData));
5320
+ }
5321
+ function isDomain(value) {
5322
+ if (value.type !== "tuple")
5323
+ return false;
5324
+ const { name, version, "chain-id": chainId } = value.value;
5325
+ return name?.type === "ascii" && version?.type === "ascii" && chainId?.type === "uint";
5326
+ }
5327
+ function encodeStructuredData(opts) {
5328
+ if (!isDomain(opts.domain)) {
5329
+ throw new Error("domain must be a tuple { name: ascii, version: ascii, chain-id: uint }");
5330
+ }
5331
+ return concatBytes(SIP018_PREFIX, hashStructuredData(opts.domain), hashStructuredData(opts.message));
5332
+ }
5333
+ function structuredDataHash(opts) {
5334
+ return import_sha26.sha256(encodeStructuredData(opts));
5335
+ }
5336
+ async function signStructuredData(account, opts) {
5337
+ const vrs = await account.sign(structuredDataHash(opts));
5338
+ if (vrs.length !== 65) {
5339
+ throw new Error(`Expected 65-byte recoverable signature, got ${vrs.length}`);
5340
+ }
5341
+ return bytesToHex(concatBytes(vrs.slice(1), vrs.slice(0, 1)));
5342
+ }
5343
+
5344
+ // src/pox5/grants.ts
1707
5345
  function computeSignerGrantHash(opts) {
1708
5346
  return structuredDataHash({
1709
5347
  domain: Cl.tuple({
@@ -1731,17 +5369,236 @@ function verifySignerGrant(opts) {
1731
5369
  return false;
1732
5370
  const pubkey = typeof opts.publicKey === "string" ? hexToBytes(opts.publicKey) : opts.publicKey;
1733
5371
  const hash = computeSignerGrantHash(opts);
1734
- const recovered = import_secp256k1.secp256k1.Signature.fromBytes(sig.slice(0, 64)).addRecoveryBit(sig[64]).recoverPublicKey(hash).toBytes(true);
5372
+ const recovered = import_secp256k14.secp256k1.Signature.fromBytes(sig.slice(0, 64)).addRecoveryBit(sig[64]).recoverPublicKey(hash).toBytes(true);
1735
5373
  return bytesToHex(recovered) === bytesToHex(pubkey);
1736
5374
  } catch {
1737
5375
  return false;
1738
5376
  }
1739
5377
  }
1740
5378
  // src/pox5/lockProof.ts
1741
- var import_sha22 = require("@noble/hashes/sha2.js");
5379
+ var import_sha27 = require("@noble/hashes/sha2.js");
5380
+
5381
+ // src/bitcoin/merkle.ts
5382
+ function hashPair(left, right) {
5383
+ return doubleSha256(concatBytes(left, right));
5384
+ }
5385
+ function nextLevel(level) {
5386
+ const next = [];
5387
+ for (let i = 0;i < level.length; i += 2) {
5388
+ const left = level[i];
5389
+ if (left === undefined)
5390
+ throw new Error("merkle: missing left node");
5391
+ const right = level[i + 1] ?? left;
5392
+ next.push(hashPair(left, right));
5393
+ }
5394
+ return next;
5395
+ }
5396
+ function merkleRoot(txidsInternal) {
5397
+ if (txidsInternal.length === 0) {
5398
+ throw new Error("merkleRoot: empty tx list");
5399
+ }
5400
+ let level = txidsInternal.slice();
5401
+ while (level.length > 1) {
5402
+ level = nextLevel(level);
5403
+ }
5404
+ const root = level[0];
5405
+ if (root === undefined)
5406
+ throw new Error("merkleRoot: no root");
5407
+ return root;
5408
+ }
5409
+ function buildMerkleProof(txidsInternal, txIndex) {
5410
+ const txCount = txidsInternal.length;
5411
+ if (txCount === 0) {
5412
+ throw new Error("buildMerkleProof: empty tx list");
5413
+ }
5414
+ if (txIndex < 0 || txIndex >= txCount) {
5415
+ throw new Error(`buildMerkleProof: txIndex ${txIndex} out of range for ${txCount} txs`);
5416
+ }
5417
+ const siblings = [];
5418
+ let index = txIndex;
5419
+ let level = txidsInternal.slice();
5420
+ while (level.length > 1) {
5421
+ const isRight = index % 2 === 1;
5422
+ const siblingIndex = isRight ? index - 1 : index + 1;
5423
+ const self = level[index];
5424
+ if (self === undefined)
5425
+ throw new Error("buildMerkleProof: missing node");
5426
+ siblings.push(level[siblingIndex] ?? self);
5427
+ level = nextLevel(level);
5428
+ index = Math.floor(index / 2);
5429
+ }
5430
+ return { siblings, txIndex, txCount };
5431
+ }
5432
+ function rootFromProof(leafInternal, proof) {
5433
+ let hash = leafInternal;
5434
+ let index = proof.txIndex;
5435
+ for (const sibling of proof.siblings) {
5436
+ hash = index % 2 === 1 ? hashPair(sibling, hash) : hashPair(hash, sibling);
5437
+ index = Math.floor(index / 2);
5438
+ }
5439
+ return hash;
5440
+ }
5441
+
5442
+ // src/bitcoin/proof.ts
5443
+ function normalizeTxid2(txid) {
5444
+ return without0x(txid).toLowerCase();
5445
+ }
5446
+ function assembleBlockForTx(args) {
5447
+ const txIndex = args.txidsDisplay.indexOf(normalizeTxid2(args.txid));
5448
+ if (txIndex < 0) {
5449
+ throw new Error(`tx ${args.txid} not found in block ${args.blockId}`);
5450
+ }
5451
+ return {
5452
+ header: hexToBytes(args.headerHex),
5453
+ height: args.height,
5454
+ txidsInternal: args.txidsDisplay.map((t) => reverseBytes(hexToBytes(t))),
5455
+ txIndex
5456
+ };
5457
+ }
5458
+ async function buildTxProof(source, params) {
5459
+ const { txid, vout } = params;
5460
+ const want = normalizeTxid2(txid);
5461
+ const [rawTx, block] = await Promise.all([
5462
+ source.getRawTx(txid),
5463
+ source.getBlockForTx(txid)
5464
+ ]);
5465
+ const parsed = parseBitcoinTx(rawTx);
5466
+ const gotDisplay = bytesToHex(reverseBytes(parsed.txidInternal));
5467
+ if (gotDisplay !== want) {
5468
+ throw new Error(`source returned a tx whose id ${gotDisplay} does not match requested ${want}`);
5469
+ }
5470
+ const atIndex = block.txidsInternal[block.txIndex];
5471
+ if (!atIndex || bytesToHex(atIndex) !== bytesToHex(parsed.txidInternal)) {
5472
+ throw new Error(`source txIndex ${block.txIndex} does not point at tx ${want}`);
5473
+ }
5474
+ const merkle = buildMerkleProof(block.txidsInternal, block.txIndex);
5475
+ const headerRoot = parseBlockHeader(block.header).merkleRoot;
5476
+ const computed = rootFromProof(parsed.txidInternal, merkle);
5477
+ if (bytesToHex(computed) !== bytesToHex(headerRoot)) {
5478
+ throw new Error("constructed merkle proof does not reconcile with the block header merkle root");
5479
+ }
5480
+ return {
5481
+ rawTx,
5482
+ txidInternal: parsed.txidInternal,
5483
+ vout,
5484
+ merkle,
5485
+ header: block.header,
5486
+ height: block.height
5487
+ };
5488
+ }
5489
+ function fallbackProofSource(sources) {
5490
+ if (sources.length === 0) {
5491
+ throw new Error("fallbackProofSource: at least one source is required");
5492
+ }
5493
+ async function firstSuccess(fn) {
5494
+ let lastError;
5495
+ for (const source of sources) {
5496
+ try {
5497
+ return await fn(source);
5498
+ } catch (error) {
5499
+ lastError = error;
5500
+ }
5501
+ }
5502
+ throw lastError;
5503
+ }
5504
+ return {
5505
+ getRawTx: (txid) => firstSuccess((s) => s.getRawTx(txid)),
5506
+ getBlockForTx: (txid) => firstSuccess((s) => s.getBlockForTx(txid))
5507
+ };
5508
+ }
5509
+ function bitcoinRpcSource(config) {
5510
+ const doFetch = config.fetch ?? fetch;
5511
+ async function rpc(method, rpcParams) {
5512
+ const headers = {
5513
+ "content-type": "application/json"
5514
+ };
5515
+ if (config.auth) {
5516
+ const basic = typeof config.auth === "string" ? config.auth : btoa(`${config.auth.username}:${config.auth.password}`);
5517
+ headers.authorization = `Basic ${basic}`;
5518
+ }
5519
+ const res = await doFetch(config.url, {
5520
+ method: "POST",
5521
+ headers,
5522
+ body: JSON.stringify({
5523
+ jsonrpc: "1.0",
5524
+ id: "secondlayer",
5525
+ method,
5526
+ params: rpcParams
5527
+ })
5528
+ });
5529
+ if (!res.ok) {
5530
+ throw new Error(`bitcoin rpc ${method} failed: HTTP ${res.status}`);
5531
+ }
5532
+ const json = await res.json();
5533
+ if (json.error) {
5534
+ throw new Error(`bitcoin rpc ${method} error: ${json.error.message}`);
5535
+ }
5536
+ return json.result;
5537
+ }
5538
+ return {
5539
+ async getRawTx(txid) {
5540
+ return hexToBytes(await rpc("getrawtransaction", [txid, false]));
5541
+ },
5542
+ async getBlockForTx(txid) {
5543
+ const tx = await rpc("getrawtransaction", [
5544
+ txid,
5545
+ true
5546
+ ]);
5547
+ if (!tx.blockhash) {
5548
+ throw new Error(`tx ${txid} is not in a block (node needs -txindex, or the tx is unconfirmed)`);
5549
+ }
5550
+ const block = await rpc("getblock", [
5551
+ tx.blockhash,
5552
+ 1
5553
+ ]);
5554
+ const header = await rpc("getblockheader", [tx.blockhash, false]);
5555
+ return assembleBlockForTx({
5556
+ txid,
5557
+ blockId: tx.blockhash,
5558
+ headerHex: header,
5559
+ height: block.height,
5560
+ txidsDisplay: block.tx
5561
+ });
5562
+ }
5563
+ };
5564
+ }
5565
+ function esploraSource(config) {
5566
+ const doFetch = config.fetch ?? fetch;
5567
+ const base = config.url.replace(/\/+$/, "");
5568
+ async function get(path) {
5569
+ const res = await doFetch(`${base}${path}`);
5570
+ if (!res.ok) {
5571
+ throw new Error(`esplora GET ${path} failed: HTTP ${res.status}`);
5572
+ }
5573
+ return res;
5574
+ }
5575
+ return {
5576
+ async getRawTx(txid) {
5577
+ return hexToBytes((await (await get(`/tx/${txid}/hex`)).text()).trim());
5578
+ },
5579
+ async getBlockForTx(txid) {
5580
+ const status = await (await get(`/tx/${txid}`)).json();
5581
+ if (!status.status.confirmed) {
5582
+ throw new Error(`tx ${txid} is unconfirmed`);
5583
+ }
5584
+ const blockHashHex = status.status.block_hash;
5585
+ const header = (await (await get(`/block/${blockHashHex}/header`)).text()).trim();
5586
+ const txids = await (await get(`/block/${blockHashHex}/txids`)).json();
5587
+ return assembleBlockForTx({
5588
+ txid,
5589
+ blockId: blockHashHex,
5590
+ headerHex: header,
5591
+ height: status.status.block_height,
5592
+ txidsDisplay: txids
5593
+ });
5594
+ }
5595
+ };
5596
+ }
5597
+
5598
+ // src/pox5/lockProof.ts
1742
5599
  var MAX_LEAF_HASHES2 = 14;
1743
5600
  function lockupScriptPubKey(lockScript) {
1744
- return concatBytes(Uint8Array.of(0, 32), import_sha22.sha256(lockScript));
5601
+ return concatBytes(Uint8Array.of(0, 32), import_sha27.sha256(lockScript));
1745
5602
  }
1746
5603
  function scriptsEqual(a, b) {
1747
5604
  return bytesToHex(a) === bytesToHex(b);
@@ -1800,9 +5657,9 @@ async function buildPox5LockProof(opts) {
1800
5657
  });
1801
5658
  }
1802
5659
  // src/pox5/reclaim.ts
1803
- var import_sha23 = require("@noble/hashes/sha2.js");
1804
- var btc = __toESM(require("@scure/btc-signer"));
1805
- var import_utils = require("@scure/btc-signer/utils.js");
5660
+ var import_sha28 = require("@noble/hashes/sha2.js");
5661
+ var btc = __toESM(require("@scure/btc-signer"), 1);
5662
+ var import_utils5 = require("@scure/btc-signer/utils.js");
1806
5663
  var SIGHASH_ALL = 1;
1807
5664
  var DUST_LIMIT_SATS = 546n;
1808
5665
  var ELSE_SELECTOR = new Uint8Array(0);
@@ -1830,7 +5687,7 @@ function bytesEqual(a, b) {
1830
5687
  return bytesToHex(a) === bytesToHex(b);
1831
5688
  }
1832
5689
  function scriptToWshOutput(lockScript) {
1833
- return concatBytes(Uint8Array.of(0, 32), import_sha23.sha256(lockScript));
5690
+ return concatBytes(Uint8Array.of(0, 32), import_sha28.sha256(lockScript));
1834
5691
  }
1835
5692
  var SCAFFOLD_PREFIX_LEN = 10;
1836
5693
  function decodeLockScript(script) {
@@ -1898,7 +5755,7 @@ function computeReclaimSighash(tx, opts) {
1898
5755
  }
1899
5756
  function signReclaim(sighash, privateKey, opts) {
1900
5757
  const priv = toPrivBytes(privateKey);
1901
- return concatBytes(import_utils.signECDSA(sighash, priv, opts?.lowR ?? false), Uint8Array.of(SIGHASH_ALL));
5758
+ return concatBytes(import_utils5.signECDSA(sighash, priv, opts?.lowR ?? false), Uint8Array.of(SIGHASH_ALL));
1902
5759
  }
1903
5760
  function finalizeReclaim(opts) {
1904
5761
  const { tx } = opts;
@@ -1963,6 +5820,48 @@ function reclaim(opts) {
1963
5820
  }
1964
5821
  return finalizeReclaim({ path: "locktime", tx });
1965
5822
  }
5823
+ // src/actions/public/multicall.ts
5824
+ async function mapWithConcurrency(items, limit, fn) {
5825
+ const results = new Array(items.length);
5826
+ let cursor = 0;
5827
+ const worker = async () => {
5828
+ while (cursor < items.length) {
5829
+ const index = cursor++;
5830
+ try {
5831
+ results[index] = {
5832
+ status: "fulfilled",
5833
+ value: await fn(items[index])
5834
+ };
5835
+ } catch (reason) {
5836
+ results[index] = { status: "rejected", reason };
5837
+ }
5838
+ }
5839
+ };
5840
+ const workers = Math.max(1, Math.min(limit, items.length));
5841
+ await Promise.all(Array.from({ length: workers }, worker));
5842
+ return results;
5843
+ }
5844
+ async function multicall(client, params) {
5845
+ const { calls, allowFailure = true, concurrency = 8 } = params;
5846
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
5847
+ throw new RangeError(`multicall concurrency must be a positive integer, got ${concurrency}`);
5848
+ }
5849
+ const settled = await mapWithConcurrency(calls, concurrency, (call) => readContract(client, call));
5850
+ if (allowFailure) {
5851
+ return settled.map((r) => r.status === "fulfilled" ? { status: "success", result: r.value } : {
5852
+ status: "failure",
5853
+ error: r.reason instanceof Error ? r.reason : new Error(String(r.reason))
5854
+ });
5855
+ }
5856
+ const results = [];
5857
+ for (const r of settled) {
5858
+ if (r.status === "rejected")
5859
+ throw r.reason;
5860
+ results.push(r.value);
5861
+ }
5862
+ return results;
5863
+ }
5864
+
1966
5865
  // src/pox5/extension.ts
1967
5866
  async function getStakerState(client, staker) {
1968
5867
  const contract = pox5ContractId(client);
@@ -2047,6 +5946,136 @@ function pox5() {
2047
5946
  }
2048
5947
  });
2049
5948
  }
5949
+ // src/pox5/btcAddress.ts
5950
+ var import_base7 = require("@scure/base");
5951
+
5952
+ // src/pox/constants.ts
5953
+ var POX_CONTRACTS = {
5954
+ mainnet: {
5955
+ address: "SP000000000000000000002Q6VF78",
5956
+ name: "pox-4"
5957
+ },
5958
+ testnet: {
5959
+ address: "ST000000000000000000002AMW42H",
5960
+ name: "pox-4"
5961
+ }
5962
+ };
5963
+ var MIN_LOCK_PERIOD = 1;
5964
+ var MAX_LOCK_PERIOD = 12;
5965
+ var POX_ADDRESS_VERSION = {
5966
+ p2pkh: 0,
5967
+ p2sh: 1,
5968
+ p2sh_p2wpkh: 2,
5969
+ p2sh_p2wsh: 3,
5970
+ p2wpkh: 4,
5971
+ p2wsh: 5,
5972
+ p2tr: 6
5973
+ };
5974
+
5975
+ // src/pox5/btcAddress.ts
5976
+ function expectedHashLen(version) {
5977
+ if (!Number.isInteger(version) || version < 0 || version > 6) {
5978
+ throw new Error(`Unknown PoX address version: 0x${version.toString(16)}`);
5979
+ }
5980
+ return version <= 4 ? 20 : 32;
5981
+ }
5982
+ function canonicalizeBtcAddress(repr) {
5983
+ const expected = expectedHashLen(repr.version);
5984
+ const { hashbytes } = repr;
5985
+ if (hashbytes.length === expected)
5986
+ return { version: repr.version, hashbytes };
5987
+ if (expected === 20 && hashbytes.length === 32 && hashbytes.slice(20).every((b) => b === 0)) {
5988
+ return { version: repr.version, hashbytes: hashbytes.slice(0, 20) };
5989
+ }
5990
+ throw new Error(`Invalid hashbytes length for PoX version 0x${repr.version.toString(16)}: ${hashbytes.length}`);
5991
+ }
5992
+ function parseBtcAddress(address) {
5993
+ if (address.startsWith("bc1") || address.startsWith("tb1") || address.startsWith("bcrt1")) {
5994
+ return parseSegwitAddress(address);
5995
+ }
5996
+ return parseLegacyAddress(address);
5997
+ }
5998
+ function parseSegwitAddress(address) {
5999
+ let decoded;
6000
+ try {
6001
+ decoded = import_base7.bech32.decode(address);
6002
+ } catch {
6003
+ decoded = import_base7.bech32m.decode(address);
6004
+ }
6005
+ const witnessVersion = decoded.words[0];
6006
+ if (witnessVersion === undefined) {
6007
+ throw new Error("Invalid segwit address: missing witness version");
6008
+ }
6009
+ const data = import_base7.bech32.fromWords(decoded.words.slice(1));
6010
+ const hashbytes = new Uint8Array(data);
6011
+ let version;
6012
+ if (witnessVersion === 0) {
6013
+ if (hashbytes.length === 20) {
6014
+ version = POX_ADDRESS_VERSION.p2wpkh;
6015
+ } else if (hashbytes.length === 32) {
6016
+ version = POX_ADDRESS_VERSION.p2wsh;
6017
+ } else {
6018
+ throw new Error(`Invalid witness v0 program length: ${hashbytes.length}`);
6019
+ }
6020
+ } else if (witnessVersion === 1) {
6021
+ if (hashbytes.length !== 32) {
6022
+ throw new Error(`Invalid witness v1 program length: ${hashbytes.length}`);
6023
+ }
6024
+ version = POX_ADDRESS_VERSION.p2tr;
6025
+ } else {
6026
+ throw new Error(`Unsupported witness version: ${witnessVersion}`);
6027
+ }
6028
+ return { version, hashbytes };
6029
+ }
6030
+ function parseLegacyAddress(address) {
6031
+ const decoded = import_base7.base58.decode(address);
6032
+ if (decoded.length !== 25) {
6033
+ throw new Error(`Invalid legacy address length: ${decoded.length}`);
6034
+ }
6035
+ const versionByte = decoded[0];
6036
+ if (versionByte === undefined) {
6037
+ throw new Error("Invalid legacy address: missing version byte");
6038
+ }
6039
+ const payload = decoded.slice(0, 21);
6040
+ const checksum = decoded.slice(21);
6041
+ const expected = doubleSha256(payload).slice(0, 4);
6042
+ if (checksum.length !== 4 || expected.some((b, i) => b !== checksum[i])) {
6043
+ throw new Error("Invalid legacy address checksum");
6044
+ }
6045
+ const hashbytes = decoded.slice(1, 21);
6046
+ let version;
6047
+ if (versionByte === 0 || versionByte === 111) {
6048
+ version = POX_ADDRESS_VERSION.p2pkh;
6049
+ } else if (versionByte === 5 || versionByte === 196) {
6050
+ version = POX_ADDRESS_VERSION.p2sh;
6051
+ } else {
6052
+ throw new Error(`Unknown legacy address version byte: 0x${versionByte.toString(16)}`);
6053
+ }
6054
+ return { version, hashbytes };
6055
+ }
6056
+ function stringifyBtcAddress(repr, network) {
6057
+ const { version, hashbytes } = canonicalizeBtcAddress(repr);
6058
+ const params = BITCOIN_NETWORK_PARAMS[network];
6059
+ switch (version) {
6060
+ case POX_ADDRESS_VERSION.p2pkh:
6061
+ return base58CheckEncode(params.p2pkh, hashbytes);
6062
+ case POX_ADDRESS_VERSION.p2sh:
6063
+ case POX_ADDRESS_VERSION.p2sh_p2wpkh:
6064
+ case POX_ADDRESS_VERSION.p2sh_p2wsh:
6065
+ return base58CheckEncode(params.p2sh, hashbytes);
6066
+ case POX_ADDRESS_VERSION.p2wpkh:
6067
+ case POX_ADDRESS_VERSION.p2wsh:
6068
+ return import_base7.bech32.encode(params.hrp, [0, ...import_base7.bech32.toWords(hashbytes)]);
6069
+ case POX_ADDRESS_VERSION.p2tr:
6070
+ return import_base7.bech32m.encode(params.hrp, [1, ...import_base7.bech32m.toWords(hashbytes)]);
6071
+ default:
6072
+ throw new Error(`Unknown PoX address version: 0x${version.toString(16)}`);
6073
+ }
6074
+ }
6075
+ var BtcAddress = {
6076
+ parse: parseBtcAddress,
6077
+ stringify: stringifyBtcAddress
6078
+ };
2050
6079
  // src/pox5/signerCalldata.ts
2051
6080
  function buildSignerCalldata(opts) {
2052
6081
  const repr = canonicalizeBtcAddress(typeof opts.poxAddress === "string" ? parseBtcAddress(opts.poxAddress) : opts.poxAddress);
@@ -2096,5 +6125,5 @@ function parseSignerCalldata(calldata) {
2096
6125
  };
2097
6126
  }
2098
6127
 
2099
- //# debugId=90830B6EA47D48EC64756E2164756E21
6128
+ //# debugId=4C601AE15AFDE5D164756E2164756E21
2100
6129
  //# sourceMappingURL=index.cjs.map