@secondlayer/stacks 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/README.md +92 -0
  2. package/dist/shared/stacks-02actsrx.cjs +17 -0
  3. package/dist/shared/stacks-02actsrx.cjs.map +10 -0
  4. package/dist/shared/stacks-1aqm7c2h.cjs +110 -0
  5. package/dist/shared/stacks-1aqm7c2h.cjs.map +11 -0
  6. package/dist/shared/stacks-24h5k94q.cjs +74 -0
  7. package/dist/shared/stacks-24h5k94q.cjs.map +11 -0
  8. package/dist/shared/stacks-2ar4prfz.cjs +328 -0
  9. package/dist/shared/stacks-2ar4prfz.cjs.map +11 -0
  10. package/dist/shared/stacks-4py5pm0r.cjs +237 -0
  11. package/dist/shared/stacks-4py5pm0r.cjs.map +10 -0
  12. package/dist/shared/stacks-5tprhns9.cjs +54 -0
  13. package/dist/shared/stacks-5tprhns9.cjs.map +11 -0
  14. package/dist/shared/stacks-61rvzkz1.cjs +132 -0
  15. package/dist/shared/stacks-61rvzkz1.cjs.map +17 -0
  16. package/dist/shared/stacks-709tra19.js +30 -0
  17. package/dist/shared/stacks-709tra19.js.map +10 -0
  18. package/dist/shared/stacks-74k8cxgb.cjs +567 -0
  19. package/dist/shared/stacks-74k8cxgb.cjs.map +13 -0
  20. package/dist/shared/stacks-8m9byk2j.js +7 -0
  21. package/dist/shared/stacks-8m9byk2j.js.map +9 -0
  22. package/dist/shared/stacks-8yykgdww.js +125 -0
  23. package/dist/shared/stacks-8yykgdww.js.map +11 -0
  24. package/dist/shared/stacks-9g0jhab3.cjs +40 -0
  25. package/dist/shared/stacks-9g0jhab3.cjs.map +10 -0
  26. package/dist/shared/stacks-an5k8n4t.cjs +291 -0
  27. package/dist/shared/stacks-an5k8n4t.cjs.map +23 -0
  28. package/dist/shared/stacks-b008c3w8.cjs +214 -0
  29. package/dist/shared/stacks-b008c3w8.cjs.map +11 -0
  30. package/dist/shared/stacks-bnvfmt7y.cjs +31 -0
  31. package/dist/shared/stacks-bnvfmt7y.cjs.map +9 -0
  32. package/dist/shared/stacks-bycy6t9k.js +22 -0
  33. package/dist/shared/stacks-bycy6t9k.js.map +10 -0
  34. package/dist/shared/stacks-d1fmkv3p.js +258 -0
  35. package/dist/shared/stacks-d1fmkv3p.js.map +13 -0
  36. package/dist/shared/stacks-dr5en54r.cjs +119 -0
  37. package/dist/shared/stacks-dr5en54r.cjs.map +10 -0
  38. package/dist/shared/stacks-dxhntr76.js +278 -0
  39. package/dist/shared/stacks-dxhntr76.js.map +10 -0
  40. package/dist/shared/stacks-evnzth1q.cjs +35 -0
  41. package/dist/shared/stacks-evnzth1q.cjs.map +10 -0
  42. package/dist/shared/stacks-f3tk2k5s.js +27 -0
  43. package/dist/shared/stacks-f3tk2k5s.js.map +9 -0
  44. package/dist/shared/stacks-f7wdrzs3.js +285 -0
  45. package/dist/shared/stacks-f7wdrzs3.js.map +11 -0
  46. package/dist/shared/stacks-fcaefc5b.cjs +16 -0
  47. package/dist/shared/stacks-fcaefc5b.cjs.map +10 -0
  48. package/dist/shared/stacks-g9mcjcqg.cjs +3 -0
  49. package/dist/shared/stacks-g9mcjcqg.cjs.map +9 -0
  50. package/dist/shared/stacks-gck1sq7h.cjs +28 -0
  51. package/dist/shared/stacks-gck1sq7h.cjs.map +10 -0
  52. package/dist/shared/stacks-gjvbq6w7.js +46 -0
  53. package/dist/shared/stacks-gjvbq6w7.js.map +10 -0
  54. package/dist/shared/stacks-j2cy7qtt.js +237 -0
  55. package/dist/shared/stacks-j2cy7qtt.js.map +11 -0
  56. package/dist/shared/stacks-k08tgzyp.cjs +232 -0
  57. package/dist/shared/stacks-k08tgzyp.cjs.map +13 -0
  58. package/dist/shared/stacks-k2p5tv6x.js +37 -0
  59. package/dist/shared/stacks-k2p5tv6x.js.map +10 -0
  60. package/dist/shared/stacks-k58k970n.js +234 -0
  61. package/dist/shared/stacks-k58k970n.js.map +10 -0
  62. package/dist/shared/stacks-n2g56wgg.js +338 -0
  63. package/dist/shared/stacks-n2g56wgg.js.map +23 -0
  64. package/dist/shared/stacks-nqytwfcc.js +243 -0
  65. package/dist/shared/stacks-nqytwfcc.js.map +11 -0
  66. package/dist/shared/stacks-qcae5852.js +19 -0
  67. package/dist/shared/stacks-qcae5852.js.map +10 -0
  68. package/dist/shared/stacks-qt8ehebn.js +76 -0
  69. package/dist/shared/stacks-qt8ehebn.js.map +11 -0
  70. package/dist/shared/stacks-qvg7c24g.cjs +232 -0
  71. package/dist/shared/stacks-qvg7c24g.cjs.map +10 -0
  72. package/dist/shared/stacks-r1t6g3c3.cjs +241 -0
  73. package/dist/shared/stacks-r1t6g3c3.cjs.map +11 -0
  74. package/dist/shared/stacks-tjxmrssa.js +282 -0
  75. package/dist/shared/stacks-tjxmrssa.js.map +11 -0
  76. package/dist/shared/stacks-v9jqcpd4.js +18 -0
  77. package/dist/shared/stacks-v9jqcpd4.js.map +10 -0
  78. package/dist/shared/stacks-vdfag81a.cjs +121 -0
  79. package/dist/shared/stacks-vdfag81a.cjs.map +10 -0
  80. package/dist/shared/stacks-vdfs3e5v.js +134 -0
  81. package/dist/shared/stacks-vdfs3e5v.js.map +10 -0
  82. package/dist/shared/stacks-y3dh7hv1.js +60 -0
  83. package/dist/shared/stacks-y3dh7hv1.js.map +11 -0
  84. package/dist/shared/stacks-ya3x01yd.cjs +16 -0
  85. package/dist/shared/stacks-ya3x01yd.cjs.map +10 -0
  86. package/dist/shared/stacks-yfgsm6ap.js +599 -0
  87. package/dist/shared/stacks-yfgsm6ap.js.map +13 -0
  88. package/dist/shared/stacks-yfveb68e.js +121 -0
  89. package/dist/shared/stacks-yfveb68e.js.map +10 -0
  90. package/dist/shared/stacks-zm0b3tgy.js +160 -0
  91. package/dist/shared/stacks-zm0b3tgy.js.map +17 -0
  92. package/dist/shared/stacks-zyv9qqme.cjs +249 -0
  93. package/dist/shared/stacks-zyv9qqme.cjs.map +11 -0
  94. package/dist/src/accounts/index.cjs +90 -0
  95. package/dist/src/accounts/index.cjs.map +12 -0
  96. package/dist/src/accounts/index.d.cts +47 -0
  97. package/dist/src/accounts/index.d.ts +47 -0
  98. package/dist/src/accounts/index.js +104 -0
  99. package/dist/src/accounts/index.js.map +12 -0
  100. package/dist/src/actions/index.cjs +36 -0
  101. package/dist/src/actions/index.cjs.map +9 -0
  102. package/dist/src/actions/index.d.cts +886 -0
  103. package/dist/src/actions/index.d.ts +886 -0
  104. package/dist/src/actions/index.js +81 -0
  105. package/dist/src/actions/index.js.map +9 -0
  106. package/dist/src/bns/index.cjs +590 -0
  107. package/dist/src/bns/index.cjs.map +15 -0
  108. package/dist/src/bns/index.d.cts +241 -0
  109. package/dist/src/bns/index.d.ts +241 -0
  110. package/dist/src/bns/index.js +611 -0
  111. package/dist/src/bns/index.js.map +15 -0
  112. package/dist/src/chains/index.cjs +13 -0
  113. package/dist/src/chains/index.cjs.map +9 -0
  114. package/dist/src/chains/index.d.cts +53 -0
  115. package/dist/src/chains/index.d.ts +53 -0
  116. package/dist/src/chains/index.js +18 -0
  117. package/dist/src/chains/index.js.map +9 -0
  118. package/dist/src/clarity/index.cjs +3 -0
  119. package/dist/src/clarity/index.cjs.map +9 -0
  120. package/dist/src/clarity/index.d.cts +821 -0
  121. package/dist/src/clarity/index.d.ts +821 -0
  122. package/dist/src/clarity/index.js +145 -0
  123. package/dist/src/clarity/index.js.map +9 -0
  124. package/dist/src/connect/index.cjs +480 -0
  125. package/dist/src/connect/index.cjs.map +19 -0
  126. package/dist/src/connect/index.d.cts +110 -0
  127. package/dist/src/connect/index.d.ts +110 -0
  128. package/dist/src/connect/index.js +448 -0
  129. package/dist/src/connect/index.js.map +19 -0
  130. package/dist/src/connect/walletconnect/index.cjs +1322 -0
  131. package/dist/src/connect/walletconnect/index.cjs.map +18 -0
  132. package/dist/src/connect/walletconnect/index.d.cts +132 -0
  133. package/dist/src/connect/walletconnect/index.d.ts +132 -0
  134. package/dist/src/connect/walletconnect/index.js +1290 -0
  135. package/dist/src/connect/walletconnect/index.js.map +18 -0
  136. package/dist/src/index.cjs +557 -0
  137. package/dist/src/index.cjs.map +21 -0
  138. package/dist/src/index.d.cts +847 -0
  139. package/dist/src/index.d.ts +847 -0
  140. package/dist/src/index.js +629 -0
  141. package/dist/src/index.js.map +21 -0
  142. package/dist/src/postconditions/index.cjs +3 -0
  143. package/dist/src/postconditions/index.cjs.map +9 -0
  144. package/dist/src/postconditions/index.d.cts +91 -0
  145. package/dist/src/postconditions/index.d.ts +91 -0
  146. package/dist/src/postconditions/index.js +12 -0
  147. package/dist/src/postconditions/index.js.map +9 -0
  148. package/dist/src/pox/index.cjs +860 -0
  149. package/dist/src/pox/index.cjs.map +15 -0
  150. package/dist/src/pox/index.d.cts +244 -0
  151. package/dist/src/pox/index.d.ts +244 -0
  152. package/dist/src/pox/index.js +877 -0
  153. package/dist/src/pox/index.js.map +15 -0
  154. package/dist/src/stackingdao/index.cjs +300 -0
  155. package/dist/src/stackingdao/index.cjs.map +13 -0
  156. package/dist/src/stackingdao/index.d.cts +179 -0
  157. package/dist/src/stackingdao/index.d.ts +179 -0
  158. package/dist/src/stackingdao/index.js +318 -0
  159. package/dist/src/stackingdao/index.js.map +13 -0
  160. package/dist/src/subscriptions/index.cjs +14 -0
  161. package/dist/src/subscriptions/index.cjs.map +9 -0
  162. package/dist/src/subscriptions/index.d.cts +250 -0
  163. package/dist/src/subscriptions/index.d.ts +250 -0
  164. package/dist/src/subscriptions/index.js +21 -0
  165. package/dist/src/subscriptions/index.js.map +9 -0
  166. package/dist/src/transactions/index.cjs +50 -0
  167. package/dist/src/transactions/index.cjs.map +9 -0
  168. package/dist/src/transactions/index.d.cts +412 -0
  169. package/dist/src/transactions/index.d.ts +412 -0
  170. package/dist/src/transactions/index.js +101 -0
  171. package/dist/src/transactions/index.js.map +9 -0
  172. package/dist/src/utils/index.cjs +168 -0
  173. package/dist/src/utils/index.cjs.map +11 -0
  174. package/dist/src/utils/index.d.cts +140 -0
  175. package/dist/src/utils/index.d.ts +140 -0
  176. package/dist/src/utils/index.js +222 -0
  177. package/dist/src/utils/index.js.map +11 -0
  178. package/package.json +105 -0
@@ -0,0 +1,1322 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __moduleCache = /* @__PURE__ */ new WeakMap;
6
+ var __toCommonJS = (from) => {
7
+ var entry = __moduleCache.get(from), desc;
8
+ if (entry)
9
+ return entry;
10
+ entry = __defProp({}, "__esModule", { value: true });
11
+ if (from && typeof from === "object" || typeof from === "function")
12
+ __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
13
+ get: () => from[key],
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ }));
16
+ __moduleCache.set(from, entry);
17
+ return entry;
18
+ };
19
+ var __export = (target, all) => {
20
+ for (var name in all)
21
+ __defProp(target, name, {
22
+ get: all[name],
23
+ enumerable: true,
24
+ configurable: true,
25
+ set: (newValue) => all[name] = () => newValue
26
+ });
27
+ };
28
+
29
+ // src/connect/walletconnect/index.ts
30
+ var exports_walletconnect = {};
31
+ __export(exports_walletconnect, {
32
+ showModal: () => showModal,
33
+ qrSvg: () => qrSvg,
34
+ hideModal: () => hideModal,
35
+ WcSession: () => WcSession,
36
+ WcRelay: () => WcRelay,
37
+ WalletConnectProvider: () => WalletConnectProvider
38
+ });
39
+ module.exports = __toCommonJS(exports_walletconnect);
40
+
41
+ // src/connect/walletconnect/crypto.ts
42
+ var import_ed25519 = require("@noble/curves/ed25519.js");
43
+ var import_sha2 = require("@noble/hashes/sha2.js");
44
+ var import_hkdf = require("@noble/hashes/hkdf.js");
45
+ var import_utils = require("@noble/hashes/utils.js");
46
+ var import_aes = require("@noble/ciphers/aes.js");
47
+
48
+ // ../../node_modules/@scure/base/index.js
49
+ /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
50
+ function isBytes(a) {
51
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
52
+ }
53
+ function abytes(b) {
54
+ if (!isBytes(b))
55
+ throw new Error("Uint8Array expected");
56
+ }
57
+ function isArrayOf(isString, arr) {
58
+ if (!Array.isArray(arr))
59
+ return false;
60
+ if (arr.length === 0)
61
+ return true;
62
+ if (isString) {
63
+ return arr.every((item) => typeof item === "string");
64
+ } else {
65
+ return arr.every((item) => Number.isSafeInteger(item));
66
+ }
67
+ }
68
+ function afn(input) {
69
+ if (typeof input !== "function")
70
+ throw new Error("function expected");
71
+ return true;
72
+ }
73
+ function astr(label, input) {
74
+ if (typeof input !== "string")
75
+ throw new Error(`${label}: string expected`);
76
+ return true;
77
+ }
78
+ function anumber(n) {
79
+ if (!Number.isSafeInteger(n))
80
+ throw new Error(`invalid integer: ${n}`);
81
+ }
82
+ function aArr(input) {
83
+ if (!Array.isArray(input))
84
+ throw new Error("array expected");
85
+ }
86
+ function astrArr(label, input) {
87
+ if (!isArrayOf(true, input))
88
+ throw new Error(`${label}: array of strings expected`);
89
+ }
90
+ function anumArr(label, input) {
91
+ if (!isArrayOf(false, input))
92
+ throw new Error(`${label}: array of numbers expected`);
93
+ }
94
+ function chain(...args) {
95
+ const id = (a) => a;
96
+ const wrap = (a, b) => (c) => a(b(c));
97
+ const encode = args.map((x) => x.encode).reduceRight(wrap, id);
98
+ const decode = args.map((x) => x.decode).reduce(wrap, id);
99
+ return { encode, decode };
100
+ }
101
+ function alphabet(letters) {
102
+ const lettersA = typeof letters === "string" ? letters.split("") : letters;
103
+ const len = lettersA.length;
104
+ astrArr("alphabet", lettersA);
105
+ const indexes = new Map(lettersA.map((l, i) => [l, i]));
106
+ return {
107
+ encode: (digits) => {
108
+ aArr(digits);
109
+ return digits.map((i) => {
110
+ if (!Number.isSafeInteger(i) || i < 0 || i >= len)
111
+ throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
112
+ return lettersA[i];
113
+ });
114
+ },
115
+ decode: (input) => {
116
+ aArr(input);
117
+ return input.map((letter) => {
118
+ astr("alphabet.decode", letter);
119
+ const i = indexes.get(letter);
120
+ if (i === undefined)
121
+ throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
122
+ return i;
123
+ });
124
+ }
125
+ };
126
+ }
127
+ function join(separator = "") {
128
+ astr("join", separator);
129
+ return {
130
+ encode: (from) => {
131
+ astrArr("join.decode", from);
132
+ return from.join(separator);
133
+ },
134
+ decode: (to) => {
135
+ astr("join.decode", to);
136
+ return to.split(separator);
137
+ }
138
+ };
139
+ }
140
+ function padding(bits, chr = "=") {
141
+ anumber(bits);
142
+ astr("padding", chr);
143
+ return {
144
+ encode(data) {
145
+ astrArr("padding.encode", data);
146
+ while (data.length * bits % 8)
147
+ data.push(chr);
148
+ return data;
149
+ },
150
+ decode(input) {
151
+ astrArr("padding.decode", input);
152
+ let end = input.length;
153
+ if (end * bits % 8)
154
+ throw new Error("padding: invalid, string should have whole number of bytes");
155
+ for (;end > 0 && input[end - 1] === chr; end--) {
156
+ const last = end - 1;
157
+ const byte = last * bits;
158
+ if (byte % 8 === 0)
159
+ throw new Error("padding: invalid, string has too much padding");
160
+ }
161
+ return input.slice(0, end);
162
+ }
163
+ };
164
+ }
165
+ function normalize(fn) {
166
+ afn(fn);
167
+ return { encode: (from) => from, decode: (to) => fn(to) };
168
+ }
169
+ function convertRadix(data, from, to) {
170
+ if (from < 2)
171
+ throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);
172
+ if (to < 2)
173
+ throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);
174
+ aArr(data);
175
+ if (!data.length)
176
+ return [];
177
+ let pos = 0;
178
+ const res = [];
179
+ const digits = Array.from(data, (d) => {
180
+ anumber(d);
181
+ if (d < 0 || d >= from)
182
+ throw new Error(`invalid integer: ${d}`);
183
+ return d;
184
+ });
185
+ const dlen = digits.length;
186
+ while (true) {
187
+ let carry = 0;
188
+ let done = true;
189
+ for (let i = pos;i < dlen; i++) {
190
+ const digit = digits[i];
191
+ const fromCarry = from * carry;
192
+ const digitBase = fromCarry + digit;
193
+ if (!Number.isSafeInteger(digitBase) || fromCarry / from !== carry || digitBase - digit !== fromCarry) {
194
+ throw new Error("convertRadix: carry overflow");
195
+ }
196
+ const div = digitBase / to;
197
+ carry = digitBase % to;
198
+ const rounded = Math.floor(div);
199
+ digits[i] = rounded;
200
+ if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
201
+ throw new Error("convertRadix: carry overflow");
202
+ if (!done)
203
+ continue;
204
+ else if (!rounded)
205
+ pos = i;
206
+ else
207
+ done = false;
208
+ }
209
+ res.push(carry);
210
+ if (done)
211
+ break;
212
+ }
213
+ for (let i = 0;i < data.length - 1 && data[i] === 0; i++)
214
+ res.push(0);
215
+ return res.reverse();
216
+ }
217
+ var gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
218
+ var radix2carry = (from, to) => from + (to - gcd(from, to));
219
+ var powers = /* @__PURE__ */ (() => {
220
+ let res = [];
221
+ for (let i = 0;i < 40; i++)
222
+ res.push(2 ** i);
223
+ return res;
224
+ })();
225
+ function convertRadix2(data, from, to, padding2) {
226
+ aArr(data);
227
+ if (from <= 0 || from > 32)
228
+ throw new Error(`convertRadix2: wrong from=${from}`);
229
+ if (to <= 0 || to > 32)
230
+ throw new Error(`convertRadix2: wrong to=${to}`);
231
+ if (radix2carry(from, to) > 32) {
232
+ throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);
233
+ }
234
+ let carry = 0;
235
+ let pos = 0;
236
+ const max = powers[from];
237
+ const mask = powers[to] - 1;
238
+ const res = [];
239
+ for (const n of data) {
240
+ anumber(n);
241
+ if (n >= max)
242
+ throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
243
+ carry = carry << from | n;
244
+ if (pos + from > 32)
245
+ throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
246
+ pos += from;
247
+ for (;pos >= to; pos -= to)
248
+ res.push((carry >> pos - to & mask) >>> 0);
249
+ const pow = powers[pos];
250
+ if (pow === undefined)
251
+ throw new Error("invalid carry");
252
+ carry &= pow - 1;
253
+ }
254
+ carry = carry << to - pos & mask;
255
+ if (!padding2 && pos >= from)
256
+ throw new Error("Excess padding");
257
+ if (!padding2 && carry > 0)
258
+ throw new Error(`Non-zero padding: ${carry}`);
259
+ if (padding2 && pos > 0)
260
+ res.push(carry >>> 0);
261
+ return res;
262
+ }
263
+ function radix(num) {
264
+ anumber(num);
265
+ const _256 = 2 ** 8;
266
+ return {
267
+ encode: (bytes) => {
268
+ if (!isBytes(bytes))
269
+ throw new Error("radix.encode input should be Uint8Array");
270
+ return convertRadix(Array.from(bytes), _256, num);
271
+ },
272
+ decode: (digits) => {
273
+ anumArr("radix.decode", digits);
274
+ return Uint8Array.from(convertRadix(digits, num, _256));
275
+ }
276
+ };
277
+ }
278
+ function radix2(bits, revPadding = false) {
279
+ anumber(bits);
280
+ if (bits <= 0 || bits > 32)
281
+ throw new Error("radix2: bits should be in (0..32]");
282
+ if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
283
+ throw new Error("radix2: carry overflow");
284
+ return {
285
+ encode: (bytes) => {
286
+ if (!isBytes(bytes))
287
+ throw new Error("radix2.encode input should be Uint8Array");
288
+ return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
289
+ },
290
+ decode: (digits) => {
291
+ anumArr("radix2.decode", digits);
292
+ return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
293
+ }
294
+ };
295
+ }
296
+ function unsafeWrapper(fn) {
297
+ afn(fn);
298
+ return function(...args) {
299
+ try {
300
+ return fn.apply(null, args);
301
+ } catch (e) {}
302
+ };
303
+ }
304
+ var base16 = chain(radix2(4), alphabet("0123456789ABCDEF"), join(""));
305
+ var base32 = chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding(5), join(""));
306
+ var base32nopad = chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), join(""));
307
+ var base32hex = chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding(5), join(""));
308
+ var base32hexnopad = chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), join(""));
309
+ var base32crockford = chain(radix2(5), alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join(""), normalize((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1")));
310
+ var hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === "function" && typeof Uint8Array.fromBase64 === "function")();
311
+ var decodeBase64Builtin = (s, isUrl) => {
312
+ astr("base64", s);
313
+ const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;
314
+ const alphabet2 = isUrl ? "base64url" : "base64";
315
+ if (s.length > 0 && !re.test(s))
316
+ throw new Error("invalid base64");
317
+ return Uint8Array.fromBase64(s, { alphabet: alphabet2, lastChunkHandling: "strict" });
318
+ };
319
+ var base64 = hasBase64Builtin ? {
320
+ encode(b) {
321
+ abytes(b);
322
+ return b.toBase64();
323
+ },
324
+ decode(s) {
325
+ return decodeBase64Builtin(s, false);
326
+ }
327
+ } : chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding(6), join(""));
328
+ var base64nopad = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), join(""));
329
+ var base64url = hasBase64Builtin ? {
330
+ encode(b) {
331
+ abytes(b);
332
+ return b.toBase64({ alphabet: "base64url" });
333
+ },
334
+ decode(s) {
335
+ return decodeBase64Builtin(s, true);
336
+ }
337
+ } : chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding(6), join(""));
338
+ var base64urlnopad = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), join(""));
339
+ var genBase58 = (abc) => chain(radix(58), alphabet(abc), join(""));
340
+ var base58 = genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
341
+ var base58flickr = genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ");
342
+ var base58xrp = genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");
343
+ var BECH_ALPHABET = chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), join(""));
344
+ var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059];
345
+ function bech32Polymod(pre) {
346
+ const b = pre >> 25;
347
+ let chk = (pre & 33554431) << 5;
348
+ for (let i = 0;i < POLYMOD_GENERATORS.length; i++) {
349
+ if ((b >> i & 1) === 1)
350
+ chk ^= POLYMOD_GENERATORS[i];
351
+ }
352
+ return chk;
353
+ }
354
+ function bechChecksum(prefix, words, encodingConst = 1) {
355
+ const len = prefix.length;
356
+ let chk = 1;
357
+ for (let i = 0;i < len; i++) {
358
+ const c = prefix.charCodeAt(i);
359
+ if (c < 33 || c > 126)
360
+ throw new Error(`Invalid prefix (${prefix})`);
361
+ chk = bech32Polymod(chk) ^ c >> 5;
362
+ }
363
+ chk = bech32Polymod(chk);
364
+ for (let i = 0;i < len; i++)
365
+ chk = bech32Polymod(chk) ^ prefix.charCodeAt(i) & 31;
366
+ for (let v of words)
367
+ chk = bech32Polymod(chk) ^ v;
368
+ for (let i = 0;i < 6; i++)
369
+ chk = bech32Polymod(chk);
370
+ chk ^= encodingConst;
371
+ return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]], 30, 5, false));
372
+ }
373
+ function genBech32(encoding) {
374
+ const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939;
375
+ const _words = radix2(5);
376
+ const fromWords = _words.decode;
377
+ const toWords = _words.encode;
378
+ const fromWordsUnsafe = unsafeWrapper(fromWords);
379
+ function encode(prefix, words, limit = 90) {
380
+ astr("bech32.encode prefix", prefix);
381
+ if (isBytes(words))
382
+ words = Array.from(words);
383
+ anumArr("bech32.encode", words);
384
+ const plen = prefix.length;
385
+ if (plen === 0)
386
+ throw new TypeError(`Invalid prefix length ${plen}`);
387
+ const actualLength = plen + 7 + words.length;
388
+ if (limit !== false && actualLength > limit)
389
+ throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
390
+ const lowered = prefix.toLowerCase();
391
+ const sum = bechChecksum(lowered, words, ENCODING_CONST);
392
+ return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`;
393
+ }
394
+ function decode(str, limit = 90) {
395
+ astr("bech32.decode input", str);
396
+ const slen = str.length;
397
+ if (slen < 8 || limit !== false && slen > limit)
398
+ throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);
399
+ const lowered = str.toLowerCase();
400
+ if (str !== lowered && str !== str.toUpperCase())
401
+ throw new Error(`String must be lowercase or uppercase`);
402
+ const sepIndex = lowered.lastIndexOf("1");
403
+ if (sepIndex === 0 || sepIndex === -1)
404
+ throw new Error(`Letter "1" must be present between prefix and data only`);
405
+ const prefix = lowered.slice(0, sepIndex);
406
+ const data = lowered.slice(sepIndex + 1);
407
+ if (data.length < 6)
408
+ throw new Error("Data must be at least 6 characters long");
409
+ const words = BECH_ALPHABET.decode(data).slice(0, -6);
410
+ const sum = bechChecksum(prefix, words, ENCODING_CONST);
411
+ if (!data.endsWith(sum))
412
+ throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
413
+ return { prefix, words };
414
+ }
415
+ const decodeUnsafe = unsafeWrapper(decode);
416
+ function decodeToBytes(str) {
417
+ const { prefix, words } = decode(str, false);
418
+ return { prefix, words, bytes: fromWords(words) };
419
+ }
420
+ function encodeFromBytes(prefix, bytes) {
421
+ return encode(prefix, toWords(bytes));
422
+ }
423
+ return {
424
+ encode,
425
+ decode,
426
+ encodeFromBytes,
427
+ decodeToBytes,
428
+ decodeUnsafe,
429
+ fromWords,
430
+ fromWordsUnsafe,
431
+ toWords
432
+ };
433
+ }
434
+ var bech32 = genBech32("bech32");
435
+ var bech32m = genBech32("bech32m");
436
+ var hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
437
+ var hexBuiltin = {
438
+ encode(data) {
439
+ abytes(data);
440
+ return data.toHex();
441
+ },
442
+ decode(s) {
443
+ astr("hex", s);
444
+ return Uint8Array.fromHex(s);
445
+ }
446
+ };
447
+ var hex = hasHexBuiltin ? hexBuiltin : chain(radix2(4), alphabet("0123456789abcdef"), join(""), normalize((s) => {
448
+ if (typeof s !== "string" || s.length % 2 !== 0)
449
+ throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
450
+ return s.toLowerCase();
451
+ }));
452
+
453
+ // src/utils/encoding.ts
454
+ var hexes = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
455
+ function bytesToHex(bytes) {
456
+ let hex2 = "";
457
+ for (const b of bytes) {
458
+ hex2 += hexes[b];
459
+ }
460
+ return hex2;
461
+ }
462
+ function hexToBytes(hex2) {
463
+ hex2 = without0x(hex2);
464
+ if (hex2.length % 2)
465
+ hex2 = `0${hex2}`;
466
+ const array = new Uint8Array(hex2.length / 2);
467
+ for (let i = 0;i < array.length; i++) {
468
+ const j = i * 2;
469
+ const byte = Number.parseInt(hex2.slice(j, j + 2), 16);
470
+ if (Number.isNaN(byte) || byte < 0)
471
+ throw new Error("Invalid byte sequence");
472
+ array[i] = byte;
473
+ }
474
+ return array;
475
+ }
476
+ function without0x(value) {
477
+ return /^0x/i.test(value) ? value.slice(2) : value;
478
+ }
479
+
480
+ // src/connect/walletconnect/crypto.ts
481
+ var IV_LENGTH = 12;
482
+ var KEY_LENGTH = 32;
483
+ var TYPE_0 = 0;
484
+ var TYPE_1 = 1;
485
+ function generateKeyPair() {
486
+ const privateKey = import_utils.randomBytes(KEY_LENGTH);
487
+ const publicKey = import_ed25519.x25519.getPublicKey(privateKey);
488
+ return { privateKey, publicKey };
489
+ }
490
+ function generateSymKey() {
491
+ return import_utils.randomBytes(KEY_LENGTH);
492
+ }
493
+ function deriveSymKey(selfPrivate, peerPublic) {
494
+ const shared = import_ed25519.x25519.getSharedSecret(selfPrivate, peerPublic);
495
+ return import_hkdf.hkdf(import_sha2.sha256, shared, undefined, undefined, KEY_LENGTH);
496
+ }
497
+ function symKeyToTopic(symKey) {
498
+ return bytesToHex(import_sha2.sha256(symKey));
499
+ }
500
+ function encodeBase64(data) {
501
+ let binary = "";
502
+ for (let i = 0;i < data.length; i++)
503
+ binary += String.fromCharCode(data[i]);
504
+ return btoa(binary);
505
+ }
506
+ function decodeBase64(str) {
507
+ const binary = atob(str);
508
+ const bytes = new Uint8Array(binary.length);
509
+ for (let i = 0;i < binary.length; i++)
510
+ bytes[i] = binary.charCodeAt(i);
511
+ return bytes;
512
+ }
513
+ function encryptType0(symKey, plaintext) {
514
+ const iv = import_utils.randomBytes(IV_LENGTH);
515
+ const data = new TextEncoder().encode(plaintext);
516
+ const cipher = import_aes.gcm(symKey, iv);
517
+ const sealed = cipher.encrypt(data);
518
+ const envelope = new Uint8Array(1 + IV_LENGTH + sealed.length);
519
+ envelope[0] = TYPE_0;
520
+ envelope.set(iv, 1);
521
+ envelope.set(sealed, 1 + IV_LENGTH);
522
+ return envelope;
523
+ }
524
+ function decryptType0(symKey, envelope) {
525
+ if (envelope[0] !== TYPE_0)
526
+ throw new Error("Not a type-0 envelope");
527
+ const iv = envelope.subarray(1, 1 + IV_LENGTH);
528
+ const sealed = envelope.subarray(1 + IV_LENGTH);
529
+ const cipher = import_aes.gcm(symKey, iv);
530
+ const plain = cipher.decrypt(sealed);
531
+ return new TextDecoder().decode(plain);
532
+ }
533
+ function decryptType1(receiverPrivate, envelope) {
534
+ if (envelope[0] !== TYPE_1)
535
+ throw new Error("Not a type-1 envelope");
536
+ const senderPublic = envelope.subarray(1, 1 + KEY_LENGTH);
537
+ const iv = envelope.subarray(1 + KEY_LENGTH, 1 + KEY_LENGTH + IV_LENGTH);
538
+ const sealed = envelope.subarray(1 + KEY_LENGTH + IV_LENGTH);
539
+ const symKey = deriveSymKey(receiverPrivate, senderPublic);
540
+ const cipher = import_aes.gcm(symKey, iv);
541
+ const plain = cipher.decrypt(sealed);
542
+ return new TextDecoder().decode(plain);
543
+ }
544
+ var ED25519_MULTICODEC = new Uint8Array([237, 1]);
545
+ function encodeDidKey(publicKey) {
546
+ const prefixed = new Uint8Array(ED25519_MULTICODEC.length + publicKey.length);
547
+ prefixed.set(ED25519_MULTICODEC);
548
+ prefixed.set(publicKey, ED25519_MULTICODEC.length);
549
+ return `did:key:z${base58.encode(prefixed)}`;
550
+ }
551
+ function base64urlEncode(data) {
552
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
553
+ return base64urlnopad.encode(bytes);
554
+ }
555
+ function createRelayAuthJwt(relayUrl) {
556
+ const privateKey = import_ed25519.ed25519.utils.randomSecretKey();
557
+ const publicKey = import_ed25519.ed25519.getPublicKey(privateKey);
558
+ const clientId = encodeDidKey(publicKey);
559
+ const now = Math.floor(Date.now() / 1000);
560
+ const header = base64urlEncode(JSON.stringify({ alg: "EdDSA", typ: "JWT" }));
561
+ const payload = base64urlEncode(JSON.stringify({
562
+ iss: clientId,
563
+ sub: bytesToHex(import_utils.randomBytes(32)),
564
+ aud: relayUrl,
565
+ iat: now,
566
+ exp: now + 86400,
567
+ act: "client_auth"
568
+ }));
569
+ const message = new TextEncoder().encode(`${header}.${payload}`);
570
+ const signature = base64urlEncode(import_ed25519.ed25519.sign(message, privateKey));
571
+ return { jwt: `${header}.${payload}.${signature}`, clientId };
572
+ }
573
+
574
+ // src/connect/walletconnect/relay.ts
575
+ var DEFAULT_RELAY = "wss://relay.walletconnect.com";
576
+ var DEFAULT_TTL = 300;
577
+
578
+ class WcRelay {
579
+ ws = null;
580
+ url;
581
+ projectId;
582
+ nextId = Date.now() * 1000 + Math.floor(Math.random() * 1000);
583
+ pending = new Map;
584
+ subscriptions = new Map;
585
+ subIdToTopic = new Map;
586
+ destroyed = false;
587
+ reconnecting = false;
588
+ reconnectAttempt = 0;
589
+ reconnectTimer = null;
590
+ connectPromise = null;
591
+ connectReject = null;
592
+ constructor(projectId, relayUrl) {
593
+ this.projectId = projectId;
594
+ this.url = relayUrl ?? DEFAULT_RELAY;
595
+ }
596
+ async connect() {
597
+ if (this.ws?.readyState === WebSocket.OPEN)
598
+ return;
599
+ if (this.connectPromise)
600
+ return this.connectPromise;
601
+ this.connectPromise = new Promise((resolve, reject) => {
602
+ this.connectReject = reject;
603
+ const { jwt } = createRelayAuthJwt(this.url);
604
+ const wsUrl = `${this.url}/?auth=${jwt}&projectId=${this.projectId}`;
605
+ this.ws = new WebSocket(wsUrl);
606
+ this.ws.addEventListener("open", () => {
607
+ this.reconnectAttempt = 0;
608
+ this.reconnecting = false;
609
+ this.connectPromise = null;
610
+ this.connectReject = null;
611
+ resolve();
612
+ }, { once: true });
613
+ this.ws.addEventListener("error", (e) => {
614
+ this.connectPromise = null;
615
+ this.connectReject = null;
616
+ reject(new Error(`WC relay connection failed: ${e}`));
617
+ }, { once: true });
618
+ this.ws.addEventListener("message", (event) => {
619
+ this.handleMessage(typeof event.data === "string" ? event.data : new TextDecoder().decode(event.data));
620
+ });
621
+ this.ws.addEventListener("close", () => {
622
+ this.connectPromise = null;
623
+ if (!this.destroyed)
624
+ this.handleDisconnect();
625
+ });
626
+ });
627
+ return this.connectPromise;
628
+ }
629
+ async subscribe(topic, handler) {
630
+ await this.connect();
631
+ this.subscriptions.set(topic, handler);
632
+ const subId = await this.rpc("irn_subscribe", { topic });
633
+ this.subIdToTopic.set(subId, topic);
634
+ return subId;
635
+ }
636
+ async publish(topic, message, tag, ttl = DEFAULT_TTL) {
637
+ await this.connect();
638
+ await this.rpc("irn_publish", {
639
+ topic,
640
+ message,
641
+ ttl,
642
+ tag,
643
+ prompt: false
644
+ });
645
+ }
646
+ async publishEncrypted(topic, symKey, payload, tag, ttl = DEFAULT_TTL) {
647
+ const plaintext = JSON.stringify(payload);
648
+ const envelope = encryptType0(symKey, plaintext);
649
+ await this.publish(topic, encodeBase64(envelope), tag, ttl);
650
+ }
651
+ rpc(method, params) {
652
+ return new Promise((resolve, reject) => {
653
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
654
+ return reject(new Error("WC relay not connected"));
655
+ }
656
+ const id = this.nextId++;
657
+ this.pending.set(id, { resolve, reject });
658
+ this.ws.send(JSON.stringify({ id, jsonrpc: "2.0", method, params }));
659
+ });
660
+ }
661
+ handleMessage(raw) {
662
+ let msg;
663
+ try {
664
+ msg = JSON.parse(raw);
665
+ } catch {
666
+ return;
667
+ }
668
+ if ("id" in msg && msg.id != null && this.pending.has(msg.id)) {
669
+ const p = this.pending.get(msg.id);
670
+ this.pending.delete(msg.id);
671
+ if (msg.error) {
672
+ p.reject(new Error(`WC relay error: ${msg.error.message}`));
673
+ } else {
674
+ p.resolve(msg.result);
675
+ }
676
+ return;
677
+ }
678
+ if (msg.method === "irn_subscription" && msg.params) {
679
+ const { id: subId, data } = msg.params;
680
+ const topic = data?.topic ?? this.subIdToTopic.get(subId);
681
+ const handler = topic ? this.subscriptions.get(topic) : undefined;
682
+ if (handler && data) {
683
+ handler({
684
+ topic: data.topic,
685
+ message: data.message,
686
+ publishedAt: data.publishedAt ?? Date.now(),
687
+ tag: data.tag ?? 0
688
+ });
689
+ }
690
+ if (msg.id != null) {
691
+ this.ws?.send(JSON.stringify({ id: msg.id, jsonrpc: "2.0", result: true }));
692
+ }
693
+ }
694
+ }
695
+ handleDisconnect() {
696
+ this.ws = null;
697
+ for (const [, p] of this.pending) {
698
+ p.reject(new Error("WC relay disconnected"));
699
+ }
700
+ this.pending.clear();
701
+ if (this.subscriptions.size > 0 && this.reconnectAttempt < 5) {
702
+ this.scheduleReconnect();
703
+ }
704
+ }
705
+ scheduleReconnect() {
706
+ if (this.destroyed || this.reconnecting)
707
+ return;
708
+ this.reconnecting = true;
709
+ const delay = 1000 * 2 ** this.reconnectAttempt;
710
+ this.reconnectAttempt++;
711
+ this.reconnectTimer = setTimeout(async () => {
712
+ this.reconnecting = false;
713
+ try {
714
+ await this.connect();
715
+ for (const [topic] of this.subscriptions) {
716
+ const subId = await this.rpc("irn_subscribe", { topic });
717
+ this.subIdToTopic.set(subId, topic);
718
+ }
719
+ } catch {
720
+ if (!this.destroyed && this.subscriptions.size > 0) {
721
+ this.handleDisconnect();
722
+ }
723
+ }
724
+ }, delay);
725
+ }
726
+ destroy() {
727
+ this.destroyed = true;
728
+ if (this.reconnectTimer)
729
+ clearTimeout(this.reconnectTimer);
730
+ if (this.connectReject) {
731
+ this.connectReject(new Error("WC relay destroyed"));
732
+ this.connectReject = null;
733
+ this.connectPromise = null;
734
+ }
735
+ for (const [, p] of this.pending) {
736
+ p.reject(new Error("WC relay destroyed"));
737
+ }
738
+ this.pending.clear();
739
+ this.subscriptions.clear();
740
+ this.subIdToTopic.clear();
741
+ if (this.ws) {
742
+ this.ws.close();
743
+ this.ws = null;
744
+ }
745
+ }
746
+ }
747
+
748
+ // src/connect/walletconnect/session.ts
749
+ var STORAGE_KEY = "@secondlayer/wc:session";
750
+ var SESSION_EXPIRY = 7 * 24 * 60 * 60;
751
+ var STACKS_METHODS = [
752
+ "stx_getAddresses",
753
+ "stx_transferStx",
754
+ "stx_callContract",
755
+ "stx_deployContract",
756
+ "stx_signMessage",
757
+ "stx_signTransaction"
758
+ ];
759
+ var STACKS_EVENTS = ["chainChanged", "accountsChanged"];
760
+ function getStorage() {
761
+ return typeof localStorage !== "undefined" ? localStorage : undefined;
762
+ }
763
+
764
+ class WcSession {
765
+ relay;
766
+ config;
767
+ chains;
768
+ pairingSymKey = null;
769
+ pairingTopic = null;
770
+ selfKeyPair = null;
771
+ sessionData = null;
772
+ sessionSymKey = null;
773
+ pending = new Map;
774
+ nextId = Date.now();
775
+ constructor(config) {
776
+ this.config = config;
777
+ this.chains = config.chains ?? ["stacks:1"];
778
+ this.relay = new WcRelay(config.projectId, config.relayUrl);
779
+ }
780
+ restore() {
781
+ try {
782
+ const raw = getStorage()?.getItem(STORAGE_KEY);
783
+ if (!raw)
784
+ return false;
785
+ const data = JSON.parse(raw);
786
+ if (data.expiry < Date.now() / 1000) {
787
+ getStorage()?.removeItem(STORAGE_KEY);
788
+ return false;
789
+ }
790
+ this.sessionData = data;
791
+ this.sessionSymKey = hexToBytes(data.symKey);
792
+ this.subscribeSession().catch(() => {});
793
+ return true;
794
+ } catch {
795
+ return false;
796
+ }
797
+ }
798
+ async pair() {
799
+ this.pairingSymKey = generateSymKey();
800
+ this.pairingTopic = symKeyToTopic(this.pairingSymKey);
801
+ this.selfKeyPair = generateKeyPair();
802
+ const symKeyHex = bytesToHex(this.pairingSymKey);
803
+ const uri = `wc:${this.pairingTopic}@2?relay-protocol=irn&symKey=${symKeyHex}`;
804
+ const approval = new Promise((resolve, reject) => {
805
+ this.relay.subscribe(this.pairingTopic, (msg) => {
806
+ try {
807
+ this.handlePairingMessage(msg.message, resolve, reject);
808
+ } catch (err) {
809
+ reject(err instanceof Error ? err : new Error(String(err)));
810
+ }
811
+ }).catch(reject);
812
+ });
813
+ return { uri, approval };
814
+ }
815
+ async request(method, params) {
816
+ if (!this.sessionData || !this.sessionSymKey) {
817
+ throw new Error("No active WC session");
818
+ }
819
+ const id = this.nextId++;
820
+ const payload = {
821
+ id,
822
+ jsonrpc: "2.0",
823
+ method: "wc_sessionRequest",
824
+ params: {
825
+ request: { method, params },
826
+ chainId: this.chains[0]
827
+ }
828
+ };
829
+ return new Promise((resolve, reject) => {
830
+ this.pending.set(id, { resolve, reject });
831
+ this.relay.publishEncrypted(this.sessionData.topic, this.sessionSymKey, payload, 1108, SESSION_EXPIRY).catch((err) => {
832
+ this.pending.delete(id);
833
+ reject(err);
834
+ });
835
+ });
836
+ }
837
+ disconnect() {
838
+ if (this.sessionData && this.sessionSymKey) {
839
+ const id = this.nextId++;
840
+ const payload = {
841
+ id,
842
+ jsonrpc: "2.0",
843
+ method: "wc_sessionDelete",
844
+ params: { code: 6000, message: "User disconnected" }
845
+ };
846
+ this.relay.publishEncrypted(this.sessionData.topic, this.sessionSymKey, payload, 1112).catch(() => {});
847
+ }
848
+ this.sessionData = null;
849
+ this.sessionSymKey = null;
850
+ this.pending.clear();
851
+ getStorage()?.removeItem(STORAGE_KEY);
852
+ this.relay.destroy();
853
+ }
854
+ get session() {
855
+ return this.sessionData;
856
+ }
857
+ handlePairingMessage(message, resolve, reject) {
858
+ const envelope = decodeBase64(message);
859
+ let plaintext;
860
+ if (envelope[0] === 1 && this.selfKeyPair) {
861
+ plaintext = decryptType1(this.selfKeyPair.privateKey, envelope);
862
+ } else if (this.pairingSymKey) {
863
+ plaintext = decryptType0(this.pairingSymKey, envelope);
864
+ } else {
865
+ return;
866
+ }
867
+ let rpc;
868
+ try {
869
+ rpc = JSON.parse(plaintext);
870
+ } catch {
871
+ return;
872
+ }
873
+ if (rpc.method === "wc_sessionPropose") {
874
+ this.handleProposal(rpc, resolve, reject).catch(reject);
875
+ }
876
+ }
877
+ async handleProposal(rpc, resolve, reject) {
878
+ try {
879
+ const proposal = rpc.params;
880
+ const peerPublicKey = hexToBytes(proposal.proposer.publicKey);
881
+ const sessionKp = generateKeyPair();
882
+ const sessionSymKey = deriveSymKey(sessionKp.privateKey, peerPublicKey);
883
+ const sessionTopic = symKeyToTopic(sessionSymKey);
884
+ const expiry = Math.floor(Date.now() / 1000) + SESSION_EXPIRY;
885
+ const settled = {
886
+ relay: { protocol: "irn" },
887
+ namespaces: {
888
+ stacks: {
889
+ chains: this.chains,
890
+ methods: STACKS_METHODS,
891
+ events: STACKS_EVENTS,
892
+ accounts: this.chains.map((c) => `${c}:placeholder`)
893
+ }
894
+ },
895
+ controller: {
896
+ publicKey: bytesToHex(sessionKp.publicKey),
897
+ metadata: this.config.metadata
898
+ },
899
+ expiry
900
+ };
901
+ const approvePayload = {
902
+ id: rpc.id,
903
+ jsonrpc: "2.0",
904
+ result: {
905
+ relay: { protocol: "irn" },
906
+ responderPublicKey: bytesToHex(sessionKp.publicKey)
907
+ }
908
+ };
909
+ await this.relay.publishEncrypted(this.pairingTopic, this.pairingSymKey, approvePayload, 1101);
910
+ this.sessionSymKey = sessionSymKey;
911
+ this.sessionData = {
912
+ topic: sessionTopic,
913
+ symKey: bytesToHex(sessionSymKey),
914
+ peerMeta: proposal.proposer.metadata,
915
+ expiry,
916
+ accounts: [],
917
+ controllerPublicKey: proposal.proposer.publicKey
918
+ };
919
+ await this.subscribeSession();
920
+ const settlePayload = {
921
+ id: this.nextId++,
922
+ jsonrpc: "2.0",
923
+ method: "wc_sessionSettle",
924
+ params: settled
925
+ };
926
+ await this.relay.publishEncrypted(sessionTopic, sessionSymKey, settlePayload, 1104);
927
+ getStorage()?.setItem(STORAGE_KEY, JSON.stringify(this.sessionData));
928
+ resolve(settled);
929
+ } catch (err) {
930
+ reject(err instanceof Error ? err : new Error(String(err)));
931
+ }
932
+ }
933
+ async subscribeSession() {
934
+ if (!this.sessionData || !this.sessionSymKey)
935
+ return;
936
+ const symKey = this.sessionSymKey;
937
+ await this.relay.subscribe(this.sessionData.topic, (msg) => {
938
+ try {
939
+ const envelope = decodeBase64(msg.message);
940
+ const plaintext = decryptType0(symKey, envelope);
941
+ const rpc = JSON.parse(plaintext);
942
+ if ("id" in rpc && this.pending.has(rpc.id)) {
943
+ const p = this.pending.get(rpc.id);
944
+ this.pending.delete(rpc.id);
945
+ if (rpc.error) {
946
+ p.reject(new Error(rpc.error.message ?? "WC request failed"));
947
+ } else {
948
+ p.resolve(rpc.result);
949
+ }
950
+ }
951
+ if (rpc.method === "wc_sessionDelete") {
952
+ this.sessionData = null;
953
+ this.sessionSymKey = null;
954
+ this.pending.clear();
955
+ getStorage()?.removeItem(STORAGE_KEY);
956
+ }
957
+ } catch {}
958
+ });
959
+ }
960
+ }
961
+
962
+ // src/connect/walletconnect/provider.ts
963
+ class WalletConnectProvider {
964
+ session;
965
+ constructor(config) {
966
+ this.session = new WcSession(config);
967
+ }
968
+ restore() {
969
+ return this.session.restore();
970
+ }
971
+ async pair() {
972
+ return this.session.pair();
973
+ }
974
+ async request(method, params) {
975
+ return this.session.request(method, params);
976
+ }
977
+ disconnect() {
978
+ this.session.disconnect();
979
+ }
980
+ get sessionData() {
981
+ return this.session.session;
982
+ }
983
+ }
984
+ // src/connect/walletconnect/qr.ts
985
+ var CAPACITIES = [0, 17, 32, 53, 78, 106, 134, 154, 192, 230, 271];
986
+ var EC_PARAMS = [
987
+ [0, 0, 0],
988
+ [26, 7, 1],
989
+ [44, 10, 1],
990
+ [70, 15, 1],
991
+ [100, 20, 1],
992
+ [134, 26, 1],
993
+ [172, 18, 2],
994
+ [196, 20, 2],
995
+ [242, 24, 2],
996
+ [292, 30, 2],
997
+ [346, 18, 4]
998
+ ];
999
+ function selectVersion(len) {
1000
+ for (let v = 1;v <= 10; v++) {
1001
+ if (len <= CAPACITIES[v])
1002
+ return v;
1003
+ }
1004
+ throw new Error("QR data too long");
1005
+ }
1006
+ var GF_EXP = new Uint8Array(512);
1007
+ var GF_LOG = new Uint8Array(256);
1008
+ {
1009
+ let x = 1;
1010
+ for (let i = 0;i < 255; i++) {
1011
+ GF_EXP[i] = x;
1012
+ GF_LOG[x] = i;
1013
+ x = x << 1 ^ (x >= 128 ? 285 : 0);
1014
+ }
1015
+ for (let i = 255;i < 512; i++)
1016
+ GF_EXP[i] = GF_EXP[i - 255];
1017
+ }
1018
+ function gfMul(a, b) {
1019
+ if (a === 0 || b === 0)
1020
+ return 0;
1021
+ return GF_EXP[GF_LOG[a] + GF_LOG[b]];
1022
+ }
1023
+ function rsGenPoly(n) {
1024
+ let poly = new Uint8Array([1]);
1025
+ for (let i = 0;i < n; i++) {
1026
+ const next = new Uint8Array(poly.length + 1);
1027
+ for (let j = 0;j < poly.length; j++) {
1028
+ next[j] ^= poly[j];
1029
+ next[j + 1] ^= gfMul(poly[j], GF_EXP[i]);
1030
+ }
1031
+ poly = next;
1032
+ }
1033
+ return poly;
1034
+ }
1035
+ function rsEncode(data, ecLen) {
1036
+ const gen = rsGenPoly(ecLen);
1037
+ const result = new Uint8Array(data.length + ecLen);
1038
+ result.set(data);
1039
+ for (let i = 0;i < data.length; i++) {
1040
+ const coef = result[i];
1041
+ if (coef === 0)
1042
+ continue;
1043
+ for (let j = 0;j < gen.length; j++) {
1044
+ result[i + j] ^= gfMul(gen[j], coef);
1045
+ }
1046
+ }
1047
+ return result.subarray(data.length);
1048
+ }
1049
+ function encodeData(bytes, version) {
1050
+ const [totalCw, ecPerBlock, numBlocks] = EC_PARAMS[version];
1051
+ const dataCw = totalCw - ecPerBlock * numBlocks;
1052
+ const bits = [];
1053
+ const push = (val, len) => {
1054
+ for (let i = len - 1;i >= 0; i--)
1055
+ bits.push(val >> i & 1);
1056
+ };
1057
+ push(4, 4);
1058
+ push(bytes.length, version <= 9 ? 8 : 16);
1059
+ for (const b of bytes)
1060
+ push(b, 8);
1061
+ push(0, 4);
1062
+ while (bits.length % 8 !== 0)
1063
+ bits.push(0);
1064
+ const codewords = new Uint8Array(dataCw);
1065
+ for (let i = 0;i < dataCw; i++) {
1066
+ let byte = 0;
1067
+ for (let j = 0;j < 8; j++) {
1068
+ const idx = i * 8 + j;
1069
+ byte = byte << 1 | (idx < bits.length ? bits[idx] : 0);
1070
+ }
1071
+ codewords[i] = byte;
1072
+ }
1073
+ let padByte = 236;
1074
+ for (let i = Math.ceil(bits.length / 8);i < dataCw; i++) {
1075
+ codewords[i] = padByte;
1076
+ padByte = padByte === 236 ? 17 : 236;
1077
+ }
1078
+ const cwPerBlock = Math.floor(dataCw / numBlocks);
1079
+ const dataBlocks = [];
1080
+ const ecBlocks = [];
1081
+ let offset = 0;
1082
+ for (let b = 0;b < numBlocks; b++) {
1083
+ const blockLen = cwPerBlock + (b < dataCw % numBlocks ? 1 : 0);
1084
+ const block = codewords.subarray(offset, offset + blockLen);
1085
+ dataBlocks.push(block);
1086
+ ecBlocks.push(rsEncode(block, ecPerBlock));
1087
+ offset += blockLen;
1088
+ }
1089
+ const result = [];
1090
+ const maxDataLen = Math.max(...dataBlocks.map((b) => b.length));
1091
+ for (let i = 0;i < maxDataLen; i++) {
1092
+ for (const block of dataBlocks) {
1093
+ if (i < block.length)
1094
+ result.push(block[i]);
1095
+ }
1096
+ }
1097
+ for (let i = 0;i < ecPerBlock; i++) {
1098
+ for (const block of ecBlocks) {
1099
+ if (i < block.length)
1100
+ result.push(block[i]);
1101
+ }
1102
+ }
1103
+ return new Uint8Array(result);
1104
+ }
1105
+ function createMatrix(size) {
1106
+ return Array.from({ length: size }, () => new Uint8Array(size));
1107
+ }
1108
+ function setModule(m, r, c, val, reserved) {
1109
+ if (r >= 0 && r < m.length && c >= 0 && c < m.length) {
1110
+ m[r][c] = val;
1111
+ reserved[r][c] = 1;
1112
+ }
1113
+ }
1114
+ function addFinderPattern(m, r, c, res) {
1115
+ for (let dr = -1;dr <= 7; dr++) {
1116
+ for (let dc = -1;dc <= 7; dc++) {
1117
+ const rr = r + dr, cc = c + dc;
1118
+ if (rr < 0 || rr >= m.length || cc < 0 || cc >= m.length)
1119
+ continue;
1120
+ const inOuter = dr >= 0 && dr <= 6 && dc >= 0 && dc <= 6;
1121
+ const inInner = dr >= 2 && dr <= 4 && dc >= 2 && dc <= 4;
1122
+ const onBorder = dr === 0 || dr === 6 || dc === 0 || dc === 6;
1123
+ const val = inInner || inOuter && onBorder ? 1 : 0;
1124
+ setModule(m, rr, cc, val, res);
1125
+ }
1126
+ }
1127
+ }
1128
+ function addTimingPatterns(m, res) {
1129
+ for (let i = 8;i < m.length - 8; i++) {
1130
+ const val = i % 2 === 0 ? 1 : 0;
1131
+ if (!res[6][i])
1132
+ setModule(m, 6, i, val, res);
1133
+ if (!res[i][6])
1134
+ setModule(m, i, 6, val, res);
1135
+ }
1136
+ }
1137
+ function addFormatInfo(m, res) {
1138
+ const fmt = 30660;
1139
+ const n = m.length;
1140
+ for (let i = 0;i < 15; i++) {
1141
+ const bit = fmt >> 14 - i & 1;
1142
+ if (i < 6)
1143
+ setModule(m, 8, i, bit, res);
1144
+ else if (i === 6)
1145
+ setModule(m, 8, 7, bit, res);
1146
+ else if (i === 7)
1147
+ setModule(m, 8, 8, bit, res);
1148
+ else if (i === 8)
1149
+ setModule(m, 7, 8, bit, res);
1150
+ else
1151
+ setModule(m, 14 - i, 8, bit, res);
1152
+ if (i < 8)
1153
+ setModule(m, n - 1 - i, 8, bit, res);
1154
+ else
1155
+ setModule(m, 8, n - 15 + i, bit, res);
1156
+ }
1157
+ setModule(m, n - 8, 8, 1, res);
1158
+ }
1159
+ function placeData(m, res, data) {
1160
+ const n = m.length;
1161
+ let bitIdx = 0;
1162
+ const totalBits = data.length * 8;
1163
+ let col = n - 1;
1164
+ let upward = true;
1165
+ while (col >= 0) {
1166
+ if (col === 6)
1167
+ col--;
1168
+ const rows = upward ? Array.from({ length: n }, (_, i) => n - 1 - i) : Array.from({ length: n }, (_, i) => i);
1169
+ for (const row of rows) {
1170
+ for (const dc of [0, -1]) {
1171
+ const c = col + dc;
1172
+ if (c < 0 || res[row][c])
1173
+ continue;
1174
+ if (bitIdx < totalBits) {
1175
+ const byteIdx = bitIdx >> 3;
1176
+ const bitPos = 7 - (bitIdx & 7);
1177
+ const bit = data[byteIdx] >> bitPos & 1;
1178
+ m[row][c] = bit ^ ((row + c) % 2 === 0 ? 1 : 0);
1179
+ bitIdx++;
1180
+ }
1181
+ }
1182
+ }
1183
+ col -= 2;
1184
+ upward = !upward;
1185
+ }
1186
+ }
1187
+ function buildMatrix(version, codewords) {
1188
+ const n = version * 4 + 17;
1189
+ const m = createMatrix(n);
1190
+ const res = createMatrix(n);
1191
+ addFinderPattern(m, 0, 0, res);
1192
+ addFinderPattern(m, 0, n - 7, res);
1193
+ addFinderPattern(m, n - 7, 0, res);
1194
+ addTimingPatterns(m, res);
1195
+ addFormatInfo(m, res);
1196
+ if (version >= 2) {
1197
+ const pos = [6, version * 4 + 10];
1198
+ for (const r of pos) {
1199
+ for (const c of pos) {
1200
+ if (res[r]?.[c])
1201
+ continue;
1202
+ for (let dr = -2;dr <= 2; dr++) {
1203
+ for (let dc = -2;dc <= 2; dc++) {
1204
+ const val = Math.abs(dr) === 2 || Math.abs(dc) === 2 || dr === 0 && dc === 0 ? 1 : 0;
1205
+ setModule(m, r + dr, c + dc, val, res);
1206
+ }
1207
+ }
1208
+ }
1209
+ }
1210
+ }
1211
+ placeData(m, res, codewords);
1212
+ return m;
1213
+ }
1214
+ function qrSvg(data, opts) {
1215
+ const size = opts?.size ?? 256;
1216
+ const dark = opts?.dark ?? "#000000";
1217
+ const light = opts?.light ?? "#ffffff";
1218
+ const bytes = new TextEncoder().encode(data);
1219
+ const version = selectVersion(bytes.length);
1220
+ const codewords = encodeData(bytes, version);
1221
+ const matrix = buildMatrix(version, codewords);
1222
+ const n = matrix.length;
1223
+ const quiet = 4;
1224
+ const total = n + quiet * 2;
1225
+ const scale = size / total;
1226
+ let paths = "";
1227
+ for (let r = 0;r < n; r++) {
1228
+ for (let c = 0;c < n; c++) {
1229
+ if (matrix[r][c]) {
1230
+ const x = (c + quiet) * scale;
1231
+ const y = (r + quiet) * scale;
1232
+ paths += `M${x},${y}h${scale}v${scale}h-${scale}z`;
1233
+ }
1234
+ }
1235
+ }
1236
+ return [
1237
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size} ${size}" width="${size}" height="${size}">`,
1238
+ `<rect width="${size}" height="${size}" fill="${light}"/>`,
1239
+ `<path d="${paths}" fill="${dark}"/>`,
1240
+ `</svg>`
1241
+ ].join("");
1242
+ }
1243
+ // src/connect/provider.ts
1244
+ function isWalletInstalled() {
1245
+ return typeof window !== "undefined" && !!(window.StacksProvider || window.LeatherProvider || window.XverseProvider || window.HiroWalletProvider);
1246
+ }
1247
+
1248
+ // src/connect/walletconnect/modal.ts
1249
+ var MODAL_ID = "sl-wc-modal";
1250
+ var STYLES = `
1251
+ #${MODAL_ID} { position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.5) }
1252
+ #${MODAL_ID} .sl-wc-box { background:#fff;border-radius:16px;padding:24px;max-width:360px;width:90%;text-align:center;font-family:system-ui,sans-serif }
1253
+ #${MODAL_ID} .sl-wc-title { margin:0 0 16px;font-size:18px;font-weight:600;color:#1a1a1a }
1254
+ #${MODAL_ID} .sl-wc-btn { display:block;width:100%;padding:12px;margin:8px 0;border:1px solid #e5e5e5;border-radius:12px;background:#fff;cursor:pointer;font-size:15px;font-weight:500;color:#1a1a1a;transition:background .15s }
1255
+ #${MODAL_ID} .sl-wc-btn:hover { background:#f5f5f5 }
1256
+ #${MODAL_ID} .sl-wc-divider { margin:16px 0;color:#999;font-size:13px }
1257
+ #${MODAL_ID} .sl-wc-qr { margin:16px auto 0 }
1258
+ #${MODAL_ID} .sl-wc-close { position:absolute;top:12px;right:16px;background:none;border:none;font-size:20px;cursor:pointer;color:#999 }
1259
+ `;
1260
+ function showModal(opts) {
1261
+ if (typeof document === "undefined")
1262
+ return () => {};
1263
+ document.getElementById(MODAL_ID)?.remove();
1264
+ const overlay = document.createElement("div");
1265
+ overlay.id = MODAL_ID;
1266
+ const style = document.createElement("style");
1267
+ style.textContent = STYLES;
1268
+ overlay.appendChild(style);
1269
+ const box = document.createElement("div");
1270
+ box.className = "sl-wc-box";
1271
+ box.style.position = "relative";
1272
+ const close = document.createElement("button");
1273
+ close.className = "sl-wc-close";
1274
+ close.textContent = "×";
1275
+ close.onclick = dismiss;
1276
+ box.appendChild(close);
1277
+ const title = document.createElement("h2");
1278
+ title.className = "sl-wc-title";
1279
+ title.textContent = "Connect Wallet";
1280
+ box.appendChild(title);
1281
+ if (isWalletInstalled()) {
1282
+ const btn = document.createElement("button");
1283
+ btn.className = "sl-wc-btn";
1284
+ btn.textContent = "Browser Wallet";
1285
+ btn.onclick = () => {
1286
+ dismiss();
1287
+ opts.onSelectInjected?.();
1288
+ };
1289
+ box.appendChild(btn);
1290
+ }
1291
+ if (opts.wcUri) {
1292
+ if (isWalletInstalled()) {
1293
+ const divider = document.createElement("div");
1294
+ divider.className = "sl-wc-divider";
1295
+ divider.textContent = "or scan with mobile wallet";
1296
+ box.appendChild(divider);
1297
+ }
1298
+ const qr = document.createElement("div");
1299
+ qr.className = "sl-wc-qr";
1300
+ qr.innerHTML = qrSvg(opts.wcUri, { size: 240 });
1301
+ box.appendChild(qr);
1302
+ }
1303
+ overlay.appendChild(box);
1304
+ overlay.onclick = (e) => {
1305
+ if (e.target === overlay)
1306
+ dismiss();
1307
+ };
1308
+ document.body.appendChild(overlay);
1309
+ function dismiss() {
1310
+ overlay.remove();
1311
+ opts.onClose?.();
1312
+ }
1313
+ return dismiss;
1314
+ }
1315
+ function hideModal() {
1316
+ if (typeof document === "undefined")
1317
+ return;
1318
+ document.getElementById(MODAL_ID)?.remove();
1319
+ }
1320
+
1321
+ //# debugId=91582566EF1D837E64756E2164756E21
1322
+ //# sourceMappingURL=index.cjs.map