@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,1728 @@
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/postconditions/index.ts
65
+ var exports_postconditions = {};
66
+ __export(exports_postconditions, {
67
+ wireToPostCondition: () => wireToPostCondition,
68
+ postConditionToHex: () => postConditionToHex,
69
+ parsePostConditionAmount: () => parsePostConditionAmount,
70
+ fromHex: () => fromHex,
71
+ Pc: () => Pc
72
+ });
73
+ module.exports = __toCommonJS(exports_postconditions);
74
+
75
+ // src/utils/c32.ts
76
+ var import_sha2 = require("@noble/hashes/sha2.js");
77
+
78
+ // src/utils/encoding.ts
79
+ var hexes = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
80
+ function bytesToHex(bytes) {
81
+ let hex = "";
82
+ for (const b of bytes) {
83
+ hex += hexes[b];
84
+ }
85
+ return hex;
86
+ }
87
+ function hexToBytes(hex) {
88
+ let h = without0x(hex);
89
+ if (h.length % 2)
90
+ h = `0${h}`;
91
+ const array = new Uint8Array(h.length / 2);
92
+ for (let i = 0;i < array.length; i++) {
93
+ const j = i * 2;
94
+ const byte = Number.parseInt(h.slice(j, j + 2), 16);
95
+ if (Number.isNaN(byte) || byte < 0)
96
+ throw new Error("Invalid byte sequence");
97
+ array[i] = byte;
98
+ }
99
+ return array;
100
+ }
101
+ function with0x(value) {
102
+ return /^0x/i.test(value) ? value : `0x${value}`;
103
+ }
104
+ function without0x(value) {
105
+ return /^0x/i.test(value) ? value.slice(2) : value;
106
+ }
107
+ function utf8ToBytes(str) {
108
+ return new TextEncoder().encode(str);
109
+ }
110
+ function bytesToUtf8(bytes) {
111
+ return new TextDecoder().decode(bytes);
112
+ }
113
+ function asciiToBytes(str) {
114
+ const bytes = new Uint8Array(str.length);
115
+ for (let i = 0;i < str.length; i++) {
116
+ bytes[i] = str.charCodeAt(i) & 255;
117
+ }
118
+ return bytes;
119
+ }
120
+ function bytesToAscii(bytes) {
121
+ return String.fromCharCode(...bytes);
122
+ }
123
+ function concatBytes(...arrays) {
124
+ if (arrays.length === 1)
125
+ return arrays[0];
126
+ const length = arrays.reduce((a, arr) => a + arr.length, 0);
127
+ const result = new Uint8Array(length);
128
+ let pad = 0;
129
+ for (const arr of arrays) {
130
+ result.set(arr, pad);
131
+ pad += arr.length;
132
+ }
133
+ return result;
134
+ }
135
+ function intToBigInt(value) {
136
+ if (typeof value === "bigint")
137
+ return value;
138
+ if (typeof value === "string")
139
+ return BigInt(value);
140
+ if (typeof value === "number") {
141
+ if (!Number.isInteger(value))
142
+ throw new RangeError("Values of type 'number' must be an integer.");
143
+ if (value > Number.MAX_SAFE_INTEGER)
144
+ throw new RangeError(`Values of type 'number' must be <= ${Number.MAX_SAFE_INTEGER}. Use BigInt instead.`);
145
+ return BigInt(value);
146
+ }
147
+ if (value instanceof Uint8Array)
148
+ return BigInt(`0x${bytesToHex(value)}`);
149
+ throw new TypeError("Must be a number, bigint, string, or Uint8Array.");
150
+ }
151
+ function intToBytes(value, byteLength) {
152
+ return bigIntToBytes(intToBigInt(value), byteLength);
153
+ }
154
+ function bigIntToBytes(value, length = 16) {
155
+ const hex = value.toString(16).padStart(length * 2, "0");
156
+ return hexToBytes(hex);
157
+ }
158
+ function intToHex(integer, byteLength = 8) {
159
+ const value = typeof integer === "bigint" ? integer : intToBigInt(integer);
160
+ return value.toString(16).padStart(byteLength * 2, "0");
161
+ }
162
+ function toTwos(value, width) {
163
+ const limit = BigInt(1) << width - BigInt(1);
164
+ if (value < -limit || value > limit - BigInt(1)) {
165
+ throw new Error(`Unable to represent integer in width: ${width}`);
166
+ }
167
+ if (value >= BigInt(0))
168
+ return value;
169
+ return value + (BigInt(1) << width);
170
+ }
171
+ function fromTwos(value, width) {
172
+ if (value & BigInt(1) << width - BigInt(1)) {
173
+ return value - (BigInt(1) << width);
174
+ }
175
+ return value;
176
+ }
177
+ function bytesToTwosBigInt(bytes) {
178
+ if (bytes.length === 0)
179
+ return 0n;
180
+ const hex = bytesToHex(bytes);
181
+ if (hex.length === 0)
182
+ return 0n;
183
+ return fromTwos(BigInt(`0x${hex}`), BigInt(bytes.byteLength * 8));
184
+ }
185
+ function writeUInt32BE(value) {
186
+ const buf = new Uint8Array(4);
187
+ buf[0] = value >>> 24 & 255;
188
+ buf[1] = value >>> 16 & 255;
189
+ buf[2] = value >>> 8 & 255;
190
+ buf[3] = value & 255;
191
+ return buf;
192
+ }
193
+ function readUInt32BE(bytes, offset = 0) {
194
+ return (bytes[offset] << 24 | bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3]) >>> 0;
195
+ }
196
+ function writeUInt16BE(value) {
197
+ const buf = new Uint8Array(2);
198
+ buf[0] = value >>> 8 & 255;
199
+ buf[1] = value & 255;
200
+ return buf;
201
+ }
202
+ function readUInt16BE(bytes, offset = 0) {
203
+ return (bytes[offset] << 8 | bytes[offset + 1]) >>> 0;
204
+ }
205
+ function writeUInt8(value) {
206
+ return new Uint8Array([value & 255]);
207
+ }
208
+
209
+ // src/utils/c32.ts
210
+ var C32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
211
+ var HEX = "0123456789abcdef";
212
+ function c32normalize(input) {
213
+ return input.toUpperCase().replace(/O/g, "0").replace(/L|I/g, "1");
214
+ }
215
+ function c32encode(inputHex) {
216
+ let hex = inputHex;
217
+ if (hex.length % 2 !== 0)
218
+ hex = `0${hex}`;
219
+ hex = hex.toLowerCase();
220
+ const res = [];
221
+ let carry = 0;
222
+ for (let i = hex.length - 1;i >= 0; i--) {
223
+ if (carry < 4) {
224
+ const currentCode = HEX.indexOf(hex[i]) >> carry;
225
+ const nextCode = i !== 0 ? HEX.indexOf(hex[i - 1]) : 0;
226
+ const nextBits = 1 + carry;
227
+ const nextLowBits = nextCode % (1 << nextBits) << 5 - nextBits;
228
+ res.unshift(C32[currentCode + nextLowBits]);
229
+ carry = nextBits;
230
+ } else {
231
+ carry = 0;
232
+ }
233
+ }
234
+ let leadingZeros = 0;
235
+ while (leadingZeros < res.length && res[leadingZeros] === "0")
236
+ leadingZeros++;
237
+ const stripped = res.slice(leadingZeros);
238
+ const bytes = hexToBytes(hex);
239
+ let zeroBytesCount = 0;
240
+ while (zeroBytesCount < bytes.length && bytes[zeroBytesCount] === 0)
241
+ zeroBytesCount++;
242
+ const prefix = Array(zeroBytesCount).fill(C32[0]);
243
+ return [...prefix, ...stripped].join("");
244
+ }
245
+ function c32decode(c32input) {
246
+ const input = c32normalize(c32input);
247
+ if (!input.match(`^[${C32}]*$`))
248
+ throw new Error("Not a c32-encoded string");
249
+ const zeroPrefix = input.match(`^${C32[0]}*`);
250
+ const numLeadingZeroBytes = zeroPrefix ? zeroPrefix[0]?.length : 0;
251
+ const res = [];
252
+ let carry = 0;
253
+ let carryBits = 0;
254
+ for (let i = input.length - 1;i >= 0; i--) {
255
+ if (carryBits === 4) {
256
+ res.unshift(HEX[carry]);
257
+ carryBits = 0;
258
+ carry = 0;
259
+ }
260
+ const currentValue = (C32.indexOf(input[i]) << carryBits) + carry;
261
+ res.unshift(HEX[currentValue % 16]);
262
+ carryBits += 1;
263
+ carry = currentValue >> 4;
264
+ if (carry > 1 << carryBits)
265
+ throw new Error("Panic error in c32 decoding");
266
+ }
267
+ res.unshift(HEX[carry]);
268
+ if (res.length % 2 === 1)
269
+ res.unshift("0");
270
+ let hexLeadingZeros = 0;
271
+ while (hexLeadingZeros < res.length && res[hexLeadingZeros] === "0")
272
+ hexLeadingZeros++;
273
+ let hexStr = res.slice(hexLeadingZeros - hexLeadingZeros % 2).join("");
274
+ for (let i = 0;i < numLeadingZeroBytes; i++)
275
+ hexStr = `00${hexStr}`;
276
+ return hexStr;
277
+ }
278
+ function c32checksum(dataHex) {
279
+ return bytesToHex(import_sha2.sha256(import_sha2.sha256(hexToBytes(dataHex))).slice(0, 4));
280
+ }
281
+ function c32checkEncode(version, data) {
282
+ if (version < 0 || version >= 32)
283
+ throw new Error("Invalid version (must be between 0 and 31)");
284
+ if (!data.match(/^[0-9a-fA-F]*$/))
285
+ throw new Error("Invalid data (not a hex string)");
286
+ let d = data.toLowerCase();
287
+ if (d.length % 2 !== 0)
288
+ d = `0${d}`;
289
+ let versionHex = version.toString(16);
290
+ if (versionHex.length === 1)
291
+ versionHex = `0${versionHex}`;
292
+ const checksumHex = c32checksum(`${versionHex}${d}`);
293
+ return `${C32[version]}${c32encode(`${d}${checksumHex}`)}`;
294
+ }
295
+ function c32checkDecode(c32data) {
296
+ const normalized = c32normalize(c32data);
297
+ const dataHex = c32decode(normalized.slice(1));
298
+ const version = C32.indexOf(normalized[0]);
299
+ const checksum = dataHex.slice(-8);
300
+ let versionHex = version.toString(16);
301
+ if (versionHex.length === 1)
302
+ versionHex = `0${versionHex}`;
303
+ if (c32checksum(`${versionHex}${dataHex.substring(0, dataHex.length - 8)}`) !== checksum) {
304
+ throw new Error("Invalid c32check string: checksum mismatch");
305
+ }
306
+ return [version, dataHex.substring(0, dataHex.length - 8)];
307
+ }
308
+ function c32address(version, hash160hex) {
309
+ if (!hash160hex.match(/^[0-9a-fA-F]{40}$/)) {
310
+ throw new Error("Invalid argument: not a hash160 hex string");
311
+ }
312
+ return `S${c32checkEncode(version, hash160hex)}`;
313
+ }
314
+ function c32addressDecode(c32addr) {
315
+ if (c32addr.length <= 5)
316
+ throw new Error("Invalid c32 address: invalid length");
317
+ if (c32addr[0] !== "S")
318
+ throw new Error('Invalid c32 address: must start with "S"');
319
+ return c32checkDecode(c32addr.slice(1));
320
+ }
321
+
322
+ // src/utils/constants.ts
323
+ var MAX_U128 = (1n << 128n) - 1n;
324
+ var MAX_I128 = (1n << 127n) - 1n;
325
+ var MIN_I128 = -(1n << 127n);
326
+ var AddressVersion = {
327
+ MainnetSingleSig: 22,
328
+ MainnetMultiSig: 20,
329
+ TestnetSingleSig: 26,
330
+ TestnetMultiSig: 21
331
+ };
332
+ var ZERO_ADDRESS = "SP000000000000000000002Q6VF78";
333
+ var TESTNET_ZERO_ADDRESS = "ST000000000000000000002AMW42H";
334
+ var MICROSTX_PER_STX = 1000000n;
335
+
336
+ // src/utils/hash.ts
337
+ var import_legacy = require("@noble/hashes/legacy.js");
338
+ var import_sha22 = require("@noble/hashes/sha2.js");
339
+ var import_sha23 = require("@noble/hashes/sha2.js");
340
+ function hash160(input) {
341
+ return import_legacy.ripemd160(import_sha22.sha256(input));
342
+ }
343
+ function txidFromBytes(data) {
344
+ return bytesToHex(import_sha23.sha512_256(data));
345
+ }
346
+ function hashP2PKH(input) {
347
+ return bytesToHex(hash160(input));
348
+ }
349
+
350
+ // src/utils/address.ts
351
+ function publicKeyToAddress(publicKey, network = "mainnet") {
352
+ const bytes = typeof publicKey === "string" ? hexToBytes(without0x(publicKey)) : publicKey;
353
+ const version = network === "mainnet" ? AddressVersion.MainnetSingleSig : AddressVersion.TestnetSingleSig;
354
+ return c32address(version, bytesToHex(hash160(bytes)));
355
+ }
356
+ var CONTRACT_NAME_REGEX = /^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/;
357
+ function validateStacksAddress(address) {
358
+ try {
359
+ c32addressDecode(address);
360
+ return true;
361
+ } catch {
362
+ return false;
363
+ }
364
+ }
365
+ var isValidAddress = validateStacksAddress;
366
+ function parsePrincipal(value) {
367
+ const parts = value.split(".");
368
+ if (parts.length > 2)
369
+ return null;
370
+ const [address, contractName] = parts;
371
+ if (!validateStacksAddress(address))
372
+ return null;
373
+ if (contractName === undefined)
374
+ return { address };
375
+ if (!CONTRACT_NAME_REGEX.test(contractName))
376
+ return null;
377
+ return { address, contractName };
378
+ }
379
+ function parseContractId(contractId) {
380
+ const parsed = parsePrincipal(contractId);
381
+ if (!parsed?.contractName)
382
+ throw new Error(`Invalid contract identifier: ${contractId}`);
383
+ return [parsed.address, parsed.contractName];
384
+ }
385
+ function isClarityName(name) {
386
+ const regex = /^[a-zA-Z]([a-zA-Z0-9]|[-_!?+<>=/*])*$|^[-+=/*]$|^[<>]=?$/;
387
+ return regex.test(name) && name.length < 128;
388
+ }
389
+ function isAddressEqual(a, b) {
390
+ const [versionA, hashA] = c32addressDecode(a);
391
+ const [versionB, hashB] = c32addressDecode(b);
392
+ return versionA === versionB && hashA.toLowerCase() === hashB.toLowerCase();
393
+ }
394
+ function addressToVersion(address) {
395
+ return c32addressDecode(address)[0];
396
+ }
397
+ function getContractAddress(deployer, contractName) {
398
+ if (!validateStacksAddress(deployer)) {
399
+ throw new Error(`Invalid deployer address: ${deployer}`);
400
+ }
401
+ if (!isClarityName(contractName)) {
402
+ throw new Error(`Invalid contract name: ${contractName}`);
403
+ }
404
+ return `${deployer}.${contractName}`;
405
+ }
406
+
407
+ // src/transactions/types.ts
408
+ var AuthType = {
409
+ Standard: 4,
410
+ Sponsored: 5
411
+ };
412
+ var PayloadType = {
413
+ TokenTransfer: 0,
414
+ SmartContract: 1,
415
+ ContractCall: 2,
416
+ PoisonMicroblock: 3,
417
+ Coinbase: 4,
418
+ CoinbaseToAltRecipient: 5,
419
+ VersionedSmartContract: 6,
420
+ TenureChange: 7,
421
+ NakamotoCoinbase: 8
422
+ };
423
+ var ClarityVersion = {
424
+ Clarity1: 1,
425
+ Clarity2: 2,
426
+ Clarity3: 3,
427
+ Clarity4: 4,
428
+ Clarity5: 5,
429
+ Clarity6: 6
430
+ };
431
+ var AnchorMode = {
432
+ OnChainOnly: 1,
433
+ OffChainOnly: 2,
434
+ Any: 3
435
+ };
436
+ var PostConditionModeWire = {
437
+ Allow: 1,
438
+ Deny: 2,
439
+ Originator: 3
440
+ };
441
+ var AddressHashMode = {
442
+ P2PKH: 0,
443
+ P2SH: 1,
444
+ P2WPKH: 2,
445
+ P2WSH: 3,
446
+ P2SH_NonSequential: 5,
447
+ P2WSH_P2SH_NonSequential: 7
448
+ };
449
+ var PubKeyEncoding = {
450
+ Compressed: 0,
451
+ Uncompressed: 1
452
+ };
453
+ var FungibleConditionCode = {
454
+ Equal: 1,
455
+ Greater: 2,
456
+ GreaterEqual: 3,
457
+ Less: 4,
458
+ LessEqual: 5
459
+ };
460
+ var NonFungibleConditionCode = {
461
+ Sends: 16,
462
+ DoesNotSend: 17,
463
+ MaybeSent: 18
464
+ };
465
+ var PoxConditionCode = {
466
+ WillNotPerform: 48,
467
+ MayPerform: 49,
468
+ WillPerform: 50
469
+ };
470
+ var PostConditionPrincipalId = {
471
+ Origin: 1,
472
+ Standard: 2,
473
+ Contract: 3
474
+ };
475
+ var AssetType = {
476
+ STX: 0,
477
+ Fungible: 1,
478
+ NonFungible: 2,
479
+ Staking: 3,
480
+ Pox: 4
481
+ };
482
+ var AuthFieldType = {
483
+ PublicKeyCompressed: 0,
484
+ PublicKeyUncompressed: 1,
485
+ SignatureCompressed: 2,
486
+ SignatureUncompressed: 3
487
+ };
488
+ var RECOVERABLE_ECDSA_SIG_LENGTH_BYTES = 65;
489
+ var MEMO_MAX_LENGTH_BYTES = 34;
490
+ var MAX_STRING_LENGTH_BYTES = 128;
491
+ var COINBASE_BYTES_LENGTH = 32;
492
+ var VRF_PROOF_BYTES_LENGTH = 80;
493
+ var MICROBLOCK_HEADER_BYTES_LENGTH = 132;
494
+ var TenureChangeCause = {
495
+ BlockFound: 0,
496
+ Extended: 1,
497
+ ExtendedRuntime: 2,
498
+ ExtendedReadCount: 3,
499
+ ExtendedReadLength: 4,
500
+ ExtendedWriteCount: 5,
501
+ ExtendedWriteLength: 6
502
+ };
503
+
504
+ // src/errors/base.ts
505
+ function codeFromName(name) {
506
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toUpperCase();
507
+ }
508
+
509
+ class BaseError extends Error {
510
+ name = "StacksError";
511
+ #code;
512
+ shortMessage;
513
+ details;
514
+ constructor(shortMessage, options) {
515
+ const message = [
516
+ shortMessage,
517
+ options?.details ? `
518
+ ${options.details}` : ""
519
+ ].join("");
520
+ super(message, { cause: options?.cause });
521
+ if (options?.code !== undefined)
522
+ this.#code = options.code;
523
+ this.shortMessage = shortMessage;
524
+ this.details = options?.details;
525
+ }
526
+ get code() {
527
+ return this.#code ?? codeFromName(this.name);
528
+ }
529
+ set code(value) {
530
+ this.#code = value;
531
+ }
532
+ toJSON() {
533
+ return {
534
+ name: this.name,
535
+ code: this.code,
536
+ message: this.message,
537
+ shortMessage: this.shortMessage,
538
+ details: this.details,
539
+ cause: this.cause instanceof Error ? this.cause.message : undefined
540
+ };
541
+ }
542
+ }
543
+
544
+ // src/errors/transaction.ts
545
+ class TransactionError extends BaseError {
546
+ name = "TransactionError";
547
+ }
548
+
549
+ class BroadcastError extends BaseError {
550
+ name = "BroadcastError";
551
+ txid;
552
+ reason;
553
+ reasonData;
554
+ constructor(message, options) {
555
+ super(message, options);
556
+ this.txid = options?.txid;
557
+ this.reason = options?.reason;
558
+ this.reasonData = options?.reasonData;
559
+ }
560
+ }
561
+
562
+ class TransactionAbortedError extends BaseError {
563
+ name = "TransactionAbortedError";
564
+ receipt;
565
+ constructor(message, options) {
566
+ super(message, options);
567
+ this.receipt = options.receipt;
568
+ }
569
+ }
570
+
571
+ class TransactionDroppedError extends BaseError {
572
+ name = "TransactionDroppedError";
573
+ txid;
574
+ constructor(message, options) {
575
+ super(message, options);
576
+ this.txid = options.txid;
577
+ }
578
+ }
579
+
580
+ class WaitForTransactionTimeoutError extends BaseError {
581
+ name = "WaitForTransactionTimeoutError";
582
+ txid;
583
+ constructor(message, options) {
584
+ super(message, options);
585
+ this.txid = options.txid;
586
+ }
587
+ }
588
+
589
+ class SerializationError extends BaseError {
590
+ name = "SerializationError";
591
+ }
592
+
593
+ class SigningError extends BaseError {
594
+ name = "SigningError";
595
+ }
596
+
597
+ // src/utils/bytes-reader.ts
598
+ class BytesReader {
599
+ data;
600
+ offset = 0;
601
+ constructor(data) {
602
+ this.data = data;
603
+ }
604
+ remaining() {
605
+ return this.data.length - this.offset;
606
+ }
607
+ ensure(length) {
608
+ if (this.offset + length > this.data.length) {
609
+ throw new SerializationError(`Buffer underflow: need ${length} bytes at offset ${this.offset}, have ${this.data.length}`);
610
+ }
611
+ }
612
+ readUInt8() {
613
+ this.ensure(1);
614
+ return this.data[this.offset++];
615
+ }
616
+ readUInt16BE() {
617
+ this.ensure(2);
618
+ const val = (this.data[this.offset] << 8 | this.data[this.offset + 1]) >>> 0;
619
+ this.offset += 2;
620
+ return val;
621
+ }
622
+ readUInt32BE() {
623
+ this.ensure(4);
624
+ 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;
625
+ this.offset += 4;
626
+ return val;
627
+ }
628
+ readBytes(length) {
629
+ this.ensure(length);
630
+ const slice = this.data.slice(this.offset, this.offset + length);
631
+ this.offset += length;
632
+ return slice;
633
+ }
634
+ readBigUInt64BE() {
635
+ const hex = bytesToHex(this.readBytes(8));
636
+ return hex.length > 0 ? BigInt(`0x${hex}`) : 0n;
637
+ }
638
+ }
639
+
640
+ // src/clarity/types.ts
641
+ var ClarityWireType = {
642
+ int: 0,
643
+ uint: 1,
644
+ buffer: 2,
645
+ true: 3,
646
+ false: 4,
647
+ address: 5,
648
+ contract: 6,
649
+ ok: 7,
650
+ err: 8,
651
+ none: 9,
652
+ some: 10,
653
+ list: 11,
654
+ tuple: 12,
655
+ ascii: 13,
656
+ utf8: 14
657
+ };
658
+ var wireTypeToClarity = Object.fromEntries(Object.entries(ClarityWireType).map(([k, v]) => [v, k]));
659
+ function clarityTypeFromByte(byte) {
660
+ const type = wireTypeToClarity[byte];
661
+ if (!type)
662
+ throw new Error(`Unknown clarity wire type: ${byte}`);
663
+ return type;
664
+ }
665
+
666
+ // src/clarity/serialize.ts
667
+ var CLARITY_INT_SIZE = 128n;
668
+ var CLARITY_INT_BYTE_SIZE = 16;
669
+ function typeIdByte(type) {
670
+ return ClarityWireType[type];
671
+ }
672
+ function withTypeId(type, bytes) {
673
+ return concatBytes(new Uint8Array([typeIdByte(type)]), bytes);
674
+ }
675
+ function serializeAddress(c32Address) {
676
+ const [version, hash1602] = c32addressDecode(c32Address);
677
+ return concatBytes(new Uint8Array([version]), hexToBytes(hash1602));
678
+ }
679
+ function serializeLPString(str, prefixBytes = 1) {
680
+ const content = utf8ToBytes(str);
681
+ const lengthPrefix = hexToBytes(intToHex(content.byteLength, prefixBytes));
682
+ return concatBytes(lengthPrefix, content);
683
+ }
684
+ function serializeCVBytes(value) {
685
+ switch (value.type) {
686
+ case "true":
687
+ case "false":
688
+ return new Uint8Array([typeIdByte(value.type)]);
689
+ case "int": {
690
+ const bytes = bigIntToBytes(toTwos(BigInt(value.value), CLARITY_INT_SIZE), CLARITY_INT_BYTE_SIZE);
691
+ return withTypeId(value.type, bytes);
692
+ }
693
+ case "uint": {
694
+ const bytes = bigIntToBytes(BigInt(value.value), CLARITY_INT_BYTE_SIZE);
695
+ return withTypeId(value.type, bytes);
696
+ }
697
+ case "buffer": {
698
+ const bufBytes = hexToBytes(value.value);
699
+ return withTypeId(value.type, concatBytes(writeUInt32BE(bufBytes.length), bufBytes));
700
+ }
701
+ case "none":
702
+ return new Uint8Array([typeIdByte(value.type)]);
703
+ case "some":
704
+ return withTypeId(value.type, serializeCVBytes(value.value));
705
+ case "ok":
706
+ case "err":
707
+ return withTypeId(value.type, serializeCVBytes(value.value));
708
+ case "address":
709
+ return withTypeId(value.type, serializeAddress(value.value));
710
+ case "contract": {
711
+ const [addr, name] = value.value.split(".");
712
+ if (!addr || !name)
713
+ throw new Error(`Invalid contract principal: ${value.value}`);
714
+ return withTypeId(value.type, concatBytes(serializeAddress(addr), serializeLPString(name)));
715
+ }
716
+ case "list": {
717
+ const parts = [writeUInt32BE(value.value.length)];
718
+ for (const item of value.value) {
719
+ parts.push(serializeCVBytes(item));
720
+ }
721
+ return withTypeId(value.type, concatBytes(...parts));
722
+ }
723
+ case "tuple": {
724
+ const keys = Object.keys(value.value).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
725
+ const parts = [writeUInt32BE(keys.length)];
726
+ for (const key of keys) {
727
+ parts.push(serializeLPString(key));
728
+ parts.push(serializeCVBytes(value.value[key]));
729
+ }
730
+ return withTypeId(value.type, concatBytes(...parts));
731
+ }
732
+ case "ascii": {
733
+ const strBytes = asciiToBytes(value.value);
734
+ return withTypeId(value.type, concatBytes(writeUInt32BE(strBytes.length), strBytes));
735
+ }
736
+ case "utf8": {
737
+ const strBytes = utf8ToBytes(value.value);
738
+ return withTypeId(value.type, concatBytes(writeUInt32BE(strBytes.length), strBytes));
739
+ }
740
+ default:
741
+ throw new Error("Cannot serialize unknown clarity type");
742
+ }
743
+ }
744
+ function serializeCV(value) {
745
+ return bytesToHex(serializeCVBytes(value));
746
+ }
747
+
748
+ // src/clarity/values.ts
749
+ var MAX_U1282 = BigInt("0xffffffffffffffffffffffffffffffff");
750
+ var MIN_I1282 = BigInt("-170141183460469231731687303715884105728");
751
+ var MAX_I1282 = BigInt("0x7fffffffffffffffffffffffffffffff");
752
+ function intCV(value) {
753
+ let v = value;
754
+ if (typeof v === "string" && v.toLowerCase().startsWith("0x")) {
755
+ v = bytesToTwosBigInt(hexToBytes(v));
756
+ }
757
+ if (v instanceof Uint8Array)
758
+ v = bytesToTwosBigInt(v);
759
+ const n = intToBigInt(v);
760
+ if (n > MAX_I1282)
761
+ throw new RangeError(`Int exceeds max i128: ${MAX_I1282}`);
762
+ if (n < MIN_I1282)
763
+ throw new RangeError(`Int below min i128: ${MIN_I1282}`);
764
+ return { type: "int", value: n };
765
+ }
766
+ function uintCV(value) {
767
+ const n = intToBigInt(value);
768
+ if (n < 0n)
769
+ throw new RangeError("Cannot construct unsigned int from negative value");
770
+ if (n > MAX_U1282)
771
+ throw new RangeError(`UInt exceeds max u128: ${MAX_U1282}`);
772
+ return { type: "uint", value: n };
773
+ }
774
+ var trueCV = () => ({ type: "true" });
775
+ var falseCV = () => ({ type: "false" });
776
+ var boolCV = (v) => v ? trueCV() : falseCV();
777
+ function bufferCV(buffer) {
778
+ if (buffer.byteLength > 1048576) {
779
+ throw new Error("Buffer exceeds max size of 1MB");
780
+ }
781
+ return { type: "buffer", value: bytesToHex(buffer) };
782
+ }
783
+ function standardPrincipalCV(address) {
784
+ const [version, hash1602] = c32addressDecode(address);
785
+ const normalized = c32address(version, hash1602);
786
+ return { type: "address", value: normalized };
787
+ }
788
+ function contractPrincipalCV(address, contractName) {
789
+ const [version, hash1602] = c32addressDecode(address);
790
+ const normalized = c32address(version, hash1602);
791
+ if (utf8ToBytes(contractName).byteLength >= 128) {
792
+ throw new Error("Contract name must be less than 128 bytes");
793
+ }
794
+ return { type: "contract", value: `${normalized}.${contractName}` };
795
+ }
796
+ function noneCV() {
797
+ return { type: "none" };
798
+ }
799
+ function someCV(value) {
800
+ return { type: "some", value };
801
+ }
802
+ function responseOkCV(value) {
803
+ return { type: "ok", value };
804
+ }
805
+ function responseErrorCV(value) {
806
+ return { type: "err", value };
807
+ }
808
+ function listCV(values) {
809
+ return { type: "list", value: values };
810
+ }
811
+ function tupleCV(data) {
812
+ for (const key in data) {
813
+ if (!isClarityName(key)) {
814
+ throw new Error(`"${key}" is not a valid Clarity name`);
815
+ }
816
+ }
817
+ return { type: "tuple", value: data };
818
+ }
819
+ function stringAsciiCV(value) {
820
+ return { type: "ascii", value };
821
+ }
822
+ function stringUtf8CV(value) {
823
+ return { type: "utf8", value };
824
+ }
825
+ var Cl = {
826
+ int: intCV,
827
+ uint: uintCV,
828
+ bool: boolCV,
829
+ principal(address) {
830
+ const parsed = parsePrincipal(address);
831
+ if (!parsed)
832
+ throw new Error(`Invalid principal: ${address}`);
833
+ return parsed.contractName ? contractPrincipalCV(parsed.address, parsed.contractName) : standardPrincipalCV(parsed.address);
834
+ },
835
+ address(address) {
836
+ return Cl.principal(address);
837
+ },
838
+ contractPrincipal: contractPrincipalCV,
839
+ standardPrincipal: standardPrincipalCV,
840
+ buffer: bufferCV,
841
+ bufferFromHex: (hex) => bufferCV(hexToBytes(hex)),
842
+ bufferFromAscii: (ascii) => bufferCV(asciiToBytes(ascii)),
843
+ bufferFromUtf8: (utf8) => bufferCV(utf8ToBytes(utf8)),
844
+ none: noneCV,
845
+ some: someCV,
846
+ ok: responseOkCV,
847
+ error: responseErrorCV,
848
+ list: listCV,
849
+ tuple: tupleCV,
850
+ stringAscii: stringAsciiCV,
851
+ stringUtf8: stringUtf8CV,
852
+ serialize(value) {
853
+ return bytesToHex(serializeCVBytes(value));
854
+ },
855
+ deserialize: deserializeCVBytes
856
+ };
857
+
858
+ // src/clarity/deserialize.ts
859
+ function readAddress(reader) {
860
+ const version = reader.readUInt8();
861
+ const hash1602 = bytesToHex(reader.readBytes(20));
862
+ return c32address(version, hash1602);
863
+ }
864
+ function readLPString(reader, prefixBytes = 1) {
865
+ let length = 0;
866
+ for (let i = 0;i < prefixBytes; i++) {
867
+ length = length << 8 | reader.readUInt8();
868
+ }
869
+ return bytesToUtf8(reader.readBytes(length));
870
+ }
871
+ var MAX_CV_DEPTH = 64;
872
+ var MIN_LIST_ITEM_BYTES = 1;
873
+ var MIN_TUPLE_ENTRY_BYTES = 2;
874
+ function checkCount(reader, count, minBytes) {
875
+ if (count * minBytes > reader.remaining()) {
876
+ throw new SerializationError(`Clarity value declares ${count} elements but only ${reader.remaining()} bytes remain`);
877
+ }
878
+ }
879
+ function readCV(reader, depth = 0) {
880
+ if (depth > MAX_CV_DEPTH) {
881
+ throw new SerializationError(`Clarity value nests deeper than ${MAX_CV_DEPTH} levels`);
882
+ }
883
+ const typeByte = reader.readUInt8();
884
+ const type = clarityTypeFromByte(typeByte);
885
+ switch (type) {
886
+ case "int":
887
+ return intCV(bytesToTwosBigInt(reader.readBytes(16)));
888
+ case "uint":
889
+ return uintCV(reader.readBytes(16));
890
+ case "true":
891
+ return trueCV();
892
+ case "false":
893
+ return falseCV();
894
+ case "buffer": {
895
+ const len = reader.readUInt32BE();
896
+ return bufferCV(reader.readBytes(len));
897
+ }
898
+ case "none":
899
+ return noneCV();
900
+ case "some":
901
+ return someCV(readCV(reader, depth + 1));
902
+ case "ok":
903
+ return responseOkCV(readCV(reader, depth + 1));
904
+ case "err":
905
+ return responseErrorCV(readCV(reader, depth + 1));
906
+ case "address":
907
+ return standardPrincipalCV(readAddress(reader));
908
+ case "contract": {
909
+ const addr = readAddress(reader);
910
+ const name = readLPString(reader);
911
+ return contractPrincipalCV(addr, name);
912
+ }
913
+ case "list": {
914
+ const len = reader.readUInt32BE();
915
+ checkCount(reader, len, MIN_LIST_ITEM_BYTES);
916
+ const items = [];
917
+ for (let i = 0;i < len; i++) {
918
+ items.push(readCV(reader, depth + 1));
919
+ }
920
+ return listCV(items);
921
+ }
922
+ case "tuple": {
923
+ const len = reader.readUInt32BE();
924
+ checkCount(reader, len, MIN_TUPLE_ENTRY_BYTES);
925
+ const data = {};
926
+ for (let i = 0;i < len; i++) {
927
+ const key = readLPString(reader);
928
+ data[key] = readCV(reader, depth + 1);
929
+ }
930
+ return tupleCV(data);
931
+ }
932
+ case "ascii": {
933
+ const len = reader.readUInt32BE();
934
+ return stringAsciiCV(bytesToAscii(reader.readBytes(len)));
935
+ }
936
+ case "utf8": {
937
+ const len = reader.readUInt32BE();
938
+ return stringUtf8CV(bytesToUtf8(reader.readBytes(len)));
939
+ }
940
+ default:
941
+ throw new SerializationError(`Cannot deserialize unknown clarity type: ${type}`);
942
+ }
943
+ }
944
+ function deserializeCVBytes(input) {
945
+ const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
946
+ return readCV(new BytesReader(bytes));
947
+ }
948
+ function deserializeCV(input) {
949
+ return deserializeCVBytes(input);
950
+ }
951
+
952
+ // src/transactions/wire/deserialize.ts
953
+ function readSpendingCondition(r) {
954
+ const hashMode = r.readUInt8();
955
+ const signer = bytesToHex(r.readBytes(20));
956
+ const nonce = r.readBigUInt64BE();
957
+ const fee = r.readBigUInt64BE();
958
+ if (hashMode === AddressHashMode.P2PKH || hashMode === AddressHashMode.P2WPKH) {
959
+ const keyEncoding = r.readUInt8();
960
+ const signature = bytesToHex(r.readBytes(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES));
961
+ return {
962
+ hashMode,
963
+ signer,
964
+ nonce,
965
+ fee,
966
+ keyEncoding,
967
+ signature
968
+ };
969
+ }
970
+ const fieldCount = r.readUInt32BE();
971
+ const fields = [];
972
+ for (let i = 0;i < fieldCount; i++) {
973
+ const fieldType = r.readUInt8();
974
+ if (fieldType <= 1) {
975
+ const keyLen = fieldType === 0 ? 33 : 65;
976
+ fields.push({
977
+ type: "publicKey",
978
+ pubKeyEncoding: fieldType,
979
+ data: bytesToHex(r.readBytes(keyLen))
980
+ });
981
+ } else {
982
+ fields.push({
983
+ type: "signature",
984
+ pubKeyEncoding: fieldType === 2 ? 0 : 1,
985
+ data: bytesToHex(r.readBytes(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES))
986
+ });
987
+ }
988
+ }
989
+ const signaturesRequired = r.readUInt16BE();
990
+ return {
991
+ hashMode,
992
+ signer,
993
+ nonce,
994
+ fee,
995
+ fields,
996
+ signaturesRequired
997
+ };
998
+ }
999
+ function readAuthorization(r) {
1000
+ const authType = r.readUInt8();
1001
+ const spendingCondition = readSpendingCondition(r);
1002
+ if (authType === AuthType.Standard) {
1003
+ return { authType: AuthType.Standard, spendingCondition };
1004
+ }
1005
+ const sponsorSpendingCondition = readSpendingCondition(r);
1006
+ return {
1007
+ authType: AuthType.Sponsored,
1008
+ spendingCondition,
1009
+ sponsorSpendingCondition
1010
+ };
1011
+ }
1012
+ function readAssetInfo(r) {
1013
+ return {
1014
+ address: readAddress(r),
1015
+ contractName: readLPString(r),
1016
+ assetName: readLPString(r)
1017
+ };
1018
+ }
1019
+ function readPostConditionPrincipal(r) {
1020
+ const type = r.readUInt8();
1021
+ switch (type) {
1022
+ case PostConditionPrincipalId.Origin:
1023
+ return { type: "origin" };
1024
+ case PostConditionPrincipalId.Standard:
1025
+ return { type: "standard", address: readAddress(r) };
1026
+ case PostConditionPrincipalId.Contract:
1027
+ return {
1028
+ type: "contract",
1029
+ address: readAddress(r),
1030
+ contractName: readLPString(r)
1031
+ };
1032
+ default:
1033
+ return { type: "origin" };
1034
+ }
1035
+ }
1036
+ function readPostCondition(r) {
1037
+ const assetType = r.readUInt8();
1038
+ const principal = readPostConditionPrincipal(r);
1039
+ switch (assetType) {
1040
+ case AssetType.STX:
1041
+ return {
1042
+ type: "stx",
1043
+ principal,
1044
+ conditionCode: r.readUInt8(),
1045
+ amount: r.readBigUInt64BE()
1046
+ };
1047
+ case AssetType.Fungible:
1048
+ return {
1049
+ type: "ft",
1050
+ principal,
1051
+ asset: readAssetInfo(r),
1052
+ conditionCode: r.readUInt8(),
1053
+ amount: r.readBigUInt64BE()
1054
+ };
1055
+ case AssetType.NonFungible:
1056
+ return {
1057
+ type: "nft",
1058
+ principal,
1059
+ asset: readAssetInfo(r),
1060
+ assetId: readCV(r),
1061
+ conditionCode: r.readUInt8()
1062
+ };
1063
+ case AssetType.Staking:
1064
+ return {
1065
+ type: "staking",
1066
+ principal,
1067
+ conditionCode: r.readUInt8(),
1068
+ amount: r.readBigUInt64BE()
1069
+ };
1070
+ case AssetType.Pox:
1071
+ return {
1072
+ type: "pox",
1073
+ principal,
1074
+ conditionCode: r.readUInt8()
1075
+ };
1076
+ default:
1077
+ throw new Error(`Unknown post-condition asset type: 0x${assetType.toString(16).padStart(2, "0")}`);
1078
+ }
1079
+ }
1080
+ function readPostConditions(r) {
1081
+ const count = r.readUInt32BE();
1082
+ const pcs = [];
1083
+ for (let i = 0;i < count; i++) {
1084
+ try {
1085
+ pcs.push(readPostCondition(r));
1086
+ } catch (e) {
1087
+ if (e instanceof Error && e.message.startsWith("Unknown post-condition asset type:")) {
1088
+ throw new Error(`${e.message} (post-condition ${i + 1}/${count})`);
1089
+ }
1090
+ throw e;
1091
+ }
1092
+ }
1093
+ return pcs;
1094
+ }
1095
+ function readPayload(r) {
1096
+ const payloadType = r.readUInt8();
1097
+ switch (payloadType) {
1098
+ case PayloadType.TokenTransfer: {
1099
+ const recipient = readCV(r);
1100
+ const amount = r.readBigUInt64BE();
1101
+ const memoBytes = r.readBytes(MEMO_MAX_LENGTH_BYTES);
1102
+ const memo = bytesToAscii(memoBytes).replace(/\0+$/, "");
1103
+ return {
1104
+ payloadType: PayloadType.TokenTransfer,
1105
+ recipient,
1106
+ amount,
1107
+ memo
1108
+ };
1109
+ }
1110
+ case PayloadType.ContractCall: {
1111
+ const contractAddress = readAddress(r);
1112
+ const contractName = readLPString(r);
1113
+ const functionName = readLPString(r);
1114
+ const numArgs = r.readUInt32BE();
1115
+ const functionArgs = [];
1116
+ for (let i = 0;i < numArgs; i++)
1117
+ functionArgs.push(readCV(r));
1118
+ return {
1119
+ payloadType: PayloadType.ContractCall,
1120
+ contractAddress,
1121
+ contractName,
1122
+ functionName,
1123
+ functionArgs
1124
+ };
1125
+ }
1126
+ case PayloadType.SmartContract: {
1127
+ const contractName = readLPString(r);
1128
+ const codeBody = readLPString(r, 4);
1129
+ return { payloadType: PayloadType.SmartContract, contractName, codeBody };
1130
+ }
1131
+ case PayloadType.VersionedSmartContract: {
1132
+ const clarityVersion = r.readUInt8();
1133
+ const contractName = readLPString(r);
1134
+ const codeBody = readLPString(r, 4);
1135
+ return {
1136
+ payloadType: PayloadType.VersionedSmartContract,
1137
+ clarityVersion,
1138
+ contractName,
1139
+ codeBody
1140
+ };
1141
+ }
1142
+ case PayloadType.Coinbase: {
1143
+ const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
1144
+ return { payloadType: PayloadType.Coinbase, coinbaseBuffer };
1145
+ }
1146
+ case PayloadType.CoinbaseToAltRecipient: {
1147
+ const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
1148
+ const recipient = readCV(r);
1149
+ return {
1150
+ payloadType: PayloadType.CoinbaseToAltRecipient,
1151
+ coinbaseBuffer,
1152
+ recipient
1153
+ };
1154
+ }
1155
+ case PayloadType.PoisonMicroblock: {
1156
+ const header1 = bytesToHex(r.readBytes(MICROBLOCK_HEADER_BYTES_LENGTH));
1157
+ const header2 = bytesToHex(r.readBytes(MICROBLOCK_HEADER_BYTES_LENGTH));
1158
+ return { payloadType: PayloadType.PoisonMicroblock, header1, header2 };
1159
+ }
1160
+ case PayloadType.TenureChange: {
1161
+ const tenureConsensusHash = bytesToHex(r.readBytes(20));
1162
+ const prevTenureConsensusHash = bytesToHex(r.readBytes(20));
1163
+ const burnViewConsensusHash = bytesToHex(r.readBytes(20));
1164
+ const previousTenureEnd = bytesToHex(r.readBytes(32));
1165
+ const previousTenureBlocks = r.readUInt32BE();
1166
+ const cause = r.readUInt8();
1167
+ const pubkeyHash = bytesToHex(r.readBytes(20));
1168
+ return {
1169
+ payloadType: PayloadType.TenureChange,
1170
+ tenureConsensusHash,
1171
+ prevTenureConsensusHash,
1172
+ burnViewConsensusHash,
1173
+ previousTenureEnd,
1174
+ previousTenureBlocks,
1175
+ cause,
1176
+ pubkeyHash
1177
+ };
1178
+ }
1179
+ case PayloadType.NakamotoCoinbase: {
1180
+ const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
1181
+ const optionalCV = readCV(r);
1182
+ const recipient = optionalCV.type === "none" ? null : optionalCV.type === "some" ? optionalCV.value : optionalCV;
1183
+ const vrfProof = bytesToHex(r.readBytes(VRF_PROOF_BYTES_LENGTH));
1184
+ return {
1185
+ payloadType: PayloadType.NakamotoCoinbase,
1186
+ coinbaseBuffer,
1187
+ recipient,
1188
+ vrfProof
1189
+ };
1190
+ }
1191
+ default:
1192
+ throw new Error(`Unknown payload type: ${payloadType}`);
1193
+ }
1194
+ }
1195
+ function deserializePostConditionWire(input) {
1196
+ const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
1197
+ return readPostCondition(new BytesReader(bytes));
1198
+ }
1199
+ function deserializeTransaction(input, meta) {
1200
+ const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
1201
+ const r = new BytesReader(bytes);
1202
+ const tx = {
1203
+ version: r.readUInt8(),
1204
+ chainId: r.readUInt32BE(),
1205
+ auth: readAuthorization(r),
1206
+ anchorMode: r.readUInt8(),
1207
+ postConditionMode: r.readUInt8(),
1208
+ postConditions: readPostConditions(r),
1209
+ payload: readPayload(r)
1210
+ };
1211
+ if (meta?._multisig) {
1212
+ tx._multisig = meta._multisig;
1213
+ }
1214
+ return tx;
1215
+ }
1216
+
1217
+ // src/transactions/wire/serialize.ts
1218
+ function serializeAddress2(c32Address) {
1219
+ const [version, hash1602] = c32addressDecode(c32Address);
1220
+ return concatBytes(new Uint8Array([version]), hexToBytes(hash1602));
1221
+ }
1222
+ function serializeLPString2(str, prefixBytes = 1) {
1223
+ const content = utf8ToBytes(str);
1224
+ const prefix = hexToBytes(intToHex(content.byteLength, prefixBytes));
1225
+ return concatBytes(prefix, content);
1226
+ }
1227
+ function serializeLPStringLong(str) {
1228
+ return serializeLPString2(str, 4);
1229
+ }
1230
+ function serializeMemo(memo) {
1231
+ const content = asciiToBytes(memo);
1232
+ const padded = new Uint8Array(MEMO_MAX_LENGTH_BYTES);
1233
+ padded.set(content.slice(0, MEMO_MAX_LENGTH_BYTES));
1234
+ return padded;
1235
+ }
1236
+ function serializeSpendingCondition(condition) {
1237
+ const parts = [
1238
+ writeUInt8(condition.hashMode),
1239
+ hexToBytes(condition.signer),
1240
+ intToBytes(condition.nonce, 8),
1241
+ intToBytes(condition.fee, 8)
1242
+ ];
1243
+ if ("signature" in condition) {
1244
+ const sc = condition;
1245
+ parts.push(writeUInt8(sc.keyEncoding));
1246
+ parts.push(hexToBytes(sc.signature));
1247
+ } else {
1248
+ const mc = condition;
1249
+ parts.push(writeUInt32BE(mc.fields.length));
1250
+ for (const field of mc.fields) {
1251
+ parts.push(serializeAuthField(field));
1252
+ }
1253
+ parts.push(writeUInt16BE(mc.signaturesRequired));
1254
+ }
1255
+ return concatBytes(...parts);
1256
+ }
1257
+ function serializeAuthField(field) {
1258
+ if (field.type === "publicKey") {
1259
+ const typeId2 = field.pubKeyEncoding === 0 ? 0 : 1;
1260
+ return concatBytes(writeUInt8(typeId2), hexToBytes(field.data));
1261
+ }
1262
+ const typeId = field.pubKeyEncoding === 0 ? 2 : 3;
1263
+ return concatBytes(writeUInt8(typeId), hexToBytes(field.data));
1264
+ }
1265
+ function serializeAuthorization(auth) {
1266
+ const parts = [writeUInt8(auth.authType)];
1267
+ parts.push(serializeSpendingCondition(auth.spendingCondition));
1268
+ if (auth.authType === AuthType.Sponsored) {
1269
+ parts.push(serializeSpendingCondition(auth.sponsorSpendingCondition));
1270
+ }
1271
+ return concatBytes(...parts);
1272
+ }
1273
+ function serializePrincipal(principal) {
1274
+ switch (principal.type) {
1275
+ case "origin":
1276
+ return writeUInt8(PostConditionPrincipalId.Origin);
1277
+ case "standard":
1278
+ return concatBytes(writeUInt8(PostConditionPrincipalId.Standard), serializeAddress2(principal.address));
1279
+ case "contract":
1280
+ return concatBytes(writeUInt8(PostConditionPrincipalId.Contract), serializeAddress2(principal.address), serializeLPString2(principal.contractName));
1281
+ }
1282
+ }
1283
+ function serializeAssetInfo(asset) {
1284
+ return concatBytes(serializeAddress2(asset.address), serializeLPString2(asset.contractName), serializeLPString2(asset.assetName));
1285
+ }
1286
+ function serializePostConditionWire(pc) {
1287
+ const parts = [];
1288
+ switch (pc.type) {
1289
+ case "stx":
1290
+ parts.push(writeUInt8(AssetType.STX));
1291
+ parts.push(serializePrincipal(pc.principal));
1292
+ parts.push(writeUInt8(pc.conditionCode));
1293
+ parts.push(intToBytes(pc.amount, 8));
1294
+ break;
1295
+ case "ft":
1296
+ parts.push(writeUInt8(AssetType.Fungible));
1297
+ parts.push(serializePrincipal(pc.principal));
1298
+ parts.push(serializeAssetInfo(pc.asset));
1299
+ parts.push(writeUInt8(pc.conditionCode));
1300
+ parts.push(intToBytes(pc.amount, 8));
1301
+ break;
1302
+ case "nft":
1303
+ parts.push(writeUInt8(AssetType.NonFungible));
1304
+ parts.push(serializePrincipal(pc.principal));
1305
+ parts.push(serializeAssetInfo(pc.asset));
1306
+ parts.push(serializeCVBytes(pc.assetId));
1307
+ parts.push(writeUInt8(pc.conditionCode));
1308
+ break;
1309
+ case "staking":
1310
+ parts.push(writeUInt8(AssetType.Staking));
1311
+ parts.push(serializePrincipal(pc.principal));
1312
+ parts.push(writeUInt8(pc.conditionCode));
1313
+ parts.push(intToBytes(pc.amount, 8));
1314
+ break;
1315
+ case "pox":
1316
+ parts.push(writeUInt8(AssetType.Pox));
1317
+ parts.push(serializePrincipal(pc.principal));
1318
+ parts.push(writeUInt8(pc.conditionCode));
1319
+ break;
1320
+ }
1321
+ return concatBytes(...parts);
1322
+ }
1323
+ function serializePostConditions(pcs) {
1324
+ const parts = [writeUInt32BE(pcs.length)];
1325
+ for (const pc of pcs)
1326
+ parts.push(serializePostConditionWire(pc));
1327
+ return concatBytes(...parts);
1328
+ }
1329
+ function serializePayload(payload) {
1330
+ const parts = [writeUInt8(payload.payloadType)];
1331
+ switch (payload.payloadType) {
1332
+ case PayloadType.TokenTransfer:
1333
+ parts.push(serializeCVBytes(payload.recipient));
1334
+ parts.push(intToBytes(payload.amount, 8));
1335
+ parts.push(serializeMemo(payload.memo));
1336
+ break;
1337
+ case PayloadType.ContractCall:
1338
+ parts.push(serializeAddress2(payload.contractAddress));
1339
+ parts.push(serializeLPString2(payload.contractName));
1340
+ parts.push(serializeLPString2(payload.functionName));
1341
+ parts.push(writeUInt32BE(payload.functionArgs.length));
1342
+ for (const arg of payload.functionArgs) {
1343
+ parts.push(serializeCVBytes(arg));
1344
+ }
1345
+ break;
1346
+ case PayloadType.SmartContract:
1347
+ parts.push(serializeLPString2(payload.contractName));
1348
+ parts.push(serializeLPStringLong(payload.codeBody));
1349
+ break;
1350
+ case PayloadType.VersionedSmartContract:
1351
+ parts.push(writeUInt8(payload.clarityVersion ?? 2));
1352
+ parts.push(serializeLPString2(payload.contractName));
1353
+ parts.push(serializeLPStringLong(payload.codeBody));
1354
+ break;
1355
+ case PayloadType.Coinbase:
1356
+ parts.push(hexToBytes(payload.coinbaseBuffer));
1357
+ break;
1358
+ case PayloadType.CoinbaseToAltRecipient: {
1359
+ const cbAlt = payload;
1360
+ parts.push(hexToBytes(cbAlt.coinbaseBuffer));
1361
+ parts.push(serializeCVBytes(cbAlt.recipient));
1362
+ break;
1363
+ }
1364
+ case PayloadType.PoisonMicroblock: {
1365
+ const pm = payload;
1366
+ parts.push(hexToBytes(pm.header1));
1367
+ parts.push(hexToBytes(pm.header2));
1368
+ break;
1369
+ }
1370
+ case PayloadType.TenureChange: {
1371
+ const tc = payload;
1372
+ parts.push(hexToBytes(tc.tenureConsensusHash));
1373
+ parts.push(hexToBytes(tc.prevTenureConsensusHash));
1374
+ parts.push(hexToBytes(tc.burnViewConsensusHash));
1375
+ parts.push(hexToBytes(tc.previousTenureEnd));
1376
+ parts.push(writeUInt32BE(tc.previousTenureBlocks));
1377
+ parts.push(writeUInt8(tc.cause));
1378
+ parts.push(hexToBytes(tc.pubkeyHash));
1379
+ break;
1380
+ }
1381
+ case PayloadType.NakamotoCoinbase: {
1382
+ const nc = payload;
1383
+ parts.push(hexToBytes(nc.coinbaseBuffer));
1384
+ if (nc.recipient) {
1385
+ parts.push(serializeCVBytes({ type: "some", value: nc.recipient }));
1386
+ } else {
1387
+ parts.push(serializeCVBytes({ type: "none" }));
1388
+ }
1389
+ parts.push(hexToBytes(nc.vrfProof));
1390
+ break;
1391
+ }
1392
+ }
1393
+ return concatBytes(...parts);
1394
+ }
1395
+ var _txCache = new WeakMap;
1396
+ function clearTxCache(tx) {
1397
+ _txCache.delete(tx);
1398
+ }
1399
+ function serializeTransaction(tx) {
1400
+ const cached = _txCache.get(tx);
1401
+ if (cached)
1402
+ return cached;
1403
+ const bytes = concatBytes(writeUInt8(tx.version), writeUInt32BE(tx.chainId), serializeAuthorization(tx.auth), writeUInt8(tx.anchorMode), writeUInt8(tx.postConditionMode), serializePostConditions(tx.postConditions), serializePayload(tx.payload));
1404
+ _txCache.set(tx, bytes);
1405
+ return bytes;
1406
+ }
1407
+ function serializeTransactionHex(tx) {
1408
+ return bytesToHex(serializeTransaction(tx));
1409
+ }
1410
+
1411
+ // src/postconditions/convert.ts
1412
+ var MAX_U64 = 18446744073709551615n;
1413
+ function parsePostConditionAmount(amount) {
1414
+ const value = intToBigInt(amount);
1415
+ if (value < 0n || value > MAX_U64) {
1416
+ throw new RangeError(`Post-condition amount must be between 0 and ${MAX_U64} (u64 max), received: ${value}`);
1417
+ }
1418
+ return value;
1419
+ }
1420
+ var FUNGIBLE_CODE_MAP = {
1421
+ eq: FungibleConditionCode.Equal,
1422
+ gt: FungibleConditionCode.Greater,
1423
+ gte: FungibleConditionCode.GreaterEqual,
1424
+ lt: FungibleConditionCode.Less,
1425
+ lte: FungibleConditionCode.LessEqual
1426
+ };
1427
+ var FUNGIBLE_CODE_REVERSE = {
1428
+ [FungibleConditionCode.Equal]: "eq",
1429
+ [FungibleConditionCode.Greater]: "gt",
1430
+ [FungibleConditionCode.GreaterEqual]: "gte",
1431
+ [FungibleConditionCode.Less]: "lt",
1432
+ [FungibleConditionCode.LessEqual]: "lte"
1433
+ };
1434
+ var NFT_CODE_MAP = {
1435
+ sent: NonFungibleConditionCode.Sends,
1436
+ "not-sent": NonFungibleConditionCode.DoesNotSend,
1437
+ "maybe-sent": NonFungibleConditionCode.MaybeSent
1438
+ };
1439
+ var NFT_CODE_REVERSE = {
1440
+ [NonFungibleConditionCode.Sends]: "sent",
1441
+ [NonFungibleConditionCode.DoesNotSend]: "not-sent",
1442
+ [NonFungibleConditionCode.MaybeSent]: "maybe-sent"
1443
+ };
1444
+ var POX_CODE_MAP = {
1445
+ "will-not-perform": PoxConditionCode.WillNotPerform,
1446
+ "may-perform": PoxConditionCode.MayPerform,
1447
+ "will-perform": PoxConditionCode.WillPerform
1448
+ };
1449
+ var POX_CODE_REVERSE = {
1450
+ [PoxConditionCode.WillNotPerform]: "will-not-perform",
1451
+ [PoxConditionCode.MayPerform]: "may-perform",
1452
+ [PoxConditionCode.WillPerform]: "will-perform"
1453
+ };
1454
+ function resolvePrincipal(address) {
1455
+ if (address === "origin")
1456
+ return { type: "origin" };
1457
+ const [addr, name] = address.split(".");
1458
+ if (name) {
1459
+ return { type: "contract", address: addr, contractName: name };
1460
+ }
1461
+ return { type: "standard", address: addr };
1462
+ }
1463
+ function principalToString(principal) {
1464
+ if (principal.type === "origin")
1465
+ return "origin";
1466
+ if (principal.type === "contract") {
1467
+ return `${principal.address}.${principal.contractName}`;
1468
+ }
1469
+ return principal.address;
1470
+ }
1471
+ function assetToString(asset) {
1472
+ return `${asset.address}.${asset.contractName}::${asset.assetName}`;
1473
+ }
1474
+ function parseAsset(asset) {
1475
+ const [contractId, tokenName] = asset.split("::");
1476
+ const [addr, name] = parseContractId(contractId);
1477
+ return { address: addr, contractName: name, assetName: tokenName };
1478
+ }
1479
+ function convertPostCondition(pc) {
1480
+ switch (pc.type) {
1481
+ case "stx-postcondition":
1482
+ return {
1483
+ type: "stx",
1484
+ principal: resolvePrincipal(pc.address),
1485
+ conditionCode: FUNGIBLE_CODE_MAP[pc.condition],
1486
+ amount: parsePostConditionAmount(pc.amount)
1487
+ };
1488
+ case "ft-postcondition":
1489
+ return {
1490
+ type: "ft",
1491
+ principal: resolvePrincipal(pc.address),
1492
+ asset: parseAsset(pc.asset),
1493
+ conditionCode: FUNGIBLE_CODE_MAP[pc.condition],
1494
+ amount: parsePostConditionAmount(pc.amount)
1495
+ };
1496
+ case "nft-postcondition":
1497
+ return {
1498
+ type: "nft",
1499
+ principal: resolvePrincipal(pc.address),
1500
+ asset: parseAsset(pc.asset),
1501
+ conditionCode: NFT_CODE_MAP[pc.condition],
1502
+ assetId: pc.assetId
1503
+ };
1504
+ case "staking-postcondition":
1505
+ return {
1506
+ type: "staking",
1507
+ principal: resolvePrincipal(pc.address),
1508
+ conditionCode: FUNGIBLE_CODE_MAP[pc.condition],
1509
+ amount: parsePostConditionAmount(pc.amount)
1510
+ };
1511
+ case "pox-postcondition":
1512
+ return {
1513
+ type: "pox",
1514
+ principal: resolvePrincipal(pc.address),
1515
+ conditionCode: POX_CODE_MAP[pc.condition]
1516
+ };
1517
+ }
1518
+ }
1519
+ function wireToPostCondition(wire) {
1520
+ switch (wire.type) {
1521
+ case "stx":
1522
+ return {
1523
+ type: "stx-postcondition",
1524
+ address: principalToString(wire.principal),
1525
+ condition: fungibleName(wire.conditionCode),
1526
+ amount: wire.amount.toString()
1527
+ };
1528
+ case "ft":
1529
+ return {
1530
+ type: "ft-postcondition",
1531
+ address: principalToString(wire.principal),
1532
+ condition: fungibleName(wire.conditionCode),
1533
+ amount: wire.amount.toString(),
1534
+ asset: assetToString(wire.asset)
1535
+ };
1536
+ case "nft":
1537
+ return {
1538
+ type: "nft-postcondition",
1539
+ address: principalToString(wire.principal),
1540
+ condition: nftName(wire.conditionCode),
1541
+ asset: assetToString(wire.asset),
1542
+ assetId: wire.assetId
1543
+ };
1544
+ case "staking":
1545
+ return {
1546
+ type: "staking-postcondition",
1547
+ address: principalToString(wire.principal),
1548
+ condition: fungibleName(wire.conditionCode),
1549
+ amount: wire.amount.toString()
1550
+ };
1551
+ case "pox":
1552
+ return {
1553
+ type: "pox-postcondition",
1554
+ address: principalToString(wire.principal),
1555
+ condition: poxName(wire.conditionCode)
1556
+ };
1557
+ }
1558
+ }
1559
+ function fungibleName(code) {
1560
+ const name = FUNGIBLE_CODE_REVERSE[code];
1561
+ if (!name)
1562
+ throw new Error(`Unknown fungible post-condition code: ${code}`);
1563
+ return name;
1564
+ }
1565
+ function nftName(code) {
1566
+ const name = NFT_CODE_REVERSE[code];
1567
+ if (!name)
1568
+ throw new Error(`Unknown nft post-condition code: ${code}`);
1569
+ return name;
1570
+ }
1571
+ function poxName(code) {
1572
+ const name = POX_CODE_REVERSE[code];
1573
+ if (!name)
1574
+ throw new Error(`Unknown pox post-condition code: ${code}`);
1575
+ return name;
1576
+ }
1577
+ function fromHex(hex) {
1578
+ return wireToPostCondition(deserializePostConditionWire(hex));
1579
+ }
1580
+ function postConditionToHex(pc) {
1581
+ return bytesToHex(serializePostConditionWire(convertPostCondition(pc)));
1582
+ }
1583
+
1584
+ // src/postconditions/builder.ts
1585
+ class PartialPcWithPrincipal {
1586
+ address;
1587
+ constructor(address) {
1588
+ this.address = address;
1589
+ }
1590
+ willSendEq(amount) {
1591
+ return new PartialPcFtWithCode(this.address, amount, "eq");
1592
+ }
1593
+ willSendGte(amount) {
1594
+ return new PartialPcFtWithCode(this.address, amount, "gte");
1595
+ }
1596
+ willSendGt(amount) {
1597
+ return new PartialPcFtWithCode(this.address, amount, "gt");
1598
+ }
1599
+ willSendLte(amount) {
1600
+ return new PartialPcFtWithCode(this.address, amount, "lte");
1601
+ }
1602
+ willSendLt(amount) {
1603
+ return new PartialPcFtWithCode(this.address, amount, "lt");
1604
+ }
1605
+ willSendAsset() {
1606
+ return new PartialPcNftWithCode(this.address, "sent");
1607
+ }
1608
+ willNotSendAsset() {
1609
+ return new PartialPcNftWithCode(this.address, "not-sent");
1610
+ }
1611
+ willMaybeSendAsset() {
1612
+ return new PartialPcNftWithCode(this.address, "maybe-sent");
1613
+ }
1614
+ willPerformPox() {
1615
+ return {
1616
+ type: "pox-postcondition",
1617
+ address: this.address,
1618
+ condition: "will-perform"
1619
+ };
1620
+ }
1621
+ willNotPerformPox() {
1622
+ return {
1623
+ type: "pox-postcondition",
1624
+ address: this.address,
1625
+ condition: "will-not-perform"
1626
+ };
1627
+ }
1628
+ mayPerformPox() {
1629
+ return {
1630
+ type: "pox-postcondition",
1631
+ address: this.address,
1632
+ condition: "may-perform"
1633
+ };
1634
+ }
1635
+ }
1636
+
1637
+ class PartialPcFtWithCode {
1638
+ address;
1639
+ amount;
1640
+ code;
1641
+ constructor(address, amount, code) {
1642
+ this.address = address;
1643
+ this.amount = amount;
1644
+ this.code = code;
1645
+ }
1646
+ ustx() {
1647
+ return {
1648
+ type: "stx-postcondition",
1649
+ address: this.address,
1650
+ condition: this.code,
1651
+ amount: parsePostConditionAmount(this.amount).toString()
1652
+ };
1653
+ }
1654
+ ustxToLock() {
1655
+ return {
1656
+ type: "staking-postcondition",
1657
+ address: this.address,
1658
+ condition: this.code,
1659
+ amount: parsePostConditionAmount(this.amount).toString()
1660
+ };
1661
+ }
1662
+ ft(contractId, tokenName) {
1663
+ const [address, name] = contractId.split(".");
1664
+ if (!address || !validateStacksAddress(address) || !name) {
1665
+ throw new Error(`Invalid contract id: ${contractId}`);
1666
+ }
1667
+ return {
1668
+ type: "ft-postcondition",
1669
+ address: this.address,
1670
+ condition: this.code,
1671
+ amount: parsePostConditionAmount(this.amount).toString(),
1672
+ asset: `${contractId}::${tokenName}`
1673
+ };
1674
+ }
1675
+ }
1676
+
1677
+ class PartialPcNftWithCode {
1678
+ address;
1679
+ code;
1680
+ constructor(address, code) {
1681
+ this.address = address;
1682
+ this.code = code;
1683
+ }
1684
+ nft(assetOrContractId, tokenNameOrAssetId, assetId) {
1685
+ let contractAddress;
1686
+ let contractName;
1687
+ let tokenName;
1688
+ let id;
1689
+ if (assetId !== undefined) {
1690
+ [contractAddress, contractName] = parseContractId(assetOrContractId);
1691
+ tokenName = tokenNameOrAssetId;
1692
+ id = assetId;
1693
+ } else {
1694
+ const [principal, tName] = assetOrContractId.split("::");
1695
+ if (!principal || !tName)
1696
+ throw new Error(`Invalid asset name: ${assetOrContractId}`);
1697
+ [contractAddress, contractName] = parseContractId(principal);
1698
+ tokenName = tName;
1699
+ id = tokenNameOrAssetId;
1700
+ }
1701
+ if (!validateStacksAddress(contractAddress)) {
1702
+ throw new Error(`Invalid contract address: ${contractAddress}`);
1703
+ }
1704
+ return {
1705
+ type: "nft-postcondition",
1706
+ address: this.address,
1707
+ condition: this.code,
1708
+ asset: `${contractAddress}.${contractName}::${tokenName}`,
1709
+ assetId: id
1710
+ };
1711
+ }
1712
+ }
1713
+ var Pc = {
1714
+ principal(address) {
1715
+ const [addr, name] = address.split(".");
1716
+ if (!addr || !validateStacksAddress(addr) || typeof name === "string" && !name) {
1717
+ throw new Error(`Invalid principal: ${address}`);
1718
+ }
1719
+ return new PartialPcWithPrincipal(address);
1720
+ },
1721
+ origin() {
1722
+ return new PartialPcWithPrincipal("origin");
1723
+ },
1724
+ fromHex: (hex) => fromHex(hex)
1725
+ };
1
1726
  // src/pox/index.ts
2
1727
  var exports_pox = {};
3
1728
  __export(exports_pox, {
@@ -14,6 +1739,1792 @@ __export(exports_pox, {
14
1739
  });
15
1740
  module.exports = __toCommonJS(exports_pox);
16
1741
 
1742
+ // src/clarity/abi/utils.ts
1743
+ function toCamelCase(str) {
1744
+ return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/-([A-Z])/g, (_, letter) => letter).replace(/-(\d)/g, (_, digit) => digit).replace(/-/g, "").replace(/^\d/, "_$&");
1745
+ }
1746
+ // src/clarity/abi/guards.ts
1747
+ function isUint128(value) {
1748
+ return typeof value === "bigint" && value >= 0n && value <= MAX_U128;
1749
+ }
1750
+ function isInt128(value) {
1751
+ return typeof value === "bigint" && value >= MIN_I128 && value <= MAX_I128;
1752
+ }
1753
+ function isBool(value) {
1754
+ return typeof value === "boolean";
1755
+ }
1756
+ function isPrincipal(value) {
1757
+ return typeof value === "string" && parsePrincipal(value) !== null;
1758
+ }
1759
+ function isStandardPrincipal(value) {
1760
+ if (typeof value !== "string")
1761
+ return false;
1762
+ const parsed = parsePrincipal(value);
1763
+ return parsed !== null && parsed.contractName === undefined;
1764
+ }
1765
+ function isContractPrincipal(value) {
1766
+ if (typeof value !== "string")
1767
+ return false;
1768
+ const parsed = parsePrincipal(value);
1769
+ return parsed !== null && parsed.contractName !== undefined;
1770
+ }
1771
+ function isTraitReference(value) {
1772
+ return isContractPrincipal(value);
1773
+ }
1774
+ function isString(value) {
1775
+ return typeof value === "string";
1776
+ }
1777
+ function isUint8Array(value) {
1778
+ return value instanceof Uint8Array;
1779
+ }
1780
+ function isArray(value, itemGuard) {
1781
+ return Array.isArray(value) && value.every(itemGuard);
1782
+ }
1783
+ function isOptional(value, guard) {
1784
+ return value === null || guard(value);
1785
+ }
1786
+ function isOkResponse(response) {
1787
+ return "ok" in response && !("err" in response);
1788
+ }
1789
+ function isErrResponse(response) {
1790
+ return "err" in response && !("ok" in response);
1791
+ }
1792
+ function isResponse(value, okGuard, errGuard) {
1793
+ if (typeof value !== "object" || value === null)
1794
+ return false;
1795
+ const obj = value;
1796
+ if ("ok" in value && !("err" in value))
1797
+ return okGuard(obj.ok);
1798
+ if ("err" in value && !("ok" in value))
1799
+ return errGuard(obj.err);
1800
+ return false;
1801
+ }
1802
+ function isAbiList(type) {
1803
+ return typeof type === "object" && type !== null && "list" in type;
1804
+ }
1805
+ function isAbiTuple(type) {
1806
+ return typeof type === "object" && type !== null && "tuple" in type;
1807
+ }
1808
+ function isAbiOptional(type) {
1809
+ return typeof type === "object" && type !== null && "optional" in type;
1810
+ }
1811
+ function isAbiResponse(type) {
1812
+ return typeof type === "object" && type !== null && "response" in type;
1813
+ }
1814
+ function isAbiBuffer(type) {
1815
+ return typeof type === "object" && type !== null && "buff" in type;
1816
+ }
1817
+ function isAbiStringAscii(type) {
1818
+ return typeof type === "object" && type !== null && "string-ascii" in type;
1819
+ }
1820
+ function isAbiStringUtf8(type) {
1821
+ return typeof type === "object" && type !== null && "string-utf8" in type;
1822
+ }
1823
+ function isAbiTraitReference(type) {
1824
+ return type === "trait_reference";
1825
+ }
1826
+
1827
+ // src/clarity/bridge.ts
1828
+ var CV_TYPE_TAGS = new Set([
1829
+ "int",
1830
+ "uint",
1831
+ "true",
1832
+ "false",
1833
+ "address",
1834
+ "contract",
1835
+ "ascii",
1836
+ "utf8",
1837
+ "buffer",
1838
+ "list",
1839
+ "tuple",
1840
+ "none",
1841
+ "some",
1842
+ "ok",
1843
+ "err"
1844
+ ]);
1845
+ function isClarityValue(value) {
1846
+ if (typeof value !== "object" || value === null)
1847
+ return false;
1848
+ const type = value.type;
1849
+ if (typeof type !== "string" || !CV_TYPE_TAGS.has(type))
1850
+ return false;
1851
+ if (type === "true" || type === "false" || type === "none")
1852
+ return true;
1853
+ return "value" in value;
1854
+ }
1855
+ var HEX_PAIRS_REGEX = /^(?:[0-9a-fA-F]{2})+$/;
1856
+ function coerceBuffer(value) {
1857
+ if (value instanceof Uint8Array)
1858
+ return bufferCV(value);
1859
+ if (typeof value === "object" && value !== null && "type" in value) {
1860
+ const tagged = value;
1861
+ if (tagged.type === "buffer" && isClarityValue(value))
1862
+ return value;
1863
+ if (typeof tagged.value === "string") {
1864
+ if (tagged.type === "ascii")
1865
+ return Cl.bufferFromAscii(tagged.value);
1866
+ if (tagged.type === "utf8")
1867
+ return Cl.bufferFromUtf8(tagged.value);
1868
+ if (tagged.type === "hex")
1869
+ return Cl.bufferFromHex(tagged.value);
1870
+ }
1871
+ throw new Error(`Unsupported buffer input: ${JSON.stringify(value)}`);
1872
+ }
1873
+ if (typeof value === "string") {
1874
+ const hex = value.startsWith("0x") ? value.slice(2) : value;
1875
+ if (HEX_PAIRS_REGEX.test(hex))
1876
+ return Cl.bufferFromHex(hex);
1877
+ return Cl.bufferFromUtf8(value);
1878
+ }
1879
+ throw new Error("buffer arg expects Uint8Array, hex string, { type, value }, or BufferCV");
1880
+ }
1881
+ function jsToClarityValue(abiType, value) {
1882
+ if (isAbiBuffer(abiType))
1883
+ return coerceBuffer(value);
1884
+ if (isClarityValue(value))
1885
+ return value;
1886
+ if (abiType === "uint128")
1887
+ return uintCV(value);
1888
+ if (abiType === "int128")
1889
+ return intCV(value);
1890
+ if (abiType === "bool")
1891
+ return boolCV(value);
1892
+ if (abiType === "principal" || abiType === "trait_reference")
1893
+ return Cl.principal(value);
1894
+ if (isAbiStringAscii(abiType))
1895
+ return stringAsciiCV(value);
1896
+ if (isAbiStringUtf8(abiType))
1897
+ return stringUtf8CV(value);
1898
+ if (isAbiList(abiType)) {
1899
+ const arr = value;
1900
+ return listCV(arr.map((item) => jsToClarityValue(abiType.list.type, item)));
1901
+ }
1902
+ if (isAbiTuple(abiType)) {
1903
+ const obj = value;
1904
+ const data = {};
1905
+ for (const field of abiType.tuple) {
1906
+ const camelKey = toCamelCase(field.name);
1907
+ const hasOriginal = field.name in obj;
1908
+ const hasCamel = camelKey in obj;
1909
+ const fieldValue = hasOriginal ? obj[field.name] : hasCamel ? obj[camelKey] : undefined;
1910
+ if (fieldValue === undefined && !isAbiOptional(field.type)) {
1911
+ throw new Error(`Missing tuple field: ${field.name}`);
1912
+ }
1913
+ data[field.name] = jsToClarityValue(field.type, fieldValue);
1914
+ }
1915
+ return tupleCV(data);
1916
+ }
1917
+ if (isAbiOptional(abiType)) {
1918
+ if (value === null || value === undefined)
1919
+ return noneCV();
1920
+ return someCV(jsToClarityValue(abiType.optional, value));
1921
+ }
1922
+ if (isAbiResponse(abiType)) {
1923
+ const obj = value;
1924
+ if ("ok" in obj && !("err" in obj))
1925
+ return responseOkCV(jsToClarityValue(abiType.response.ok, obj.ok));
1926
+ if ("err" in obj && !("ok" in obj))
1927
+ return responseErrorCV(jsToClarityValue(abiType.response.error, obj.err));
1928
+ throw new Error("Response must have exactly 'ok' or 'err' property");
1929
+ }
1930
+ throw new Error(`Unknown ABI type: ${JSON.stringify(abiType)}`);
1931
+ }
1932
+ function clarityValueToJS(abiType, cv) {
1933
+ return clarityValueToJSInner(abiType, cv);
1934
+ }
1935
+ function clarityValueToJSUntyped(abiType, cv) {
1936
+ return clarityValueToJSInner(abiType, cv);
1937
+ }
1938
+ function clarityValueToJSInner(abiType, cv) {
1939
+ if (abiType === "uint128" || abiType === "int128") {
1940
+ if (cv.type !== "int" && cv.type !== "uint")
1941
+ throw new Error(`Expected int/uint CV, got ${cv.type}`);
1942
+ return cv.value;
1943
+ }
1944
+ if (abiType === "bool") {
1945
+ if (cv.type === "true")
1946
+ return true;
1947
+ if (cv.type === "false")
1948
+ return false;
1949
+ throw new Error(`Expected bool CV, got ${cv.type}`);
1950
+ }
1951
+ if (abiType === "principal" || abiType === "trait_reference") {
1952
+ if (cv.type !== "address" && cv.type !== "contract")
1953
+ throw new Error(`Expected principal CV, got ${cv.type}`);
1954
+ return cv.value;
1955
+ }
1956
+ if (isAbiStringAscii(abiType) || isAbiStringUtf8(abiType)) {
1957
+ if (cv.type !== "ascii" && cv.type !== "utf8")
1958
+ throw new Error(`Expected string CV, got ${cv.type}`);
1959
+ return cv.value;
1960
+ }
1961
+ if (isAbiBuffer(abiType)) {
1962
+ if (cv.type !== "buffer")
1963
+ throw new Error(`Expected buffer CV, got ${cv.type}`);
1964
+ const hex = cv.value;
1965
+ const bytes = new Uint8Array(hex.length / 2);
1966
+ for (let i = 0;i < bytes.length; i++) {
1967
+ bytes[i] = Number.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
1968
+ }
1969
+ return bytes;
1970
+ }
1971
+ if (isAbiList(abiType)) {
1972
+ if (cv.type !== "list")
1973
+ throw new Error(`Expected list CV, got ${cv.type}`);
1974
+ return cv.value.map((item) => clarityValueToJSInner(abiType.list.type, item));
1975
+ }
1976
+ if (isAbiTuple(abiType)) {
1977
+ if (cv.type !== "tuple")
1978
+ throw new Error(`Expected tuple CV, got ${cv.type}`);
1979
+ const result = {};
1980
+ for (const field of abiType.tuple) {
1981
+ const fieldCV = cv.value[field.name];
1982
+ if (!fieldCV)
1983
+ throw new Error(`Missing tuple field in CV: ${field.name}`);
1984
+ const camelKey = toCamelCase(field.name);
1985
+ result[camelKey] = clarityValueToJSInner(field.type, fieldCV);
1986
+ }
1987
+ return result;
1988
+ }
1989
+ if (isAbiOptional(abiType)) {
1990
+ if (cv.type === "none")
1991
+ return null;
1992
+ if (cv.type === "some")
1993
+ return clarityValueToJSInner(abiType.optional, cv.value);
1994
+ throw new Error(`Expected optional CV, got ${cv.type}`);
1995
+ }
1996
+ if (isAbiResponse(abiType)) {
1997
+ if (cv.type === "ok")
1998
+ return { ok: clarityValueToJSInner(abiType.response.ok, cv.value) };
1999
+ if (cv.type === "err")
2000
+ return { err: clarityValueToJSInner(abiType.response.error, cv.value) };
2001
+ throw new Error(`Expected response CV, got ${cv.type}`);
2002
+ }
2003
+ throw new Error(`Unknown ABI type: ${JSON.stringify(abiType)}`);
2004
+ }
2005
+
2006
+ // src/transactions/authorization.ts
2007
+ var import_hmac = require("@noble/hashes/hmac.js");
2008
+ var import_sha24 = require("@noble/hashes/sha2.js");
2009
+ var import_secp256k1 = require("@noble/secp256k1");
2010
+ import_secp256k1.etc.hmacSha256Sync = (key, ...msgs) => {
2011
+ const h = import_hmac.hmac.create(import_sha24.sha256, key);
2012
+ for (const msg of msgs)
2013
+ h.update(msg);
2014
+ return h.digest();
2015
+ };
2016
+ var EMPTY_SIG = bytesToHex(new Uint8Array(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES));
2017
+ function createSingleSigSpendingCondition(publicKey, nonce, fee) {
2018
+ const pubKeyBytes = hexToBytes(publicKey);
2019
+ const signer = hashP2PKH(pubKeyBytes);
2020
+ const isCompressed = pubKeyBytes.length === 33;
2021
+ return {
2022
+ hashMode: AddressHashMode.P2PKH,
2023
+ signer,
2024
+ nonce,
2025
+ fee,
2026
+ keyEncoding: isCompressed ? PubKeyEncoding.Compressed : PubKeyEncoding.Uncompressed,
2027
+ signature: EMPTY_SIG
2028
+ };
2029
+ }
2030
+ function createStandardAuth(spendingCondition) {
2031
+ return { authType: AuthType.Standard, spendingCondition };
2032
+ }
2033
+ function createSponsoredAuth(spendingCondition, sponsorSpendingCondition) {
2034
+ return {
2035
+ authType: AuthType.Sponsored,
2036
+ spendingCondition,
2037
+ sponsorSpendingCondition: sponsorSpendingCondition ?? createSingleSigSpendingCondition("0".repeat(66), 0n, 0n)
2038
+ };
2039
+ }
2040
+ function clearCondition(condition) {
2041
+ if ("signature" in condition) {
2042
+ return {
2043
+ ...condition,
2044
+ nonce: 0n,
2045
+ fee: 0n,
2046
+ signature: EMPTY_SIG
2047
+ };
2048
+ }
2049
+ return {
2050
+ ...condition,
2051
+ nonce: 0n,
2052
+ fee: 0n,
2053
+ fields: []
2054
+ };
2055
+ }
2056
+ function sponsorSigningSentinel() {
2057
+ return {
2058
+ hashMode: AddressHashMode.P2PKH,
2059
+ signer: "00".repeat(20),
2060
+ nonce: 0n,
2061
+ fee: 0n,
2062
+ keyEncoding: PubKeyEncoding.Compressed,
2063
+ signature: EMPTY_SIG
2064
+ };
2065
+ }
2066
+ function intoInitialSighashAuth(auth) {
2067
+ if (auth.authType === AuthType.Standard) {
2068
+ return createStandardAuth(clearCondition(auth.spendingCondition));
2069
+ }
2070
+ return createSponsoredAuth(clearCondition(auth.spendingCondition), sponsorSigningSentinel());
2071
+ }
2072
+ function sigHashPreSign(curSigHash, authType, fee, nonce) {
2073
+ const data = concatBytes(hexToBytes(curSigHash), new Uint8Array([authType]), intToBytes(fee, 8), intToBytes(nonce, 8));
2074
+ return txidFromBytes(data);
2075
+ }
2076
+ function sigHashPostSign(curSigHash, pubKeyEncoding, signature) {
2077
+ const data = concatBytes(hexToBytes(curSigHash), new Uint8Array([pubKeyEncoding]), hexToBytes(signature));
2078
+ return txidFromBytes(data);
2079
+ }
2080
+ function signWithKey(privateKey, messageHash) {
2081
+ const keyBytes = hexToBytes(privateKey).slice(0, 32);
2082
+ const sig = import_secp256k1.sign(messageHash, keyBytes, { lowS: true });
2083
+ const recoveryIdHex = intToHex(sig.recovery, 1);
2084
+ return recoveryIdHex + sig.toCompactHex();
2085
+ }
2086
+ function nextSignature(curSigHash, authType, fee, nonce, privateKey) {
2087
+ const sigHashPre = sigHashPreSign(curSigHash, authType, fee, nonce);
2088
+ const keyBytes = hexToBytes(privateKey).slice(0, 32);
2089
+ const pubKey = import_secp256k1.getPublicKey(keyBytes, true);
2090
+ const isCompressed = pubKey.length === 33;
2091
+ const pubKeyEncoding = isCompressed ? PubKeyEncoding.Compressed : PubKeyEncoding.Uncompressed;
2092
+ const nextSig = signWithKey(privateKey, sigHashPre);
2093
+ const nextSigHash = sigHashPostSign(sigHashPre, pubKeyEncoding, nextSig);
2094
+ return { nextSig, nextSigHash };
2095
+ }
2096
+
2097
+ // src/transactions/multisig.ts
2098
+ var import_secp256k12 = require("@noble/secp256k1");
2099
+ var OP_CHECKMULTISIG = 174;
2100
+ function isNonSequential(hashMode) {
2101
+ return (hashMode & 4) !== 0;
2102
+ }
2103
+ function makeRedeemScript(publicKeys, signaturesRequired) {
2104
+ const parts = [];
2105
+ parts.push(new Uint8Array([80 + signaturesRequired]));
2106
+ for (const pk of publicKeys) {
2107
+ const pkBytes = hexToBytes(pk);
2108
+ parts.push(new Uint8Array([pkBytes.length]));
2109
+ parts.push(pkBytes);
2110
+ }
2111
+ parts.push(new Uint8Array([80 + publicKeys.length]));
2112
+ parts.push(new Uint8Array([OP_CHECKMULTISIG]));
2113
+ return concatBytes(...parts);
2114
+ }
2115
+ function makeMultiSigAddress(publicKeys, signaturesRequired, chain) {
2116
+ if (signaturesRequired < 1 || signaturesRequired > publicKeys.length) {
2117
+ throw new Error(`signaturesRequired must be between 1 and ${publicKeys.length}`);
2118
+ }
2119
+ const redeemScript = makeRedeemScript(publicKeys, signaturesRequired);
2120
+ const signer = hash160(redeemScript);
2121
+ const version = chain?.addressVersion?.multiSig ?? 20;
2122
+ return c32address(version, bytesToHex(signer));
2123
+ }
2124
+ function createMultiSigSpendingCondition(publicKeys, signaturesRequired, nonce, fee, hashMode = AddressHashMode.P2SH) {
2125
+ const redeemScript = makeRedeemScript(publicKeys, signaturesRequired);
2126
+ const signer = bytesToHex(hash160(redeemScript));
2127
+ return {
2128
+ hashMode,
2129
+ signer,
2130
+ nonce,
2131
+ fee,
2132
+ fields: [],
2133
+ signaturesRequired
2134
+ };
2135
+ }
2136
+ function initialSigHash(tx) {
2137
+ const cleared = {
2138
+ ...tx,
2139
+ auth: intoInitialSighashAuth(tx.auth)
2140
+ };
2141
+ return txidFromBytes(serializeTransaction(cleared));
2142
+ }
2143
+ function nonSequentialPreSignHash(tx) {
2144
+ const condition = tx.auth.spendingCondition;
2145
+ const initHash = initialSigHash(tx);
2146
+ return sigHashPreSign(initHash, AuthType.Standard, condition.fee, condition.nonce);
2147
+ }
2148
+ function replayMultiSigSigHash(tx) {
2149
+ const condition = tx.auth.spendingCondition;
2150
+ if (isNonSequential(condition.hashMode)) {
2151
+ const preSign = nonSequentialPreSignHash(tx);
2152
+ let curSigHash2 = preSign;
2153
+ for (const field of condition.fields) {
2154
+ curSigHash2 = sigHashPostSign(curSigHash2, field.pubKeyEncoding, field.data);
2155
+ }
2156
+ return curSigHash2;
2157
+ }
2158
+ let curSigHash = initialSigHash(tx);
2159
+ for (const field of condition.fields) {
2160
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2161
+ curSigHash = sigHashPostSign(preSign, field.pubKeyEncoding, field.data);
2162
+ }
2163
+ return curSigHash;
2164
+ }
2165
+ function signMultiSig(tx, privateKey, publicKeys) {
2166
+ const keyBytes = hexToBytes(privateKey).slice(0, 32);
2167
+ const signerPubKey = bytesToHex(import_secp256k12.getPublicKey(keyBytes, true));
2168
+ const signerIndex = publicKeys.findIndex((pk) => pk === signerPubKey);
2169
+ if (signerIndex === -1) {
2170
+ throw new Error("Private key does not correspond to any signer in the multi-sig");
2171
+ }
2172
+ const condition = {
2173
+ ...tx.auth.spendingCondition
2174
+ };
2175
+ if (isNonSequential(condition.hashMode)) {
2176
+ return signNonSequential(tx, condition, privateKey);
2177
+ }
2178
+ return signSequential(tx, condition, privateKey, publicKeys, signerIndex);
2179
+ }
2180
+ function signNonSequential(tx, condition, privateKey) {
2181
+ const fields = [...condition.fields];
2182
+ const preSignHash = nonSequentialPreSignHash(tx);
2183
+ const keyBytes = hexToBytes(privateKey).slice(0, 32);
2184
+ const sig = import_secp256k12.sign(preSignHash, keyBytes, { lowS: true });
2185
+ const recoveryIdHex = intToHex(sig.recovery, 1);
2186
+ const nextSig = recoveryIdHex + sig.toCompactHex();
2187
+ fields.push({
2188
+ type: "signature",
2189
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2190
+ data: nextSig
2191
+ });
2192
+ const newCondition = { ...condition, fields };
2193
+ const sigCount = fields.filter((f) => f.type === "signature").length;
2194
+ if (sigCount >= condition.signaturesRequired) {
2195
+ return {
2196
+ ...tx,
2197
+ auth: { ...tx.auth, spendingCondition: newCondition }
2198
+ };
2199
+ }
2200
+ return {
2201
+ ...tx,
2202
+ auth: { ...tx.auth, spendingCondition: newCondition }
2203
+ };
2204
+ }
2205
+ function signSequential(tx, condition, privateKey, publicKeys, signerIndex) {
2206
+ const fields = [...condition.fields];
2207
+ let curSigHash = initialSigHash(tx);
2208
+ for (const field of fields) {
2209
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2210
+ curSigHash = sigHashPostSign(preSign, field.pubKeyEncoding, field.data);
2211
+ }
2212
+ for (let i = fields.length;i < signerIndex; i++) {
2213
+ const pubKeyField = {
2214
+ type: "publicKey",
2215
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2216
+ data: publicKeys[i]
2217
+ };
2218
+ fields.push(pubKeyField);
2219
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2220
+ curSigHash = sigHashPostSign(preSign, pubKeyField.pubKeyEncoding, pubKeyField.data);
2221
+ }
2222
+ const { nextSig, nextSigHash } = nextSignature(curSigHash, AuthType.Standard, condition.fee, condition.nonce, privateKey);
2223
+ fields.push({
2224
+ type: "signature",
2225
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2226
+ data: nextSig
2227
+ });
2228
+ curSigHash = nextSigHash;
2229
+ const newCondition = { ...condition, fields };
2230
+ const sigCount = fields.filter((f) => f.type === "signature").length;
2231
+ let finalCondition = newCondition;
2232
+ if (sigCount >= condition.signaturesRequired) {
2233
+ finalCondition = finalizeMultiSigCondition(newCondition, publicKeys, curSigHash);
2234
+ }
2235
+ return {
2236
+ ...tx,
2237
+ auth: {
2238
+ ...tx.auth,
2239
+ spendingCondition: finalCondition
2240
+ }
2241
+ };
2242
+ }
2243
+ async function signMultiSigWithAccount(tx, account, publicKeys) {
2244
+ const signerPubKey = account.publicKey;
2245
+ const signerIndex = publicKeys.findIndex((pk) => pk === signerPubKey);
2246
+ if (signerIndex === -1) {
2247
+ throw new Error("Account does not correspond to any signer in the multi-sig");
2248
+ }
2249
+ const condition = {
2250
+ ...tx.auth.spendingCondition
2251
+ };
2252
+ if (isNonSequential(condition.hashMode)) {
2253
+ return signNonSequentialWithAccount(tx, condition, account);
2254
+ }
2255
+ return signSequentialWithAccount(tx, condition, account, publicKeys, signerIndex);
2256
+ }
2257
+ async function signNonSequentialWithAccount(tx, condition, account) {
2258
+ const fields = [...condition.fields];
2259
+ const preSignHash = nonSequentialPreSignHash(tx);
2260
+ const sigBytes = await account.sign(hexToBytes(preSignHash));
2261
+ const nextSig = bytesToHex(sigBytes);
2262
+ fields.push({
2263
+ type: "signature",
2264
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2265
+ data: nextSig
2266
+ });
2267
+ const newCondition = { ...condition, fields };
2268
+ return {
2269
+ ...tx,
2270
+ auth: { ...tx.auth, spendingCondition: newCondition }
2271
+ };
2272
+ }
2273
+ async function signSequentialWithAccount(tx, condition, account, publicKeys, signerIndex) {
2274
+ const fields = [...condition.fields];
2275
+ let curSigHash = initialSigHash(tx);
2276
+ for (const field of fields) {
2277
+ const preSign2 = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2278
+ curSigHash = sigHashPostSign(preSign2, field.pubKeyEncoding, field.data);
2279
+ }
2280
+ for (let i = fields.length;i < signerIndex; i++) {
2281
+ const pubKeyField = {
2282
+ type: "publicKey",
2283
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2284
+ data: publicKeys[i]
2285
+ };
2286
+ fields.push(pubKeyField);
2287
+ const preSign2 = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2288
+ curSigHash = sigHashPostSign(preSign2, pubKeyField.pubKeyEncoding, pubKeyField.data);
2289
+ }
2290
+ const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
2291
+ const sigBytes = await account.sign(hexToBytes(preSign));
2292
+ const nextSig = bytesToHex(sigBytes);
2293
+ const nextSigHash = sigHashPostSign(preSign, PubKeyEncoding.Compressed, nextSig);
2294
+ fields.push({
2295
+ type: "signature",
2296
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2297
+ data: nextSig
2298
+ });
2299
+ curSigHash = nextSigHash;
2300
+ const newCondition = { ...condition, fields };
2301
+ const sigCount = fields.filter((f) => f.type === "signature").length;
2302
+ let finalCondition = newCondition;
2303
+ if (sigCount >= condition.signaturesRequired) {
2304
+ finalCondition = finalizeMultiSigCondition(newCondition, publicKeys, curSigHash);
2305
+ }
2306
+ return {
2307
+ ...tx,
2308
+ auth: {
2309
+ ...tx.auth,
2310
+ spendingCondition: finalCondition
2311
+ }
2312
+ };
2313
+ }
2314
+ function finalizeMultiSig(tx, publicKeys) {
2315
+ const condition = tx.auth.spendingCondition;
2316
+ if (isNonSequential(condition.hashMode)) {
2317
+ return tx;
2318
+ }
2319
+ const curSigHash = replayMultiSigSigHash(tx);
2320
+ const finalCondition = finalizeMultiSigCondition(condition, publicKeys, curSigHash);
2321
+ return {
2322
+ ...tx,
2323
+ auth: {
2324
+ ...tx.auth,
2325
+ spendingCondition: finalCondition
2326
+ }
2327
+ };
2328
+ }
2329
+ function finalizeMultiSigCondition(condition, publicKeys, curSigHash) {
2330
+ const fields = [...condition.fields];
2331
+ let sigHash = curSigHash;
2332
+ for (let i = fields.length;i < publicKeys.length; i++) {
2333
+ const pubKeyField = {
2334
+ type: "publicKey",
2335
+ pubKeyEncoding: PubKeyEncoding.Compressed,
2336
+ data: publicKeys[i]
2337
+ };
2338
+ fields.push(pubKeyField);
2339
+ const preSign = sigHashPreSign(sigHash, AuthType.Standard, condition.fee, condition.nonce);
2340
+ sigHash = sigHashPostSign(preSign, pubKeyField.pubKeyEncoding, pubKeyField.data);
2341
+ }
2342
+ return { ...condition, fields };
2343
+ }
2344
+ function combineMultiSigSignatures(baseTx, signedTxs) {
2345
+ const condition = baseTx.auth.spendingCondition;
2346
+ if (!isNonSequential(condition.hashMode)) {
2347
+ throw new Error("combineMultiSigSignatures only works with non-sequential hash modes (SIP-027)");
2348
+ }
2349
+ const seenSigs = new Set;
2350
+ const signatures = [];
2351
+ for (const stx of signedTxs) {
2352
+ const stxCondition = stx.auth.spendingCondition;
2353
+ for (const field of stxCondition.fields) {
2354
+ if (field.type === "signature" && !seenSigs.has(field.data)) {
2355
+ seenSigs.add(field.data);
2356
+ signatures.push(field);
2357
+ }
2358
+ }
2359
+ }
2360
+ if (signatures.length === 0) {
2361
+ throw new Error("No signatures found in the provided transactions");
2362
+ }
2363
+ const newCondition = {
2364
+ ...condition,
2365
+ fields: signatures
2366
+ };
2367
+ return {
2368
+ ...baseTx,
2369
+ auth: { ...baseTx.auth, spendingCondition: newCondition }
2370
+ };
2371
+ }
2372
+
2373
+ // src/transactions/build.ts
2374
+ function resolvePcMode(mode) {
2375
+ if (mode === "allow")
2376
+ return PostConditionModeWire.Allow;
2377
+ if (mode === "originator")
2378
+ return PostConditionModeWire.Originator;
2379
+ return PostConditionModeWire.Deny;
2380
+ }
2381
+ function convertPostConditions(pcs) {
2382
+ if (!pcs || pcs.length === 0)
2383
+ return [];
2384
+ return pcs.map((pc) => convertPostCondition(typeof pc === "string" ? fromHex(pc) : pc));
2385
+ }
2386
+ function resolveSpendingCondition(opts, nonce, fee) {
2387
+ if (opts.publicKeys) {
2388
+ return createMultiSigSpendingCondition(opts.publicKeys, opts.signaturesRequired, nonce, fee, opts.hashMode);
2389
+ }
2390
+ return createSingleSigSpendingCondition(opts.publicKey, nonce, fee);
2391
+ }
2392
+ function resolveAuth(spendingCondition, sponsored) {
2393
+ return sponsored ? createSponsoredAuth(spendingCondition) : createStandardAuth(spendingCondition);
2394
+ }
2395
+ function resolveVersionAndChainId(chain) {
2396
+ if (!chain)
2397
+ return { version: 0, chainId: 1 };
2398
+ return { version: chain.transactionVersion, chainId: chain.id };
2399
+ }
2400
+ function buildTokenTransfer(options) {
2401
+ const { version, chainId } = resolveVersionAndChainId(options.chain);
2402
+ const fee = intToBigInt(options.fee);
2403
+ const nonce = intToBigInt(options.nonce);
2404
+ const spendingCondition = resolveSpendingCondition(options, nonce, fee);
2405
+ const recipient = Cl.principal(options.recipient);
2406
+ const tx = {
2407
+ version,
2408
+ chainId,
2409
+ auth: resolveAuth(spendingCondition, options.sponsored),
2410
+ anchorMode: AnchorMode.Any,
2411
+ postConditionMode: resolvePcMode(options.postConditionMode),
2412
+ postConditions: convertPostConditions(options.postConditions),
2413
+ payload: {
2414
+ payloadType: PayloadType.TokenTransfer,
2415
+ recipient,
2416
+ amount: intToBigInt(options.amount),
2417
+ memo: options.memo ?? ""
2418
+ }
2419
+ };
2420
+ if (options.publicKeys) {
2421
+ tx._multisig = { publicKeys: options.publicKeys };
2422
+ }
2423
+ return tx;
2424
+ }
2425
+ function buildContractCall(options) {
2426
+ const { version, chainId } = resolveVersionAndChainId(options.chain);
2427
+ const fee = intToBigInt(options.fee);
2428
+ const nonce = intToBigInt(options.nonce);
2429
+ const spendingCondition = resolveSpendingCondition(options, nonce, fee);
2430
+ const tx = {
2431
+ version,
2432
+ chainId,
2433
+ auth: resolveAuth(spendingCondition, options.sponsored),
2434
+ anchorMode: AnchorMode.Any,
2435
+ postConditionMode: resolvePcMode(options.postConditionMode),
2436
+ postConditions: convertPostConditions(options.postConditions),
2437
+ payload: {
2438
+ payloadType: PayloadType.ContractCall,
2439
+ contractAddress: options.contractAddress,
2440
+ contractName: options.contractName,
2441
+ functionName: options.functionName,
2442
+ functionArgs: options.functionArgs
2443
+ }
2444
+ };
2445
+ if (options.publicKeys) {
2446
+ tx._multisig = { publicKeys: options.publicKeys };
2447
+ }
2448
+ return tx;
2449
+ }
2450
+ function buildContractDeploy(options) {
2451
+ const { version, chainId } = resolveVersionAndChainId(options.chain);
2452
+ const fee = intToBigInt(options.fee);
2453
+ const nonce = intToBigInt(options.nonce);
2454
+ const spendingCondition = resolveSpendingCondition(options, nonce, fee);
2455
+ const clarityVersion = options.clarityVersion ?? ClarityVersion.Clarity4;
2456
+ const tx = {
2457
+ version,
2458
+ chainId,
2459
+ auth: resolveAuth(spendingCondition, options.sponsored),
2460
+ anchorMode: AnchorMode.Any,
2461
+ postConditionMode: resolvePcMode(options.postConditionMode),
2462
+ postConditions: convertPostConditions(options.postConditions),
2463
+ payload: {
2464
+ payloadType: PayloadType.VersionedSmartContract,
2465
+ clarityVersion,
2466
+ contractName: options.contractName,
2467
+ codeBody: options.codeBody
2468
+ }
2469
+ };
2470
+ if (options.publicKeys) {
2471
+ tx._multisig = { publicKeys: options.publicKeys };
2472
+ }
2473
+ return tx;
2474
+ }
2475
+
2476
+ // src/errors/response.ts
2477
+ class MalformedResponseError extends BaseError {
2478
+ name = "MalformedResponseError";
2479
+ }
2480
+
2481
+ class ReadContractError extends BaseError {
2482
+ name = "ReadContractError";
2483
+ }
2484
+
2485
+ // src/actions/public/getMapEntry.ts
2486
+ async function getMapEntry(client, params) {
2487
+ const [address, name] = parseContractId(params.contract);
2488
+ const serializedKey = with0x(bytesToHex(serializeCVBytes(params.key)));
2489
+ const data = await client.request(`/v2/map_entry/${address}/${name}/${params.mapName}`, {
2490
+ method: "POST",
2491
+ body: serializedKey
2492
+ });
2493
+ if (typeof data?.data !== "string") {
2494
+ throw new MalformedResponseError(`getMapEntry: /v2/map_entry/${address}/${name}/${params.mapName} response is missing "data"`);
2495
+ }
2496
+ return deserializeCVBytes(data.data);
2497
+ }
2498
+
2499
+ // src/actions/public/getNonce.ts
2500
+ async function getNonce(client, params) {
2501
+ const data = await client.request(`/v2/accounts/${encodeURIComponent(params.address)}`, { method: "GET" });
2502
+ const nonce = data?.nonce;
2503
+ if (typeof nonce !== "number" && typeof nonce !== "string") {
2504
+ throw new MalformedResponseError(`getNonce: /v2/accounts/${params.address} response is missing "nonce"`);
2505
+ }
2506
+ return BigInt(nonce);
2507
+ }
2508
+
2509
+ // src/actions/public/readContract.ts
2510
+ async function readContract(client, params) {
2511
+ const [address, name] = parseContractId(params.contract);
2512
+ const sender = params.sender ?? address;
2513
+ const serializedArgs = (params.args ?? []).map((arg) => with0x(bytesToHex(serializeCVBytes(arg))));
2514
+ const path = `/v2/contracts/call-read/${encodeURIComponent(address)}/${encodeURIComponent(name)}/${encodeURIComponent(params.functionName)}`;
2515
+ const data = await client.request(params.tip ? `${path}?tip=${encodeURIComponent(params.tip)}` : path, {
2516
+ method: "POST",
2517
+ body: {
2518
+ sender,
2519
+ arguments: serializedArgs
2520
+ }
2521
+ });
2522
+ if (data.okay) {
2523
+ if (typeof data.result !== "string") {
2524
+ throw new MalformedResponseError(`readContract: /v2/contracts/call-read response is missing "result"`);
2525
+ }
2526
+ return deserializeCVBytes(data.result);
2527
+ }
2528
+ throw new ReadContractError(data.cause ?? "Read-only call failed");
2529
+ }
2530
+
2531
+ // src/transactions/signer.ts
2532
+ function txid(tx) {
2533
+ return txidFromBytes(serializeTransaction(tx));
2534
+ }
2535
+ function signBegin(tx) {
2536
+ const cleared = {
2537
+ ...tx,
2538
+ auth: intoInitialSighashAuth(tx.auth)
2539
+ };
2540
+ return txid(cleared);
2541
+ }
2542
+ function signTransaction(tx, privateKey) {
2543
+ const sigHash = signBegin(tx);
2544
+ const condition = tx.auth.spendingCondition;
2545
+ const { nextSig } = nextSignature(sigHash, AuthType.Standard, condition.fee, condition.nonce, privateKey);
2546
+ return {
2547
+ ...tx,
2548
+ auth: {
2549
+ ...tx.auth,
2550
+ spendingCondition: {
2551
+ ...condition,
2552
+ signature: nextSig
2553
+ }
2554
+ }
2555
+ };
2556
+ }
2557
+ async function signTransactionWithAccount(tx, account) {
2558
+ const sigHash = signBegin(tx);
2559
+ const condition = tx.auth.spendingCondition;
2560
+ const sigHashPre = sigHashPreSign(sigHash, AuthType.Standard, condition.fee, condition.nonce);
2561
+ const sigBytes = await account.sign(hexToBytes(sigHashPre));
2562
+ const nextSig = bytesToHex(sigBytes);
2563
+ return {
2564
+ ...tx,
2565
+ auth: {
2566
+ ...tx.auth,
2567
+ spendingCondition: {
2568
+ ...condition,
2569
+ signature: nextSig
2570
+ }
2571
+ }
2572
+ };
2573
+ }
2574
+ function getTransactionId(tx) {
2575
+ return txid(tx);
2576
+ }
2577
+ function getOriginSigHash(tx) {
2578
+ const condition = tx.auth.spendingCondition;
2579
+ if ("fields" in condition) {
2580
+ return replayMultiSigSigHash(tx);
2581
+ }
2582
+ const initialSigHash2 = signBegin(tx);
2583
+ const sc = condition;
2584
+ const preSign = sigHashPreSign(initialSigHash2, AuthType.Standard, sc.fee, sc.nonce);
2585
+ return sigHashPostSign(preSign, sc.keyEncoding, sc.signature);
2586
+ }
2587
+ function signSponsor(tx, privateKey) {
2588
+ if (tx.auth.authType !== AuthType.Sponsored) {
2589
+ throw new Error("Transaction must be sponsored");
2590
+ }
2591
+ const auth = tx.auth;
2592
+ const sponsorCondition = auth.sponsorSpendingCondition;
2593
+ const originSigHash = getOriginSigHash(tx);
2594
+ const { nextSig } = nextSignature(originSigHash, AuthType.Sponsored, sponsorCondition.fee, sponsorCondition.nonce, privateKey);
2595
+ return {
2596
+ ...tx,
2597
+ auth: {
2598
+ ...auth,
2599
+ sponsorSpendingCondition: {
2600
+ ...sponsorCondition,
2601
+ signature: nextSig
2602
+ }
2603
+ }
2604
+ };
2605
+ }
2606
+ async function signSponsorWithAccount(tx, account) {
2607
+ if (tx.auth.authType !== AuthType.Sponsored) {
2608
+ throw new Error("Transaction must be sponsored");
2609
+ }
2610
+ const auth = tx.auth;
2611
+ const sponsorCondition = auth.sponsorSpendingCondition;
2612
+ const originSigHash = getOriginSigHash(tx);
2613
+ const sigHashPre = sigHashPreSign(originSigHash, AuthType.Sponsored, sponsorCondition.fee, sponsorCondition.nonce);
2614
+ const sigBytes = await account.sign(hexToBytes(sigHashPre));
2615
+ const nextSig = bytesToHex(sigBytes);
2616
+ return {
2617
+ ...tx,
2618
+ auth: {
2619
+ ...auth,
2620
+ sponsorSpendingCondition: {
2621
+ ...sponsorCondition,
2622
+ signature: nextSig
2623
+ }
2624
+ }
2625
+ };
2626
+ }
2627
+
2628
+ // src/errors/http.ts
2629
+ class HttpRequestError extends BaseError {
2630
+ name = "HttpRequestError";
2631
+ status;
2632
+ url;
2633
+ method;
2634
+ constructor(status, options) {
2635
+ const where = options?.url !== undefined ? ` (${options.method ?? "GET"} ${options.url})` : "";
2636
+ super(`HTTP request failed with status ${status}${where}`, options);
2637
+ this.status = status;
2638
+ this.url = options?.url;
2639
+ this.method = options?.method;
2640
+ }
2641
+ }
2642
+
2643
+ // src/errors/transport.ts
2644
+ class TimeoutError extends BaseError {
2645
+ name = "TimeoutError";
2646
+ method;
2647
+ url;
2648
+ timeout;
2649
+ attempt;
2650
+ constructor(params) {
2651
+ super(`${params.method} ${params.url} did not complete within ${params.timeout}ms (attempt ${params.attempt + 1})`);
2652
+ this.method = params.method;
2653
+ this.url = params.url;
2654
+ this.timeout = params.timeout;
2655
+ this.attempt = params.attempt;
2656
+ }
2657
+ }
2658
+
2659
+ // src/transports/createTransport.ts
2660
+ function createTransport(type, config) {
2661
+ const { request, apiKey: _apiKey, ...exposed } = config;
2662
+ return {
2663
+ type,
2664
+ request,
2665
+ config: exposed
2666
+ };
2667
+ }
2668
+ var MAX_ERROR_DETAILS_BYTES = 4096;
2669
+ function capDetails(body) {
2670
+ if (body === undefined)
2671
+ return;
2672
+ const bytes = new TextEncoder().encode(body);
2673
+ if (bytes.length <= MAX_ERROR_DETAILS_BYTES)
2674
+ return body;
2675
+ const head = new TextDecoder().decode(bytes.subarray(0, MAX_ERROR_DETAILS_BYTES));
2676
+ return `${head}... [truncated ${bytes.length - MAX_ERROR_DETAILS_BYTES} bytes]`;
2677
+ }
2678
+ function isRetryableStatus(status) {
2679
+ return status === 429 || status >= 500;
2680
+ }
2681
+ var MAX_RETRY_AFTER_MS = 60000;
2682
+ function retryAfterMs(response) {
2683
+ const value = response.headers.get("Retry-After");
2684
+ if (!value)
2685
+ return;
2686
+ const seconds = Number(value);
2687
+ const ms = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - Date.now();
2688
+ if (!Number.isFinite(ms) || ms < 0 || ms > MAX_RETRY_AFTER_MS)
2689
+ return;
2690
+ return ms;
2691
+ }
2692
+ function abortReason(signal) {
2693
+ const reason = signal.reason;
2694
+ if (reason instanceof Error)
2695
+ return reason;
2696
+ return new DOMException(typeof reason === "string" ? reason : "The operation was aborted", "AbortError");
2697
+ }
2698
+ function sleep(ms, signal) {
2699
+ return new Promise((resolve, reject) => {
2700
+ if (signal?.aborted)
2701
+ return reject(abortReason(signal));
2702
+ const onAbort = () => {
2703
+ clearTimeout(id);
2704
+ reject(abortReason(signal));
2705
+ };
2706
+ const id = setTimeout(() => {
2707
+ signal?.removeEventListener("abort", onAbort);
2708
+ resolve();
2709
+ }, ms);
2710
+ signal?.addEventListener("abort", onAbort, { once: true });
2711
+ });
2712
+ }
2713
+ async function fetchWithRetry(url, options, retryCount, retryDelay, timeout, extra = {}) {
2714
+ const { signal } = extra;
2715
+ const read = extra.read ?? (async (response) => response);
2716
+ const method = options.method ?? "GET";
2717
+ let lastError;
2718
+ for (let attempt = 0;attempt <= retryCount; attempt++) {
2719
+ if (signal?.aborted)
2720
+ throw abortReason(signal);
2721
+ const controller = new AbortController;
2722
+ let timedOut = false;
2723
+ const timeoutId = setTimeout(() => {
2724
+ timedOut = true;
2725
+ controller.abort(new TimeoutError({ method, url, timeout, attempt }));
2726
+ }, timeout);
2727
+ const onCallerAbort = () => controller.abort(abortReason(signal));
2728
+ signal?.addEventListener("abort", onCallerAbort, { once: true });
2729
+ const aborted = new Promise((_, reject) => {
2730
+ if (controller.signal.aborted)
2731
+ return reject(controller.signal.reason);
2732
+ controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
2733
+ });
2734
+ let response;
2735
+ try {
2736
+ try {
2737
+ response = await Promise.race([
2738
+ fetch(url, { ...options, signal: controller.signal }),
2739
+ aborted
2740
+ ]);
2741
+ } catch (error) {
2742
+ if (signal?.aborted)
2743
+ throw abortReason(signal);
2744
+ lastError = timedOut ? new TimeoutError({ method, url, timeout, attempt }) : error instanceof Error ? error : new Error(String(error));
2745
+ if (attempt < retryCount) {
2746
+ clearTimeout(timeoutId);
2747
+ await sleep(retryDelay * (attempt + 1), signal);
2748
+ continue;
2749
+ }
2750
+ throw lastError;
2751
+ }
2752
+ if (response.ok) {
2753
+ try {
2754
+ return await Promise.race([read(response), aborted]);
2755
+ } catch (error) {
2756
+ response.body?.cancel().catch(() => {});
2757
+ if (signal?.aborted)
2758
+ throw abortReason(signal);
2759
+ if (!timedOut)
2760
+ throw error;
2761
+ lastError = new TimeoutError({ method, url, timeout, attempt });
2762
+ if (attempt < retryCount) {
2763
+ clearTimeout(timeoutId);
2764
+ await sleep(retryDelay * (attempt + 1), signal);
2765
+ continue;
2766
+ }
2767
+ throw lastError;
2768
+ }
2769
+ }
2770
+ const retryable = isRetryableStatus(response.status);
2771
+ if (!retryable || attempt === retryCount) {
2772
+ const body = await Promise.race([
2773
+ response.text().catch(() => {
2774
+ return;
2775
+ }),
2776
+ aborted.catch(() => {
2777
+ return;
2778
+ })
2779
+ ]);
2780
+ throw new HttpRequestError(response.status, {
2781
+ details: capDetails(body),
2782
+ url,
2783
+ method
2784
+ });
2785
+ }
2786
+ lastError = new HttpRequestError(response.status, { url, method });
2787
+ const delay = retryAfterMs(response) ?? retryDelay * (attempt + 1);
2788
+ response.body?.cancel().catch(() => {});
2789
+ clearTimeout(timeoutId);
2790
+ await sleep(delay, signal);
2791
+ } finally {
2792
+ clearTimeout(timeoutId);
2793
+ signal?.removeEventListener("abort", onCallerAbort);
2794
+ }
2795
+ }
2796
+ throw lastError ?? new Error("Request failed");
2797
+ }
2798
+ async function readBody(response) {
2799
+ const contentType = response.headers.get("content-type") ?? "";
2800
+ if (contentType.includes("application/json")) {
2801
+ return response.json();
2802
+ }
2803
+ return response.text();
2804
+ }
2805
+ function buildRequestFn(baseUrl, config) {
2806
+ const {
2807
+ timeout = 30000,
2808
+ retryCount = 3,
2809
+ retryDelay = 150,
2810
+ fetchOptions = {},
2811
+ apiKey
2812
+ } = config;
2813
+ return async (path, options) => {
2814
+ const url = `${baseUrl.replace(/\/$/, "")}${path}`;
2815
+ const headers = {
2816
+ "Content-Type": "application/json",
2817
+ ...fetchOptions.headers,
2818
+ ...options?.headers
2819
+ };
2820
+ if (apiKey) {
2821
+ headers["x-api-key"] = apiKey;
2822
+ }
2823
+ const init = {
2824
+ ...fetchOptions,
2825
+ method: options?.method ?? "GET",
2826
+ headers
2827
+ };
2828
+ if (options?.body !== undefined) {
2829
+ init.body = JSON.stringify(options.body);
2830
+ }
2831
+ return fetchWithRetry(url, init, options?.retryCount ?? retryCount, retryDelay, timeout, { signal: options?.signal, read: readBody });
2832
+ };
2833
+ }
2834
+
2835
+ // src/actions/public/txSources.ts
2836
+ class IndexSourceConfigError extends Error {
2837
+ name = "IndexSourceConfigError";
2838
+ }
2839
+ function isHiroHost(url, client) {
2840
+ let hostname;
2841
+ try {
2842
+ hostname = new URL(url).hostname;
2843
+ } catch {
2844
+ return false;
2845
+ }
2846
+ if (hostname === "hiro.so" || hostname.endsWith(".hiro.so"))
2847
+ return true;
2848
+ const defaults = client.chain?.rpcUrls?.default?.http ?? [];
2849
+ return defaults.some((d) => {
2850
+ try {
2851
+ return new URL(d).hostname === hostname && hostname !== "localhost";
2852
+ } catch {
2853
+ return false;
2854
+ }
2855
+ });
2856
+ }
2857
+ function indexRequestFn(client, baseUrl, sourceName) {
2858
+ const transportUrl = client.transport.config.url?.replace(/\/$/, "");
2859
+ if (baseUrl === undefined) {
2860
+ if (!transportUrl) {
2861
+ throw new IndexSourceConfigError(`${sourceName} needs the URL of your Secondlayer instance: pass baseUrl, or use an http() transport pointed at the instance`);
2862
+ }
2863
+ if (isHiroHost(transportUrl, client)) {
2864
+ 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`);
2865
+ }
2866
+ return client.request;
2867
+ }
2868
+ const target = baseUrl.replace(/\/$/, "");
2869
+ if (target === transportUrl)
2870
+ return client.request;
2871
+ const { timeout, retryCount, retryDelay } = client.transport.config;
2872
+ return buildRequestFn(target, { timeout, retryCount, retryDelay });
2873
+ }
2874
+ function indexNotFound(error, sourceName) {
2875
+ if (!(error instanceof HttpRequestError) || error.status !== 404) {
2876
+ return false;
2877
+ }
2878
+ const body = error.details;
2879
+ if (body !== undefined) {
2880
+ try {
2881
+ JSON.parse(body);
2882
+ } catch {
2883
+ 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 });
2884
+ }
2885
+ }
2886
+ return true;
2887
+ }
2888
+ function normalizeTxid(txid2) {
2889
+ return txid2.startsWith("0x") ? txid2 : `0x${txid2}`;
2890
+ }
2891
+ function decodeResultHex(hex) {
2892
+ if (!hex)
2893
+ return {};
2894
+ try {
2895
+ return { result: deserializeCVBytes(hex), resultHex: hex };
2896
+ } catch {
2897
+ return { resultHex: hex };
2898
+ }
2899
+ }
2900
+ function normalizeStatus(txStatus) {
2901
+ switch (txStatus) {
2902
+ case "pending":
2903
+ case "success":
2904
+ case "abort_by_response":
2905
+ case "abort_by_post_condition":
2906
+ return txStatus;
2907
+ default:
2908
+ return txStatus.startsWith("dropped") ? "dropped" : undefined;
2909
+ }
2910
+ }
2911
+ function extendedApiSource() {
2912
+ return {
2913
+ async get({ client, txid: txid2 }) {
2914
+ let data;
2915
+ try {
2916
+ data = await client.request(`/extended/v1/tx/${encodeURIComponent(normalizeTxid(txid2))}`, { method: "GET" });
2917
+ } catch (error) {
2918
+ if (error instanceof HttpRequestError && error.status === 404) {
2919
+ return { receipt: null };
2920
+ }
2921
+ throw error;
2922
+ }
2923
+ const txStatus = typeof data?.tx_status === "string" ? data.tx_status : undefined;
2924
+ if (!txStatus)
2925
+ return { receipt: null };
2926
+ const status = normalizeStatus(txStatus);
2927
+ if (!status)
2928
+ return { receipt: null };
2929
+ return {
2930
+ receipt: {
2931
+ txid: normalizeTxid(txid2),
2932
+ status,
2933
+ blockHeight: typeof data.block_height === "number" && data.block_height > 0 ? data.block_height : undefined,
2934
+ blockHash: data.block_hash ?? undefined,
2935
+ ...decodeResultHex(data.tx_result?.hex),
2936
+ events: Array.isArray(data.events) ? data.events : [],
2937
+ raw: data
2938
+ }
2939
+ };
2940
+ }
2941
+ };
2942
+ }
2943
+ function indexTxSource(params = {}) {
2944
+ const headers = params.apiKey ? { authorization: `Bearer ${params.apiKey}` } : undefined;
2945
+ return {
2946
+ canonicalOnly: true,
2947
+ async get({ client, txid: txid2 }) {
2948
+ const request = indexRequestFn(client, params.baseUrl, "indexTxSource");
2949
+ let data;
2950
+ try {
2951
+ data = await request(`/v1/index/transactions/${normalizeTxid(txid2)}`, {
2952
+ method: "GET",
2953
+ headers
2954
+ });
2955
+ } catch (error) {
2956
+ if (indexNotFound(error, "indexTxSource"))
2957
+ return { receipt: null };
2958
+ throw error;
2959
+ }
2960
+ const tx = data.transaction;
2961
+ const tip = data.tip?.block_height;
2962
+ if (!tx)
2963
+ return { receipt: null, tip };
2964
+ const status = normalizeStatus(tx.status) ?? "success";
2965
+ return {
2966
+ receipt: {
2967
+ txid: normalizeTxid(tx.tx_id),
2968
+ status,
2969
+ blockHeight: tx.block_height,
2970
+ ...decodeResultHex(tx.contract_call?.result_hex),
2971
+ events: [],
2972
+ raw: data
2973
+ },
2974
+ tip
2975
+ };
2976
+ }
2977
+ };
2978
+ }
2979
+
2980
+ // src/actions/public/getTransaction.ts
2981
+ async function getTransaction(client, params) {
2982
+ const source = params.source ?? extendedApiSource();
2983
+ const { receipt } = await source.get({ client, txid: params.txid });
2984
+ return receipt;
2985
+ }
2986
+
2987
+ // src/actions/public/getBlockHeight.ts
2988
+ async function getBlockHeight(client) {
2989
+ const data = await client.request("/v2/info", { method: "GET" });
2990
+ if (typeof data?.stacks_tip_height !== "number") {
2991
+ throw new MalformedResponseError('getBlockHeight: /v2/info response is missing "stacks_tip_height"');
2992
+ }
2993
+ return data.stacks_tip_height;
2994
+ }
2995
+
2996
+ // src/actions/public/waitForTransactionReceipt.ts
2997
+ var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
2998
+ async function waitForTransactionReceipt(client, params) {
2999
+ const {
3000
+ txid: txid2,
3001
+ confirmations = 1,
3002
+ timeout = 180000,
3003
+ pollingInterval = 3000
3004
+ } = params;
3005
+ const source = params.source ?? extendedApiSource();
3006
+ const droppedGracePeriod = params.droppedGracePeriod ?? (source.canonicalOnly ? timeout : 30000);
3007
+ const startedAt = Date.now();
3008
+ let unknownSince = null;
3009
+ let everPending = false;
3010
+ while (true) {
3011
+ const snapshot = await source.get({ client, txid: txid2 });
3012
+ const receipt = snapshot.receipt;
3013
+ if (receipt === null) {
3014
+ unknownSince ??= Date.now();
3015
+ if (Date.now() - unknownSince >= droppedGracePeriod) {
3016
+ throw new TransactionDroppedError(everPending ? `Transaction ${txid2} left the mempool without being mined` : `Transaction ${txid2} was never observed by the status source`, { txid: txid2 });
3017
+ }
3018
+ } else {
3019
+ unknownSince = null;
3020
+ switch (receipt.status) {
3021
+ case "dropped":
3022
+ throw new TransactionDroppedError(`Transaction ${txid2} was dropped from the mempool`, { txid: txid2 });
3023
+ case "abort_by_response":
3024
+ case "abort_by_post_condition":
3025
+ throw new TransactionAbortedError(`Transaction ${txid2} aborted (${receipt.status})`, { receipt });
3026
+ case "pending":
3027
+ everPending = true;
3028
+ break;
3029
+ case "success": {
3030
+ if (confirmations <= 1)
3031
+ return receipt;
3032
+ if (receipt.blockHeight !== undefined) {
3033
+ const tip = snapshot.tip ?? await getBlockHeight(client);
3034
+ if (tip - receipt.blockHeight + 1 >= confirmations)
3035
+ return receipt;
3036
+ }
3037
+ break;
3038
+ }
3039
+ }
3040
+ }
3041
+ if (Date.now() - startedAt >= timeout) {
3042
+ throw new WaitForTransactionTimeoutError(`Timed out after ${timeout}ms waiting for transaction ${txid2}`, { txid: txid2 });
3043
+ }
3044
+ await sleep2(pollingInterval);
3045
+ }
3046
+ }
3047
+
3048
+ // src/actions/wallet/sendTransaction.ts
3049
+ async function sendTransaction(client, params) {
3050
+ const hex = bytesToHex(serializeTransaction(params.transaction));
3051
+ const body = { tx: hex };
3052
+ if (params.attachment) {
3053
+ body.attachment = typeof params.attachment === "string" ? params.attachment : bytesToHex(params.attachment);
3054
+ }
3055
+ let data;
3056
+ try {
3057
+ data = await client.request("/v2/transactions", {
3058
+ method: "POST",
3059
+ body,
3060
+ retryCount: 0
3061
+ });
3062
+ } catch (error) {
3063
+ if (error instanceof HttpRequestError && error.details) {
3064
+ try {
3065
+ data = JSON.parse(error.details);
3066
+ } catch {
3067
+ throw error;
3068
+ }
3069
+ } else if (error instanceof TimeoutError) {
3070
+ const txid3 = getTransactionId(params.transaction);
3071
+ const receipt = await getTransaction(client, { txid: txid3 }).catch(() => null);
3072
+ if (receipt === null)
3073
+ throw error;
3074
+ data = { txid: txid3 };
3075
+ } else {
3076
+ throw error;
3077
+ }
3078
+ }
3079
+ if (data.error) {
3080
+ throw new BroadcastError(data.reason ?? data.error, {
3081
+ reason: data.reason,
3082
+ reasonData: data.reason_data,
3083
+ txid: data.txid ?? getTransactionId(params.transaction)
3084
+ });
3085
+ }
3086
+ const txid2 = typeof data === "string" ? data.replace(/"/g, "") : data.txid ?? getTransactionId(params.transaction);
3087
+ if (params.wait) {
3088
+ const confirmations = params.wait === true ? 1 : params.wait;
3089
+ const receipt = await waitForTransactionReceipt(client, {
3090
+ txid: txid2,
3091
+ confirmations
3092
+ });
3093
+ return { txid: txid2, receipt };
3094
+ }
3095
+ return { txid: txid2 };
3096
+ }
3097
+
3098
+ // src/actions/wallet/nonceManager.ts
3099
+ function jsonRpcSource() {
3100
+ return {
3101
+ get: ({ client, address }) => getNonce(client, { address })
3102
+ };
3103
+ }
3104
+ function memoryStore() {
3105
+ const next = new Map;
3106
+ const locks = new Map;
3107
+ function withLock(key, fn) {
3108
+ const prev = locks.get(key) ?? Promise.resolve();
3109
+ const run = prev.then(fn, fn);
3110
+ locks.set(key, run.catch(() => {}));
3111
+ return run;
3112
+ }
3113
+ return {
3114
+ reserve(key, getFloor) {
3115
+ return withLock(key, async () => {
3116
+ let current = next.get(key);
3117
+ if (current === undefined)
3118
+ current = await getFloor();
3119
+ next.set(key, current + 1n);
3120
+ return current;
3121
+ });
3122
+ },
3123
+ reset(key) {
3124
+ next.delete(key);
3125
+ },
3126
+ release(key, nonce) {
3127
+ return withLock(key, async () => {
3128
+ if (next.get(key) === nonce + 1n)
3129
+ next.set(key, nonce);
3130
+ });
3131
+ },
3132
+ peek(key) {
3133
+ return next.get(key);
3134
+ }
3135
+ };
3136
+ }
3137
+ function nonceKey(client, address) {
3138
+ return `${client.chain?.id ?? "stacks"}:${address}`;
3139
+ }
3140
+ function createNonceManager(params = {}) {
3141
+ const source = params.source ?? jsonRpcSource();
3142
+ const store = params.store ?? memoryStore();
3143
+ return {
3144
+ consume({ client, address }) {
3145
+ return store.reserve(nonceKey(client, address), () => source.get({ client, address }));
3146
+ },
3147
+ reset({ client, address }) {
3148
+ return store.reset(nonceKey(client, address));
3149
+ },
3150
+ release({ client, address, nonce }) {
3151
+ return store.release?.(nonceKey(client, address), nonce);
3152
+ },
3153
+ async peek({ client, address }) {
3154
+ return store.peek?.(nonceKey(client, address));
3155
+ }
3156
+ };
3157
+ }
3158
+ async function resolveNonce(client, address) {
3159
+ if (client.nonceManager)
3160
+ return client.nonceManager.consume({ client, address });
3161
+ return getNonce(client, { address });
3162
+ }
3163
+ async function releaseNonce(client, address, nonce) {
3164
+ if (!client.nonceManager)
3165
+ return;
3166
+ try {
3167
+ await client.nonceManager.release({ client, address, nonce });
3168
+ } catch {}
3169
+ }
3170
+ async function reconcileNonce(manager, params) {
3171
+ const { client, address, source } = params;
3172
+ const downward = params.downward ?? true;
3173
+ const authoritative = await source.get({ client, address });
3174
+ const tracked = await manager.peek({ client, address });
3175
+ if (tracked === undefined || authoritative === tracked) {
3176
+ return { reset: false, authoritative, tracked };
3177
+ }
3178
+ if (authoritative < tracked && !downward) {
3179
+ return { reset: false, authoritative, tracked };
3180
+ }
3181
+ await manager.reset({ client, address });
3182
+ return { reset: true, authoritative, tracked };
3183
+ }
3184
+ function startNonceReconciler(manager, params) {
3185
+ const { client, addresses, source, clock } = params;
3186
+ const intervalMs = params.intervalMs ?? 60000;
3187
+ let running = true;
3188
+ const tick = async () => {
3189
+ if (!running)
3190
+ return;
3191
+ for (const address of addresses) {
3192
+ try {
3193
+ const result = await reconcileNonce(manager, {
3194
+ client,
3195
+ address,
3196
+ source,
3197
+ downward: params.downward
3198
+ });
3199
+ params.onReconcile?.(address, result);
3200
+ } catch (error) {
3201
+ try {
3202
+ params.onError?.(address, error);
3203
+ } catch {}
3204
+ }
3205
+ }
3206
+ if (running && clock) {
3207
+ await clock.advance(intervalMs);
3208
+ tick();
3209
+ }
3210
+ };
3211
+ if (clock) {
3212
+ tick();
3213
+ return {
3214
+ stop: () => {
3215
+ running = false;
3216
+ }
3217
+ };
3218
+ }
3219
+ const timer = setInterval(tick, intervalMs);
3220
+ timer.unref?.();
3221
+ return {
3222
+ stop: () => clearInterval(timer)
3223
+ };
3224
+ }
3225
+ function isNonceConflictError(error) {
3226
+ if (!(error instanceof BroadcastError))
3227
+ return false;
3228
+ if (error.reason === "ConflictingNonceInMempool" || error.reason === "BadNonce") {
3229
+ return true;
3230
+ }
3231
+ if (error.reason !== undefined)
3232
+ return false;
3233
+ return error.message.toLowerCase().includes("nonce");
3234
+ }
3235
+ async function broadcastWithNonceReset(client, params) {
3236
+ try {
3237
+ const result = await sendTransaction(client, {
3238
+ transaction: params.transaction
3239
+ });
3240
+ return result.txid;
3241
+ } catch (error) {
3242
+ if (client.nonceManager && isNonceConflictError(error)) {
3243
+ await client.nonceManager.reset({ client, address: params.address });
3244
+ }
3245
+ throw error;
3246
+ }
3247
+ }
3248
+
3249
+ // src/actions/public/estimateFee.ts
3250
+ function isValidEstimation(e) {
3251
+ 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");
3252
+ }
3253
+ async function estimateFee(client, params) {
3254
+ const payloadHex = bytesToHex(serializePayload(params.transaction.payload));
3255
+ const txHex = bytesToHex(serializeTransaction(params.transaction));
3256
+ const data = await client.request("/v2/fees/transaction", {
3257
+ method: "POST",
3258
+ body: {
3259
+ estimated_len: Math.ceil(txHex.length / 2),
3260
+ transaction_payload: `0x${payloadHex}`
3261
+ }
3262
+ });
3263
+ const raw = data?.estimations ?? [];
3264
+ return raw.map((e) => {
3265
+ if (!isValidEstimation(e)) {
3266
+ throw new MalformedResponseError("estimateFee: node response contains invalid fee estimation entry");
3267
+ }
3268
+ return {
3269
+ feeRate: Number(e.fee_rate),
3270
+ fee: Number(e.fee)
3271
+ };
3272
+ });
3273
+ }
3274
+
3275
+ // src/actions/wallet/utils.ts
3276
+ function isProviderAccount(account) {
3277
+ return account.type === "provider";
3278
+ }
3279
+ var FEE_TIERS = ["min", "low", "mid", "high"];
3280
+ var TIER_INDEX = { low: 0, mid: 1, high: 2 };
3281
+ function isFeeTier(fee) {
3282
+ return typeof fee === "string" && FEE_TIERS.includes(fee);
3283
+ }
3284
+ function minimumFee(transaction) {
3285
+ return BigInt(serializeTransaction(transaction).length);
3286
+ }
3287
+ function isNoEstimateAvailable(error) {
3288
+ return error instanceof HttpRequestError && error.status === 400 && (error.details?.includes("NoEstimateAvailable") ?? false);
3289
+ }
3290
+ async function resolveFee(client, transaction, fee) {
3291
+ if (fee !== undefined && !isFeeTier(fee))
3292
+ return { fee: intToBigInt(fee) };
3293
+ const tier = fee ?? "mid";
3294
+ if (tier === "min")
3295
+ return { fee: minimumFee(transaction), tier };
3296
+ let estimates;
3297
+ try {
3298
+ estimates = await estimateFee(client, { transaction });
3299
+ } catch (error) {
3300
+ if (!isNoEstimateAvailable(error))
3301
+ throw error;
3302
+ return { fee: minimumFee(transaction), tier: "min" };
3303
+ }
3304
+ const pick = estimates[TIER_INDEX[tier]] ?? estimates[estimates.length - 1];
3305
+ if (pick)
3306
+ return { fee: BigInt(pick.fee), tier };
3307
+ return { fee: minimumFee(transaction), tier: "min" };
3308
+ }
3309
+ function setUnsignedFee(transaction, fee) {
3310
+ transaction.auth.spendingCondition.fee = fee;
3311
+ clearTxCache(transaction);
3312
+ }
3313
+ function assertNoFeeTierForProvider(fee) {
3314
+ if (isFeeTier(fee)) {
3315
+ throw new Error(`Fee tier '${fee}' requires local signing; provider (wallet) accounts set their own fee`);
3316
+ }
3317
+ }
3318
+
3319
+ // src/actions/wallet/callContract.ts
3320
+ async function callContract(client, params) {
3321
+ const account = client.account;
3322
+ if (!account)
3323
+ throw new Error("Account required");
3324
+ const [contractAddress, contractName] = parseContractId(params.contract);
3325
+ if (isProviderAccount(account)) {
3326
+ assertNoFeeTierForProvider(params.fee);
3327
+ const result = await account.provider.request("stx_callContract", {
3328
+ contract: params.contract,
3329
+ functionName: params.functionName,
3330
+ functionArgs: params.functionArgs ?? []
3331
+ });
3332
+ return result.txid;
3333
+ }
3334
+ const managed = params.nonce === undefined && client.nonceManager !== undefined;
3335
+ const nonce = params.nonce ?? await resolveNonce(client, account.address);
3336
+ try {
3337
+ const needsFeeResolution = params.fee === undefined || isFeeTier(params.fee);
3338
+ const unsigned = buildContractCall({
3339
+ contractAddress,
3340
+ contractName,
3341
+ functionName: params.functionName,
3342
+ functionArgs: params.functionArgs ?? [],
3343
+ fee: needsFeeResolution ? 0n : params.fee,
3344
+ nonce,
3345
+ publicKey: account.publicKey,
3346
+ chain: client.chain,
3347
+ postConditionMode: params.postConditionMode,
3348
+ postConditions: params.postConditions
3349
+ });
3350
+ if (needsFeeResolution) {
3351
+ const { fee } = await resolveFee(client, unsigned, params.fee);
3352
+ setUnsignedFee(unsigned, fee);
3353
+ }
3354
+ const signed = await signTransactionWithAccount(unsigned, account);
3355
+ return await broadcastWithNonceReset(client, {
3356
+ transaction: signed,
3357
+ address: account.address
3358
+ });
3359
+ } catch (error) {
3360
+ if (managed)
3361
+ await releaseNonce(client, account.address, nonce);
3362
+ throw error;
3363
+ }
3364
+ }
3365
+
3366
+ // src/actions/getContract.ts
3367
+ function getContract(params) {
3368
+ const { client, address, name: contractName, abi } = params;
3369
+ const contractId = `${address}.${contractName}`;
3370
+ const fnByName = new Map;
3371
+ for (const fn of abi.functions) {
3372
+ fnByName.set(fn.name, fn);
3373
+ }
3374
+ const mapByName = new Map;
3375
+ if (abi.maps) {
3376
+ for (const m of abi.maps) {
3377
+ mapByName.set(m.name, m);
3378
+ }
3379
+ }
3380
+ const camelToKebab = new Map;
3381
+ for (const fn of abi.functions) {
3382
+ camelToKebab.set(toCamelCase(fn.name), fn.name);
3383
+ }
3384
+ if (abi.maps) {
3385
+ for (const m of abi.maps) {
3386
+ camelToKebab.set(toCamelCase(m.name), m.name);
3387
+ }
3388
+ }
3389
+ const read = new Proxy({}, {
3390
+ get(_target, prop) {
3391
+ const fnName = camelToKebab.get(prop) ?? prop;
3392
+ const fn = fnByName.get(fnName);
3393
+ if (!fn || fn.access !== "read-only")
3394
+ return;
3395
+ return async (args = {}) => {
3396
+ const clarityArgs = buildFunctionArgs(fn, args);
3397
+ const result = await readContract(client, {
3398
+ contract: contractId,
3399
+ functionName: fn.name,
3400
+ args: clarityArgs
3401
+ });
3402
+ const jsValue = clarityValueToJSUntyped(fn.outputs, result);
3403
+ if (isResponseOutput(fn.outputs)) {
3404
+ const resp = jsValue;
3405
+ if ("ok" in resp)
3406
+ return resp.ok;
3407
+ throw new ContractResponseError(`${contractId}::${fn.name} returned (err ${formatErrValue(resp.err)})`, resp.err);
3408
+ }
3409
+ return jsValue;
3410
+ };
3411
+ }
3412
+ });
3413
+ const call = new Proxy({}, {
3414
+ get(_target, prop) {
3415
+ const fnName = camelToKebab.get(prop) ?? prop;
3416
+ const fn = fnByName.get(fnName);
3417
+ if (!fn || fn.access !== "public")
3418
+ return;
3419
+ return async (args = {}, options) => {
3420
+ const clarityArgs = buildFunctionArgs(fn, args);
3421
+ return callContract(client, {
3422
+ contract: contractId,
3423
+ functionName: fn.name,
3424
+ functionArgs: clarityArgs,
3425
+ ...options
3426
+ });
3427
+ };
3428
+ }
3429
+ });
3430
+ const buildCall = new Proxy({}, {
3431
+ get(_target, prop) {
3432
+ const fnName = camelToKebab.get(prop) ?? prop;
3433
+ const fn = fnByName.get(fnName);
3434
+ if (!fn || fn.access !== "public")
3435
+ return;
3436
+ return async (args = {}, options) => {
3437
+ const publicKey = options?.publicKey ?? client.account?.publicKey;
3438
+ if (!publicKey) {
3439
+ throw new Error("buildCall requires a publicKey (pass options.publicKey or configure a client account)");
3440
+ }
3441
+ const functionArgs = buildFunctionArgs(fn, args);
3442
+ const network = client.chain?.network ?? "mainnet";
3443
+ const nonce = options?.nonce ?? await getNonce(client, {
3444
+ address: publicKeyToAddress(publicKey, network)
3445
+ });
3446
+ const unsigned = buildContractCall({
3447
+ contractAddress: address,
3448
+ contractName,
3449
+ functionName: fn.name,
3450
+ functionArgs,
3451
+ fee: options?.fee ?? 0n,
3452
+ nonce,
3453
+ publicKey,
3454
+ chain: client.chain,
3455
+ postConditionMode: options?.postConditionMode,
3456
+ postConditions: options?.postConditions,
3457
+ sponsored: options?.sponsored
3458
+ });
3459
+ if (options?.fee === undefined) {
3460
+ const { fee } = await resolveFee(client, unsigned, undefined);
3461
+ setUnsignedFee(unsigned, fee);
3462
+ }
3463
+ return unsigned;
3464
+ };
3465
+ }
3466
+ });
3467
+ const maps = new Proxy({}, {
3468
+ get(_target, prop) {
3469
+ const mapName = camelToKebab.get(prop) ?? prop;
3470
+ const map = mapByName.get(mapName);
3471
+ if (!map)
3472
+ return;
3473
+ return async (key) => {
3474
+ const clarityKey = jsToClarityValue(map.key, key);
3475
+ const result = await getMapEntry(client, {
3476
+ contract: contractId,
3477
+ mapName: map.name,
3478
+ key: clarityKey
3479
+ });
3480
+ if (result.type === "none")
3481
+ return null;
3482
+ if (result.type === "some") {
3483
+ return clarityValueToJSUntyped(map.value, result.value);
3484
+ }
3485
+ return clarityValueToJSUntyped(map.value, result);
3486
+ };
3487
+ }
3488
+ });
3489
+ return { read, call, buildCall, maps };
3490
+ }
3491
+ function resolveNetworkContract(client, contracts) {
3492
+ if (!client.chain) {
3493
+ throw new Error("Client must have a chain configured");
3494
+ }
3495
+ return contracts[client.chain.network];
3496
+ }
3497
+ function buildFunctionArgs(fn, args = {}) {
3498
+ return fn.args.map((arg) => {
3499
+ const camelKey = toCamelCase(arg.name);
3500
+ const hasOriginal = arg.name in args;
3501
+ const hasCamel = camelKey in args;
3502
+ const value = hasOriginal ? args[arg.name] : hasCamel ? args[camelKey] : undefined;
3503
+ if (value === undefined)
3504
+ throw new Error(`Missing argument: ${arg.name}`);
3505
+ return jsToClarityValue(arg.type, value);
3506
+ });
3507
+ }
3508
+ function isResponseOutput(type) {
3509
+ return typeof type === "object" && type !== null && "response" in type;
3510
+ }
3511
+ function formatErrValue(value) {
3512
+ if (typeof value === "bigint")
3513
+ return value.toString();
3514
+ if (typeof value === "string")
3515
+ return `"${value}"`;
3516
+ return String(value);
3517
+ }
3518
+
3519
+ class ContractResponseError extends Error {
3520
+ errorValue;
3521
+ name = "ContractResponseError";
3522
+ constructor(message, errorValue) {
3523
+ super(message);
3524
+ this.errorValue = errorValue;
3525
+ }
3526
+ }
3527
+
17
3528
  // src/pox/abi.ts
18
3529
  var POX_ABI = {
19
3530
  functions: [
@@ -259,6 +3770,349 @@ var POX_ABI = {
259
3770
  ]
260
3771
  };
261
3772
 
3773
+ // src/pox/constants.ts
3774
+ var POX_CONTRACTS = {
3775
+ mainnet: {
3776
+ address: "SP000000000000000000002Q6VF78",
3777
+ name: "pox-4"
3778
+ },
3779
+ testnet: {
3780
+ address: "ST000000000000000000002AMW42H",
3781
+ name: "pox-4"
3782
+ }
3783
+ };
3784
+ var MIN_LOCK_PERIOD = 1;
3785
+ var MAX_LOCK_PERIOD = 12;
3786
+ var POX_ADDRESS_VERSION = {
3787
+ p2pkh: 0,
3788
+ p2sh: 1,
3789
+ p2sh_p2wpkh: 2,
3790
+ p2sh_p2wsh: 3,
3791
+ p2wpkh: 4,
3792
+ p2wsh: 5,
3793
+ p2tr: 6
3794
+ };
3795
+
3796
+ // src/pox5/btcAddress.ts
3797
+ var import_base6 = require("@scure/base");
3798
+
3799
+ // src/bitcoin/address.ts
3800
+ var import_secp256k13 = require("@noble/curves/secp256k1.js");
3801
+ var import_base5 = require("@scure/base");
3802
+
3803
+ // src/bitcoin/serialize.ts
3804
+ function doubleSha256(bytes) {
3805
+ return import_sha22.sha256(import_sha22.sha256(bytes));
3806
+ }
3807
+ function reverseBytes(bytes) {
3808
+ const out = new Uint8Array(bytes.length);
3809
+ for (let i = 0;i < bytes.length; i++) {
3810
+ out[i] = bytes[bytes.length - 1 - i];
3811
+ }
3812
+ return out;
3813
+ }
3814
+
3815
+ class BtcReader {
3816
+ data;
3817
+ view;
3818
+ offset = 0;
3819
+ constructor(data) {
3820
+ this.data = data;
3821
+ this.view = new DataView(data.buffer, data.byteOffset, data.byteLength);
3822
+ }
3823
+ get length() {
3824
+ return this.data.length;
3825
+ }
3826
+ readUInt8() {
3827
+ const v = this.view.getUint8(this.offset);
3828
+ this.offset += 1;
3829
+ return v;
3830
+ }
3831
+ peekUInt8() {
3832
+ return this.view.getUint8(this.offset);
3833
+ }
3834
+ readUInt32LE() {
3835
+ const v = this.view.getUint32(this.offset, true);
3836
+ this.offset += 4;
3837
+ return v;
3838
+ }
3839
+ readUInt64LE() {
3840
+ const v = this.view.getBigUint64(this.offset, true);
3841
+ this.offset += 8;
3842
+ return v;
3843
+ }
3844
+ readBytes(n) {
3845
+ if (this.offset + n > this.data.length) {
3846
+ throw new Error(`Bitcoin tx underflow: need ${n} bytes at offset ${this.offset}, have ${this.data.length}`);
3847
+ }
3848
+ const slice = this.data.slice(this.offset, this.offset + n);
3849
+ this.offset += n;
3850
+ return slice;
3851
+ }
3852
+ readVarInt() {
3853
+ const first = this.readUInt8();
3854
+ if (first < 253)
3855
+ return first;
3856
+ if (first === 253) {
3857
+ const v = this.view.getUint16(this.offset, true);
3858
+ this.offset += 2;
3859
+ return v;
3860
+ }
3861
+ if (first === 254) {
3862
+ return this.readUInt32LE();
3863
+ }
3864
+ const big = this.readUInt64LE();
3865
+ if (big > BigInt(Number.MAX_SAFE_INTEGER)) {
3866
+ throw new Error("Bitcoin varint exceeds safe integer range");
3867
+ }
3868
+ return Number(big);
3869
+ }
3870
+ }
3871
+ function scanTx(rawTx) {
3872
+ const r = new BtcReader(rawTx);
3873
+ const version = r.readUInt32LE();
3874
+ let hasWitness = false;
3875
+ if (r.peekUInt8() === 0) {
3876
+ r.readUInt8();
3877
+ const flag = r.readUInt8();
3878
+ if (flag !== 1) {
3879
+ throw new Error(`Unexpected SegWit flag 0x${flag.toString(16)}`);
3880
+ }
3881
+ hasWitness = true;
3882
+ }
3883
+ const bodyStart = r.offset;
3884
+ const inputCount = r.readVarInt();
3885
+ const inputs = [];
3886
+ for (let i = 0;i < inputCount; i++) {
3887
+ const prevTxid = r.readBytes(32);
3888
+ const vout = r.readUInt32LE();
3889
+ const scriptSig = r.readBytes(r.readVarInt());
3890
+ const sequence = r.readUInt32LE();
3891
+ inputs.push({ prevTxid, vout, scriptSig, sequence });
3892
+ }
3893
+ const outputCount = r.readVarInt();
3894
+ const outputs = [];
3895
+ for (let i = 0;i < outputCount; i++) {
3896
+ const value = r.readUInt64LE();
3897
+ const scriptPubKey = r.readBytes(r.readVarInt());
3898
+ outputs.push({ value, scriptPubKey });
3899
+ }
3900
+ const bodyEnd = r.offset;
3901
+ if (hasWitness) {
3902
+ for (let i = 0;i < inputCount; i++) {
3903
+ const itemCount = r.readVarInt();
3904
+ for (let j = 0;j < itemCount; j++) {
3905
+ r.readBytes(r.readVarInt());
3906
+ }
3907
+ }
3908
+ }
3909
+ const locktime = r.readUInt32LE();
3910
+ const legacy = concatBytes(rawTx.slice(0, 4), rawTx.slice(bodyStart, bodyEnd), rawTx.slice(r.offset - 4, r.offset));
3911
+ return { version, hasWitness, inputs, outputs, locktime, legacy };
3912
+ }
3913
+ function parseBitcoinTx(rawTx) {
3914
+ const s = scanTx(rawTx);
3915
+ return {
3916
+ version: s.version,
3917
+ hasWitness: s.hasWitness,
3918
+ inputs: s.inputs,
3919
+ outputs: s.outputs,
3920
+ locktime: s.locktime,
3921
+ txidInternal: doubleSha256(s.legacy)
3922
+ };
3923
+ }
3924
+ function stripWitness(rawTx) {
3925
+ return scanTx(rawTx).legacy;
3926
+ }
3927
+ function bitcoinTxid(rawTx, { display = false } = {}) {
3928
+ const txid2 = doubleSha256(scanTx(rawTx).legacy);
3929
+ return display ? reverseBytes(txid2) : txid2;
3930
+ }
3931
+ function parseBlockHeader(header) {
3932
+ if (header.length !== 80) {
3933
+ throw new Error(`Bitcoin block header must be 80 bytes, got ${header.length}`);
3934
+ }
3935
+ const r = new BtcReader(header);
3936
+ const version = r.readUInt32LE();
3937
+ const prevBlock = r.readBytes(32);
3938
+ const merkleRoot = r.readBytes(32);
3939
+ const timestamp = r.readUInt32LE();
3940
+ const bits = r.readUInt32LE();
3941
+ const nonce = r.readUInt32LE();
3942
+ return { version, prevBlock, merkleRoot, timestamp, bits, nonce };
3943
+ }
3944
+ function blockHash(header, { display = false } = {}) {
3945
+ const hash = doubleSha256(header);
3946
+ return display ? reverseBytes(hash) : hash;
3947
+ }
3948
+
3949
+ // src/bitcoin/address.ts
3950
+ var BITCOIN_NETWORK_PARAMS = {
3951
+ mainnet: { p2pkh: 0, p2sh: 5, hrp: "bc" },
3952
+ testnet: { p2pkh: 111, p2sh: 196, hrp: "tb" },
3953
+ regtest: { p2pkh: 111, p2sh: 196, hrp: "bcrt" }
3954
+ };
3955
+ var NETWORK_PARAMS = BITCOIN_NETWORK_PARAMS;
3956
+ function base58CheckEncode(version, payload) {
3957
+ const data = concatBytes(Uint8Array.of(version), payload);
3958
+ const checksum = doubleSha256(data).slice(0, 4);
3959
+ return import_base5.base58.encode(concatBytes(data, checksum));
3960
+ }
3961
+ function formatBitcoinAddress(parsed, network = "mainnet") {
3962
+ const params = NETWORK_PARAMS[network];
3963
+ const hash = parsed.hash;
3964
+ if (!hash)
3965
+ return;
3966
+ switch (parsed.type) {
3967
+ case "p2pkh":
3968
+ return base58CheckEncode(params.p2pkh, hash);
3969
+ case "p2sh":
3970
+ return base58CheckEncode(params.p2sh, hash);
3971
+ case "p2wpkh":
3972
+ case "p2wsh":
3973
+ return import_base5.bech32.encode(params.hrp, [0, ...import_base5.bech32.toWords(hash)]);
3974
+ case "p2tr":
3975
+ return import_base5.bech32m.encode(params.hrp, [1, ...import_base5.bech32m.toWords(hash)]);
3976
+ default:
3977
+ return;
3978
+ }
3979
+ }
3980
+ function toPubkeyBytes(publicKey) {
3981
+ return typeof publicKey === "string" ? hexToBytes(publicKey) : publicKey;
3982
+ }
3983
+ function taprootTweakPubkey(xonly) {
3984
+ if (xonly.length !== 32)
3985
+ throw new Error(`Expected 32-byte x-only pubkey, got ${xonly.length}`);
3986
+ const tweak = import_secp256k13.schnorr.utils.taggedHash("TapTweak", xonly);
3987
+ const t = BigInt(`0x${Array.from(tweak, (b) => b.toString(16).padStart(2, "0")).join("")}`);
3988
+ if (t >= import_secp256k13.secp256k1.Point.Fn.ORDER)
3989
+ throw new Error("Invalid tap tweak (exceeds curve order)");
3990
+ const internal = import_secp256k13.secp256k1.Point.fromBytes(concatBytes(Uint8Array.of(2), xonly));
3991
+ const output = internal.add(import_secp256k13.secp256k1.Point.BASE.multiply(t));
3992
+ return output.toBytes(true).slice(1);
3993
+ }
3994
+ function publicKeyToP2wpkhAddress(publicKey, network = "mainnet") {
3995
+ const pubkey = toPubkeyBytes(publicKey);
3996
+ if (pubkey.length !== 33)
3997
+ throw new Error(`Expected 33-byte compressed pubkey, got ${pubkey.length}`);
3998
+ const params = NETWORK_PARAMS[network];
3999
+ return import_base5.bech32.encode(params.hrp, [0, ...import_base5.bech32.toWords(hash160(pubkey))]);
4000
+ }
4001
+ function publicKeyToP2trAddress(publicKey, network = "mainnet") {
4002
+ const pubkey = toPubkeyBytes(publicKey);
4003
+ const xonly = pubkey.length === 33 ? pubkey.slice(1) : pubkey.length === 32 ? pubkey : undefined;
4004
+ if (!xonly)
4005
+ throw new Error(`Expected 33-byte compressed or 32-byte x-only pubkey, got ${pubkey.length}`);
4006
+ const params = NETWORK_PARAMS[network];
4007
+ const outputKey = taprootTweakPubkey(xonly);
4008
+ return import_base5.bech32m.encode(params.hrp, [1, ...import_base5.bech32m.toWords(outputKey)]);
4009
+ }
4010
+
4011
+ // src/pox5/btcAddress.ts
4012
+ function expectedHashLen(version) {
4013
+ if (!Number.isInteger(version) || version < 0 || version > 6) {
4014
+ throw new Error(`Unknown PoX address version: 0x${version.toString(16)}`);
4015
+ }
4016
+ return version <= 4 ? 20 : 32;
4017
+ }
4018
+ function canonicalizeBtcAddress(repr) {
4019
+ const expected = expectedHashLen(repr.version);
4020
+ const { hashbytes } = repr;
4021
+ if (hashbytes.length === expected)
4022
+ return { version: repr.version, hashbytes };
4023
+ if (expected === 20 && hashbytes.length === 32 && hashbytes.slice(20).every((b) => b === 0)) {
4024
+ return { version: repr.version, hashbytes: hashbytes.slice(0, 20) };
4025
+ }
4026
+ throw new Error(`Invalid hashbytes length for PoX version 0x${repr.version.toString(16)}: ${hashbytes.length}`);
4027
+ }
4028
+ function parseBtcAddress(address) {
4029
+ if (address.startsWith("bc1") || address.startsWith("tb1") || address.startsWith("bcrt1")) {
4030
+ return parseSegwitAddress(address);
4031
+ }
4032
+ return parseLegacyAddress(address);
4033
+ }
4034
+ function parseSegwitAddress(address) {
4035
+ let decoded;
4036
+ try {
4037
+ decoded = import_base6.bech32.decode(address);
4038
+ } catch {
4039
+ decoded = import_base6.bech32m.decode(address);
4040
+ }
4041
+ const witnessVersion = decoded.words[0];
4042
+ if (witnessVersion === undefined) {
4043
+ throw new Error("Invalid segwit address: missing witness version");
4044
+ }
4045
+ const data = import_base6.bech32.fromWords(decoded.words.slice(1));
4046
+ const hashbytes = new Uint8Array(data);
4047
+ let version;
4048
+ if (witnessVersion === 0) {
4049
+ if (hashbytes.length === 20) {
4050
+ version = POX_ADDRESS_VERSION.p2wpkh;
4051
+ } else if (hashbytes.length === 32) {
4052
+ version = POX_ADDRESS_VERSION.p2wsh;
4053
+ } else {
4054
+ throw new Error(`Invalid witness v0 program length: ${hashbytes.length}`);
4055
+ }
4056
+ } else if (witnessVersion === 1) {
4057
+ if (hashbytes.length !== 32) {
4058
+ throw new Error(`Invalid witness v1 program length: ${hashbytes.length}`);
4059
+ }
4060
+ version = POX_ADDRESS_VERSION.p2tr;
4061
+ } else {
4062
+ throw new Error(`Unsupported witness version: ${witnessVersion}`);
4063
+ }
4064
+ return { version, hashbytes };
4065
+ }
4066
+ function parseLegacyAddress(address) {
4067
+ const decoded = import_base6.base58.decode(address);
4068
+ if (decoded.length !== 25) {
4069
+ throw new Error(`Invalid legacy address length: ${decoded.length}`);
4070
+ }
4071
+ const versionByte = decoded[0];
4072
+ if (versionByte === undefined) {
4073
+ throw new Error("Invalid legacy address: missing version byte");
4074
+ }
4075
+ const payload = decoded.slice(0, 21);
4076
+ const checksum = decoded.slice(21);
4077
+ const expected = doubleSha256(payload).slice(0, 4);
4078
+ if (checksum.length !== 4 || expected.some((b, i) => b !== checksum[i])) {
4079
+ throw new Error("Invalid legacy address checksum");
4080
+ }
4081
+ const hashbytes = decoded.slice(1, 21);
4082
+ let version;
4083
+ if (versionByte === 0 || versionByte === 111) {
4084
+ version = POX_ADDRESS_VERSION.p2pkh;
4085
+ } else if (versionByte === 5 || versionByte === 196) {
4086
+ version = POX_ADDRESS_VERSION.p2sh;
4087
+ } else {
4088
+ throw new Error(`Unknown legacy address version byte: 0x${versionByte.toString(16)}`);
4089
+ }
4090
+ return { version, hashbytes };
4091
+ }
4092
+ function stringifyBtcAddress(repr, network) {
4093
+ const { version, hashbytes } = canonicalizeBtcAddress(repr);
4094
+ const params = BITCOIN_NETWORK_PARAMS[network];
4095
+ switch (version) {
4096
+ case POX_ADDRESS_VERSION.p2pkh:
4097
+ return base58CheckEncode(params.p2pkh, hashbytes);
4098
+ case POX_ADDRESS_VERSION.p2sh:
4099
+ case POX_ADDRESS_VERSION.p2sh_p2wpkh:
4100
+ case POX_ADDRESS_VERSION.p2sh_p2wsh:
4101
+ return base58CheckEncode(params.p2sh, hashbytes);
4102
+ case POX_ADDRESS_VERSION.p2wpkh:
4103
+ case POX_ADDRESS_VERSION.p2wsh:
4104
+ return import_base6.bech32.encode(params.hrp, [0, ...import_base6.bech32.toWords(hashbytes)]);
4105
+ case POX_ADDRESS_VERSION.p2tr:
4106
+ return import_base6.bech32m.encode(params.hrp, [1, ...import_base6.bech32m.toWords(hashbytes)]);
4107
+ default:
4108
+ throw new Error(`Unknown PoX address version: 0x${version.toString(16)}`);
4109
+ }
4110
+ }
4111
+ var BtcAddress = {
4112
+ parse: parseBtcAddress,
4113
+ stringify: stringifyBtcAddress
4114
+ };
4115
+
262
4116
  // src/pox/utils.ts
263
4117
  function parseBtcAddress2(address) {
264
4118
  const { version, hashbytes } = parseBtcAddress(address);
@@ -405,5 +4259,5 @@ function pox() {
405
4259
  });
406
4260
  }
407
4261
 
408
- //# debugId=240A704E1334768E64756E2164756E21
4262
+ //# debugId=E01835A817EE70FD64756E2164756E21
409
4263
  //# sourceMappingURL=index.cjs.map