@secondlayer/stacks 5.1.3 → 6.1.0

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