@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,140 +1,3560 @@
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/index.ts
2
67
  var exports_src = {};
3
68
  __export(exports_src, {
4
- webSocket: () => webSocket,
5
- walletActions: () => walletActions,
6
- waitForTransactionReceipt: () => waitForTransactionReceipt,
7
- testnet: () => testnet,
8
- startNonceReconciler: () => startNonceReconciler,
9
- resolveNonce: () => resolveNonce,
10
- redisStore: () => redisStore,
11
- reconcileNonce: () => reconcileNonce,
12
- publicActions: () => publicActions,
13
- providerToAccount: () => providerToAccount,
14
- postgresStore: () => postgresStore,
15
- parseStx: () => parseStx,
16
- on: () => on,
17
- nextFreeNonce: () => nextFreeNonce,
18
- multisigActions: () => multisigActions,
19
- mocknet: () => mocknet,
20
- mempoolAwareSource: () => mempoolAwareSource,
21
- memoryStore: () => memoryStore,
22
- mainnet: () => mainnet,
23
- jsonRpcSource: () => jsonRpcSource,
24
- isValidAddress: () => isValidAddress,
25
- isNonceConflictError: () => isNonceConflictError,
26
- isAddressEqual: () => isAddressEqual,
27
- indexTxSource: () => indexTxSource,
28
- indexSource: () => indexSource,
29
- http: () => http,
30
- hiroNonceSource: () => hiroNonceSource,
31
- getTransaction: () => getTransaction,
32
- getContractAddress: () => getContractAddress,
33
- formatStx: () => formatStx,
34
- fallback: () => fallback,
35
- extendedApiSource: () => extendedApiSource,
36
- devnet: () => devnet,
37
- defineChain: () => defineChain,
38
- custom: () => custom,
39
- createWalletClient: () => createWalletClient,
40
- createPublicClient: () => createPublicClient,
41
- createNonceManager: () => createNonceManager,
42
- createMultiSigClient: () => createMultiSigClient,
43
- createClient: () => createClient,
44
- broadcastWithNonceReset: () => broadcastWithNonceReset,
45
- ZERO_ADDRESS: () => ZERO_ADDRESS,
46
- WebSocketError: () => WebSocketError,
47
- WaitForTransactionTimeoutError: () => WaitForTransactionTimeoutError,
48
- TransactionError: () => TransactionError,
49
- TransactionDroppedError: () => TransactionDroppedError,
50
- TransactionAbortedError: () => TransactionAbortedError,
51
- TimeoutError: () => TimeoutError,
52
- TESTNET_ZERO_ADDRESS: () => TESTNET_ZERO_ADDRESS,
53
- SimulationError: () => SimulationError,
54
- SigningError: () => SigningError,
55
- SerializationError: () => SerializationError,
56
- ReadContractError: () => ReadContractError,
57
- MalformedResponseError: () => MalformedResponseError,
58
- MICROSTX_PER_STX: () => MICROSTX_PER_STX,
59
- IndexSourceConfigError: () => IndexSourceConfigError,
60
- HttpRequestError: () => HttpRequestError,
61
- BroadcastError: () => BroadcastError,
69
+ AddressVersion: () => AddressVersion,
62
70
  BaseError: () => BaseError,
63
- AddressVersion: () => AddressVersion
71
+ BroadcastError: () => BroadcastError,
72
+ HttpRequestError: () => HttpRequestError,
73
+ IndexSourceConfigError: () => IndexSourceConfigError,
74
+ MICROSTX_PER_STX: () => MICROSTX_PER_STX,
75
+ MalformedResponseError: () => MalformedResponseError,
76
+ ReadContractError: () => ReadContractError,
77
+ SerializationError: () => SerializationError,
78
+ SigningError: () => SigningError,
79
+ SimulationError: () => SimulationError,
80
+ TESTNET_ZERO_ADDRESS: () => TESTNET_ZERO_ADDRESS,
81
+ TimeoutError: () => TimeoutError,
82
+ TransactionAbortedError: () => TransactionAbortedError,
83
+ TransactionDroppedError: () => TransactionDroppedError,
84
+ TransactionError: () => TransactionError,
85
+ WaitForTransactionTimeoutError: () => WaitForTransactionTimeoutError,
86
+ WebSocketError: () => WebSocketError,
87
+ ZERO_ADDRESS: () => ZERO_ADDRESS,
88
+ broadcastWithNonceReset: () => broadcastWithNonceReset,
89
+ createClient: () => createClient,
90
+ createMultiSigClient: () => createMultiSigClient,
91
+ createNonceManager: () => createNonceManager,
92
+ createPublicClient: () => createPublicClient,
93
+ createWalletClient: () => createWalletClient,
94
+ custom: () => custom,
95
+ defineChain: () => defineChain,
96
+ devnet: () => devnet,
97
+ extendedApiSource: () => extendedApiSource,
98
+ fallback: () => fallback,
99
+ formatStx: () => formatStx,
100
+ getContractAddress: () => getContractAddress,
101
+ getTransaction: () => getTransaction,
102
+ hiroNonceSource: () => hiroNonceSource,
103
+ http: () => http,
104
+ indexSource: () => indexSource,
105
+ indexTxSource: () => indexTxSource,
106
+ isAddressEqual: () => isAddressEqual,
107
+ isNonceConflictError: () => isNonceConflictError,
108
+ isValidAddress: () => isValidAddress,
109
+ jsonRpcSource: () => jsonRpcSource,
110
+ mainnet: () => mainnet,
111
+ memoryStore: () => memoryStore,
112
+ mempoolAwareSource: () => mempoolAwareSource,
113
+ mocknet: () => mocknet,
114
+ multisigActions: () => multisigActions,
115
+ nextFreeNonce: () => nextFreeNonce,
116
+ on: () => on,
117
+ parseStx: () => parseStx,
118
+ postgresStore: () => postgresStore,
119
+ providerToAccount: () => providerToAccount,
120
+ publicActions: () => publicActions,
121
+ reconcileNonce: () => reconcileNonce,
122
+ redisStore: () => redisStore,
123
+ resolveNonce: () => resolveNonce,
124
+ startNonceReconciler: () => startNonceReconciler,
125
+ testnet: () => testnet,
126
+ waitForTransactionReceipt: () => waitForTransactionReceipt,
127
+ walletActions: () => walletActions,
128
+ webSocket: () => webSocket
64
129
  });
65
130
  module.exports = __toCommonJS(exports_src);
66
131
 
67
- // src/clients/createClient.ts
68
- var BASE_KEYS = new Set([
69
- "chain",
70
- "account",
71
- "transport",
72
- "request",
73
- "nonceManager",
74
- "extend"
75
- ]);
76
- function bindExtend(base) {
77
- return (fn) => {
78
- const extensions = fn(base);
79
- const next = { ...base };
80
- for (const [key, value] of Object.entries(extensions)) {
81
- if (BASE_KEYS.has(key))
82
- continue;
83
- next[key] = value;
132
+ // src/clients/createClient.ts
133
+ var BASE_KEYS = new Set([
134
+ "chain",
135
+ "account",
136
+ "transport",
137
+ "request",
138
+ "nonceManager",
139
+ "extend"
140
+ ]);
141
+ function bindExtend(base) {
142
+ return (fn) => {
143
+ const extensions = fn(base);
144
+ const next = { ...base };
145
+ for (const [key, value] of Object.entries(extensions)) {
146
+ if (BASE_KEYS.has(key))
147
+ continue;
148
+ next[key] = value;
149
+ }
150
+ next.extend = bindExtend(next);
151
+ return next;
152
+ };
153
+ }
154
+ function createClient(config) {
155
+ const transport = config.transport({ chain: config.chain });
156
+ const client = {
157
+ chain: config.chain,
158
+ account: config.account,
159
+ transport,
160
+ request: transport.request,
161
+ nonceManager: config.nonceManager,
162
+ extend: null
163
+ };
164
+ client.extend = bindExtend(client);
165
+ return client;
166
+ }
167
+ // src/errors/base.ts
168
+ function codeFromName(name) {
169
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toUpperCase();
170
+ }
171
+
172
+ class BaseError extends Error {
173
+ name = "StacksError";
174
+ #code;
175
+ shortMessage;
176
+ details;
177
+ constructor(shortMessage, options) {
178
+ const message = [
179
+ shortMessage,
180
+ options?.details ? `
181
+ ${options.details}` : ""
182
+ ].join("");
183
+ super(message, { cause: options?.cause });
184
+ if (options?.code !== undefined)
185
+ this.#code = options.code;
186
+ this.shortMessage = shortMessage;
187
+ this.details = options?.details;
188
+ }
189
+ get code() {
190
+ return this.#code ?? codeFromName(this.name);
191
+ }
192
+ set code(value) {
193
+ this.#code = value;
194
+ }
195
+ toJSON() {
196
+ return {
197
+ name: this.name,
198
+ code: this.code,
199
+ message: this.message,
200
+ shortMessage: this.shortMessage,
201
+ details: this.details,
202
+ cause: this.cause instanceof Error ? this.cause.message : undefined
203
+ };
204
+ }
205
+ }
206
+
207
+ // src/errors/response.ts
208
+ class MalformedResponseError extends BaseError {
209
+ name = "MalformedResponseError";
210
+ }
211
+
212
+ class ReadContractError extends BaseError {
213
+ name = "ReadContractError";
214
+ }
215
+
216
+ // src/utils/c32.ts
217
+ var import_sha2 = require("@noble/hashes/sha2.js");
218
+
219
+ // src/utils/encoding.ts
220
+ var hexes = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
221
+ function bytesToHex(bytes) {
222
+ let hex = "";
223
+ for (const b of bytes) {
224
+ hex += hexes[b];
225
+ }
226
+ return hex;
227
+ }
228
+ function hexToBytes(hex) {
229
+ let h = without0x(hex);
230
+ if (h.length % 2)
231
+ h = `0${h}`;
232
+ const array = new Uint8Array(h.length / 2);
233
+ for (let i = 0;i < array.length; i++) {
234
+ const j = i * 2;
235
+ const byte = Number.parseInt(h.slice(j, j + 2), 16);
236
+ if (Number.isNaN(byte) || byte < 0)
237
+ throw new Error("Invalid byte sequence");
238
+ array[i] = byte;
239
+ }
240
+ return array;
241
+ }
242
+ function with0x(value) {
243
+ return /^0x/i.test(value) ? value : `0x${value}`;
244
+ }
245
+ function without0x(value) {
246
+ return /^0x/i.test(value) ? value.slice(2) : value;
247
+ }
248
+ function utf8ToBytes(str) {
249
+ return new TextEncoder().encode(str);
250
+ }
251
+ function bytesToUtf8(bytes) {
252
+ return new TextDecoder().decode(bytes);
253
+ }
254
+ function asciiToBytes(str) {
255
+ const bytes = new Uint8Array(str.length);
256
+ for (let i = 0;i < str.length; i++) {
257
+ bytes[i] = str.charCodeAt(i) & 255;
258
+ }
259
+ return bytes;
260
+ }
261
+ function bytesToAscii(bytes) {
262
+ return String.fromCharCode(...bytes);
263
+ }
264
+ function concatBytes(...arrays) {
265
+ if (arrays.length === 1)
266
+ return arrays[0];
267
+ const length = arrays.reduce((a, arr) => a + arr.length, 0);
268
+ const result = new Uint8Array(length);
269
+ let pad = 0;
270
+ for (const arr of arrays) {
271
+ result.set(arr, pad);
272
+ pad += arr.length;
273
+ }
274
+ return result;
275
+ }
276
+ function intToBigInt(value) {
277
+ if (typeof value === "bigint")
278
+ return value;
279
+ if (typeof value === "string")
280
+ return BigInt(value);
281
+ if (typeof value === "number") {
282
+ if (!Number.isInteger(value))
283
+ throw new RangeError("Values of type 'number' must be an integer.");
284
+ if (value > Number.MAX_SAFE_INTEGER)
285
+ throw new RangeError(`Values of type 'number' must be <= ${Number.MAX_SAFE_INTEGER}. Use BigInt instead.`);
286
+ return BigInt(value);
287
+ }
288
+ if (value instanceof Uint8Array)
289
+ return BigInt(`0x${bytesToHex(value)}`);
290
+ throw new TypeError("Must be a number, bigint, string, or Uint8Array.");
291
+ }
292
+ function intToBytes(value, byteLength) {
293
+ return bigIntToBytes(intToBigInt(value), byteLength);
294
+ }
295
+ function bigIntToBytes(value, length = 16) {
296
+ const hex = value.toString(16).padStart(length * 2, "0");
297
+ return hexToBytes(hex);
298
+ }
299
+ function intToHex(integer, byteLength = 8) {
300
+ const value = typeof integer === "bigint" ? integer : intToBigInt(integer);
301
+ return value.toString(16).padStart(byteLength * 2, "0");
302
+ }
303
+ function toTwos(value, width) {
304
+ const limit = BigInt(1) << width - BigInt(1);
305
+ if (value < -limit || value > limit - BigInt(1)) {
306
+ throw new Error(`Unable to represent integer in width: ${width}`);
307
+ }
308
+ if (value >= BigInt(0))
309
+ return value;
310
+ return value + (BigInt(1) << width);
311
+ }
312
+ function fromTwos(value, width) {
313
+ if (value & BigInt(1) << width - BigInt(1)) {
314
+ return value - (BigInt(1) << width);
315
+ }
316
+ return value;
317
+ }
318
+ function bytesToTwosBigInt(bytes) {
319
+ if (bytes.length === 0)
320
+ return 0n;
321
+ const hex = bytesToHex(bytes);
322
+ if (hex.length === 0)
323
+ return 0n;
324
+ return fromTwos(BigInt(`0x${hex}`), BigInt(bytes.byteLength * 8));
325
+ }
326
+ function writeUInt32BE(value) {
327
+ const buf = new Uint8Array(4);
328
+ buf[0] = value >>> 24 & 255;
329
+ buf[1] = value >>> 16 & 255;
330
+ buf[2] = value >>> 8 & 255;
331
+ buf[3] = value & 255;
332
+ return buf;
333
+ }
334
+ function readUInt32BE(bytes, offset = 0) {
335
+ return (bytes[offset] << 24 | bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3]) >>> 0;
336
+ }
337
+ function writeUInt16BE(value) {
338
+ const buf = new Uint8Array(2);
339
+ buf[0] = value >>> 8 & 255;
340
+ buf[1] = value & 255;
341
+ return buf;
342
+ }
343
+ function readUInt16BE(bytes, offset = 0) {
344
+ return (bytes[offset] << 8 | bytes[offset + 1]) >>> 0;
345
+ }
346
+ function writeUInt8(value) {
347
+ return new Uint8Array([value & 255]);
348
+ }
349
+
350
+ // src/utils/c32.ts
351
+ var C32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
352
+ var HEX = "0123456789abcdef";
353
+ function c32normalize(input) {
354
+ return input.toUpperCase().replace(/O/g, "0").replace(/L|I/g, "1");
355
+ }
356
+ function c32encode(inputHex) {
357
+ let hex = inputHex;
358
+ if (hex.length % 2 !== 0)
359
+ hex = `0${hex}`;
360
+ hex = hex.toLowerCase();
361
+ const res = [];
362
+ let carry = 0;
363
+ for (let i = hex.length - 1;i >= 0; i--) {
364
+ if (carry < 4) {
365
+ const currentCode = HEX.indexOf(hex[i]) >> carry;
366
+ const nextCode = i !== 0 ? HEX.indexOf(hex[i - 1]) : 0;
367
+ const nextBits = 1 + carry;
368
+ const nextLowBits = nextCode % (1 << nextBits) << 5 - nextBits;
369
+ res.unshift(C32[currentCode + nextLowBits]);
370
+ carry = nextBits;
371
+ } else {
372
+ carry = 0;
373
+ }
374
+ }
375
+ let leadingZeros = 0;
376
+ while (leadingZeros < res.length && res[leadingZeros] === "0")
377
+ leadingZeros++;
378
+ const stripped = res.slice(leadingZeros);
379
+ const bytes = hexToBytes(hex);
380
+ let zeroBytesCount = 0;
381
+ while (zeroBytesCount < bytes.length && bytes[zeroBytesCount] === 0)
382
+ zeroBytesCount++;
383
+ const prefix = Array(zeroBytesCount).fill(C32[0]);
384
+ return [...prefix, ...stripped].join("");
385
+ }
386
+ function c32decode(c32input) {
387
+ const input = c32normalize(c32input);
388
+ if (!input.match(`^[${C32}]*$`))
389
+ throw new Error("Not a c32-encoded string");
390
+ const zeroPrefix = input.match(`^${C32[0]}*`);
391
+ const numLeadingZeroBytes = zeroPrefix ? zeroPrefix[0]?.length : 0;
392
+ const res = [];
393
+ let carry = 0;
394
+ let carryBits = 0;
395
+ for (let i = input.length - 1;i >= 0; i--) {
396
+ if (carryBits === 4) {
397
+ res.unshift(HEX[carry]);
398
+ carryBits = 0;
399
+ carry = 0;
400
+ }
401
+ const currentValue = (C32.indexOf(input[i]) << carryBits) + carry;
402
+ res.unshift(HEX[currentValue % 16]);
403
+ carryBits += 1;
404
+ carry = currentValue >> 4;
405
+ if (carry > 1 << carryBits)
406
+ throw new Error("Panic error in c32 decoding");
407
+ }
408
+ res.unshift(HEX[carry]);
409
+ if (res.length % 2 === 1)
410
+ res.unshift("0");
411
+ let hexLeadingZeros = 0;
412
+ while (hexLeadingZeros < res.length && res[hexLeadingZeros] === "0")
413
+ hexLeadingZeros++;
414
+ let hexStr = res.slice(hexLeadingZeros - hexLeadingZeros % 2).join("");
415
+ for (let i = 0;i < numLeadingZeroBytes; i++)
416
+ hexStr = `00${hexStr}`;
417
+ return hexStr;
418
+ }
419
+ function c32checksum(dataHex) {
420
+ return bytesToHex(import_sha2.sha256(import_sha2.sha256(hexToBytes(dataHex))).slice(0, 4));
421
+ }
422
+ function c32checkEncode(version, data) {
423
+ if (version < 0 || version >= 32)
424
+ throw new Error("Invalid version (must be between 0 and 31)");
425
+ if (!data.match(/^[0-9a-fA-F]*$/))
426
+ throw new Error("Invalid data (not a hex string)");
427
+ let d = data.toLowerCase();
428
+ if (d.length % 2 !== 0)
429
+ d = `0${d}`;
430
+ let versionHex = version.toString(16);
431
+ if (versionHex.length === 1)
432
+ versionHex = `0${versionHex}`;
433
+ const checksumHex = c32checksum(`${versionHex}${d}`);
434
+ return `${C32[version]}${c32encode(`${d}${checksumHex}`)}`;
435
+ }
436
+ function c32checkDecode(c32data) {
437
+ const normalized = c32normalize(c32data);
438
+ const dataHex = c32decode(normalized.slice(1));
439
+ const version = C32.indexOf(normalized[0]);
440
+ const checksum = dataHex.slice(-8);
441
+ let versionHex = version.toString(16);
442
+ if (versionHex.length === 1)
443
+ versionHex = `0${versionHex}`;
444
+ if (c32checksum(`${versionHex}${dataHex.substring(0, dataHex.length - 8)}`) !== checksum) {
445
+ throw new Error("Invalid c32check string: checksum mismatch");
446
+ }
447
+ return [version, dataHex.substring(0, dataHex.length - 8)];
448
+ }
449
+ function c32address(version, hash160hex) {
450
+ if (!hash160hex.match(/^[0-9a-fA-F]{40}$/)) {
451
+ throw new Error("Invalid argument: not a hash160 hex string");
452
+ }
453
+ return `S${c32checkEncode(version, hash160hex)}`;
454
+ }
455
+ function c32addressDecode(c32addr) {
456
+ if (c32addr.length <= 5)
457
+ throw new Error("Invalid c32 address: invalid length");
458
+ if (c32addr[0] !== "S")
459
+ throw new Error('Invalid c32 address: must start with "S"');
460
+ return c32checkDecode(c32addr.slice(1));
461
+ }
462
+
463
+ // src/clarity/types.ts
464
+ var ClarityWireType = {
465
+ int: 0,
466
+ uint: 1,
467
+ buffer: 2,
468
+ true: 3,
469
+ false: 4,
470
+ address: 5,
471
+ contract: 6,
472
+ ok: 7,
473
+ err: 8,
474
+ none: 9,
475
+ some: 10,
476
+ list: 11,
477
+ tuple: 12,
478
+ ascii: 13,
479
+ utf8: 14
480
+ };
481
+ var wireTypeToClarity = Object.fromEntries(Object.entries(ClarityWireType).map(([k, v]) => [v, k]));
482
+ function clarityTypeFromByte(byte) {
483
+ const type = wireTypeToClarity[byte];
484
+ if (!type)
485
+ throw new Error(`Unknown clarity wire type: ${byte}`);
486
+ return type;
487
+ }
488
+
489
+ // src/clarity/serialize.ts
490
+ var CLARITY_INT_SIZE = 128n;
491
+ var CLARITY_INT_BYTE_SIZE = 16;
492
+ function typeIdByte(type) {
493
+ return ClarityWireType[type];
494
+ }
495
+ function withTypeId(type, bytes) {
496
+ return concatBytes(new Uint8Array([typeIdByte(type)]), bytes);
497
+ }
498
+ function serializeAddress(c32Address) {
499
+ const [version, hash160] = c32addressDecode(c32Address);
500
+ return concatBytes(new Uint8Array([version]), hexToBytes(hash160));
501
+ }
502
+ function serializeLPString(str, prefixBytes = 1) {
503
+ const content = utf8ToBytes(str);
504
+ const lengthPrefix = hexToBytes(intToHex(content.byteLength, prefixBytes));
505
+ return concatBytes(lengthPrefix, content);
506
+ }
507
+ function serializeCVBytes(value) {
508
+ switch (value.type) {
509
+ case "true":
510
+ case "false":
511
+ return new Uint8Array([typeIdByte(value.type)]);
512
+ case "int": {
513
+ const bytes = bigIntToBytes(toTwos(BigInt(value.value), CLARITY_INT_SIZE), CLARITY_INT_BYTE_SIZE);
514
+ return withTypeId(value.type, bytes);
515
+ }
516
+ case "uint": {
517
+ const bytes = bigIntToBytes(BigInt(value.value), CLARITY_INT_BYTE_SIZE);
518
+ return withTypeId(value.type, bytes);
519
+ }
520
+ case "buffer": {
521
+ const bufBytes = hexToBytes(value.value);
522
+ return withTypeId(value.type, concatBytes(writeUInt32BE(bufBytes.length), bufBytes));
523
+ }
524
+ case "none":
525
+ return new Uint8Array([typeIdByte(value.type)]);
526
+ case "some":
527
+ return withTypeId(value.type, serializeCVBytes(value.value));
528
+ case "ok":
529
+ case "err":
530
+ return withTypeId(value.type, serializeCVBytes(value.value));
531
+ case "address":
532
+ return withTypeId(value.type, serializeAddress(value.value));
533
+ case "contract": {
534
+ const [addr, name] = value.value.split(".");
535
+ if (!addr || !name)
536
+ throw new Error(`Invalid contract principal: ${value.value}`);
537
+ return withTypeId(value.type, concatBytes(serializeAddress(addr), serializeLPString(name)));
538
+ }
539
+ case "list": {
540
+ const parts = [writeUInt32BE(value.value.length)];
541
+ for (const item of value.value) {
542
+ parts.push(serializeCVBytes(item));
543
+ }
544
+ return withTypeId(value.type, concatBytes(...parts));
545
+ }
546
+ case "tuple": {
547
+ const keys = Object.keys(value.value).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
548
+ const parts = [writeUInt32BE(keys.length)];
549
+ for (const key of keys) {
550
+ parts.push(serializeLPString(key));
551
+ parts.push(serializeCVBytes(value.value[key]));
552
+ }
553
+ return withTypeId(value.type, concatBytes(...parts));
554
+ }
555
+ case "ascii": {
556
+ const strBytes = asciiToBytes(value.value);
557
+ return withTypeId(value.type, concatBytes(writeUInt32BE(strBytes.length), strBytes));
558
+ }
559
+ case "utf8": {
560
+ const strBytes = utf8ToBytes(value.value);
561
+ return withTypeId(value.type, concatBytes(writeUInt32BE(strBytes.length), strBytes));
562
+ }
563
+ default:
564
+ throw new Error("Cannot serialize unknown clarity type");
565
+ }
566
+ }
567
+ function serializeCV(value) {
568
+ return bytesToHex(serializeCVBytes(value));
569
+ }
570
+
571
+ // src/transactions/types.ts
572
+ var AuthType = {
573
+ Standard: 4,
574
+ Sponsored: 5
575
+ };
576
+ var PayloadType = {
577
+ TokenTransfer: 0,
578
+ SmartContract: 1,
579
+ ContractCall: 2,
580
+ PoisonMicroblock: 3,
581
+ Coinbase: 4,
582
+ CoinbaseToAltRecipient: 5,
583
+ VersionedSmartContract: 6,
584
+ TenureChange: 7,
585
+ NakamotoCoinbase: 8
586
+ };
587
+ var ClarityVersion = {
588
+ Clarity1: 1,
589
+ Clarity2: 2,
590
+ Clarity3: 3,
591
+ Clarity4: 4,
592
+ Clarity5: 5,
593
+ Clarity6: 6
594
+ };
595
+ var AnchorMode = {
596
+ OnChainOnly: 1,
597
+ OffChainOnly: 2,
598
+ Any: 3
599
+ };
600
+ var PostConditionModeWire = {
601
+ Allow: 1,
602
+ Deny: 2,
603
+ Originator: 3
604
+ };
605
+ var AddressHashMode = {
606
+ P2PKH: 0,
607
+ P2SH: 1,
608
+ P2WPKH: 2,
609
+ P2WSH: 3,
610
+ P2SH_NonSequential: 5,
611
+ P2WSH_P2SH_NonSequential: 7
612
+ };
613
+ var PubKeyEncoding = {
614
+ Compressed: 0,
615
+ Uncompressed: 1
616
+ };
617
+ var FungibleConditionCode = {
618
+ Equal: 1,
619
+ Greater: 2,
620
+ GreaterEqual: 3,
621
+ Less: 4,
622
+ LessEqual: 5
623
+ };
624
+ var NonFungibleConditionCode = {
625
+ Sends: 16,
626
+ DoesNotSend: 17,
627
+ MaybeSent: 18
628
+ };
629
+ var PoxConditionCode = {
630
+ WillNotPerform: 48,
631
+ MayPerform: 49,
632
+ WillPerform: 50
633
+ };
634
+ var PostConditionPrincipalId = {
635
+ Origin: 1,
636
+ Standard: 2,
637
+ Contract: 3
638
+ };
639
+ var AssetType = {
640
+ STX: 0,
641
+ Fungible: 1,
642
+ NonFungible: 2,
643
+ Staking: 3,
644
+ Pox: 4
645
+ };
646
+ var AuthFieldType = {
647
+ PublicKeyCompressed: 0,
648
+ PublicKeyUncompressed: 1,
649
+ SignatureCompressed: 2,
650
+ SignatureUncompressed: 3
651
+ };
652
+ var RECOVERABLE_ECDSA_SIG_LENGTH_BYTES = 65;
653
+ var MEMO_MAX_LENGTH_BYTES = 34;
654
+ var MAX_STRING_LENGTH_BYTES = 128;
655
+ var COINBASE_BYTES_LENGTH = 32;
656
+ var VRF_PROOF_BYTES_LENGTH = 80;
657
+ var MICROBLOCK_HEADER_BYTES_LENGTH = 132;
658
+ var TenureChangeCause = {
659
+ BlockFound: 0,
660
+ Extended: 1,
661
+ ExtendedRuntime: 2,
662
+ ExtendedReadCount: 3,
663
+ ExtendedReadLength: 4,
664
+ ExtendedWriteCount: 5,
665
+ ExtendedWriteLength: 6
666
+ };
667
+
668
+ // src/transactions/wire/serialize.ts
669
+ function serializeAddress2(c32Address) {
670
+ const [version, hash160] = c32addressDecode(c32Address);
671
+ return concatBytes(new Uint8Array([version]), hexToBytes(hash160));
672
+ }
673
+ function serializeLPString2(str, prefixBytes = 1) {
674
+ const content = utf8ToBytes(str);
675
+ const prefix = hexToBytes(intToHex(content.byteLength, prefixBytes));
676
+ return concatBytes(prefix, content);
677
+ }
678
+ function serializeLPStringLong(str) {
679
+ return serializeLPString2(str, 4);
680
+ }
681
+ function serializeMemo(memo) {
682
+ const content = asciiToBytes(memo);
683
+ const padded = new Uint8Array(MEMO_MAX_LENGTH_BYTES);
684
+ padded.set(content.slice(0, MEMO_MAX_LENGTH_BYTES));
685
+ return padded;
686
+ }
687
+ function serializeSpendingCondition(condition) {
688
+ const parts = [
689
+ writeUInt8(condition.hashMode),
690
+ hexToBytes(condition.signer),
691
+ intToBytes(condition.nonce, 8),
692
+ intToBytes(condition.fee, 8)
693
+ ];
694
+ if ("signature" in condition) {
695
+ const sc = condition;
696
+ parts.push(writeUInt8(sc.keyEncoding));
697
+ parts.push(hexToBytes(sc.signature));
698
+ } else {
699
+ const mc = condition;
700
+ parts.push(writeUInt32BE(mc.fields.length));
701
+ for (const field of mc.fields) {
702
+ parts.push(serializeAuthField(field));
703
+ }
704
+ parts.push(writeUInt16BE(mc.signaturesRequired));
705
+ }
706
+ return concatBytes(...parts);
707
+ }
708
+ function serializeAuthField(field) {
709
+ if (field.type === "publicKey") {
710
+ const typeId = field.pubKeyEncoding === 0 ? 0 : 1;
711
+ return concatBytes(writeUInt8(typeId), hexToBytes(field.data));
712
+ }
713
+ const typeId = field.pubKeyEncoding === 0 ? 2 : 3;
714
+ return concatBytes(writeUInt8(typeId), hexToBytes(field.data));
715
+ }
716
+ function serializeAuthorization(auth) {
717
+ const parts = [writeUInt8(auth.authType)];
718
+ parts.push(serializeSpendingCondition(auth.spendingCondition));
719
+ if (auth.authType === AuthType.Sponsored) {
720
+ parts.push(serializeSpendingCondition(auth.sponsorSpendingCondition));
721
+ }
722
+ return concatBytes(...parts);
723
+ }
724
+ function serializePrincipal(principal) {
725
+ switch (principal.type) {
726
+ case "origin":
727
+ return writeUInt8(PostConditionPrincipalId.Origin);
728
+ case "standard":
729
+ return concatBytes(writeUInt8(PostConditionPrincipalId.Standard), serializeAddress2(principal.address));
730
+ case "contract":
731
+ return concatBytes(writeUInt8(PostConditionPrincipalId.Contract), serializeAddress2(principal.address), serializeLPString2(principal.contractName));
732
+ }
733
+ }
734
+ function serializeAssetInfo(asset) {
735
+ return concatBytes(serializeAddress2(asset.address), serializeLPString2(asset.contractName), serializeLPString2(asset.assetName));
736
+ }
737
+ function serializePostConditionWire(pc) {
738
+ const parts = [];
739
+ switch (pc.type) {
740
+ case "stx":
741
+ parts.push(writeUInt8(AssetType.STX));
742
+ parts.push(serializePrincipal(pc.principal));
743
+ parts.push(writeUInt8(pc.conditionCode));
744
+ parts.push(intToBytes(pc.amount, 8));
745
+ break;
746
+ case "ft":
747
+ parts.push(writeUInt8(AssetType.Fungible));
748
+ parts.push(serializePrincipal(pc.principal));
749
+ parts.push(serializeAssetInfo(pc.asset));
750
+ parts.push(writeUInt8(pc.conditionCode));
751
+ parts.push(intToBytes(pc.amount, 8));
752
+ break;
753
+ case "nft":
754
+ parts.push(writeUInt8(AssetType.NonFungible));
755
+ parts.push(serializePrincipal(pc.principal));
756
+ parts.push(serializeAssetInfo(pc.asset));
757
+ parts.push(serializeCVBytes(pc.assetId));
758
+ parts.push(writeUInt8(pc.conditionCode));
759
+ break;
760
+ case "staking":
761
+ parts.push(writeUInt8(AssetType.Staking));
762
+ parts.push(serializePrincipal(pc.principal));
763
+ parts.push(writeUInt8(pc.conditionCode));
764
+ parts.push(intToBytes(pc.amount, 8));
765
+ break;
766
+ case "pox":
767
+ parts.push(writeUInt8(AssetType.Pox));
768
+ parts.push(serializePrincipal(pc.principal));
769
+ parts.push(writeUInt8(pc.conditionCode));
770
+ break;
771
+ }
772
+ return concatBytes(...parts);
773
+ }
774
+ function serializePostConditions(pcs) {
775
+ const parts = [writeUInt32BE(pcs.length)];
776
+ for (const pc of pcs)
777
+ parts.push(serializePostConditionWire(pc));
778
+ return concatBytes(...parts);
779
+ }
780
+ function serializePayload(payload) {
781
+ const parts = [writeUInt8(payload.payloadType)];
782
+ switch (payload.payloadType) {
783
+ case PayloadType.TokenTransfer:
784
+ parts.push(serializeCVBytes(payload.recipient));
785
+ parts.push(intToBytes(payload.amount, 8));
786
+ parts.push(serializeMemo(payload.memo));
787
+ break;
788
+ case PayloadType.ContractCall:
789
+ parts.push(serializeAddress2(payload.contractAddress));
790
+ parts.push(serializeLPString2(payload.contractName));
791
+ parts.push(serializeLPString2(payload.functionName));
792
+ parts.push(writeUInt32BE(payload.functionArgs.length));
793
+ for (const arg of payload.functionArgs) {
794
+ parts.push(serializeCVBytes(arg));
795
+ }
796
+ break;
797
+ case PayloadType.SmartContract:
798
+ parts.push(serializeLPString2(payload.contractName));
799
+ parts.push(serializeLPStringLong(payload.codeBody));
800
+ break;
801
+ case PayloadType.VersionedSmartContract:
802
+ parts.push(writeUInt8(payload.clarityVersion ?? 2));
803
+ parts.push(serializeLPString2(payload.contractName));
804
+ parts.push(serializeLPStringLong(payload.codeBody));
805
+ break;
806
+ case PayloadType.Coinbase:
807
+ parts.push(hexToBytes(payload.coinbaseBuffer));
808
+ break;
809
+ case PayloadType.CoinbaseToAltRecipient: {
810
+ const cbAlt = payload;
811
+ parts.push(hexToBytes(cbAlt.coinbaseBuffer));
812
+ parts.push(serializeCVBytes(cbAlt.recipient));
813
+ break;
814
+ }
815
+ case PayloadType.PoisonMicroblock: {
816
+ const pm = payload;
817
+ parts.push(hexToBytes(pm.header1));
818
+ parts.push(hexToBytes(pm.header2));
819
+ break;
820
+ }
821
+ case PayloadType.TenureChange: {
822
+ const tc = payload;
823
+ parts.push(hexToBytes(tc.tenureConsensusHash));
824
+ parts.push(hexToBytes(tc.prevTenureConsensusHash));
825
+ parts.push(hexToBytes(tc.burnViewConsensusHash));
826
+ parts.push(hexToBytes(tc.previousTenureEnd));
827
+ parts.push(writeUInt32BE(tc.previousTenureBlocks));
828
+ parts.push(writeUInt8(tc.cause));
829
+ parts.push(hexToBytes(tc.pubkeyHash));
830
+ break;
831
+ }
832
+ case PayloadType.NakamotoCoinbase: {
833
+ const nc = payload;
834
+ parts.push(hexToBytes(nc.coinbaseBuffer));
835
+ if (nc.recipient) {
836
+ parts.push(serializeCVBytes({ type: "some", value: nc.recipient }));
837
+ } else {
838
+ parts.push(serializeCVBytes({ type: "none" }));
839
+ }
840
+ parts.push(hexToBytes(nc.vrfProof));
841
+ break;
842
+ }
843
+ }
844
+ return concatBytes(...parts);
845
+ }
846
+ var _txCache = new WeakMap;
847
+ function clearTxCache(tx) {
848
+ _txCache.delete(tx);
849
+ }
850
+ function serializeTransaction(tx) {
851
+ const cached = _txCache.get(tx);
852
+ if (cached)
853
+ return cached;
854
+ const bytes = concatBytes(writeUInt8(tx.version), writeUInt32BE(tx.chainId), serializeAuthorization(tx.auth), writeUInt8(tx.anchorMode), writeUInt8(tx.postConditionMode), serializePostConditions(tx.postConditions), serializePayload(tx.payload));
855
+ _txCache.set(tx, bytes);
856
+ return bytes;
857
+ }
858
+ function serializeTransactionHex(tx) {
859
+ return bytesToHex(serializeTransaction(tx));
860
+ }
861
+
862
+ // src/actions/public/estimateFee.ts
863
+ function isValidEstimation(e) {
864
+ 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");
865
+ }
866
+ async function estimateFee(client, params) {
867
+ const payloadHex = bytesToHex(serializePayload(params.transaction.payload));
868
+ const txHex = bytesToHex(serializeTransaction(params.transaction));
869
+ const data = await client.request("/v2/fees/transaction", {
870
+ method: "POST",
871
+ body: {
872
+ estimated_len: Math.ceil(txHex.length / 2),
873
+ transaction_payload: `0x${payloadHex}`
874
+ }
875
+ });
876
+ const raw = data?.estimations ?? [];
877
+ return raw.map((e) => {
878
+ if (!isValidEstimation(e)) {
879
+ throw new MalformedResponseError("estimateFee: node response contains invalid fee estimation entry");
880
+ }
881
+ return {
882
+ feeRate: Number(e.fee_rate),
883
+ fee: Number(e.fee)
884
+ };
885
+ });
886
+ }
887
+
888
+ // src/actions/public/getAccountHistory.ts
889
+ async function getAccountHistory(client, params) {
890
+ const limit = Math.min(params.limit ?? 20, 50);
891
+ return client.request(`/extended/v2/addresses/${encodeURIComponent(params.address)}/transactions?limit=${limit}`, { method: "GET" });
892
+ }
893
+
894
+ // src/actions/public/getAccountInfo.ts
895
+ async function getAccountInfo(client, params) {
896
+ const data = await client.request(`/v2/accounts/${encodeURIComponent(params.address)}?proof=1`, { method: "GET" });
897
+ const balance = data?.balance;
898
+ const nonce = data?.nonce;
899
+ if (typeof balance !== "string" && typeof balance !== "number" || typeof nonce !== "string" && typeof nonce !== "number") {
900
+ throw new MalformedResponseError(`getAccountInfo: /v2/accounts/${params.address} response is missing "balance" or "nonce"`);
901
+ }
902
+ return {
903
+ balance: BigInt(balance),
904
+ nonce: BigInt(nonce),
905
+ balanceProof: data.balance_proof ?? "",
906
+ nonceProof: data.nonce_proof ?? ""
907
+ };
908
+ }
909
+
910
+ // src/actions/public/getBalance.ts
911
+ async function getBalance(client, params) {
912
+ const data = await client.request(`/v2/accounts/${encodeURIComponent(params.address)}`, {
913
+ method: "GET"
914
+ });
915
+ const balance = data?.balance;
916
+ if (typeof balance !== "string" && typeof balance !== "number") {
917
+ throw new MalformedResponseError(`getBalance: /v2/accounts/${params.address} response is missing "balance"`);
918
+ }
919
+ return BigInt(balance);
920
+ }
921
+
922
+ // src/actions/public/getBlock.ts
923
+ async function getBlock(client, params) {
924
+ if (params?.hash) {
925
+ return client.request(`/extended/v2/blocks/${encodeURIComponent(params.hash)}`, { method: "GET" });
926
+ }
927
+ if (params?.height !== undefined) {
928
+ return client.request(`/extended/v2/blocks/${encodeURIComponent(String(params.height))}`, { method: "GET" });
929
+ }
930
+ const data = await client.request("/extended/v2/blocks?limit=1", {
931
+ method: "GET"
932
+ });
933
+ const results = data?.results;
934
+ return Array.isArray(results) ? results[0] ?? null : data;
935
+ }
936
+
937
+ // src/actions/public/getBlockHeight.ts
938
+ async function getBlockHeight(client) {
939
+ const data = await client.request("/v2/info", { method: "GET" });
940
+ if (typeof data?.stacks_tip_height !== "number") {
941
+ throw new MalformedResponseError('getBlockHeight: /v2/info response is missing "stacks_tip_height"');
942
+ }
943
+ return data.stacks_tip_height;
944
+ }
945
+
946
+ // src/utils/constants.ts
947
+ var MAX_U128 = (1n << 128n) - 1n;
948
+ var MAX_I128 = (1n << 127n) - 1n;
949
+ var MIN_I128 = -(1n << 127n);
950
+ var AddressVersion = {
951
+ MainnetSingleSig: 22,
952
+ MainnetMultiSig: 20,
953
+ TestnetSingleSig: 26,
954
+ TestnetMultiSig: 21
955
+ };
956
+ var ZERO_ADDRESS = "SP000000000000000000002Q6VF78";
957
+ var TESTNET_ZERO_ADDRESS = "ST000000000000000000002AMW42H";
958
+ var MICROSTX_PER_STX = 1000000n;
959
+
960
+ // src/utils/hash.ts
961
+ var import_legacy = require("@noble/hashes/legacy.js");
962
+ var import_sha22 = require("@noble/hashes/sha2.js");
963
+ var import_sha23 = require("@noble/hashes/sha2.js");
964
+ function hash160(input) {
965
+ return import_legacy.ripemd160(import_sha22.sha256(input));
966
+ }
967
+ function txidFromBytes(data) {
968
+ return bytesToHex(import_sha23.sha512_256(data));
969
+ }
970
+ function hashP2PKH(input) {
971
+ return bytesToHex(hash160(input));
972
+ }
973
+
974
+ // src/utils/address.ts
975
+ function publicKeyToAddress(publicKey, network = "mainnet") {
976
+ const bytes = typeof publicKey === "string" ? hexToBytes(without0x(publicKey)) : publicKey;
977
+ const version = network === "mainnet" ? AddressVersion.MainnetSingleSig : AddressVersion.TestnetSingleSig;
978
+ return c32address(version, bytesToHex(hash160(bytes)));
979
+ }
980
+ var CONTRACT_NAME_REGEX = /^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/;
981
+ function validateStacksAddress(address) {
982
+ try {
983
+ c32addressDecode(address);
984
+ return true;
985
+ } catch {
986
+ return false;
987
+ }
988
+ }
989
+ var isValidAddress = validateStacksAddress;
990
+ function parsePrincipal(value) {
991
+ const parts = value.split(".");
992
+ if (parts.length > 2)
993
+ return null;
994
+ const [address, contractName] = parts;
995
+ if (!validateStacksAddress(address))
996
+ return null;
997
+ if (contractName === undefined)
998
+ return { address };
999
+ if (!CONTRACT_NAME_REGEX.test(contractName))
1000
+ return null;
1001
+ return { address, contractName };
1002
+ }
1003
+ function parseContractId(contractId) {
1004
+ const parsed = parsePrincipal(contractId);
1005
+ if (!parsed?.contractName)
1006
+ throw new Error(`Invalid contract identifier: ${contractId}`);
1007
+ return [parsed.address, parsed.contractName];
1008
+ }
1009
+ function isClarityName(name) {
1010
+ const regex = /^[a-zA-Z]([a-zA-Z0-9]|[-_!?+<>=/*])*$|^[-+=/*]$|^[<>]=?$/;
1011
+ return regex.test(name) && name.length < 128;
1012
+ }
1013
+ function isAddressEqual(a, b) {
1014
+ const [versionA, hashA] = c32addressDecode(a);
1015
+ const [versionB, hashB] = c32addressDecode(b);
1016
+ return versionA === versionB && hashA.toLowerCase() === hashB.toLowerCase();
1017
+ }
1018
+ function addressToVersion(address) {
1019
+ return c32addressDecode(address)[0];
1020
+ }
1021
+ function getContractAddress(deployer, contractName) {
1022
+ if (!validateStacksAddress(deployer)) {
1023
+ throw new Error(`Invalid deployer address: ${deployer}`);
1024
+ }
1025
+ if (!isClarityName(contractName)) {
1026
+ throw new Error(`Invalid contract name: ${contractName}`);
1027
+ }
1028
+ return `${deployer}.${contractName}`;
1029
+ }
1030
+
1031
+ // src/actions/public/getContractAbi.ts
1032
+ async function getContractAbi(client, params) {
1033
+ const [address, name] = parseContractId(params.contract);
1034
+ return client.request(`/v2/contracts/interface/${address}/${name}`, {
1035
+ method: "GET"
1036
+ });
1037
+ }
1038
+
1039
+ // src/errors/http.ts
1040
+ class HttpRequestError extends BaseError {
1041
+ name = "HttpRequestError";
1042
+ status;
1043
+ url;
1044
+ method;
1045
+ constructor(status, options) {
1046
+ const where = options?.url !== undefined ? ` (${options.method ?? "GET"} ${options.url})` : "";
1047
+ super(`HTTP request failed with status ${status}${where}`, options);
1048
+ this.status = status;
1049
+ this.url = options?.url;
1050
+ this.method = options?.method;
1051
+ }
1052
+ }
1053
+
1054
+ // src/actions/public/getContractSource.ts
1055
+ async function getContractSource(client, params) {
1056
+ const [address, name] = parseContractId(params.contract);
1057
+ try {
1058
+ const data = await client.request(`/v2/contracts/source/${address}/${name}`, { method: "GET" });
1059
+ return data?.source ? data : null;
1060
+ } catch (error) {
1061
+ if (error instanceof HttpRequestError && error.status === 404)
1062
+ return null;
1063
+ throw error;
1064
+ }
1065
+ }
1066
+
1067
+ // src/errors/transaction.ts
1068
+ class TransactionError extends BaseError {
1069
+ name = "TransactionError";
1070
+ }
1071
+
1072
+ class BroadcastError extends BaseError {
1073
+ name = "BroadcastError";
1074
+ txid;
1075
+ reason;
1076
+ reasonData;
1077
+ constructor(message, options) {
1078
+ super(message, options);
1079
+ this.txid = options?.txid;
1080
+ this.reason = options?.reason;
1081
+ this.reasonData = options?.reasonData;
1082
+ }
1083
+ }
1084
+
1085
+ class TransactionAbortedError extends BaseError {
1086
+ name = "TransactionAbortedError";
1087
+ receipt;
1088
+ constructor(message, options) {
1089
+ super(message, options);
1090
+ this.receipt = options.receipt;
1091
+ }
1092
+ }
1093
+
1094
+ class TransactionDroppedError extends BaseError {
1095
+ name = "TransactionDroppedError";
1096
+ txid;
1097
+ constructor(message, options) {
1098
+ super(message, options);
1099
+ this.txid = options.txid;
1100
+ }
1101
+ }
1102
+
1103
+ class WaitForTransactionTimeoutError extends BaseError {
1104
+ name = "WaitForTransactionTimeoutError";
1105
+ txid;
1106
+ constructor(message, options) {
1107
+ super(message, options);
1108
+ this.txid = options.txid;
1109
+ }
1110
+ }
1111
+
1112
+ class SerializationError extends BaseError {
1113
+ name = "SerializationError";
1114
+ }
1115
+
1116
+ class SigningError extends BaseError {
1117
+ name = "SigningError";
1118
+ }
1119
+
1120
+ // src/utils/bytes-reader.ts
1121
+ class BytesReader {
1122
+ data;
1123
+ offset = 0;
1124
+ constructor(data) {
1125
+ this.data = data;
1126
+ }
1127
+ remaining() {
1128
+ return this.data.length - this.offset;
1129
+ }
1130
+ ensure(length) {
1131
+ if (this.offset + length > this.data.length) {
1132
+ throw new SerializationError(`Buffer underflow: need ${length} bytes at offset ${this.offset}, have ${this.data.length}`);
1133
+ }
1134
+ }
1135
+ readUInt8() {
1136
+ this.ensure(1);
1137
+ return this.data[this.offset++];
1138
+ }
1139
+ readUInt16BE() {
1140
+ this.ensure(2);
1141
+ const val = (this.data[this.offset] << 8 | this.data[this.offset + 1]) >>> 0;
1142
+ this.offset += 2;
1143
+ return val;
1144
+ }
1145
+ readUInt32BE() {
1146
+ this.ensure(4);
1147
+ 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;
1148
+ this.offset += 4;
1149
+ return val;
1150
+ }
1151
+ readBytes(length) {
1152
+ this.ensure(length);
1153
+ const slice = this.data.slice(this.offset, this.offset + length);
1154
+ this.offset += length;
1155
+ return slice;
1156
+ }
1157
+ readBigUInt64BE() {
1158
+ const hex = bytesToHex(this.readBytes(8));
1159
+ return hex.length > 0 ? BigInt(`0x${hex}`) : 0n;
1160
+ }
1161
+ }
1162
+
1163
+ // src/clarity/values.ts
1164
+ var MAX_U1282 = BigInt("0xffffffffffffffffffffffffffffffff");
1165
+ var MIN_I1282 = BigInt("-170141183460469231731687303715884105728");
1166
+ var MAX_I1282 = BigInt("0x7fffffffffffffffffffffffffffffff");
1167
+ function intCV(value) {
1168
+ let v = value;
1169
+ if (typeof v === "string" && v.toLowerCase().startsWith("0x")) {
1170
+ v = bytesToTwosBigInt(hexToBytes(v));
1171
+ }
1172
+ if (v instanceof Uint8Array)
1173
+ v = bytesToTwosBigInt(v);
1174
+ const n = intToBigInt(v);
1175
+ if (n > MAX_I1282)
1176
+ throw new RangeError(`Int exceeds max i128: ${MAX_I1282}`);
1177
+ if (n < MIN_I1282)
1178
+ throw new RangeError(`Int below min i128: ${MIN_I1282}`);
1179
+ return { type: "int", value: n };
1180
+ }
1181
+ function uintCV(value) {
1182
+ const n = intToBigInt(value);
1183
+ if (n < 0n)
1184
+ throw new RangeError("Cannot construct unsigned int from negative value");
1185
+ if (n > MAX_U1282)
1186
+ throw new RangeError(`UInt exceeds max u128: ${MAX_U1282}`);
1187
+ return { type: "uint", value: n };
1188
+ }
1189
+ var trueCV = () => ({ type: "true" });
1190
+ var falseCV = () => ({ type: "false" });
1191
+ var boolCV = (v) => v ? trueCV() : falseCV();
1192
+ function bufferCV(buffer) {
1193
+ if (buffer.byteLength > 1048576) {
1194
+ throw new Error("Buffer exceeds max size of 1MB");
1195
+ }
1196
+ return { type: "buffer", value: bytesToHex(buffer) };
1197
+ }
1198
+ function standardPrincipalCV(address) {
1199
+ const [version, hash160] = c32addressDecode(address);
1200
+ const normalized = c32address(version, hash160);
1201
+ return { type: "address", value: normalized };
1202
+ }
1203
+ function contractPrincipalCV(address, contractName) {
1204
+ const [version, hash160] = c32addressDecode(address);
1205
+ const normalized = c32address(version, hash160);
1206
+ if (utf8ToBytes(contractName).byteLength >= 128) {
1207
+ throw new Error("Contract name must be less than 128 bytes");
1208
+ }
1209
+ return { type: "contract", value: `${normalized}.${contractName}` };
1210
+ }
1211
+ function noneCV() {
1212
+ return { type: "none" };
1213
+ }
1214
+ function someCV(value) {
1215
+ return { type: "some", value };
1216
+ }
1217
+ function responseOkCV(value) {
1218
+ return { type: "ok", value };
1219
+ }
1220
+ function responseErrorCV(value) {
1221
+ return { type: "err", value };
1222
+ }
1223
+ function listCV(values) {
1224
+ return { type: "list", value: values };
1225
+ }
1226
+ function tupleCV(data) {
1227
+ for (const key in data) {
1228
+ if (!isClarityName(key)) {
1229
+ throw new Error(`"${key}" is not a valid Clarity name`);
1230
+ }
1231
+ }
1232
+ return { type: "tuple", value: data };
1233
+ }
1234
+ function stringAsciiCV(value) {
1235
+ return { type: "ascii", value };
1236
+ }
1237
+ function stringUtf8CV(value) {
1238
+ return { type: "utf8", value };
1239
+ }
1240
+ var Cl = {
1241
+ int: intCV,
1242
+ uint: uintCV,
1243
+ bool: boolCV,
1244
+ principal(address) {
1245
+ const parsed = parsePrincipal(address);
1246
+ if (!parsed)
1247
+ throw new Error(`Invalid principal: ${address}`);
1248
+ return parsed.contractName ? contractPrincipalCV(parsed.address, parsed.contractName) : standardPrincipalCV(parsed.address);
1249
+ },
1250
+ address(address) {
1251
+ return Cl.principal(address);
1252
+ },
1253
+ contractPrincipal: contractPrincipalCV,
1254
+ standardPrincipal: standardPrincipalCV,
1255
+ buffer: bufferCV,
1256
+ bufferFromHex: (hex) => bufferCV(hexToBytes(hex)),
1257
+ bufferFromAscii: (ascii) => bufferCV(asciiToBytes(ascii)),
1258
+ bufferFromUtf8: (utf8) => bufferCV(utf8ToBytes(utf8)),
1259
+ none: noneCV,
1260
+ some: someCV,
1261
+ ok: responseOkCV,
1262
+ error: responseErrorCV,
1263
+ list: listCV,
1264
+ tuple: tupleCV,
1265
+ stringAscii: stringAsciiCV,
1266
+ stringUtf8: stringUtf8CV,
1267
+ serialize(value) {
1268
+ return bytesToHex(serializeCVBytes(value));
1269
+ },
1270
+ deserialize: deserializeCVBytes
1271
+ };
1272
+
1273
+ // src/clarity/deserialize.ts
1274
+ function readAddress(reader) {
1275
+ const version = reader.readUInt8();
1276
+ const hash160 = bytesToHex(reader.readBytes(20));
1277
+ return c32address(version, hash160);
1278
+ }
1279
+ function readLPString(reader, prefixBytes = 1) {
1280
+ let length = 0;
1281
+ for (let i = 0;i < prefixBytes; i++) {
1282
+ length = length << 8 | reader.readUInt8();
1283
+ }
1284
+ return bytesToUtf8(reader.readBytes(length));
1285
+ }
1286
+ var MAX_CV_DEPTH = 64;
1287
+ var MIN_LIST_ITEM_BYTES = 1;
1288
+ var MIN_TUPLE_ENTRY_BYTES = 2;
1289
+ function checkCount(reader, count, minBytes) {
1290
+ if (count * minBytes > reader.remaining()) {
1291
+ throw new SerializationError(`Clarity value declares ${count} elements but only ${reader.remaining()} bytes remain`);
1292
+ }
1293
+ }
1294
+ function readCV(reader, depth = 0) {
1295
+ if (depth > MAX_CV_DEPTH) {
1296
+ throw new SerializationError(`Clarity value nests deeper than ${MAX_CV_DEPTH} levels`);
1297
+ }
1298
+ const typeByte = reader.readUInt8();
1299
+ const type = clarityTypeFromByte(typeByte);
1300
+ switch (type) {
1301
+ case "int":
1302
+ return intCV(bytesToTwosBigInt(reader.readBytes(16)));
1303
+ case "uint":
1304
+ return uintCV(reader.readBytes(16));
1305
+ case "true":
1306
+ return trueCV();
1307
+ case "false":
1308
+ return falseCV();
1309
+ case "buffer": {
1310
+ const len = reader.readUInt32BE();
1311
+ return bufferCV(reader.readBytes(len));
1312
+ }
1313
+ case "none":
1314
+ return noneCV();
1315
+ case "some":
1316
+ return someCV(readCV(reader, depth + 1));
1317
+ case "ok":
1318
+ return responseOkCV(readCV(reader, depth + 1));
1319
+ case "err":
1320
+ return responseErrorCV(readCV(reader, depth + 1));
1321
+ case "address":
1322
+ return standardPrincipalCV(readAddress(reader));
1323
+ case "contract": {
1324
+ const addr = readAddress(reader);
1325
+ const name = readLPString(reader);
1326
+ return contractPrincipalCV(addr, name);
1327
+ }
1328
+ case "list": {
1329
+ const len = reader.readUInt32BE();
1330
+ checkCount(reader, len, MIN_LIST_ITEM_BYTES);
1331
+ const items = [];
1332
+ for (let i = 0;i < len; i++) {
1333
+ items.push(readCV(reader, depth + 1));
1334
+ }
1335
+ return listCV(items);
1336
+ }
1337
+ case "tuple": {
1338
+ const len = reader.readUInt32BE();
1339
+ checkCount(reader, len, MIN_TUPLE_ENTRY_BYTES);
1340
+ const data = {};
1341
+ for (let i = 0;i < len; i++) {
1342
+ const key = readLPString(reader);
1343
+ data[key] = readCV(reader, depth + 1);
1344
+ }
1345
+ return tupleCV(data);
1346
+ }
1347
+ case "ascii": {
1348
+ const len = reader.readUInt32BE();
1349
+ return stringAsciiCV(bytesToAscii(reader.readBytes(len)));
1350
+ }
1351
+ case "utf8": {
1352
+ const len = reader.readUInt32BE();
1353
+ return stringUtf8CV(bytesToUtf8(reader.readBytes(len)));
1354
+ }
1355
+ default:
1356
+ throw new SerializationError(`Cannot deserialize unknown clarity type: ${type}`);
1357
+ }
1358
+ }
1359
+ function deserializeCVBytes(input) {
1360
+ const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
1361
+ return readCV(new BytesReader(bytes));
1362
+ }
1363
+ function deserializeCV(input) {
1364
+ return deserializeCVBytes(input);
1365
+ }
1366
+
1367
+ // src/actions/public/getDataVar.ts
1368
+ async function getDataVar(client, params) {
1369
+ const [address, name] = parseContractId(params.contract);
1370
+ const path = `/v2/data_var/${address}/${name}/${params.varName}?proof=0`;
1371
+ const data = await client.request(path, { method: "GET" });
1372
+ if (typeof data?.data !== "string") {
1373
+ throw new MalformedResponseError(`getDataVar: /v2/data_var/${address}/${name}/${params.varName} response is missing "data"`);
1374
+ }
1375
+ return deserializeCVBytes(data.data);
1376
+ }
1377
+
1378
+ // src/actions/public/getMapEntry.ts
1379
+ async function getMapEntry(client, params) {
1380
+ const [address, name] = parseContractId(params.contract);
1381
+ const serializedKey = with0x(bytesToHex(serializeCVBytes(params.key)));
1382
+ const data = await client.request(`/v2/map_entry/${address}/${name}/${params.mapName}`, {
1383
+ method: "POST",
1384
+ body: serializedKey
1385
+ });
1386
+ if (typeof data?.data !== "string") {
1387
+ throw new MalformedResponseError(`getMapEntry: /v2/map_entry/${address}/${name}/${params.mapName} response is missing "data"`);
1388
+ }
1389
+ return deserializeCVBytes(data.data);
1390
+ }
1391
+
1392
+ // src/actions/public/getMempoolStats.ts
1393
+ async function getMempoolStats(client) {
1394
+ return client.request("/extended/v1/tx/mempool/stats", { method: "GET" });
1395
+ }
1396
+
1397
+ // src/actions/public/getNftHoldings.ts
1398
+ async function getNftHoldings(client, params) {
1399
+ const limit = Math.min(params.limit ?? 20, 50);
1400
+ return client.request(`/extended/v1/tokens/nft/holdings?principal=${encodeURIComponent(params.address)}&limit=${limit}`, { method: "GET" });
1401
+ }
1402
+
1403
+ // src/actions/public/getNonce.ts
1404
+ async function getNonce(client, params) {
1405
+ const data = await client.request(`/v2/accounts/${encodeURIComponent(params.address)}`, { method: "GET" });
1406
+ const nonce = data?.nonce;
1407
+ if (typeof nonce !== "number" && typeof nonce !== "string") {
1408
+ throw new MalformedResponseError(`getNonce: /v2/accounts/${params.address} response is missing "nonce"`);
1409
+ }
1410
+ return BigInt(nonce);
1411
+ }
1412
+
1413
+ // src/actions/public/getRawBlock.ts
1414
+ async function getRawBlock(client, params) {
1415
+ try {
1416
+ const data = await client.request(`/v2/blocks/${params.height}`, {
1417
+ method: "GET"
1418
+ });
1419
+ return data?.hash ? data : null;
1420
+ } catch (error) {
1421
+ if (error instanceof HttpRequestError && error.status === 404)
1422
+ return null;
1423
+ throw error;
1424
+ }
1425
+ }
1426
+
1427
+ // src/errors/transport.ts
1428
+ class TimeoutError extends BaseError {
1429
+ name = "TimeoutError";
1430
+ method;
1431
+ url;
1432
+ timeout;
1433
+ attempt;
1434
+ constructor(params) {
1435
+ super(`${params.method} ${params.url} did not complete within ${params.timeout}ms (attempt ${params.attempt + 1})`);
1436
+ this.method = params.method;
1437
+ this.url = params.url;
1438
+ this.timeout = params.timeout;
1439
+ this.attempt = params.attempt;
1440
+ }
1441
+ }
1442
+
1443
+ // src/transports/createTransport.ts
1444
+ function createTransport(type, config) {
1445
+ const { request, apiKey: _apiKey, ...exposed } = config;
1446
+ return {
1447
+ type,
1448
+ request,
1449
+ config: exposed
1450
+ };
1451
+ }
1452
+ var MAX_ERROR_DETAILS_BYTES = 4096;
1453
+ function capDetails(body) {
1454
+ if (body === undefined)
1455
+ return;
1456
+ const bytes = new TextEncoder().encode(body);
1457
+ if (bytes.length <= MAX_ERROR_DETAILS_BYTES)
1458
+ return body;
1459
+ const head = new TextDecoder().decode(bytes.subarray(0, MAX_ERROR_DETAILS_BYTES));
1460
+ return `${head}... [truncated ${bytes.length - MAX_ERROR_DETAILS_BYTES} bytes]`;
1461
+ }
1462
+ function isRetryableStatus(status) {
1463
+ return status === 429 || status >= 500;
1464
+ }
1465
+ var MAX_RETRY_AFTER_MS = 60000;
1466
+ function retryAfterMs(response) {
1467
+ const value = response.headers.get("Retry-After");
1468
+ if (!value)
1469
+ return;
1470
+ const seconds = Number(value);
1471
+ const ms = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - Date.now();
1472
+ if (!Number.isFinite(ms) || ms < 0 || ms > MAX_RETRY_AFTER_MS)
1473
+ return;
1474
+ return ms;
1475
+ }
1476
+ function abortReason(signal) {
1477
+ const reason = signal.reason;
1478
+ if (reason instanceof Error)
1479
+ return reason;
1480
+ return new DOMException(typeof reason === "string" ? reason : "The operation was aborted", "AbortError");
1481
+ }
1482
+ function sleep(ms, signal) {
1483
+ return new Promise((resolve, reject) => {
1484
+ if (signal?.aborted)
1485
+ return reject(abortReason(signal));
1486
+ const onAbort = () => {
1487
+ clearTimeout(id);
1488
+ reject(abortReason(signal));
1489
+ };
1490
+ const id = setTimeout(() => {
1491
+ signal?.removeEventListener("abort", onAbort);
1492
+ resolve();
1493
+ }, ms);
1494
+ signal?.addEventListener("abort", onAbort, { once: true });
1495
+ });
1496
+ }
1497
+ async function fetchWithRetry(url, options, retryCount, retryDelay, timeout, extra = {}) {
1498
+ const { signal } = extra;
1499
+ const read = extra.read ?? (async (response) => response);
1500
+ const method = options.method ?? "GET";
1501
+ let lastError;
1502
+ for (let attempt = 0;attempt <= retryCount; attempt++) {
1503
+ if (signal?.aborted)
1504
+ throw abortReason(signal);
1505
+ const controller = new AbortController;
1506
+ let timedOut = false;
1507
+ const timeoutId = setTimeout(() => {
1508
+ timedOut = true;
1509
+ controller.abort(new TimeoutError({ method, url, timeout, attempt }));
1510
+ }, timeout);
1511
+ const onCallerAbort = () => controller.abort(abortReason(signal));
1512
+ signal?.addEventListener("abort", onCallerAbort, { once: true });
1513
+ const aborted = new Promise((_, reject) => {
1514
+ if (controller.signal.aborted)
1515
+ return reject(controller.signal.reason);
1516
+ controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
1517
+ });
1518
+ let response;
1519
+ try {
1520
+ try {
1521
+ response = await Promise.race([
1522
+ fetch(url, { ...options, signal: controller.signal }),
1523
+ aborted
1524
+ ]);
1525
+ } catch (error) {
1526
+ if (signal?.aborted)
1527
+ throw abortReason(signal);
1528
+ lastError = timedOut ? new TimeoutError({ method, url, timeout, attempt }) : error instanceof Error ? error : new Error(String(error));
1529
+ if (attempt < retryCount) {
1530
+ clearTimeout(timeoutId);
1531
+ await sleep(retryDelay * (attempt + 1), signal);
1532
+ continue;
1533
+ }
1534
+ throw lastError;
1535
+ }
1536
+ if (response.ok) {
1537
+ try {
1538
+ return await Promise.race([read(response), aborted]);
1539
+ } catch (error) {
1540
+ response.body?.cancel().catch(() => {});
1541
+ if (signal?.aborted)
1542
+ throw abortReason(signal);
1543
+ if (!timedOut)
1544
+ throw error;
1545
+ lastError = new TimeoutError({ method, url, timeout, attempt });
1546
+ if (attempt < retryCount) {
1547
+ clearTimeout(timeoutId);
1548
+ await sleep(retryDelay * (attempt + 1), signal);
1549
+ continue;
1550
+ }
1551
+ throw lastError;
1552
+ }
1553
+ }
1554
+ const retryable = isRetryableStatus(response.status);
1555
+ if (!retryable || attempt === retryCount) {
1556
+ const body = await Promise.race([
1557
+ response.text().catch(() => {
1558
+ return;
1559
+ }),
1560
+ aborted.catch(() => {
1561
+ return;
1562
+ })
1563
+ ]);
1564
+ throw new HttpRequestError(response.status, {
1565
+ details: capDetails(body),
1566
+ url,
1567
+ method
1568
+ });
1569
+ }
1570
+ lastError = new HttpRequestError(response.status, { url, method });
1571
+ const delay = retryAfterMs(response) ?? retryDelay * (attempt + 1);
1572
+ response.body?.cancel().catch(() => {});
1573
+ clearTimeout(timeoutId);
1574
+ await sleep(delay, signal);
1575
+ } finally {
1576
+ clearTimeout(timeoutId);
1577
+ signal?.removeEventListener("abort", onCallerAbort);
1578
+ }
1579
+ }
1580
+ throw lastError ?? new Error("Request failed");
1581
+ }
1582
+ async function readBody(response) {
1583
+ const contentType = response.headers.get("content-type") ?? "";
1584
+ if (contentType.includes("application/json")) {
1585
+ return response.json();
1586
+ }
1587
+ return response.text();
1588
+ }
1589
+ function buildRequestFn(baseUrl, config) {
1590
+ const {
1591
+ timeout = 30000,
1592
+ retryCount = 3,
1593
+ retryDelay = 150,
1594
+ fetchOptions = {},
1595
+ apiKey
1596
+ } = config;
1597
+ return async (path, options) => {
1598
+ const url = `${baseUrl.replace(/\/$/, "")}${path}`;
1599
+ const headers = {
1600
+ "Content-Type": "application/json",
1601
+ ...fetchOptions.headers,
1602
+ ...options?.headers
1603
+ };
1604
+ if (apiKey) {
1605
+ headers["x-api-key"] = apiKey;
1606
+ }
1607
+ const init = {
1608
+ ...fetchOptions,
1609
+ method: options?.method ?? "GET",
1610
+ headers
1611
+ };
1612
+ if (options?.body !== undefined) {
1613
+ init.body = JSON.stringify(options.body);
1614
+ }
1615
+ return fetchWithRetry(url, init, options?.retryCount ?? retryCount, retryDelay, timeout, { signal: options?.signal, read: readBody });
1616
+ };
1617
+ }
1618
+
1619
+ // src/actions/public/txSources.ts
1620
+ class IndexSourceConfigError extends Error {
1621
+ name = "IndexSourceConfigError";
1622
+ }
1623
+ function isHiroHost(url, client) {
1624
+ let hostname;
1625
+ try {
1626
+ hostname = new URL(url).hostname;
1627
+ } catch {
1628
+ return false;
1629
+ }
1630
+ if (hostname === "hiro.so" || hostname.endsWith(".hiro.so"))
1631
+ return true;
1632
+ const defaults = client.chain?.rpcUrls?.default?.http ?? [];
1633
+ return defaults.some((d) => {
1634
+ try {
1635
+ return new URL(d).hostname === hostname && hostname !== "localhost";
1636
+ } catch {
1637
+ return false;
1638
+ }
1639
+ });
1640
+ }
1641
+ function indexRequestFn(client, baseUrl, sourceName) {
1642
+ const transportUrl = client.transport.config.url?.replace(/\/$/, "");
1643
+ if (baseUrl === undefined) {
1644
+ if (!transportUrl) {
1645
+ throw new IndexSourceConfigError(`${sourceName} needs the URL of your Secondlayer instance: pass baseUrl, or use an http() transport pointed at the instance`);
1646
+ }
1647
+ if (isHiroHost(transportUrl, client)) {
1648
+ 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`);
1649
+ }
1650
+ return client.request;
1651
+ }
1652
+ const target = baseUrl.replace(/\/$/, "");
1653
+ if (target === transportUrl)
1654
+ return client.request;
1655
+ const { timeout, retryCount, retryDelay } = client.transport.config;
1656
+ return buildRequestFn(target, { timeout, retryCount, retryDelay });
1657
+ }
1658
+ function indexNotFound(error, sourceName) {
1659
+ if (!(error instanceof HttpRequestError) || error.status !== 404) {
1660
+ return false;
1661
+ }
1662
+ const body = error.details;
1663
+ if (body !== undefined) {
1664
+ try {
1665
+ JSON.parse(body);
1666
+ } catch {
1667
+ 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 });
1668
+ }
1669
+ }
1670
+ return true;
1671
+ }
1672
+ function normalizeTxid(txid) {
1673
+ return txid.startsWith("0x") ? txid : `0x${txid}`;
1674
+ }
1675
+ function decodeResultHex(hex) {
1676
+ if (!hex)
1677
+ return {};
1678
+ try {
1679
+ return { result: deserializeCVBytes(hex), resultHex: hex };
1680
+ } catch {
1681
+ return { resultHex: hex };
1682
+ }
1683
+ }
1684
+ function normalizeStatus(txStatus) {
1685
+ switch (txStatus) {
1686
+ case "pending":
1687
+ case "success":
1688
+ case "abort_by_response":
1689
+ case "abort_by_post_condition":
1690
+ return txStatus;
1691
+ default:
1692
+ return txStatus.startsWith("dropped") ? "dropped" : undefined;
1693
+ }
1694
+ }
1695
+ function extendedApiSource() {
1696
+ return {
1697
+ async get({ client, txid }) {
1698
+ let data;
1699
+ try {
1700
+ data = await client.request(`/extended/v1/tx/${encodeURIComponent(normalizeTxid(txid))}`, { method: "GET" });
1701
+ } catch (error) {
1702
+ if (error instanceof HttpRequestError && error.status === 404) {
1703
+ return { receipt: null };
1704
+ }
1705
+ throw error;
1706
+ }
1707
+ const txStatus = typeof data?.tx_status === "string" ? data.tx_status : undefined;
1708
+ if (!txStatus)
1709
+ return { receipt: null };
1710
+ const status = normalizeStatus(txStatus);
1711
+ if (!status)
1712
+ return { receipt: null };
1713
+ return {
1714
+ receipt: {
1715
+ txid: normalizeTxid(txid),
1716
+ status,
1717
+ blockHeight: typeof data.block_height === "number" && data.block_height > 0 ? data.block_height : undefined,
1718
+ blockHash: data.block_hash ?? undefined,
1719
+ ...decodeResultHex(data.tx_result?.hex),
1720
+ events: Array.isArray(data.events) ? data.events : [],
1721
+ raw: data
1722
+ }
1723
+ };
1724
+ }
1725
+ };
1726
+ }
1727
+ function indexTxSource(params = {}) {
1728
+ const headers = params.apiKey ? { authorization: `Bearer ${params.apiKey}` } : undefined;
1729
+ return {
1730
+ canonicalOnly: true,
1731
+ async get({ client, txid }) {
1732
+ const request = indexRequestFn(client, params.baseUrl, "indexTxSource");
1733
+ let data;
1734
+ try {
1735
+ data = await request(`/v1/index/transactions/${normalizeTxid(txid)}`, {
1736
+ method: "GET",
1737
+ headers
1738
+ });
1739
+ } catch (error) {
1740
+ if (indexNotFound(error, "indexTxSource"))
1741
+ return { receipt: null };
1742
+ throw error;
1743
+ }
1744
+ const tx = data.transaction;
1745
+ const tip = data.tip?.block_height;
1746
+ if (!tx)
1747
+ return { receipt: null, tip };
1748
+ const status = normalizeStatus(tx.status) ?? "success";
1749
+ return {
1750
+ receipt: {
1751
+ txid: normalizeTxid(tx.tx_id),
1752
+ status,
1753
+ blockHeight: tx.block_height,
1754
+ ...decodeResultHex(tx.contract_call?.result_hex),
1755
+ events: [],
1756
+ raw: data
1757
+ },
1758
+ tip
1759
+ };
1760
+ }
1761
+ };
1762
+ }
1763
+
1764
+ // src/actions/public/getTransaction.ts
1765
+ async function getTransaction(client, params) {
1766
+ const source = params.source ?? extendedApiSource();
1767
+ const { receipt } = await source.get({ client, txid: params.txid });
1768
+ return receipt;
1769
+ }
1770
+
1771
+ // src/actions/public/readContract.ts
1772
+ async function readContract(client, params) {
1773
+ const [address, name] = parseContractId(params.contract);
1774
+ const sender = params.sender ?? address;
1775
+ const serializedArgs = (params.args ?? []).map((arg) => with0x(bytesToHex(serializeCVBytes(arg))));
1776
+ const path = `/v2/contracts/call-read/${encodeURIComponent(address)}/${encodeURIComponent(name)}/${encodeURIComponent(params.functionName)}`;
1777
+ const data = await client.request(params.tip ? `${path}?tip=${encodeURIComponent(params.tip)}` : path, {
1778
+ method: "POST",
1779
+ body: {
1780
+ sender,
1781
+ arguments: serializedArgs
1782
+ }
1783
+ });
1784
+ if (data.okay) {
1785
+ if (typeof data.result !== "string") {
1786
+ throw new MalformedResponseError(`readContract: /v2/contracts/call-read response is missing "result"`);
1787
+ }
1788
+ return deserializeCVBytes(data.result);
1789
+ }
1790
+ throw new ReadContractError(data.cause ?? "Read-only call failed");
1791
+ }
1792
+
1793
+ // src/actions/public/multicall.ts
1794
+ async function mapWithConcurrency(items, limit, fn) {
1795
+ const results = new Array(items.length);
1796
+ let cursor = 0;
1797
+ const worker = async () => {
1798
+ while (cursor < items.length) {
1799
+ const index = cursor++;
1800
+ try {
1801
+ results[index] = {
1802
+ status: "fulfilled",
1803
+ value: await fn(items[index])
1804
+ };
1805
+ } catch (reason) {
1806
+ results[index] = { status: "rejected", reason };
1807
+ }
1808
+ }
1809
+ };
1810
+ const workers = Math.max(1, Math.min(limit, items.length));
1811
+ await Promise.all(Array.from({ length: workers }, worker));
1812
+ return results;
1813
+ }
1814
+ async function multicall(client, params) {
1815
+ const { calls, allowFailure = true, concurrency = 8 } = params;
1816
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
1817
+ throw new RangeError(`multicall concurrency must be a positive integer, got ${concurrency}`);
1818
+ }
1819
+ const settled = await mapWithConcurrency(calls, concurrency, (call) => readContract(client, call));
1820
+ if (allowFailure) {
1821
+ return settled.map((r) => r.status === "fulfilled" ? { status: "success", result: r.value } : {
1822
+ status: "failure",
1823
+ error: r.reason instanceof Error ? r.reason : new Error(String(r.reason))
1824
+ });
1825
+ }
1826
+ const results = [];
1827
+ for (const r of settled) {
1828
+ if (r.status === "rejected")
1829
+ throw r.reason;
1830
+ results.push(r.value);
1831
+ }
1832
+ return results;
1833
+ }
1834
+
1835
+ // src/errors/simulation.ts
1836
+ class SimulationError extends BaseError {
1837
+ name = "SimulationError";
1838
+ writesDetected;
1839
+ constructor(message, options) {
1840
+ super(message, { details: options.details });
1841
+ this.writesDetected = options.writesDetected;
1842
+ }
1843
+ }
1844
+
1845
+ // src/actions/public/simulateCall.ts
1846
+ async function simulateCall(client, params) {
1847
+ const [address, name] = parseContractId(params.contract);
1848
+ const sender = params.sender ?? address;
1849
+ const serializedArgs = (params.args ?? []).map((arg) => with0x(bytesToHex(serializeCVBytes(arg))));
1850
+ let path = `/v2/contracts/call-read/${address}/${name}/${params.functionName}`;
1851
+ if (params.tip) {
1852
+ path += `?tip=${params.tip}`;
1853
+ }
1854
+ const data = await client.request(path, {
1855
+ method: "POST",
1856
+ body: {
1857
+ sender,
1858
+ arguments: serializedArgs
1859
+ }
1860
+ });
1861
+ if (data.okay) {
1862
+ return { success: true, result: deserializeCVBytes(data.result) };
1863
+ }
1864
+ const cause = data.cause ?? "Simulation failed";
1865
+ const writesDetected = cause.includes("NotReadOnly") || cause.includes("CostBalanceExceeded");
1866
+ return {
1867
+ success: false,
1868
+ error: new SimulationError(writesDetected ? "Function mutates state and cannot be simulated" : "Simulation failed", { writesDetected, details: cause })
1869
+ };
1870
+ }
1871
+
1872
+ // src/actions/public/simulateTransaction.ts
1873
+ function isMultiSig(hashMode) {
1874
+ return hashMode === AddressHashMode.P2SH || hashMode === AddressHashMode.P2WSH || hashMode === AddressHashMode.P2SH_NonSequential || hashMode === AddressHashMode.P2WSH_P2SH_NonSequential;
1875
+ }
1876
+ function extractSender(tx, client) {
1877
+ const { hashMode, signer } = tx.auth.spendingCondition;
1878
+ const chain = client.chain;
1879
+ const version = isMultiSig(hashMode) ? chain?.addressVersion.multiSig ?? 20 : chain?.addressVersion.singleSig ?? 22;
1880
+ return c32address(version, signer);
1881
+ }
1882
+ async function simulateTransaction(client, params) {
1883
+ const { transaction, tip } = params;
1884
+ const { payload } = transaction;
1885
+ if (payload.payloadType === PayloadType.ContractCall) {
1886
+ const sender = params.sender ?? extractSender(transaction, client);
1887
+ const contract = `${payload.contractAddress}.${payload.contractName}`;
1888
+ const [execution, fees] = await Promise.all([
1889
+ simulateCall(client, {
1890
+ contract,
1891
+ functionName: payload.functionName,
1892
+ args: payload.functionArgs,
1893
+ sender,
1894
+ tip
1895
+ }),
1896
+ estimateFee(client, { transaction })
1897
+ ]);
1898
+ return { type: "contract-call", execution, fees };
1899
+ }
1900
+ const fees = await estimateFee(client, { transaction });
1901
+ if (payload.payloadType === PayloadType.SmartContract || payload.payloadType === PayloadType.VersionedSmartContract) {
1902
+ return { type: "contract-deploy", fees };
1903
+ }
1904
+ return { type: "token-transfer", fees };
1905
+ }
1906
+
1907
+ // src/actions/public/waitForTransactionReceipt.ts
1908
+ var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
1909
+ async function waitForTransactionReceipt(client, params) {
1910
+ const {
1911
+ txid,
1912
+ confirmations = 1,
1913
+ timeout = 180000,
1914
+ pollingInterval = 3000
1915
+ } = params;
1916
+ const source = params.source ?? extendedApiSource();
1917
+ const droppedGracePeriod = params.droppedGracePeriod ?? (source.canonicalOnly ? timeout : 30000);
1918
+ const startedAt = Date.now();
1919
+ let unknownSince = null;
1920
+ let everPending = false;
1921
+ while (true) {
1922
+ const snapshot = await source.get({ client, txid });
1923
+ const receipt = snapshot.receipt;
1924
+ if (receipt === null) {
1925
+ unknownSince ??= Date.now();
1926
+ if (Date.now() - unknownSince >= droppedGracePeriod) {
1927
+ throw new TransactionDroppedError(everPending ? `Transaction ${txid} left the mempool without being mined` : `Transaction ${txid} was never observed by the status source`, { txid });
1928
+ }
1929
+ } else {
1930
+ unknownSince = null;
1931
+ switch (receipt.status) {
1932
+ case "dropped":
1933
+ throw new TransactionDroppedError(`Transaction ${txid} was dropped from the mempool`, { txid });
1934
+ case "abort_by_response":
1935
+ case "abort_by_post_condition":
1936
+ throw new TransactionAbortedError(`Transaction ${txid} aborted (${receipt.status})`, { receipt });
1937
+ case "pending":
1938
+ everPending = true;
1939
+ break;
1940
+ case "success": {
1941
+ if (confirmations <= 1)
1942
+ return receipt;
1943
+ if (receipt.blockHeight !== undefined) {
1944
+ const tip = snapshot.tip ?? await getBlockHeight(client);
1945
+ if (tip - receipt.blockHeight + 1 >= confirmations)
1946
+ return receipt;
1947
+ }
1948
+ break;
1949
+ }
1950
+ }
1951
+ }
1952
+ if (Date.now() - startedAt >= timeout) {
1953
+ throw new WaitForTransactionTimeoutError(`Timed out after ${timeout}ms waiting for transaction ${txid}`, { txid });
1954
+ }
1955
+ await sleep2(pollingInterval);
1956
+ }
1957
+ }
1958
+
1959
+ // src/errors/websocket.ts
1960
+ class WebSocketError extends BaseError {
1961
+ name = "WebSocketError";
1962
+ }
1963
+
1964
+ // src/subscriptions/actions.ts
1965
+ function getWsTransport(client) {
1966
+ if (client.transport.type !== "webSocket") {
1967
+ throw new WebSocketError("Watch actions require a webSocket transport. Use `webSocket()` when creating your client.");
1968
+ }
1969
+ return client.transport;
1970
+ }
1971
+ async function watchBlocks(client, params) {
1972
+ const transport = getWsTransport(client);
1973
+ return transport.subscribe({ event: "block" }, params.onBlock);
1974
+ }
1975
+ async function watchMempool(client, params) {
1976
+ const transport = getWsTransport(client);
1977
+ return transport.subscribe({ event: "mempool" }, params.onTransaction);
1978
+ }
1979
+ async function watchTransaction(client, params) {
1980
+ const transport = getWsTransport(client);
1981
+ return transport.subscribe({ event: "tx_update", tx_id: params.txId }, params.onUpdate);
1982
+ }
1983
+ async function watchAddress(client, params) {
1984
+ const transport = getWsTransport(client);
1985
+ return transport.subscribe({ event: "address_tx_update", address: params.address }, params.onTransaction);
1986
+ }
1987
+ async function watchAddressBalance(client, params) {
1988
+ const transport = getWsTransport(client);
1989
+ return transport.subscribe({ event: "address_balance_update", address: params.address }, params.onBalance);
1990
+ }
1991
+ async function watchNftEvent(client, params) {
1992
+ const transport = getWsTransport(client);
1993
+ let event;
1994
+ if (params.assetIdentifier && params.value) {
1995
+ event = "nft_event";
1996
+ } else if (params.assetIdentifier) {
1997
+ event = "nft_collection_event";
1998
+ } else {
1999
+ event = "nft_event";
2000
+ }
2001
+ return transport.subscribe({
2002
+ event,
2003
+ asset_identifier: params.assetIdentifier,
2004
+ value: params.value
2005
+ }, params.onEvent);
2006
+ }
2007
+
2008
+ // src/clients/decorators/public.ts
2009
+ function publicActions(client) {
2010
+ return {
2011
+ getNonce: (params) => getNonce(client, params),
2012
+ getBalance: (params) => getBalance(client, params),
2013
+ getAccountInfo: (params) => getAccountInfo(client, params),
2014
+ getBlock: (params) => getBlock(client, params),
2015
+ getRawBlock: (params) => getRawBlock(client, params),
2016
+ getBlockHeight: () => getBlockHeight(client),
2017
+ readContract: (params) => readContract(client, params),
2018
+ getContractAbi: (params) => getContractAbi(client, params),
2019
+ getContractSource: (params) => getContractSource(client, params),
2020
+ getDataVar: (params) => getDataVar(client, params),
2021
+ getMapEntry: (params) => getMapEntry(client, params),
2022
+ estimateFee: (params) => estimateFee(client, params),
2023
+ multicall: (params) => multicall(client, params),
2024
+ simulateCall: (params) => simulateCall(client, params),
2025
+ simulateTransaction: (params) => simulateTransaction(client, params),
2026
+ getTransaction: (params) => getTransaction(client, params),
2027
+ getAccountHistory: (params) => getAccountHistory(client, params),
2028
+ getMempoolStats: () => getMempoolStats(client),
2029
+ getNftHoldings: (params) => getNftHoldings(client, params),
2030
+ waitForTransactionReceipt: (params) => waitForTransactionReceipt(client, params),
2031
+ watchBlocks: (params) => watchBlocks(client, params),
2032
+ watchMempool: (params) => watchMempool(client, params),
2033
+ watchTransaction: (params) => watchTransaction(client, params),
2034
+ watchAddress: (params) => watchAddress(client, params),
2035
+ watchAddressBalance: (params) => watchAddressBalance(client, params),
2036
+ watchNftEvent: (params) => watchNftEvent(client, params)
2037
+ };
2038
+ }
2039
+
2040
+ // src/clients/createPublicClient.ts
2041
+ function createPublicClient(config) {
2042
+ return createClient(config).extend(publicActions);
2043
+ }
2044
+ // src/transactions/wire/deserialize.ts
2045
+ function readSpendingCondition(r) {
2046
+ const hashMode = r.readUInt8();
2047
+ const signer = bytesToHex(r.readBytes(20));
2048
+ const nonce = r.readBigUInt64BE();
2049
+ const fee = r.readBigUInt64BE();
2050
+ if (hashMode === AddressHashMode.P2PKH || hashMode === AddressHashMode.P2WPKH) {
2051
+ const keyEncoding = r.readUInt8();
2052
+ const signature = bytesToHex(r.readBytes(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES));
2053
+ return {
2054
+ hashMode,
2055
+ signer,
2056
+ nonce,
2057
+ fee,
2058
+ keyEncoding,
2059
+ signature
2060
+ };
2061
+ }
2062
+ const fieldCount = r.readUInt32BE();
2063
+ const fields = [];
2064
+ for (let i = 0;i < fieldCount; i++) {
2065
+ const fieldType = r.readUInt8();
2066
+ if (fieldType <= 1) {
2067
+ const keyLen = fieldType === 0 ? 33 : 65;
2068
+ fields.push({
2069
+ type: "publicKey",
2070
+ pubKeyEncoding: fieldType,
2071
+ data: bytesToHex(r.readBytes(keyLen))
2072
+ });
2073
+ } else {
2074
+ fields.push({
2075
+ type: "signature",
2076
+ pubKeyEncoding: fieldType === 2 ? 0 : 1,
2077
+ data: bytesToHex(r.readBytes(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES))
2078
+ });
2079
+ }
2080
+ }
2081
+ const signaturesRequired = r.readUInt16BE();
2082
+ return {
2083
+ hashMode,
2084
+ signer,
2085
+ nonce,
2086
+ fee,
2087
+ fields,
2088
+ signaturesRequired
2089
+ };
2090
+ }
2091
+ function readAuthorization(r) {
2092
+ const authType = r.readUInt8();
2093
+ const spendingCondition = readSpendingCondition(r);
2094
+ if (authType === AuthType.Standard) {
2095
+ return { authType: AuthType.Standard, spendingCondition };
2096
+ }
2097
+ const sponsorSpendingCondition = readSpendingCondition(r);
2098
+ return {
2099
+ authType: AuthType.Sponsored,
2100
+ spendingCondition,
2101
+ sponsorSpendingCondition
2102
+ };
2103
+ }
2104
+ function readAssetInfo(r) {
2105
+ return {
2106
+ address: readAddress(r),
2107
+ contractName: readLPString(r),
2108
+ assetName: readLPString(r)
2109
+ };
2110
+ }
2111
+ function readPostConditionPrincipal(r) {
2112
+ const type = r.readUInt8();
2113
+ switch (type) {
2114
+ case PostConditionPrincipalId.Origin:
2115
+ return { type: "origin" };
2116
+ case PostConditionPrincipalId.Standard:
2117
+ return { type: "standard", address: readAddress(r) };
2118
+ case PostConditionPrincipalId.Contract:
2119
+ return {
2120
+ type: "contract",
2121
+ address: readAddress(r),
2122
+ contractName: readLPString(r)
2123
+ };
2124
+ default:
2125
+ return { type: "origin" };
2126
+ }
2127
+ }
2128
+ function readPostCondition(r) {
2129
+ const assetType = r.readUInt8();
2130
+ const principal = readPostConditionPrincipal(r);
2131
+ switch (assetType) {
2132
+ case AssetType.STX:
2133
+ return {
2134
+ type: "stx",
2135
+ principal,
2136
+ conditionCode: r.readUInt8(),
2137
+ amount: r.readBigUInt64BE()
2138
+ };
2139
+ case AssetType.Fungible:
2140
+ return {
2141
+ type: "ft",
2142
+ principal,
2143
+ asset: readAssetInfo(r),
2144
+ conditionCode: r.readUInt8(),
2145
+ amount: r.readBigUInt64BE()
2146
+ };
2147
+ case AssetType.NonFungible:
2148
+ return {
2149
+ type: "nft",
2150
+ principal,
2151
+ asset: readAssetInfo(r),
2152
+ assetId: readCV(r),
2153
+ conditionCode: r.readUInt8()
2154
+ };
2155
+ case AssetType.Staking:
2156
+ return {
2157
+ type: "staking",
2158
+ principal,
2159
+ conditionCode: r.readUInt8(),
2160
+ amount: r.readBigUInt64BE()
2161
+ };
2162
+ case AssetType.Pox:
2163
+ return {
2164
+ type: "pox",
2165
+ principal,
2166
+ conditionCode: r.readUInt8()
2167
+ };
2168
+ default:
2169
+ throw new Error(`Unknown post-condition asset type: 0x${assetType.toString(16).padStart(2, "0")}`);
2170
+ }
2171
+ }
2172
+ function readPostConditions(r) {
2173
+ const count = r.readUInt32BE();
2174
+ const pcs = [];
2175
+ for (let i = 0;i < count; i++) {
2176
+ try {
2177
+ pcs.push(readPostCondition(r));
2178
+ } catch (e) {
2179
+ if (e instanceof Error && e.message.startsWith("Unknown post-condition asset type:")) {
2180
+ throw new Error(`${e.message} (post-condition ${i + 1}/${count})`);
2181
+ }
2182
+ throw e;
2183
+ }
2184
+ }
2185
+ return pcs;
2186
+ }
2187
+ function readPayload(r) {
2188
+ const payloadType = r.readUInt8();
2189
+ switch (payloadType) {
2190
+ case PayloadType.TokenTransfer: {
2191
+ const recipient = readCV(r);
2192
+ const amount = r.readBigUInt64BE();
2193
+ const memoBytes = r.readBytes(MEMO_MAX_LENGTH_BYTES);
2194
+ const memo = bytesToAscii(memoBytes).replace(/\0+$/, "");
2195
+ return {
2196
+ payloadType: PayloadType.TokenTransfer,
2197
+ recipient,
2198
+ amount,
2199
+ memo
2200
+ };
2201
+ }
2202
+ case PayloadType.ContractCall: {
2203
+ const contractAddress = readAddress(r);
2204
+ const contractName = readLPString(r);
2205
+ const functionName = readLPString(r);
2206
+ const numArgs = r.readUInt32BE();
2207
+ const functionArgs = [];
2208
+ for (let i = 0;i < numArgs; i++)
2209
+ functionArgs.push(readCV(r));
2210
+ return {
2211
+ payloadType: PayloadType.ContractCall,
2212
+ contractAddress,
2213
+ contractName,
2214
+ functionName,
2215
+ functionArgs
2216
+ };
2217
+ }
2218
+ case PayloadType.SmartContract: {
2219
+ const contractName = readLPString(r);
2220
+ const codeBody = readLPString(r, 4);
2221
+ return { payloadType: PayloadType.SmartContract, contractName, codeBody };
2222
+ }
2223
+ case PayloadType.VersionedSmartContract: {
2224
+ const clarityVersion = r.readUInt8();
2225
+ const contractName = readLPString(r);
2226
+ const codeBody = readLPString(r, 4);
2227
+ return {
2228
+ payloadType: PayloadType.VersionedSmartContract,
2229
+ clarityVersion,
2230
+ contractName,
2231
+ codeBody
2232
+ };
2233
+ }
2234
+ case PayloadType.Coinbase: {
2235
+ const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
2236
+ return { payloadType: PayloadType.Coinbase, coinbaseBuffer };
2237
+ }
2238
+ case PayloadType.CoinbaseToAltRecipient: {
2239
+ const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
2240
+ const recipient = readCV(r);
2241
+ return {
2242
+ payloadType: PayloadType.CoinbaseToAltRecipient,
2243
+ coinbaseBuffer,
2244
+ recipient
2245
+ };
2246
+ }
2247
+ case PayloadType.PoisonMicroblock: {
2248
+ const header1 = bytesToHex(r.readBytes(MICROBLOCK_HEADER_BYTES_LENGTH));
2249
+ const header2 = bytesToHex(r.readBytes(MICROBLOCK_HEADER_BYTES_LENGTH));
2250
+ return { payloadType: PayloadType.PoisonMicroblock, header1, header2 };
2251
+ }
2252
+ case PayloadType.TenureChange: {
2253
+ const tenureConsensusHash = bytesToHex(r.readBytes(20));
2254
+ const prevTenureConsensusHash = bytesToHex(r.readBytes(20));
2255
+ const burnViewConsensusHash = bytesToHex(r.readBytes(20));
2256
+ const previousTenureEnd = bytesToHex(r.readBytes(32));
2257
+ const previousTenureBlocks = r.readUInt32BE();
2258
+ const cause = r.readUInt8();
2259
+ const pubkeyHash = bytesToHex(r.readBytes(20));
2260
+ return {
2261
+ payloadType: PayloadType.TenureChange,
2262
+ tenureConsensusHash,
2263
+ prevTenureConsensusHash,
2264
+ burnViewConsensusHash,
2265
+ previousTenureEnd,
2266
+ previousTenureBlocks,
2267
+ cause,
2268
+ pubkeyHash
2269
+ };
2270
+ }
2271
+ case PayloadType.NakamotoCoinbase: {
2272
+ const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
2273
+ const optionalCV = readCV(r);
2274
+ const recipient = optionalCV.type === "none" ? null : optionalCV.type === "some" ? optionalCV.value : optionalCV;
2275
+ const vrfProof = bytesToHex(r.readBytes(VRF_PROOF_BYTES_LENGTH));
2276
+ return {
2277
+ payloadType: PayloadType.NakamotoCoinbase,
2278
+ coinbaseBuffer,
2279
+ recipient,
2280
+ vrfProof
2281
+ };
2282
+ }
2283
+ default:
2284
+ throw new Error(`Unknown payload type: ${payloadType}`);
2285
+ }
2286
+ }
2287
+ function deserializePostConditionWire(input) {
2288
+ const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
2289
+ return readPostCondition(new BytesReader(bytes));
2290
+ }
2291
+ function deserializeTransaction(input, meta) {
2292
+ const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
2293
+ const r = new BytesReader(bytes);
2294
+ const tx = {
2295
+ version: r.readUInt8(),
2296
+ chainId: r.readUInt32BE(),
2297
+ auth: readAuthorization(r),
2298
+ anchorMode: r.readUInt8(),
2299
+ postConditionMode: r.readUInt8(),
2300
+ postConditions: readPostConditions(r),
2301
+ payload: readPayload(r)
2302
+ };
2303
+ if (meta?._multisig) {
2304
+ tx._multisig = meta._multisig;
2305
+ }
2306
+ return tx;
2307
+ }
2308
+
2309
+ // src/postconditions/convert.ts
2310
+ var MAX_U64 = 18446744073709551615n;
2311
+ function parsePostConditionAmount(amount) {
2312
+ const value = intToBigInt(amount);
2313
+ if (value < 0n || value > MAX_U64) {
2314
+ throw new RangeError(`Post-condition amount must be between 0 and ${MAX_U64} (u64 max), received: ${value}`);
2315
+ }
2316
+ return value;
2317
+ }
2318
+ var FUNGIBLE_CODE_MAP = {
2319
+ eq: FungibleConditionCode.Equal,
2320
+ gt: FungibleConditionCode.Greater,
2321
+ gte: FungibleConditionCode.GreaterEqual,
2322
+ lt: FungibleConditionCode.Less,
2323
+ lte: FungibleConditionCode.LessEqual
2324
+ };
2325
+ var FUNGIBLE_CODE_REVERSE = {
2326
+ [FungibleConditionCode.Equal]: "eq",
2327
+ [FungibleConditionCode.Greater]: "gt",
2328
+ [FungibleConditionCode.GreaterEqual]: "gte",
2329
+ [FungibleConditionCode.Less]: "lt",
2330
+ [FungibleConditionCode.LessEqual]: "lte"
2331
+ };
2332
+ var NFT_CODE_MAP = {
2333
+ sent: NonFungibleConditionCode.Sends,
2334
+ "not-sent": NonFungibleConditionCode.DoesNotSend,
2335
+ "maybe-sent": NonFungibleConditionCode.MaybeSent
2336
+ };
2337
+ var NFT_CODE_REVERSE = {
2338
+ [NonFungibleConditionCode.Sends]: "sent",
2339
+ [NonFungibleConditionCode.DoesNotSend]: "not-sent",
2340
+ [NonFungibleConditionCode.MaybeSent]: "maybe-sent"
2341
+ };
2342
+ var POX_CODE_MAP = {
2343
+ "will-not-perform": PoxConditionCode.WillNotPerform,
2344
+ "may-perform": PoxConditionCode.MayPerform,
2345
+ "will-perform": PoxConditionCode.WillPerform
2346
+ };
2347
+ var POX_CODE_REVERSE = {
2348
+ [PoxConditionCode.WillNotPerform]: "will-not-perform",
2349
+ [PoxConditionCode.MayPerform]: "may-perform",
2350
+ [PoxConditionCode.WillPerform]: "will-perform"
2351
+ };
2352
+ function resolvePrincipal(address) {
2353
+ if (address === "origin")
2354
+ return { type: "origin" };
2355
+ const [addr, name] = address.split(".");
2356
+ if (name) {
2357
+ return { type: "contract", address: addr, contractName: name };
2358
+ }
2359
+ return { type: "standard", address: addr };
2360
+ }
2361
+ function principalToString(principal) {
2362
+ if (principal.type === "origin")
2363
+ return "origin";
2364
+ if (principal.type === "contract") {
2365
+ return `${principal.address}.${principal.contractName}`;
2366
+ }
2367
+ return principal.address;
2368
+ }
2369
+ function assetToString(asset) {
2370
+ return `${asset.address}.${asset.contractName}::${asset.assetName}`;
2371
+ }
2372
+ function parseAsset(asset) {
2373
+ const [contractId, tokenName] = asset.split("::");
2374
+ const [addr, name] = parseContractId(contractId);
2375
+ return { address: addr, contractName: name, assetName: tokenName };
2376
+ }
2377
+ function convertPostCondition(pc) {
2378
+ switch (pc.type) {
2379
+ case "stx-postcondition":
2380
+ return {
2381
+ type: "stx",
2382
+ principal: resolvePrincipal(pc.address),
2383
+ conditionCode: FUNGIBLE_CODE_MAP[pc.condition],
2384
+ amount: parsePostConditionAmount(pc.amount)
2385
+ };
2386
+ case "ft-postcondition":
2387
+ return {
2388
+ type: "ft",
2389
+ principal: resolvePrincipal(pc.address),
2390
+ asset: parseAsset(pc.asset),
2391
+ conditionCode: FUNGIBLE_CODE_MAP[pc.condition],
2392
+ amount: parsePostConditionAmount(pc.amount)
2393
+ };
2394
+ case "nft-postcondition":
2395
+ return {
2396
+ type: "nft",
2397
+ principal: resolvePrincipal(pc.address),
2398
+ asset: parseAsset(pc.asset),
2399
+ conditionCode: NFT_CODE_MAP[pc.condition],
2400
+ assetId: pc.assetId
2401
+ };
2402
+ case "staking-postcondition":
2403
+ return {
2404
+ type: "staking",
2405
+ principal: resolvePrincipal(pc.address),
2406
+ conditionCode: FUNGIBLE_CODE_MAP[pc.condition],
2407
+ amount: parsePostConditionAmount(pc.amount)
2408
+ };
2409
+ case "pox-postcondition":
2410
+ return {
2411
+ type: "pox",
2412
+ principal: resolvePrincipal(pc.address),
2413
+ conditionCode: POX_CODE_MAP[pc.condition]
2414
+ };
2415
+ }
2416
+ }
2417
+ function wireToPostCondition(wire) {
2418
+ switch (wire.type) {
2419
+ case "stx":
2420
+ return {
2421
+ type: "stx-postcondition",
2422
+ address: principalToString(wire.principal),
2423
+ condition: fungibleName(wire.conditionCode),
2424
+ amount: wire.amount.toString()
2425
+ };
2426
+ case "ft":
2427
+ return {
2428
+ type: "ft-postcondition",
2429
+ address: principalToString(wire.principal),
2430
+ condition: fungibleName(wire.conditionCode),
2431
+ amount: wire.amount.toString(),
2432
+ asset: assetToString(wire.asset)
2433
+ };
2434
+ case "nft":
2435
+ return {
2436
+ type: "nft-postcondition",
2437
+ address: principalToString(wire.principal),
2438
+ condition: nftName(wire.conditionCode),
2439
+ asset: assetToString(wire.asset),
2440
+ assetId: wire.assetId
2441
+ };
2442
+ case "staking":
2443
+ return {
2444
+ type: "staking-postcondition",
2445
+ address: principalToString(wire.principal),
2446
+ condition: fungibleName(wire.conditionCode),
2447
+ amount: wire.amount.toString()
2448
+ };
2449
+ case "pox":
2450
+ return {
2451
+ type: "pox-postcondition",
2452
+ address: principalToString(wire.principal),
2453
+ condition: poxName(wire.conditionCode)
2454
+ };
2455
+ }
2456
+ }
2457
+ function fungibleName(code) {
2458
+ const name = FUNGIBLE_CODE_REVERSE[code];
2459
+ if (!name)
2460
+ throw new Error(`Unknown fungible post-condition code: ${code}`);
2461
+ return name;
2462
+ }
2463
+ function nftName(code) {
2464
+ const name = NFT_CODE_REVERSE[code];
2465
+ if (!name)
2466
+ throw new Error(`Unknown nft post-condition code: ${code}`);
2467
+ return name;
2468
+ }
2469
+ function poxName(code) {
2470
+ const name = POX_CODE_REVERSE[code];
2471
+ if (!name)
2472
+ throw new Error(`Unknown pox post-condition code: ${code}`);
2473
+ return name;
2474
+ }
2475
+ function fromHex(hex) {
2476
+ return wireToPostCondition(deserializePostConditionWire(hex));
2477
+ }
2478
+ function postConditionToHex(pc) {
2479
+ return bytesToHex(serializePostConditionWire(convertPostCondition(pc)));
2480
+ }
2481
+
2482
+ // src/transactions/authorization.ts
2483
+ var import_hmac = require("@noble/hashes/hmac.js");
2484
+ var import_sha24 = require("@noble/hashes/sha2.js");
2485
+ var import_secp256k1 = require("@noble/secp256k1");
2486
+ import_secp256k1.etc.hmacSha256Sync = (key, ...msgs) => {
2487
+ const h = import_hmac.hmac.create(import_sha24.sha256, key);
2488
+ for (const msg of msgs)
2489
+ h.update(msg);
2490
+ return h.digest();
2491
+ };
2492
+ var EMPTY_SIG = bytesToHex(new Uint8Array(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES));
2493
+ function createSingleSigSpendingCondition(publicKey, nonce, fee) {
2494
+ const pubKeyBytes = hexToBytes(publicKey);
2495
+ const signer = hashP2PKH(pubKeyBytes);
2496
+ const isCompressed = pubKeyBytes.length === 33;
2497
+ return {
2498
+ hashMode: AddressHashMode.P2PKH,
2499
+ signer,
2500
+ nonce,
2501
+ fee,
2502
+ keyEncoding: isCompressed ? PubKeyEncoding.Compressed : PubKeyEncoding.Uncompressed,
2503
+ signature: EMPTY_SIG
2504
+ };
2505
+ }
2506
+ function createStandardAuth(spendingCondition) {
2507
+ return { authType: AuthType.Standard, spendingCondition };
2508
+ }
2509
+ function createSponsoredAuth(spendingCondition, sponsorSpendingCondition) {
2510
+ return {
2511
+ authType: AuthType.Sponsored,
2512
+ spendingCondition,
2513
+ sponsorSpendingCondition: sponsorSpendingCondition ?? createSingleSigSpendingCondition("0".repeat(66), 0n, 0n)
2514
+ };
2515
+ }
2516
+ function clearCondition(condition) {
2517
+ if ("signature" in condition) {
2518
+ return {
2519
+ ...condition,
2520
+ nonce: 0n,
2521
+ fee: 0n,
2522
+ signature: EMPTY_SIG
2523
+ };
2524
+ }
2525
+ return {
2526
+ ...condition,
2527
+ nonce: 0n,
2528
+ fee: 0n,
2529
+ fields: []
2530
+ };
2531
+ }
2532
+ function sponsorSigningSentinel() {
2533
+ return {
2534
+ hashMode: AddressHashMode.P2PKH,
2535
+ signer: "00".repeat(20),
2536
+ nonce: 0n,
2537
+ fee: 0n,
2538
+ keyEncoding: PubKeyEncoding.Compressed,
2539
+ signature: EMPTY_SIG
2540
+ };
2541
+ }
2542
+ function intoInitialSighashAuth(auth) {
2543
+ if (auth.authType === AuthType.Standard) {
2544
+ return createStandardAuth(clearCondition(auth.spendingCondition));
2545
+ }
2546
+ return createSponsoredAuth(clearCondition(auth.spendingCondition), sponsorSigningSentinel());
2547
+ }
2548
+ function sigHashPreSign(curSigHash, authType, fee, nonce) {
2549
+ const data = concatBytes(hexToBytes(curSigHash), new Uint8Array([authType]), intToBytes(fee, 8), intToBytes(nonce, 8));
2550
+ return txidFromBytes(data);
2551
+ }
2552
+ function sigHashPostSign(curSigHash, pubKeyEncoding, signature) {
2553
+ const data = concatBytes(hexToBytes(curSigHash), new Uint8Array([pubKeyEncoding]), hexToBytes(signature));
2554
+ return txidFromBytes(data);
2555
+ }
2556
+ function signWithKey(privateKey, messageHash) {
2557
+ const keyBytes = hexToBytes(privateKey).slice(0, 32);
2558
+ const sig = import_secp256k1.sign(messageHash, keyBytes, { lowS: true });
2559
+ const recoveryIdHex = intToHex(sig.recovery, 1);
2560
+ return recoveryIdHex + sig.toCompactHex();
2561
+ }
2562
+ function nextSignature(curSigHash, authType, fee, nonce, privateKey) {
2563
+ const sigHashPre = sigHashPreSign(curSigHash, authType, fee, nonce);
2564
+ const keyBytes = hexToBytes(privateKey).slice(0, 32);
2565
+ const pubKey = import_secp256k1.getPublicKey(keyBytes, true);
2566
+ const isCompressed = pubKey.length === 33;
2567
+ const pubKeyEncoding = isCompressed ? PubKeyEncoding.Compressed : PubKeyEncoding.Uncompressed;
2568
+ const nextSig = signWithKey(privateKey, sigHashPre);
2569
+ const nextSigHash = sigHashPostSign(sigHashPre, pubKeyEncoding, nextSig);
2570
+ return { nextSig, nextSigHash };
2571
+ }
2572
+
2573
+ // src/transactions/multisig.ts
2574
+ var import_secp256k12 = require("@noble/secp256k1");
2575
+ var OP_CHECKMULTISIG = 174;
2576
+ function isNonSequential(hashMode) {
2577
+ return (hashMode & 4) !== 0;
2578
+ }
2579
+ function makeRedeemScript(publicKeys, signaturesRequired) {
2580
+ const parts = [];
2581
+ parts.push(new Uint8Array([80 + signaturesRequired]));
2582
+ for (const pk of publicKeys) {
2583
+ const pkBytes = hexToBytes(pk);
2584
+ parts.push(new Uint8Array([pkBytes.length]));
2585
+ parts.push(pkBytes);
2586
+ }
2587
+ parts.push(new Uint8Array([80 + publicKeys.length]));
2588
+ parts.push(new Uint8Array([OP_CHECKMULTISIG]));
2589
+ return concatBytes(...parts);
2590
+ }
2591
+ function makeMultiSigAddress(publicKeys, signaturesRequired, chain) {
2592
+ if (signaturesRequired < 1 || signaturesRequired > publicKeys.length) {
2593
+ throw new Error(`signaturesRequired must be between 1 and ${publicKeys.length}`);
2594
+ }
2595
+ const redeemScript = makeRedeemScript(publicKeys, signaturesRequired);
2596
+ const signer = hash160(redeemScript);
2597
+ const version = chain?.addressVersion?.multiSig ?? 20;
2598
+ return c32address(version, bytesToHex(signer));
2599
+ }
2600
+ function createMultiSigSpendingCondition(publicKeys, signaturesRequired, nonce, fee, hashMode = AddressHashMode.P2SH) {
2601
+ const redeemScript = makeRedeemScript(publicKeys, signaturesRequired);
2602
+ const signer = bytesToHex(hash160(redeemScript));
2603
+ return {
2604
+ hashMode,
2605
+ signer,
2606
+ nonce,
2607
+ fee,
2608
+ fields: [],
2609
+ signaturesRequired
2610
+ };
2611
+ }
2612
+ function initialSigHash(tx) {
2613
+ const cleared = {
2614
+ ...tx,
2615
+ auth: intoInitialSighashAuth(tx.auth)
2616
+ };
2617
+ return txidFromBytes(serializeTransaction(cleared));
2618
+ }
2619
+ function nonSequentialPreSignHash(tx) {
2620
+ const condition = tx.auth.spendingCondition;
2621
+ const initHash = initialSigHash(tx);
2622
+ return sigHashPreSign(initHash, AuthType.Standard, condition.fee, condition.nonce);
2623
+ }
2624
+ function replayMultiSigSigHash(tx) {
2625
+ const condition = tx.auth.spendingCondition;
2626
+ if (isNonSequential(condition.hashMode)) {
2627
+ const preSign = nonSequentialPreSignHash(tx);
2628
+ let curSigHash = preSign;
2629
+ for (const field of condition.fields) {
2630
+ curSigHash = sigHashPostSign(curSigHash, field.pubKeyEncoding, field.data);
2631
+ }
2632
+ return curSigHash;
2633
+ }
2634
+ let curSigHash = initialSigHash(tx);
2635
+ for (const field of condition.fields) {
2636
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2637
+ curSigHash = sigHashPostSign(preSign, field.pubKeyEncoding, field.data);
2638
+ }
2639
+ return curSigHash;
2640
+ }
2641
+ function signMultiSig(tx, privateKey, publicKeys) {
2642
+ const keyBytes = hexToBytes(privateKey).slice(0, 32);
2643
+ const signerPubKey = bytesToHex(import_secp256k12.getPublicKey(keyBytes, true));
2644
+ const signerIndex = publicKeys.findIndex((pk) => pk === signerPubKey);
2645
+ if (signerIndex === -1) {
2646
+ throw new Error("Private key does not correspond to any signer in the multi-sig");
2647
+ }
2648
+ const condition = {
2649
+ ...tx.auth.spendingCondition
2650
+ };
2651
+ if (isNonSequential(condition.hashMode)) {
2652
+ return signNonSequential(tx, condition, privateKey);
2653
+ }
2654
+ return signSequential(tx, condition, privateKey, publicKeys, signerIndex);
2655
+ }
2656
+ function signNonSequential(tx, condition, privateKey) {
2657
+ const fields = [...condition.fields];
2658
+ const preSignHash = nonSequentialPreSignHash(tx);
2659
+ const keyBytes = hexToBytes(privateKey).slice(0, 32);
2660
+ const sig = import_secp256k12.sign(preSignHash, keyBytes, { lowS: true });
2661
+ const recoveryIdHex = intToHex(sig.recovery, 1);
2662
+ const nextSig = recoveryIdHex + sig.toCompactHex();
2663
+ fields.push({
2664
+ type: "signature",
2665
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2666
+ data: nextSig
2667
+ });
2668
+ const newCondition = { ...condition, fields };
2669
+ const sigCount = fields.filter((f) => f.type === "signature").length;
2670
+ if (sigCount >= condition.signaturesRequired) {
2671
+ return {
2672
+ ...tx,
2673
+ auth: { ...tx.auth, spendingCondition: newCondition }
2674
+ };
2675
+ }
2676
+ return {
2677
+ ...tx,
2678
+ auth: { ...tx.auth, spendingCondition: newCondition }
2679
+ };
2680
+ }
2681
+ function signSequential(tx, condition, privateKey, publicKeys, signerIndex) {
2682
+ const fields = [...condition.fields];
2683
+ let curSigHash = initialSigHash(tx);
2684
+ for (const field of fields) {
2685
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2686
+ curSigHash = sigHashPostSign(preSign, field.pubKeyEncoding, field.data);
2687
+ }
2688
+ for (let i = fields.length;i < signerIndex; i++) {
2689
+ const pubKeyField = {
2690
+ type: "publicKey",
2691
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2692
+ data: publicKeys[i]
2693
+ };
2694
+ fields.push(pubKeyField);
2695
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2696
+ curSigHash = sigHashPostSign(preSign, pubKeyField.pubKeyEncoding, pubKeyField.data);
2697
+ }
2698
+ const { nextSig, nextSigHash } = nextSignature(curSigHash, AuthType.Standard, condition.fee, condition.nonce, privateKey);
2699
+ fields.push({
2700
+ type: "signature",
2701
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2702
+ data: nextSig
2703
+ });
2704
+ curSigHash = nextSigHash;
2705
+ const newCondition = { ...condition, fields };
2706
+ const sigCount = fields.filter((f) => f.type === "signature").length;
2707
+ let finalCondition = newCondition;
2708
+ if (sigCount >= condition.signaturesRequired) {
2709
+ finalCondition = finalizeMultiSigCondition(newCondition, publicKeys, curSigHash);
2710
+ }
2711
+ return {
2712
+ ...tx,
2713
+ auth: {
2714
+ ...tx.auth,
2715
+ spendingCondition: finalCondition
2716
+ }
2717
+ };
2718
+ }
2719
+ async function signMultiSigWithAccount(tx, account, publicKeys) {
2720
+ const signerPubKey = account.publicKey;
2721
+ const signerIndex = publicKeys.findIndex((pk) => pk === signerPubKey);
2722
+ if (signerIndex === -1) {
2723
+ throw new Error("Account does not correspond to any signer in the multi-sig");
2724
+ }
2725
+ const condition = {
2726
+ ...tx.auth.spendingCondition
2727
+ };
2728
+ if (isNonSequential(condition.hashMode)) {
2729
+ return signNonSequentialWithAccount(tx, condition, account);
2730
+ }
2731
+ return signSequentialWithAccount(tx, condition, account, publicKeys, signerIndex);
2732
+ }
2733
+ async function signNonSequentialWithAccount(tx, condition, account) {
2734
+ const fields = [...condition.fields];
2735
+ const preSignHash = nonSequentialPreSignHash(tx);
2736
+ const sigBytes = await account.sign(hexToBytes(preSignHash));
2737
+ const nextSig = bytesToHex(sigBytes);
2738
+ fields.push({
2739
+ type: "signature",
2740
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2741
+ data: nextSig
2742
+ });
2743
+ const newCondition = { ...condition, fields };
2744
+ return {
2745
+ ...tx,
2746
+ auth: { ...tx.auth, spendingCondition: newCondition }
2747
+ };
2748
+ }
2749
+ async function signSequentialWithAccount(tx, condition, account, publicKeys, signerIndex) {
2750
+ const fields = [...condition.fields];
2751
+ let curSigHash = initialSigHash(tx);
2752
+ for (const field of fields) {
2753
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2754
+ curSigHash = sigHashPostSign(preSign, field.pubKeyEncoding, field.data);
2755
+ }
2756
+ for (let i = fields.length;i < signerIndex; i++) {
2757
+ const pubKeyField = {
2758
+ type: "publicKey",
2759
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2760
+ data: publicKeys[i]
2761
+ };
2762
+ fields.push(pubKeyField);
2763
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2764
+ curSigHash = sigHashPostSign(preSign, pubKeyField.pubKeyEncoding, pubKeyField.data);
2765
+ }
2766
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2767
+ const sigBytes = await account.sign(hexToBytes(preSign));
2768
+ const nextSig = bytesToHex(sigBytes);
2769
+ const nextSigHash = sigHashPostSign(preSign, PubKeyEncoding.Compressed, nextSig);
2770
+ fields.push({
2771
+ type: "signature",
2772
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2773
+ data: nextSig
2774
+ });
2775
+ curSigHash = nextSigHash;
2776
+ const newCondition = { ...condition, fields };
2777
+ const sigCount = fields.filter((f) => f.type === "signature").length;
2778
+ let finalCondition = newCondition;
2779
+ if (sigCount >= condition.signaturesRequired) {
2780
+ finalCondition = finalizeMultiSigCondition(newCondition, publicKeys, curSigHash);
2781
+ }
2782
+ return {
2783
+ ...tx,
2784
+ auth: {
2785
+ ...tx.auth,
2786
+ spendingCondition: finalCondition
2787
+ }
2788
+ };
2789
+ }
2790
+ function finalizeMultiSig(tx, publicKeys) {
2791
+ const condition = tx.auth.spendingCondition;
2792
+ if (isNonSequential(condition.hashMode)) {
2793
+ return tx;
2794
+ }
2795
+ const curSigHash = replayMultiSigSigHash(tx);
2796
+ const finalCondition = finalizeMultiSigCondition(condition, publicKeys, curSigHash);
2797
+ return {
2798
+ ...tx,
2799
+ auth: {
2800
+ ...tx.auth,
2801
+ spendingCondition: finalCondition
2802
+ }
2803
+ };
2804
+ }
2805
+ function finalizeMultiSigCondition(condition, publicKeys, curSigHash) {
2806
+ const fields = [...condition.fields];
2807
+ let sigHash = curSigHash;
2808
+ for (let i = fields.length;i < publicKeys.length; i++) {
2809
+ const pubKeyField = {
2810
+ type: "publicKey",
2811
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2812
+ data: publicKeys[i]
2813
+ };
2814
+ fields.push(pubKeyField);
2815
+ const preSign = sigHashPreSign(sigHash, AuthType.Standard, condition.fee, condition.nonce);
2816
+ sigHash = sigHashPostSign(preSign, pubKeyField.pubKeyEncoding, pubKeyField.data);
2817
+ }
2818
+ return { ...condition, fields };
2819
+ }
2820
+ function combineMultiSigSignatures(baseTx, signedTxs) {
2821
+ const condition = baseTx.auth.spendingCondition;
2822
+ if (!isNonSequential(condition.hashMode)) {
2823
+ throw new Error("combineMultiSigSignatures only works with non-sequential hash modes (SIP-027)");
2824
+ }
2825
+ const seenSigs = new Set;
2826
+ const signatures = [];
2827
+ for (const stx of signedTxs) {
2828
+ const stxCondition = stx.auth.spendingCondition;
2829
+ for (const field of stxCondition.fields) {
2830
+ if (field.type === "signature" && !seenSigs.has(field.data)) {
2831
+ seenSigs.add(field.data);
2832
+ signatures.push(field);
2833
+ }
2834
+ }
2835
+ }
2836
+ if (signatures.length === 0) {
2837
+ throw new Error("No signatures found in the provided transactions");
2838
+ }
2839
+ const newCondition = {
2840
+ ...condition,
2841
+ fields: signatures
2842
+ };
2843
+ return {
2844
+ ...baseTx,
2845
+ auth: { ...baseTx.auth, spendingCondition: newCondition }
2846
+ };
2847
+ }
2848
+
2849
+ // src/transactions/build.ts
2850
+ function resolvePcMode(mode) {
2851
+ if (mode === "allow")
2852
+ return PostConditionModeWire.Allow;
2853
+ if (mode === "originator")
2854
+ return PostConditionModeWire.Originator;
2855
+ return PostConditionModeWire.Deny;
2856
+ }
2857
+ function convertPostConditions(pcs) {
2858
+ if (!pcs || pcs.length === 0)
2859
+ return [];
2860
+ return pcs.map((pc) => convertPostCondition(typeof pc === "string" ? fromHex(pc) : pc));
2861
+ }
2862
+ function resolveSpendingCondition(opts, nonce, fee) {
2863
+ if (opts.publicKeys) {
2864
+ return createMultiSigSpendingCondition(opts.publicKeys, opts.signaturesRequired, nonce, fee, opts.hashMode);
2865
+ }
2866
+ return createSingleSigSpendingCondition(opts.publicKey, nonce, fee);
2867
+ }
2868
+ function resolveAuth(spendingCondition, sponsored) {
2869
+ return sponsored ? createSponsoredAuth(spendingCondition) : createStandardAuth(spendingCondition);
2870
+ }
2871
+ function resolveVersionAndChainId(chain) {
2872
+ if (!chain)
2873
+ return { version: 0, chainId: 1 };
2874
+ return { version: chain.transactionVersion, chainId: chain.id };
2875
+ }
2876
+ function buildTokenTransfer(options) {
2877
+ const { version, chainId } = resolveVersionAndChainId(options.chain);
2878
+ const fee = intToBigInt(options.fee);
2879
+ const nonce = intToBigInt(options.nonce);
2880
+ const spendingCondition = resolveSpendingCondition(options, nonce, fee);
2881
+ const recipient = Cl.principal(options.recipient);
2882
+ const tx = {
2883
+ version,
2884
+ chainId,
2885
+ auth: resolveAuth(spendingCondition, options.sponsored),
2886
+ anchorMode: AnchorMode.Any,
2887
+ postConditionMode: resolvePcMode(options.postConditionMode),
2888
+ postConditions: convertPostConditions(options.postConditions),
2889
+ payload: {
2890
+ payloadType: PayloadType.TokenTransfer,
2891
+ recipient,
2892
+ amount: intToBigInt(options.amount),
2893
+ memo: options.memo ?? ""
2894
+ }
2895
+ };
2896
+ if (options.publicKeys) {
2897
+ tx._multisig = { publicKeys: options.publicKeys };
2898
+ }
2899
+ return tx;
2900
+ }
2901
+ function buildContractCall(options) {
2902
+ const { version, chainId } = resolveVersionAndChainId(options.chain);
2903
+ const fee = intToBigInt(options.fee);
2904
+ const nonce = intToBigInt(options.nonce);
2905
+ const spendingCondition = resolveSpendingCondition(options, nonce, fee);
2906
+ const tx = {
2907
+ version,
2908
+ chainId,
2909
+ auth: resolveAuth(spendingCondition, options.sponsored),
2910
+ anchorMode: AnchorMode.Any,
2911
+ postConditionMode: resolvePcMode(options.postConditionMode),
2912
+ postConditions: convertPostConditions(options.postConditions),
2913
+ payload: {
2914
+ payloadType: PayloadType.ContractCall,
2915
+ contractAddress: options.contractAddress,
2916
+ contractName: options.contractName,
2917
+ functionName: options.functionName,
2918
+ functionArgs: options.functionArgs
2919
+ }
2920
+ };
2921
+ if (options.publicKeys) {
2922
+ tx._multisig = { publicKeys: options.publicKeys };
2923
+ }
2924
+ return tx;
2925
+ }
2926
+ function buildContractDeploy(options) {
2927
+ const { version, chainId } = resolveVersionAndChainId(options.chain);
2928
+ const fee = intToBigInt(options.fee);
2929
+ const nonce = intToBigInt(options.nonce);
2930
+ const spendingCondition = resolveSpendingCondition(options, nonce, fee);
2931
+ const clarityVersion = options.clarityVersion ?? ClarityVersion.Clarity4;
2932
+ const tx = {
2933
+ version,
2934
+ chainId,
2935
+ auth: resolveAuth(spendingCondition, options.sponsored),
2936
+ anchorMode: AnchorMode.Any,
2937
+ postConditionMode: resolvePcMode(options.postConditionMode),
2938
+ postConditions: convertPostConditions(options.postConditions),
2939
+ payload: {
2940
+ payloadType: PayloadType.VersionedSmartContract,
2941
+ clarityVersion,
2942
+ contractName: options.contractName,
2943
+ codeBody: options.codeBody
2944
+ }
2945
+ };
2946
+ if (options.publicKeys) {
2947
+ tx._multisig = { publicKeys: options.publicKeys };
2948
+ }
2949
+ return tx;
2950
+ }
2951
+
2952
+ // src/transactions/signer.ts
2953
+ function txid(tx) {
2954
+ return txidFromBytes(serializeTransaction(tx));
2955
+ }
2956
+ function signBegin(tx) {
2957
+ const cleared = {
2958
+ ...tx,
2959
+ auth: intoInitialSighashAuth(tx.auth)
2960
+ };
2961
+ return txid(cleared);
2962
+ }
2963
+ function signTransaction(tx, privateKey) {
2964
+ const sigHash = signBegin(tx);
2965
+ const condition = tx.auth.spendingCondition;
2966
+ const { nextSig } = nextSignature(sigHash, AuthType.Standard, condition.fee, condition.nonce, privateKey);
2967
+ return {
2968
+ ...tx,
2969
+ auth: {
2970
+ ...tx.auth,
2971
+ spendingCondition: {
2972
+ ...condition,
2973
+ signature: nextSig
2974
+ }
2975
+ }
2976
+ };
2977
+ }
2978
+ async function signTransactionWithAccount(tx, account) {
2979
+ const sigHash = signBegin(tx);
2980
+ const condition = tx.auth.spendingCondition;
2981
+ const sigHashPre = sigHashPreSign(sigHash, AuthType.Standard, condition.fee, condition.nonce);
2982
+ const sigBytes = await account.sign(hexToBytes(sigHashPre));
2983
+ const nextSig = bytesToHex(sigBytes);
2984
+ return {
2985
+ ...tx,
2986
+ auth: {
2987
+ ...tx.auth,
2988
+ spendingCondition: {
2989
+ ...condition,
2990
+ signature: nextSig
2991
+ }
2992
+ }
2993
+ };
2994
+ }
2995
+ function getTransactionId(tx) {
2996
+ return txid(tx);
2997
+ }
2998
+ function getOriginSigHash(tx) {
2999
+ const condition = tx.auth.spendingCondition;
3000
+ if ("fields" in condition) {
3001
+ return replayMultiSigSigHash(tx);
3002
+ }
3003
+ const initialSigHash = signBegin(tx);
3004
+ const sc = condition;
3005
+ const preSign = sigHashPreSign(initialSigHash, AuthType.Standard, sc.fee, sc.nonce);
3006
+ return sigHashPostSign(preSign, sc.keyEncoding, sc.signature);
3007
+ }
3008
+ function signSponsor(tx, privateKey) {
3009
+ if (tx.auth.authType !== AuthType.Sponsored) {
3010
+ throw new Error("Transaction must be sponsored");
3011
+ }
3012
+ const auth = tx.auth;
3013
+ const sponsorCondition = auth.sponsorSpendingCondition;
3014
+ const originSigHash = getOriginSigHash(tx);
3015
+ const { nextSig } = nextSignature(originSigHash, AuthType.Sponsored, sponsorCondition.fee, sponsorCondition.nonce, privateKey);
3016
+ return {
3017
+ ...tx,
3018
+ auth: {
3019
+ ...auth,
3020
+ sponsorSpendingCondition: {
3021
+ ...sponsorCondition,
3022
+ signature: nextSig
3023
+ }
3024
+ }
3025
+ };
3026
+ }
3027
+ async function signSponsorWithAccount(tx, account) {
3028
+ if (tx.auth.authType !== AuthType.Sponsored) {
3029
+ throw new Error("Transaction must be sponsored");
3030
+ }
3031
+ const auth = tx.auth;
3032
+ const sponsorCondition = auth.sponsorSpendingCondition;
3033
+ const originSigHash = getOriginSigHash(tx);
3034
+ const sigHashPre = sigHashPreSign(originSigHash, AuthType.Sponsored, sponsorCondition.fee, sponsorCondition.nonce);
3035
+ const sigBytes = await account.sign(hexToBytes(sigHashPre));
3036
+ const nextSig = bytesToHex(sigBytes);
3037
+ return {
3038
+ ...tx,
3039
+ auth: {
3040
+ ...auth,
3041
+ sponsorSpendingCondition: {
3042
+ ...sponsorCondition,
3043
+ signature: nextSig
3044
+ }
3045
+ }
3046
+ };
3047
+ }
3048
+
3049
+ // src/actions/wallet/sendTransaction.ts
3050
+ async function sendTransaction(client, params) {
3051
+ const hex = bytesToHex(serializeTransaction(params.transaction));
3052
+ const body = { tx: hex };
3053
+ if (params.attachment) {
3054
+ body.attachment = typeof params.attachment === "string" ? params.attachment : bytesToHex(params.attachment);
3055
+ }
3056
+ let data;
3057
+ try {
3058
+ data = await client.request("/v2/transactions", {
3059
+ method: "POST",
3060
+ body,
3061
+ retryCount: 0
3062
+ });
3063
+ } catch (error) {
3064
+ if (error instanceof HttpRequestError && error.details) {
3065
+ try {
3066
+ data = JSON.parse(error.details);
3067
+ } catch {
3068
+ throw error;
3069
+ }
3070
+ } else if (error instanceof TimeoutError) {
3071
+ const txid = getTransactionId(params.transaction);
3072
+ const receipt = await getTransaction(client, { txid }).catch(() => null);
3073
+ if (receipt === null)
3074
+ throw error;
3075
+ data = { txid };
3076
+ } else {
3077
+ throw error;
84
3078
  }
85
- next.extend = bindExtend(next);
86
- return next;
3079
+ }
3080
+ if (data.error) {
3081
+ throw new BroadcastError(data.reason ?? data.error, {
3082
+ reason: data.reason,
3083
+ reasonData: data.reason_data,
3084
+ txid: data.txid ?? getTransactionId(params.transaction)
3085
+ });
3086
+ }
3087
+ const txid = typeof data === "string" ? data.replace(/"/g, "") : data.txid ?? getTransactionId(params.transaction);
3088
+ if (params.wait) {
3089
+ const confirmations = params.wait === true ? 1 : params.wait;
3090
+ const receipt = await waitForTransactionReceipt(client, {
3091
+ txid,
3092
+ confirmations
3093
+ });
3094
+ return { txid, receipt };
3095
+ }
3096
+ return { txid };
3097
+ }
3098
+
3099
+ // src/actions/wallet/nonceManager.ts
3100
+ function jsonRpcSource() {
3101
+ return {
3102
+ get: ({ client, address }) => getNonce(client, { address })
87
3103
  };
88
3104
  }
89
- function createClient(config) {
90
- const transport = config.transport({ chain: config.chain });
91
- const client = {
92
- chain: config.chain,
93
- account: config.account,
94
- transport,
95
- request: transport.request,
96
- nonceManager: config.nonceManager,
97
- extend: null
3105
+ function memoryStore() {
3106
+ const next = new Map;
3107
+ const locks = new Map;
3108
+ function withLock(key, fn) {
3109
+ const prev = locks.get(key) ?? Promise.resolve();
3110
+ const run = prev.then(fn, fn);
3111
+ locks.set(key, run.catch(() => {}));
3112
+ return run;
3113
+ }
3114
+ return {
3115
+ reserve(key, getFloor) {
3116
+ return withLock(key, async () => {
3117
+ let current = next.get(key);
3118
+ if (current === undefined)
3119
+ current = await getFloor();
3120
+ next.set(key, current + 1n);
3121
+ return current;
3122
+ });
3123
+ },
3124
+ reset(key) {
3125
+ next.delete(key);
3126
+ },
3127
+ release(key, nonce) {
3128
+ return withLock(key, async () => {
3129
+ if (next.get(key) === nonce + 1n)
3130
+ next.set(key, nonce);
3131
+ });
3132
+ },
3133
+ peek(key) {
3134
+ return next.get(key);
3135
+ }
98
3136
  };
99
- client.extend = bindExtend(client);
100
- return client;
101
3137
  }
102
- // src/clients/decorators/public.ts
103
- function publicActions(client) {
3138
+ function nonceKey(client, address) {
3139
+ return `${client.chain?.id ?? "stacks"}:${address}`;
3140
+ }
3141
+ function createNonceManager(params = {}) {
3142
+ const source = params.source ?? jsonRpcSource();
3143
+ const store = params.store ?? memoryStore();
104
3144
  return {
105
- getNonce: (params) => getNonce(client, params),
106
- getBalance: (params) => getBalance(client, params),
107
- getAccountInfo: (params) => getAccountInfo(client, params),
108
- getBlock: (params) => getBlock(client, params),
109
- getRawBlock: (params) => getRawBlock(client, params),
110
- getBlockHeight: () => getBlockHeight(client),
111
- readContract: (params) => readContract(client, params),
112
- getContractAbi: (params) => getContractAbi(client, params),
113
- getContractSource: (params) => getContractSource(client, params),
114
- getDataVar: (params) => getDataVar(client, params),
115
- getMapEntry: (params) => getMapEntry(client, params),
116
- estimateFee: (params) => estimateFee(client, params),
117
- multicall: (params) => multicall(client, params),
118
- simulateCall: (params) => simulateCall(client, params),
119
- simulateTransaction: (params) => simulateTransaction(client, params),
120
- getTransaction: (params) => getTransaction(client, params),
121
- getAccountHistory: (params) => getAccountHistory(client, params),
122
- getMempoolStats: () => getMempoolStats(client),
123
- getNftHoldings: (params) => getNftHoldings(client, params),
124
- waitForTransactionReceipt: (params) => waitForTransactionReceipt(client, params),
125
- watchBlocks: (params) => watchBlocks(client, params),
126
- watchMempool: (params) => watchMempool(client, params),
127
- watchTransaction: (params) => watchTransaction(client, params),
128
- watchAddress: (params) => watchAddress(client, params),
129
- watchAddressBalance: (params) => watchAddressBalance(client, params),
130
- watchNftEvent: (params) => watchNftEvent(client, params)
3145
+ consume({ client, address }) {
3146
+ return store.reserve(nonceKey(client, address), () => source.get({ client, address }));
3147
+ },
3148
+ reset({ client, address }) {
3149
+ return store.reset(nonceKey(client, address));
3150
+ },
3151
+ release({ client, address, nonce }) {
3152
+ return store.release?.(nonceKey(client, address), nonce);
3153
+ },
3154
+ async peek({ client, address }) {
3155
+ return store.peek?.(nonceKey(client, address));
3156
+ }
3157
+ };
3158
+ }
3159
+ async function resolveNonce(client, address) {
3160
+ if (client.nonceManager)
3161
+ return client.nonceManager.consume({ client, address });
3162
+ return getNonce(client, { address });
3163
+ }
3164
+ async function releaseNonce(client, address, nonce) {
3165
+ if (!client.nonceManager)
3166
+ return;
3167
+ try {
3168
+ await client.nonceManager.release({ client, address, nonce });
3169
+ } catch {}
3170
+ }
3171
+ async function reconcileNonce(manager, params) {
3172
+ const { client, address, source } = params;
3173
+ const downward = params.downward ?? true;
3174
+ const authoritative = await source.get({ client, address });
3175
+ const tracked = await manager.peek({ client, address });
3176
+ if (tracked === undefined || authoritative === tracked) {
3177
+ return { reset: false, authoritative, tracked };
3178
+ }
3179
+ if (authoritative < tracked && !downward) {
3180
+ return { reset: false, authoritative, tracked };
3181
+ }
3182
+ await manager.reset({ client, address });
3183
+ return { reset: true, authoritative, tracked };
3184
+ }
3185
+ function startNonceReconciler(manager, params) {
3186
+ const { client, addresses, source, clock } = params;
3187
+ const intervalMs = params.intervalMs ?? 60000;
3188
+ let running = true;
3189
+ const tick = async () => {
3190
+ if (!running)
3191
+ return;
3192
+ for (const address of addresses) {
3193
+ try {
3194
+ const result = await reconcileNonce(manager, {
3195
+ client,
3196
+ address,
3197
+ source,
3198
+ downward: params.downward
3199
+ });
3200
+ params.onReconcile?.(address, result);
3201
+ } catch (error) {
3202
+ try {
3203
+ params.onError?.(address, error);
3204
+ } catch {}
3205
+ }
3206
+ }
3207
+ if (running && clock) {
3208
+ await clock.advance(intervalMs);
3209
+ tick();
3210
+ }
3211
+ };
3212
+ if (clock) {
3213
+ tick();
3214
+ return {
3215
+ stop: () => {
3216
+ running = false;
3217
+ }
3218
+ };
3219
+ }
3220
+ const timer = setInterval(tick, intervalMs);
3221
+ timer.unref?.();
3222
+ return {
3223
+ stop: () => clearInterval(timer)
131
3224
  };
132
3225
  }
3226
+ function isNonceConflictError(error) {
3227
+ if (!(error instanceof BroadcastError))
3228
+ return false;
3229
+ if (error.reason === "ConflictingNonceInMempool" || error.reason === "BadNonce") {
3230
+ return true;
3231
+ }
3232
+ if (error.reason !== undefined)
3233
+ return false;
3234
+ return error.message.toLowerCase().includes("nonce");
3235
+ }
3236
+ async function broadcastWithNonceReset(client, params) {
3237
+ try {
3238
+ const result = await sendTransaction(client, {
3239
+ transaction: params.transaction
3240
+ });
3241
+ return result.txid;
3242
+ } catch (error) {
3243
+ if (client.nonceManager && isNonceConflictError(error)) {
3244
+ await client.nonceManager.reset({ client, address: params.address });
3245
+ }
3246
+ throw error;
3247
+ }
3248
+ }
133
3249
 
134
- // src/clients/createPublicClient.ts
135
- function createPublicClient(config) {
136
- return createClient(config).extend(publicActions);
3250
+ // src/actions/wallet/utils.ts
3251
+ function isProviderAccount(account) {
3252
+ return account.type === "provider";
3253
+ }
3254
+ var FEE_TIERS = ["min", "low", "mid", "high"];
3255
+ var TIER_INDEX = { low: 0, mid: 1, high: 2 };
3256
+ function isFeeTier(fee) {
3257
+ return typeof fee === "string" && FEE_TIERS.includes(fee);
3258
+ }
3259
+ function minimumFee(transaction) {
3260
+ return BigInt(serializeTransaction(transaction).length);
3261
+ }
3262
+ function isNoEstimateAvailable(error) {
3263
+ return error instanceof HttpRequestError && error.status === 400 && (error.details?.includes("NoEstimateAvailable") ?? false);
3264
+ }
3265
+ async function resolveFee(client, transaction, fee) {
3266
+ if (fee !== undefined && !isFeeTier(fee))
3267
+ return { fee: intToBigInt(fee) };
3268
+ const tier = fee ?? "mid";
3269
+ if (tier === "min")
3270
+ return { fee: minimumFee(transaction), tier };
3271
+ let estimates;
3272
+ try {
3273
+ estimates = await estimateFee(client, { transaction });
3274
+ } catch (error) {
3275
+ if (!isNoEstimateAvailable(error))
3276
+ throw error;
3277
+ return { fee: minimumFee(transaction), tier: "min" };
3278
+ }
3279
+ const pick = estimates[TIER_INDEX[tier]] ?? estimates[estimates.length - 1];
3280
+ if (pick)
3281
+ return { fee: BigInt(pick.fee), tier };
3282
+ return { fee: minimumFee(transaction), tier: "min" };
3283
+ }
3284
+ function setUnsignedFee(transaction, fee) {
3285
+ transaction.auth.spendingCondition.fee = fee;
3286
+ clearTxCache(transaction);
3287
+ }
3288
+ function assertNoFeeTierForProvider(fee) {
3289
+ if (isFeeTier(fee)) {
3290
+ throw new Error(`Fee tier '${fee}' requires local signing; provider (wallet) accounts set their own fee`);
3291
+ }
3292
+ }
3293
+
3294
+ // src/actions/wallet/callContract.ts
3295
+ async function callContract(client, params) {
3296
+ const account = client.account;
3297
+ if (!account)
3298
+ throw new Error("Account required");
3299
+ const [contractAddress, contractName] = parseContractId(params.contract);
3300
+ if (isProviderAccount(account)) {
3301
+ assertNoFeeTierForProvider(params.fee);
3302
+ const result = await account.provider.request("stx_callContract", {
3303
+ contract: params.contract,
3304
+ functionName: params.functionName,
3305
+ functionArgs: params.functionArgs ?? []
3306
+ });
3307
+ return result.txid;
3308
+ }
3309
+ const managed = params.nonce === undefined && client.nonceManager !== undefined;
3310
+ const nonce = params.nonce ?? await resolveNonce(client, account.address);
3311
+ try {
3312
+ const needsFeeResolution = params.fee === undefined || isFeeTier(params.fee);
3313
+ const unsigned = buildContractCall({
3314
+ contractAddress,
3315
+ contractName,
3316
+ functionName: params.functionName,
3317
+ functionArgs: params.functionArgs ?? [],
3318
+ fee: needsFeeResolution ? 0n : params.fee,
3319
+ nonce,
3320
+ publicKey: account.publicKey,
3321
+ chain: client.chain,
3322
+ postConditionMode: params.postConditionMode,
3323
+ postConditions: params.postConditions
3324
+ });
3325
+ if (needsFeeResolution) {
3326
+ const { fee } = await resolveFee(client, unsigned, params.fee);
3327
+ setUnsignedFee(unsigned, fee);
3328
+ }
3329
+ const signed = await signTransactionWithAccount(unsigned, account);
3330
+ return await broadcastWithNonceReset(client, {
3331
+ transaction: signed,
3332
+ address: account.address
3333
+ });
3334
+ } catch (error) {
3335
+ if (managed)
3336
+ await releaseNonce(client, account.address, nonce);
3337
+ throw error;
3338
+ }
3339
+ }
3340
+
3341
+ // src/actions/wallet/deployContract.ts
3342
+ async function deployContract(client, params) {
3343
+ const account = client.account;
3344
+ if (!account)
3345
+ throw new Error("Account required");
3346
+ if (!isClarityName(params.contractName))
3347
+ throw new Error(`Invalid contract name: ${params.contractName}`);
3348
+ if (isProviderAccount(account)) {
3349
+ assertNoFeeTierForProvider(params.fee);
3350
+ const result = await account.provider.request("stx_deployContract", {
3351
+ contractName: params.contractName,
3352
+ codeBody: params.codeBody,
3353
+ clarityVersion: params.clarityVersion
3354
+ });
3355
+ return result.txid;
3356
+ }
3357
+ const managed = params.nonce === undefined && client.nonceManager !== undefined;
3358
+ const nonce = params.nonce ?? await resolveNonce(client, account.address);
3359
+ try {
3360
+ const needsFeeResolution = params.fee === undefined || isFeeTier(params.fee);
3361
+ const unsigned = buildContractDeploy({
3362
+ contractName: params.contractName,
3363
+ codeBody: params.codeBody,
3364
+ clarityVersion: params.clarityVersion,
3365
+ fee: needsFeeResolution ? 0n : params.fee,
3366
+ nonce,
3367
+ publicKey: account.publicKey,
3368
+ chain: client.chain,
3369
+ postConditionMode: params.postConditionMode,
3370
+ postConditions: params.postConditions
3371
+ });
3372
+ if (needsFeeResolution) {
3373
+ const { fee } = await resolveFee(client, unsigned, params.fee);
3374
+ setUnsignedFee(unsigned, fee);
3375
+ }
3376
+ const signed = await signTransactionWithAccount(unsigned, account);
3377
+ return await broadcastWithNonceReset(client, {
3378
+ transaction: signed,
3379
+ address: account.address
3380
+ });
3381
+ } catch (error) {
3382
+ if (managed)
3383
+ await releaseNonce(client, account.address, nonce);
3384
+ throw error;
3385
+ }
3386
+ }
3387
+
3388
+ // src/actions/wallet/signMessage.ts
3389
+ var import_sha26 = require("@noble/hashes/sha2.js");
3390
+
3391
+ // src/clarity/structuredData.ts
3392
+ var import_sha25 = require("@noble/hashes/sha2.js");
3393
+ var SIP018_PREFIX = new Uint8Array([
3394
+ 83,
3395
+ 73,
3396
+ 80,
3397
+ 48,
3398
+ 49,
3399
+ 56
3400
+ ]);
3401
+ function hashStructuredData(structuredData) {
3402
+ return import_sha25.sha256(serializeCVBytes(structuredData));
3403
+ }
3404
+ function isDomain(value) {
3405
+ if (value.type !== "tuple")
3406
+ return false;
3407
+ const { name, version, "chain-id": chainId } = value.value;
3408
+ return name?.type === "ascii" && version?.type === "ascii" && chainId?.type === "uint";
3409
+ }
3410
+ function encodeStructuredData(opts) {
3411
+ if (!isDomain(opts.domain)) {
3412
+ throw new Error("domain must be a tuple { name: ascii, version: ascii, chain-id: uint }");
3413
+ }
3414
+ return concatBytes(SIP018_PREFIX, hashStructuredData(opts.domain), hashStructuredData(opts.message));
3415
+ }
3416
+ function structuredDataHash(opts) {
3417
+ return import_sha25.sha256(encodeStructuredData(opts));
3418
+ }
3419
+ async function signStructuredData(account, opts) {
3420
+ const vrs = await account.sign(structuredDataHash(opts));
3421
+ if (vrs.length !== 65) {
3422
+ throw new Error(`Expected 65-byte recoverable signature, got ${vrs.length}`);
3423
+ }
3424
+ return bytesToHex(concatBytes(vrs.slice(1), vrs.slice(0, 1)));
3425
+ }
3426
+
3427
+ // src/actions/wallet/signMessage.ts
3428
+ async function signMessage(client, params) {
3429
+ const account = client.account;
3430
+ if (!account)
3431
+ throw new Error("Account required");
3432
+ if (isProviderAccount(account)) {
3433
+ const method = params.domain ? "stx_signStructuredMessage" : "stx_signMessage";
3434
+ const result = await account.provider.request(method, {
3435
+ message: params.message,
3436
+ domain: params.domain
3437
+ });
3438
+ return result.signature;
3439
+ }
3440
+ const cv = typeof params.message === "string" ? Cl.stringAscii(params.message) : params.message;
3441
+ const hash = params.domain ? structuredDataHash({
3442
+ message: cv,
3443
+ domain: Cl.tuple({
3444
+ name: Cl.stringAscii(params.domain.name),
3445
+ version: Cl.stringAscii(params.domain.version),
3446
+ "chain-id": Cl.uint(params.domain.chainId)
3447
+ })
3448
+ }) : import_sha26.sha256(serializeCVBytes(cv));
3449
+ const sigBytes = await account.sign(hash);
3450
+ return bytesToHex(sigBytes);
3451
+ }
3452
+
3453
+ // src/actions/wallet/signTransaction.ts
3454
+ async function signTransactionAction(client, params) {
3455
+ const account = client.account;
3456
+ if (!account)
3457
+ throw new Error("Account required");
3458
+ if (isProviderAccount(account)) {
3459
+ const hex = serializeTransactionHex(params.transaction);
3460
+ const result = await account.provider.request("stx_signTransaction", {
3461
+ transaction: hex
3462
+ });
3463
+ return deserializeTransaction(result.transaction, {
3464
+ _multisig: params.transaction._multisig
3465
+ });
3466
+ }
3467
+ const condition = params.transaction.auth.spendingCondition;
3468
+ if ("fields" in condition) {
3469
+ const publicKeys = params.signers ?? params.transaction._multisig?.publicKeys;
3470
+ if (!publicKeys)
3471
+ throw new Error("Multi-sig signing requires signers (publicKeys)");
3472
+ return signMultiSigWithAccount(params.transaction, account, publicKeys);
3473
+ }
3474
+ return signTransactionWithAccount(params.transaction, account);
137
3475
  }
3476
+
3477
+ // src/actions/wallet/sponsorTransaction.ts
3478
+ async function sponsorTransaction(client, params) {
3479
+ const { transaction } = params;
3480
+ if (transaction.auth.authType !== AuthType.Sponsored) {
3481
+ throw new Error("Transaction must have sponsored authorization");
3482
+ }
3483
+ const account = client.account;
3484
+ if (!account)
3485
+ throw new Error("Account required");
3486
+ if (isProviderAccount(account)) {
3487
+ throw new Error("Provider accounts cannot sponsor transactions");
3488
+ }
3489
+ const managed = params.nonce == null && client.nonceManager !== undefined;
3490
+ const nonce = params.nonce != null ? intToBigInt(params.nonce) : await resolveNonce(client, account.address);
3491
+ let fee;
3492
+ try {
3493
+ ({ fee } = await resolveFee(client, transaction, params.fee));
3494
+ } catch (error) {
3495
+ if (managed)
3496
+ await releaseNonce(client, account.address, nonce);
3497
+ throw error;
3498
+ }
3499
+ const sponsorCondition = createSingleSigSpendingCondition(account.publicKey, nonce, fee);
3500
+ const auth = transaction.auth;
3501
+ const sponsored = {
3502
+ ...transaction,
3503
+ auth: {
3504
+ ...auth,
3505
+ sponsorSpendingCondition: sponsorCondition
3506
+ }
3507
+ };
3508
+ return signSponsorWithAccount(sponsored, account);
3509
+ }
3510
+
3511
+ // src/actions/wallet/transferStx.ts
3512
+ async function transferStx(client, params) {
3513
+ const account = client.account;
3514
+ if (!account)
3515
+ throw new Error("Account required");
3516
+ if (!validateStacksAddress(params.to))
3517
+ throw new Error(`Invalid recipient address: ${params.to}`);
3518
+ if (isProviderAccount(account)) {
3519
+ assertNoFeeTierForProvider(params.fee);
3520
+ const result = await account.provider.request("stx_transferStx", {
3521
+ recipient: params.to,
3522
+ amount: String(params.amount),
3523
+ memo: params.memo
3524
+ });
3525
+ return result.txid;
3526
+ }
3527
+ const managed = params.nonce === undefined && client.nonceManager !== undefined;
3528
+ const nonce = params.nonce ?? await resolveNonce(client, account.address);
3529
+ try {
3530
+ const needsFeeResolution = params.fee === undefined || isFeeTier(params.fee);
3531
+ const unsigned = buildTokenTransfer({
3532
+ recipient: params.to,
3533
+ amount: params.amount,
3534
+ memo: params.memo,
3535
+ fee: needsFeeResolution ? 0n : params.fee,
3536
+ nonce,
3537
+ publicKey: account.publicKey,
3538
+ chain: client.chain,
3539
+ postConditionMode: params.postConditionMode,
3540
+ postConditions: params.postConditions
3541
+ });
3542
+ if (needsFeeResolution) {
3543
+ const { fee } = await resolveFee(client, unsigned, params.fee);
3544
+ setUnsignedFee(unsigned, fee);
3545
+ }
3546
+ const signed = await signTransactionWithAccount(unsigned, account);
3547
+ return await broadcastWithNonceReset(client, {
3548
+ transaction: signed,
3549
+ address: account.address
3550
+ });
3551
+ } catch (error) {
3552
+ if (managed)
3553
+ await releaseNonce(client, account.address, nonce);
3554
+ throw error;
3555
+ }
3556
+ }
3557
+
138
3558
  // src/clients/decorators/wallet.ts
139
3559
  function walletActions(client) {
140
3560
  return {
@@ -158,7 +3578,7 @@ function multisigActions(client) {
158
3578
  if (!msConfig)
159
3579
  throw new Error("multisigActions requires a multi-sig client");
160
3580
  const { signers, requiredSignatures, hashMode } = msConfig;
161
- async function resolveNonce2(nonce) {
3581
+ async function resolveNonce(nonce) {
162
3582
  if (nonce !== undefined)
163
3583
  return nonce;
164
3584
  const address = makeMultiSigAddress(signers, requiredSignatures, client.chain);
@@ -168,7 +3588,7 @@ function multisigActions(client) {
168
3588
  }
169
3589
  return {
170
3590
  async transferStx(params) {
171
- const nonce = await resolveNonce2(params.nonce);
3591
+ const nonce = await resolveNonce(params.nonce);
172
3592
  const unsigned = buildTokenTransfer({
173
3593
  recipient: params.to,
174
3594
  amount: params.amount,
@@ -193,7 +3613,7 @@ function multisigActions(client) {
193
3613
  },
194
3614
  async callContract(params) {
195
3615
  const [contractAddress, contractName] = parseContractId(params.contract);
196
- const nonce = await resolveNonce2(params.nonce);
3616
+ const nonce = await resolveNonce(params.nonce);
197
3617
  const unsigned = buildContractCall({
198
3618
  contractAddress,
199
3619
  contractName,
@@ -218,7 +3638,7 @@ function multisigActions(client) {
218
3638
  return unsigned;
219
3639
  },
220
3640
  async deployContract(params) {
221
- const nonce = await resolveNonce2(params.nonce);
3641
+ const nonce = await resolveNonce(params.nonce);
222
3642
  const unsigned = buildContractDeploy({
223
3643
  contractName: params.contractName,
224
3644
  codeBody: params.codeBody,
@@ -357,7 +3777,7 @@ function resolveFetch(fetchImpl) {
357
3777
  return f;
358
3778
  }
359
3779
  function nextFreeNonce(confirmed, pending) {
360
- const taken = new Set(pending.filter((n2) => n2 >= confirmed).map((n2) => n2.toString()));
3780
+ const taken = new Set(pending.filter((n) => n >= confirmed).map((n) => n.toString()));
361
3781
  let n = confirmed;
362
3782
  while (taken.has(n.toString()))
363
3783
  n += 1n;
@@ -714,6 +4134,460 @@ function webSocket(url, config) {
714
4134
  return transport;
715
4135
  };
716
4136
  }
4137
+ // src/filters/index.ts
4138
+ var exports_filters = {};
4139
+ __export(exports_filters, {
4140
+ CHAIN_EVENT_FILTER_TYPES: () => CHAIN_EVENT_FILTER_TYPES,
4141
+ DECODED_EVENT_TYPES: () => DECODED_EVENT_TYPES,
4142
+ VM_EVENT_TYPES: () => VM_EVENT_TYPES,
4143
+ VM_NODE_TO_STORED_TYPE: () => VM_NODE_TO_STORED_TYPE,
4144
+ assertAssetIdentifier: () => assertAssetIdentifier,
4145
+ assertContractId: () => assertContractId,
4146
+ assertPrincipalish: () => assertPrincipalish,
4147
+ assetId: () => assetId,
4148
+ fromSubgraphSource: () => fromSubgraphSource,
4149
+ hasWildcard: () => hasWildcard,
4150
+ isPrincipal: () => isPrincipal,
4151
+ makeChainEventFilter: () => makeChainEventFilter,
4152
+ on: () => on
4153
+ });
4154
+
4155
+ // src/filters/event-types.ts
4156
+ var DECODED_EVENT_TYPES = [
4157
+ "stx_transfer",
4158
+ "stx_mint",
4159
+ "stx_burn",
4160
+ "stx_lock",
4161
+ "ft_transfer",
4162
+ "ft_mint",
4163
+ "ft_burn",
4164
+ "nft_transfer",
4165
+ "nft_mint",
4166
+ "nft_burn",
4167
+ "print"
4168
+ ];
4169
+ var VM_EVENT_TYPES = [
4170
+ "nested_contract_call",
4171
+ "var_set",
4172
+ "map_set",
4173
+ "map_insert",
4174
+ "map_delete"
4175
+ ];
4176
+ var VM_NODE_TO_STORED_TYPE = {
4177
+ contract_call_event: "nested_contract_call",
4178
+ var_set_event: "var_set",
4179
+ map_set_event: "map_set",
4180
+ map_insert_event: "map_insert",
4181
+ map_delete_event: "map_delete"
4182
+ };
4183
+ var CHAIN_EVENT_FILTER_TYPES = [
4184
+ "stx_transfer",
4185
+ "stx_mint",
4186
+ "stx_burn",
4187
+ "stx_lock",
4188
+ "ft_transfer",
4189
+ "ft_mint",
4190
+ "ft_burn",
4191
+ "nft_transfer",
4192
+ "nft_mint",
4193
+ "nft_burn",
4194
+ "contract_call",
4195
+ "contract_deploy",
4196
+ "print_event",
4197
+ "nested_contract_call",
4198
+ "var_set",
4199
+ "map_set",
4200
+ "map_insert",
4201
+ "map_delete",
4202
+ "sbtc_deposit",
4203
+ "sbtc_withdrawal_create",
4204
+ "sbtc_withdrawal_accept",
4205
+ "sbtc_withdrawal_reject",
4206
+ "sbtc_withdrawal_swept_confirmed"
4207
+ ];
4208
+ // src/filters/validate.ts
4209
+ function assetId(value) {
4210
+ assertAssetIdentifier("assetIdentifier", value);
4211
+ return value;
4212
+ }
4213
+ function isPrincipal(value) {
4214
+ return parsePrincipal(value) !== null;
4215
+ }
4216
+ function hasWildcard(value) {
4217
+ return value.includes("*");
4218
+ }
4219
+ function assertPrincipalish(field, value) {
4220
+ if (hasWildcard(value))
4221
+ return;
4222
+ if (!isPrincipal(value)) {
4223
+ throw new Error(`${field} "${value}" is not a valid Stacks principal (SP…/ST…, optionally .contract-name).`);
4224
+ }
4225
+ }
4226
+ function assertAssetIdentifier(field, value) {
4227
+ if (hasWildcard(value))
4228
+ return;
4229
+ const [contractId, assetName, ...rest] = value.split("::");
4230
+ if (!contractId || !assetName || rest.length > 0 || !contractId.includes(".") || !isPrincipal(contractId)) {
4231
+ throw new Error(`${field} "${value}" is not a valid asset identifier (SP….contract-name::asset-name). Passing a bare contract id here matches zero rows — use contractId for that.`);
4232
+ }
4233
+ }
4234
+ function assertContractId(field, value) {
4235
+ if (hasWildcard(value))
4236
+ return;
4237
+ if (value.includes("::")) {
4238
+ throw new Error(`${field} "${value}" is an asset identifier, not a contract id — use assetIdentifier for that.`);
4239
+ }
4240
+ if (!value.includes(".") || !isPrincipal(value)) {
4241
+ throw new Error(`${field} "${value}" is not a valid contract id (SP….contract-name).`);
4242
+ }
4243
+ }
4244
+
4245
+ // src/filters/factories.ts
4246
+ var PRINCIPAL_FIELDS = new Set([
4247
+ "sender",
4248
+ "recipient",
4249
+ "caller",
4250
+ "deployer",
4251
+ "lockedAddress"
4252
+ ]);
4253
+ var AMOUNT_FIELDS = new Set(["minAmount", "maxAmount"]);
4254
+ var DECORATIVE_FIELDS = new Set(["abi", "prints"]);
4255
+ function specEntries(spec) {
4256
+ return Object.entries(spec).filter(([key, value]) => key !== "type" && value !== undefined);
4257
+ }
4258
+ function validateSpec(spec) {
4259
+ for (const [key, value] of specEntries(spec)) {
4260
+ if (PRINCIPAL_FIELDS.has(key)) {
4261
+ assertPrincipalish(key, value);
4262
+ } else if (key === "assetIdentifier") {
4263
+ assertAssetIdentifier(key, value);
4264
+ } else if (key === "contractId") {
4265
+ for (const id of Array.isArray(value) ? value : [value]) {
4266
+ assertContractId(key, id);
4267
+ }
4268
+ }
4269
+ }
4270
+ }
4271
+ function unsupported(surface, field, hint) {
4272
+ throw new Error(`${field} cannot be expressed on ${surface} — ${hint}. Drop the field from the filter or use the surface that supports it.`);
4273
+ }
4274
+ function assertNoWildcards(surface, spec) {
4275
+ for (const [key, value] of specEntries(spec)) {
4276
+ const candidates = Array.isArray(value) ? value : [value];
4277
+ for (const candidate of candidates) {
4278
+ if (typeof candidate === "string" && hasWildcard(candidate)) {
4279
+ unsupported(surface, `${key} wildcard "${candidate}"`, "wildcard patterns are Webhooks/Subgraphs-only");
4280
+ }
4281
+ }
4282
+ }
4283
+ }
4284
+ function assertNotTraitAndContract(surface, spec) {
4285
+ const trait = "trait" in spec ? spec.trait : undefined;
4286
+ const contract = "contractId" in spec ? spec.contractId : undefined;
4287
+ if (trait !== undefined && contract !== undefined) {
4288
+ unsupported(surface, "trait with contractId", "the Index treats them as mutually exclusive — drop one, or use a subgraph source, which ANDs the pair");
4289
+ }
4290
+ }
4291
+ function toChainTrigger(spec) {
4292
+ const out = {};
4293
+ for (const [key, value] of specEntries(spec)) {
4294
+ if (DECORATIVE_FIELDS.has(key))
4295
+ continue;
4296
+ if (key === "factory") {
4297
+ unsupported("Webhooks", "factory", "dynamic factory discovery is a Subgraphs-only concept — a trigger targets addresses known when it is created");
4298
+ }
4299
+ if (Array.isArray(value)) {
4300
+ unsupported("Webhooks", `${key} set`, "a chain trigger targets ONE contract — create one subscription per contract, or use Index/Subgraphs which accept the set");
4301
+ }
4302
+ out[key] = typeof value === "bigint" ? value.toString() : value;
4303
+ }
4304
+ return { type: spec.type, ...out };
4305
+ }
4306
+ function toIndexParams(spec, extra = {}) {
4307
+ assertNoWildcards("Index events", spec);
4308
+ assertNotTraitAndContract("Index events", spec);
4309
+ const out = {
4310
+ eventType: spec.type === "print_event" ? "print" : spec.type
4311
+ };
4312
+ for (const [key, value] of specEntries(spec)) {
4313
+ if (DECORATIVE_FIELDS.has(key))
4314
+ continue;
4315
+ if (key === "factory") {
4316
+ unsupported("Index events", "factory", "dynamic factory discovery is a Subgraphs-only concept");
4317
+ }
4318
+ if (AMOUNT_FIELDS.has(key)) {
4319
+ unsupported("Index events", key, "amount predicates are Webhooks/Subgraphs-only; filter client-side on the decoded rows");
4320
+ }
4321
+ if (key === "topic") {
4322
+ unsupported("Index events", "topic", "per-topic reads are Subgraphs/Webhooks-only (or read the contract's print feed and switch on topic)");
4323
+ }
4324
+ if (key === "lockedAddress") {
4325
+ out.sender = value;
4326
+ continue;
4327
+ }
4328
+ if (key === "caller" && spec.type !== "nested_contract_call") {
4329
+ unsupported("Index events", "caller", "outer contract-call fields live on index.contractCalls");
4330
+ }
4331
+ out[key] = value;
4332
+ }
4333
+ return { ...out, ...extra };
4334
+ }
4335
+ var VM_MEMBERS = new Set([
4336
+ "nested_contract_call",
4337
+ "var_set",
4338
+ "map_set",
4339
+ "map_insert",
4340
+ "map_delete"
4341
+ ]);
4342
+ var VM_INDEX_ONLY_FIELDS = new Set([
4343
+ "functionName",
4344
+ "caller",
4345
+ "sender",
4346
+ "map",
4347
+ "varName"
4348
+ ]);
4349
+ function toStreamsParams(spec, extra = {}) {
4350
+ assertNoWildcards("Streams", spec);
4351
+ const out = {
4352
+ types: [spec.type === "print_event" ? "print" : spec.type]
4353
+ };
4354
+ const isVm = VM_MEMBERS.has(spec.type);
4355
+ if (isVm)
4356
+ out.clock = "vm";
4357
+ for (const [key, value] of specEntries(spec)) {
4358
+ if (DECORATIVE_FIELDS.has(key))
4359
+ continue;
4360
+ if (isVm && VM_INDEX_ONLY_FIELDS.has(key)) {
4361
+ unsupported("Streams", key, "vm payload predicates are Index/Subgraphs/Subscriptions-only; Streams clock=vm narrows by types and contractId");
4362
+ }
4363
+ if (key === "factory") {
4364
+ unsupported("Streams", "factory", "dynamic factory discovery is a Subgraphs-only concept");
4365
+ }
4366
+ if (AMOUNT_FIELDS.has(key)) {
4367
+ unsupported("Streams", key, "amount predicates are Webhooks/Subgraphs-only");
4368
+ }
4369
+ if (key === "trait") {
4370
+ unsupported("Streams", "trait", "Streams has no trait resolution — Index and Subgraphs do");
4371
+ }
4372
+ if (key === "topic") {
4373
+ unsupported("Streams", "topic", "per-topic filtering is Subgraphs/Webhooks-only");
4374
+ }
4375
+ if (key === "lockedAddress") {
4376
+ unsupported("Streams", "lockedAddress", "stx_lock address filtering is Webhooks/Subgraphs-only");
4377
+ }
4378
+ out[key] = value;
4379
+ }
4380
+ return { ...out, ...extra };
4381
+ }
4382
+ function toContractCallsParams(spec, extra = {}) {
4383
+ assertNoWildcards("Index contract-calls", spec);
4384
+ assertNotTraitAndContract("Index contract-calls", spec);
4385
+ const out = {};
4386
+ for (const [key, value] of specEntries(spec)) {
4387
+ if (DECORATIVE_FIELDS.has(key))
4388
+ continue;
4389
+ if (key === "factory") {
4390
+ unsupported("Index contract-calls", "factory", "dynamic factory discovery is a Subgraphs-only concept");
4391
+ }
4392
+ if (key === "caller") {
4393
+ out.sender = value;
4394
+ continue;
4395
+ }
4396
+ out[key] = value;
4397
+ }
4398
+ return { ...out, ...extra };
4399
+ }
4400
+ function toSubgraphSource(spec) {
4401
+ return Object.fromEntries([
4402
+ ["type", spec.type],
4403
+ ...specEntries(spec)
4404
+ ]);
4405
+ }
4406
+ var DECODED_MEMBERS = new Set([
4407
+ "stx_transfer",
4408
+ "stx_mint",
4409
+ "stx_burn",
4410
+ "stx_lock",
4411
+ "ft_transfer",
4412
+ "ft_mint",
4413
+ "ft_burn",
4414
+ "nft_transfer",
4415
+ "nft_mint",
4416
+ "nft_burn",
4417
+ "print_event"
4418
+ ]);
4419
+ function makeChainEventFilter(type, fields) {
4420
+ const spec = { type, ...fields };
4421
+ validateSpec(spec);
4422
+ const filter = { ...spec };
4423
+ filter.toChainTrigger = () => toChainTrigger(spec);
4424
+ if (DECODED_MEMBERS.has(type) || VM_MEMBERS.has(type)) {
4425
+ filter.toIndexParams = (extra) => toIndexParams(spec, extra);
4426
+ filter.toStreamsParams = (extra) => toStreamsParams(spec, extra);
4427
+ }
4428
+ if (type === "contract_call") {
4429
+ filter.toContractCallsParams = (extra) => toContractCallsParams(spec, extra);
4430
+ }
4431
+ if (!type.startsWith("sbtc_")) {
4432
+ filter.toSubgraphSource = () => toSubgraphSource(spec);
4433
+ }
4434
+ return filter;
4435
+ }
4436
+ function fromSubgraphSource(source) {
4437
+ const { type, ...fields } = source;
4438
+ return makeChainEventFilter(type, fields);
4439
+ }
4440
+ var on = {
4441
+ stxTransfer: (fields = {}) => makeChainEventFilter("stx_transfer", fields),
4442
+ stxMint: (fields = {}) => makeChainEventFilter("stx_mint", fields),
4443
+ stxBurn: (fields = {}) => makeChainEventFilter("stx_burn", fields),
4444
+ stxLock: (fields = {}) => makeChainEventFilter("stx_lock", fields),
4445
+ ftTransfer: (fields = {}) => makeChainEventFilter("ft_transfer", fields),
4446
+ ftMint: (fields = {}) => makeChainEventFilter("ft_mint", fields),
4447
+ ftBurn: (fields = {}) => makeChainEventFilter("ft_burn", fields),
4448
+ nftTransfer: (fields = {}) => makeChainEventFilter("nft_transfer", fields),
4449
+ nftMint: (fields = {}) => makeChainEventFilter("nft_mint", fields),
4450
+ nftBurn: (fields = {}) => makeChainEventFilter("nft_burn", fields),
4451
+ contractCall: (fields = {}) => makeChainEventFilter("contract_call", fields),
4452
+ contractDeploy: (fields = {}) => makeChainEventFilter("contract_deploy", fields),
4453
+ print: (fields = {}) => makeChainEventFilter("print_event", fields),
4454
+ nestedCall: (fields = {}) => makeChainEventFilter("nested_contract_call", fields),
4455
+ varSet: (fields = {}) => makeChainEventFilter("var_set", fields),
4456
+ mapSet: (fields = {}) => makeChainEventFilter("map_set", fields),
4457
+ mapInsert: (fields = {}) => makeChainEventFilter("map_insert", fields),
4458
+ mapDelete: (fields = {}) => makeChainEventFilter("map_delete", fields),
4459
+ sbtcDeposit: (fields = {}) => makeChainEventFilter("sbtc_deposit", fields),
4460
+ sbtcWithdrawalCreate: (fields = {}) => makeChainEventFilter("sbtc_withdrawal_create", fields),
4461
+ sbtcWithdrawalAccept: (fields = {}) => makeChainEventFilter("sbtc_withdrawal_accept", fields),
4462
+ sbtcWithdrawalReject: (fields = {}) => makeChainEventFilter("sbtc_withdrawal_reject", fields),
4463
+ sbtcWithdrawalSweptConfirmed: (fields = {}) => makeChainEventFilter("sbtc_withdrawal_swept_confirmed", fields)
4464
+ };
4465
+ // src/accounts/providerToAccount.ts
4466
+ async function providerToAccount(provider) {
4467
+ const result = await provider.request("stx_getAddresses");
4468
+ const entry = result?.addresses?.[0];
4469
+ if (!entry?.address || !entry?.publicKey) {
4470
+ throw new Error("Provider did not return a valid address");
4471
+ }
4472
+ return {
4473
+ type: "provider",
4474
+ address: entry.address,
4475
+ publicKey: entry.publicKey,
4476
+ provider
4477
+ };
4478
+ }
4479
+ // src/chains/definitions.ts
4480
+ var mainnet = {
4481
+ id: 1,
4482
+ name: "Stacks Mainnet",
4483
+ network: "mainnet",
4484
+ transactionVersion: 0,
4485
+ peerNetworkId: 385875968,
4486
+ addressVersion: { singleSig: 22, multiSig: 20 },
4487
+ magicBytes: "X2",
4488
+ bootAddress: "SP000000000000000000002Q6VF78",
4489
+ nativeCurrency: { name: "Stacks", symbol: "STX", decimals: 6 },
4490
+ rpcUrls: {
4491
+ default: {
4492
+ http: ["https://api.mainnet.hiro.so"],
4493
+ ws: ["wss://api.mainnet.hiro.so/extended/v1/ws"]
4494
+ }
4495
+ },
4496
+ blockExplorers: {
4497
+ default: { name: "Hiro Explorer", url: "https://explorer.hiro.so" }
4498
+ }
4499
+ };
4500
+ var testnet = {
4501
+ id: 2147483648,
4502
+ name: "Stacks Testnet",
4503
+ network: "testnet",
4504
+ transactionVersion: 128,
4505
+ peerNetworkId: 4278190080,
4506
+ addressVersion: { singleSig: 26, multiSig: 21 },
4507
+ magicBytes: "T2",
4508
+ bootAddress: "ST000000000000000000002AMW42H",
4509
+ nativeCurrency: { name: "Stacks", symbol: "STX", decimals: 6 },
4510
+ rpcUrls: {
4511
+ default: {
4512
+ http: ["https://api.testnet.hiro.so"],
4513
+ ws: ["wss://api.testnet.hiro.so/extended/v1/ws"]
4514
+ }
4515
+ },
4516
+ blockExplorers: {
4517
+ default: {
4518
+ name: "Hiro Explorer",
4519
+ url: "https://explorer.hiro.so/?chain=testnet"
4520
+ }
4521
+ }
4522
+ };
4523
+ var devnet = {
4524
+ id: 2147483648,
4525
+ name: "Stacks Devnet",
4526
+ network: "testnet",
4527
+ transactionVersion: 128,
4528
+ peerNetworkId: 4278190080,
4529
+ addressVersion: { singleSig: 26, multiSig: 21 },
4530
+ magicBytes: "id",
4531
+ bootAddress: "ST000000000000000000002AMW42H",
4532
+ nativeCurrency: { name: "Stacks", symbol: "STX", decimals: 6 },
4533
+ rpcUrls: {
4534
+ default: {
4535
+ http: ["http://localhost:3999"],
4536
+ ws: ["ws://localhost:3999/extended/v1/ws"]
4537
+ }
4538
+ }
4539
+ };
4540
+ var mocknet = {
4541
+ ...devnet,
4542
+ name: "Stacks Mocknet",
4543
+ addressVersion: { ...devnet.addressVersion }
4544
+ };
4545
+ // src/chains/defineChain.ts
4546
+ function defineChain(chain) {
4547
+ return chain;
4548
+ }
4549
+ // src/utils/units.ts
4550
+ function formatUnits(value, decimals) {
4551
+ let v = BigInt(value);
4552
+ const negative = v < 0n;
4553
+ if (negative)
4554
+ v = -v;
4555
+ const divisor = 10n ** BigInt(decimals);
4556
+ const integer = (v / divisor).toString();
4557
+ let fraction = (v % divisor).toString().padStart(decimals, "0");
4558
+ fraction = fraction.replace(/0+$/, "") || "0";
4559
+ const result = `${integer}.${fraction}`;
4560
+ return negative ? `-${result}` : result;
4561
+ }
4562
+ var DECIMAL_STRING = /^-?\d+(\.\d+)?$/;
4563
+ function parseUnits(value, decimals) {
4564
+ if (typeof value === "number" && !Number.isFinite(value)) {
4565
+ throw new RangeError(`Cannot parse ${value} as a decimal amount`);
4566
+ }
4567
+ let str = typeof value === "number" ? value.toFixed(decimals) : value.trim();
4568
+ if (!DECIMAL_STRING.test(str)) {
4569
+ throw new RangeError(`Cannot parse "${value}" as a decimal amount: expected digits with an optional fraction, like "1.5"`);
4570
+ }
4571
+ if (typeof value === "number" && Number(str) !== value) {
4572
+ throw new RangeError(`Cannot parse ${value} with ${decimals} decimals: pass the amount as a string to keep every digit`);
4573
+ }
4574
+ const negative = str.startsWith("-");
4575
+ if (negative)
4576
+ str = str.slice(1);
4577
+ const [integer = "", fraction = ""] = str.split(".");
4578
+ if (fraction.length > decimals) {
4579
+ throw new Error(`Too many decimal places: "${value}" has ${fraction.length} decimals, max is ${decimals}`);
4580
+ }
4581
+ const padded = fraction.padEnd(decimals, "0");
4582
+ const result = BigInt(integer + padded);
4583
+ return negative ? -result : result;
4584
+ }
4585
+ function formatStx(microStx) {
4586
+ return formatUnits(microStx, 6);
4587
+ }
4588
+ function parseStx(stx) {
4589
+ return parseUnits(stx, 6);
4590
+ }
717
4591
 
718
- //# debugId=7288BF2DFC74BFCE64756E2164756E21
4592
+ //# debugId=BBEDE03C59EADB7164756E2164756E21
719
4593
  //# sourceMappingURL=index.cjs.map