@getalby/lightning-tools 5.2.1 → 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 (54) hide show
  1. package/README.md +25 -18
  2. package/dist/cjs/bolt11.cjs +1250 -0
  3. package/dist/cjs/bolt11.cjs.map +1 -0
  4. package/dist/cjs/fiat.cjs +57 -0
  5. package/dist/cjs/fiat.cjs.map +1 -0
  6. package/dist/cjs/index.cjs +1818 -0
  7. package/dist/cjs/index.cjs.map +1 -0
  8. package/dist/cjs/l402.cjs +89 -0
  9. package/dist/cjs/l402.cjs.map +1 -0
  10. package/dist/cjs/lnurl.cjs +1674 -0
  11. package/dist/cjs/lnurl.cjs.map +1 -0
  12. package/dist/cjs/podcasting2.cjs +32 -0
  13. package/dist/cjs/podcasting2.cjs.map +1 -0
  14. package/dist/esm/bolt11.js +1246 -0
  15. package/dist/esm/bolt11.js.map +1 -0
  16. package/dist/esm/fiat.js +51 -0
  17. package/dist/esm/fiat.js.map +1 -0
  18. package/dist/esm/index.js +1792 -0
  19. package/dist/esm/index.js.map +1 -0
  20. package/dist/esm/l402.js +84 -0
  21. package/dist/esm/l402.js.map +1 -0
  22. package/dist/esm/lnurl.js +1661 -0
  23. package/dist/esm/lnurl.js.map +1 -0
  24. package/dist/esm/podcasting2.js +30 -0
  25. package/dist/esm/podcasting2.js.map +1 -0
  26. package/dist/lightning-tools.umd.js +5 -0
  27. package/dist/lightning-tools.umd.js.map +1 -0
  28. package/dist/types/bolt11.d.ts +46 -0
  29. package/dist/types/fiat.d.ts +24 -0
  30. package/dist/types/index.d.ts +284 -0
  31. package/dist/types/l402.d.ts +27 -0
  32. package/dist/types/lnurl.d.ts +211 -0
  33. package/dist/{podcasting2/types.d.ts → types/podcasting2.d.ts} +11 -4
  34. package/package.json +51 -17
  35. package/dist/bolt11/Invoice.d.ts +0 -19
  36. package/dist/bolt11/index.d.ts +0 -3
  37. package/dist/bolt11/types.d.ts +0 -14
  38. package/dist/bolt11/utils.d.ts +0 -10
  39. package/dist/fiat/fiat.d.ts +0 -14
  40. package/dist/fiat/index.d.ts +0 -1
  41. package/dist/index.cjs +0 -1
  42. package/dist/index.d.ts +0 -7
  43. package/dist/index.modern.js +0 -1
  44. package/dist/index.module.js +0 -1
  45. package/dist/index.umd.js +0 -1
  46. package/dist/l402/index.d.ts +0 -2
  47. package/dist/l402/l402.d.ts +0 -6
  48. package/dist/l402/utils.d.ts +0 -12
  49. package/dist/lnurl/LightningAddress.d.ts +0 -44
  50. package/dist/lnurl/index.d.ts +0 -3
  51. package/dist/lnurl/types.d.ts +0 -104
  52. package/dist/lnurl/utils.d.ts +0 -14
  53. package/dist/podcasting2/boostagrams.d.ts +0 -2
  54. package/dist/podcasting2/index.d.ts +0 -2
@@ -0,0 +1,1661 @@
1
+ function bytes(b, ...lengths) {
2
+ if (!(b instanceof Uint8Array))
3
+ throw new Error('Expected Uint8Array');
4
+ if (lengths.length > 0 && !lengths.includes(b.length))
5
+ throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
6
+ }
7
+ function exists(instance, checkFinished = true) {
8
+ if (instance.destroyed)
9
+ throw new Error('Hash instance has been destroyed');
10
+ if (checkFinished && instance.finished)
11
+ throw new Error('Hash#digest() has already been called');
12
+ }
13
+ function output(out, instance) {
14
+ bytes(out);
15
+ const min = instance.outputLen;
16
+ if (out.length < min) {
17
+ throw new Error(`digestInto() expects output buffer of length at least ${min}`);
18
+ }
19
+ }
20
+
21
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
22
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
23
+ // node.js versions earlier than v19 don't declare it in global scope.
24
+ // For node.js, package.json#exports field mapping rewrites import
25
+ // from `crypto` to `cryptoNode`, which imports native module.
26
+ // Makes the utils un-importable in browsers without a bundler.
27
+ // Once node.js 18 is deprecated, we can just drop the import.
28
+ const u8a = (a) => a instanceof Uint8Array;
29
+ // Cast array to view
30
+ const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
31
+ // The rotate right (circular right shift) operation for uint32
32
+ const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
33
+ // big-endian hardware is rare. Just in case someone still decides to run hashes:
34
+ // early-throw an error because we don't support BE yet.
35
+ const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
36
+ if (!isLE)
37
+ throw new Error('Non little-endian hardware is not supported');
38
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
39
+ /**
40
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
41
+ */
42
+ function bytesToHex(bytes) {
43
+ if (!u8a(bytes))
44
+ throw new Error('Uint8Array expected');
45
+ // pre-caching improves the speed 6x
46
+ let hex = '';
47
+ for (let i = 0; i < bytes.length; i++) {
48
+ hex += hexes[bytes[i]];
49
+ }
50
+ return hex;
51
+ }
52
+ /**
53
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
54
+ */
55
+ function utf8ToBytes(str) {
56
+ if (typeof str !== 'string')
57
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
58
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
59
+ }
60
+ /**
61
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
62
+ * Warning: when Uint8Array is passed, it would NOT get copied.
63
+ * Keep in mind for future mutable operations.
64
+ */
65
+ function toBytes(data) {
66
+ if (typeof data === 'string')
67
+ data = utf8ToBytes(data);
68
+ if (!u8a(data))
69
+ throw new Error(`expected Uint8Array, got ${typeof data}`);
70
+ return data;
71
+ }
72
+ // For runtime check if class implements interface
73
+ class Hash {
74
+ // Safe version that clones internal state
75
+ clone() {
76
+ return this._cloneInto();
77
+ }
78
+ }
79
+ function wrapConstructor(hashCons) {
80
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
81
+ const tmp = hashCons();
82
+ hashC.outputLen = tmp.outputLen;
83
+ hashC.blockLen = tmp.blockLen;
84
+ hashC.create = () => hashCons();
85
+ return hashC;
86
+ }
87
+
88
+ // Polyfill for Safari 14
89
+ function setBigUint64(view, byteOffset, value, isLE) {
90
+ if (typeof view.setBigUint64 === 'function')
91
+ return view.setBigUint64(byteOffset, value, isLE);
92
+ const _32n = BigInt(32);
93
+ const _u32_max = BigInt(0xffffffff);
94
+ const wh = Number((value >> _32n) & _u32_max);
95
+ const wl = Number(value & _u32_max);
96
+ const h = isLE ? 4 : 0;
97
+ const l = isLE ? 0 : 4;
98
+ view.setUint32(byteOffset + h, wh, isLE);
99
+ view.setUint32(byteOffset + l, wl, isLE);
100
+ }
101
+ // Base SHA2 class (RFC 6234)
102
+ class SHA2 extends Hash {
103
+ constructor(blockLen, outputLen, padOffset, isLE) {
104
+ super();
105
+ this.blockLen = blockLen;
106
+ this.outputLen = outputLen;
107
+ this.padOffset = padOffset;
108
+ this.isLE = isLE;
109
+ this.finished = false;
110
+ this.length = 0;
111
+ this.pos = 0;
112
+ this.destroyed = false;
113
+ this.buffer = new Uint8Array(blockLen);
114
+ this.view = createView(this.buffer);
115
+ }
116
+ update(data) {
117
+ exists(this);
118
+ const { view, buffer, blockLen } = this;
119
+ data = toBytes(data);
120
+ const len = data.length;
121
+ for (let pos = 0; pos < len;) {
122
+ const take = Math.min(blockLen - this.pos, len - pos);
123
+ // Fast path: we have at least one block in input, cast it to view and process
124
+ if (take === blockLen) {
125
+ const dataView = createView(data);
126
+ for (; blockLen <= len - pos; pos += blockLen)
127
+ this.process(dataView, pos);
128
+ continue;
129
+ }
130
+ buffer.set(data.subarray(pos, pos + take), this.pos);
131
+ this.pos += take;
132
+ pos += take;
133
+ if (this.pos === blockLen) {
134
+ this.process(view, 0);
135
+ this.pos = 0;
136
+ }
137
+ }
138
+ this.length += data.length;
139
+ this.roundClean();
140
+ return this;
141
+ }
142
+ digestInto(out) {
143
+ exists(this);
144
+ output(out, this);
145
+ this.finished = true;
146
+ // Padding
147
+ // We can avoid allocation of buffer for padding completely if it
148
+ // was previously not allocated here. But it won't change performance.
149
+ const { buffer, view, blockLen, isLE } = this;
150
+ let { pos } = this;
151
+ // append the bit '1' to the message
152
+ buffer[pos++] = 0b10000000;
153
+ this.buffer.subarray(pos).fill(0);
154
+ // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again
155
+ if (this.padOffset > blockLen - pos) {
156
+ this.process(view, 0);
157
+ pos = 0;
158
+ }
159
+ // Pad until full block byte with zeros
160
+ for (let i = pos; i < blockLen; i++)
161
+ buffer[i] = 0;
162
+ // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
163
+ // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
164
+ // So we just write lowest 64 bits of that value.
165
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
166
+ this.process(view, 0);
167
+ const oview = createView(out);
168
+ const len = this.outputLen;
169
+ // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
170
+ if (len % 4)
171
+ throw new Error('_sha2: outputLen should be aligned to 32bit');
172
+ const outLen = len / 4;
173
+ const state = this.get();
174
+ if (outLen > state.length)
175
+ throw new Error('_sha2: outputLen bigger than state');
176
+ for (let i = 0; i < outLen; i++)
177
+ oview.setUint32(4 * i, state[i], isLE);
178
+ }
179
+ digest() {
180
+ const { buffer, outputLen } = this;
181
+ this.digestInto(buffer);
182
+ const res = buffer.slice(0, outputLen);
183
+ this.destroy();
184
+ return res;
185
+ }
186
+ _cloneInto(to) {
187
+ to || (to = new this.constructor());
188
+ to.set(...this.get());
189
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
190
+ to.length = length;
191
+ to.pos = pos;
192
+ to.finished = finished;
193
+ to.destroyed = destroyed;
194
+ if (length % blockLen)
195
+ to.buffer.set(buffer);
196
+ return to;
197
+ }
198
+ }
199
+
200
+ // SHA2-256 need to try 2^128 hashes to execute birthday attack.
201
+ // BTC network is doing 2^67 hashes/sec as per early 2023.
202
+ // Choice: a ? b : c
203
+ const Chi = (a, b, c) => (a & b) ^ (~a & c);
204
+ // Majority function, true if any two inpust is true
205
+ const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
206
+ // Round constants:
207
+ // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
208
+ // prettier-ignore
209
+ const SHA256_K = /* @__PURE__ */ new Uint32Array([
210
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
211
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
212
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
213
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
214
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
215
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
216
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
217
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
218
+ ]);
219
+ // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
220
+ // prettier-ignore
221
+ const IV = /* @__PURE__ */ new Uint32Array([
222
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
223
+ ]);
224
+ // Temporary buffer, not used to store anything between runs
225
+ // Named this way because it matches specification.
226
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
227
+ class SHA256 extends SHA2 {
228
+ constructor() {
229
+ super(64, 32, 8, false);
230
+ // We cannot use array here since array allows indexing by variable
231
+ // which means optimizer/compiler cannot use registers.
232
+ this.A = IV[0] | 0;
233
+ this.B = IV[1] | 0;
234
+ this.C = IV[2] | 0;
235
+ this.D = IV[3] | 0;
236
+ this.E = IV[4] | 0;
237
+ this.F = IV[5] | 0;
238
+ this.G = IV[6] | 0;
239
+ this.H = IV[7] | 0;
240
+ }
241
+ get() {
242
+ const { A, B, C, D, E, F, G, H } = this;
243
+ return [A, B, C, D, E, F, G, H];
244
+ }
245
+ // prettier-ignore
246
+ set(A, B, C, D, E, F, G, H) {
247
+ this.A = A | 0;
248
+ this.B = B | 0;
249
+ this.C = C | 0;
250
+ this.D = D | 0;
251
+ this.E = E | 0;
252
+ this.F = F | 0;
253
+ this.G = G | 0;
254
+ this.H = H | 0;
255
+ }
256
+ process(view, offset) {
257
+ // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
258
+ for (let i = 0; i < 16; i++, offset += 4)
259
+ SHA256_W[i] = view.getUint32(offset, false);
260
+ for (let i = 16; i < 64; i++) {
261
+ const W15 = SHA256_W[i - 15];
262
+ const W2 = SHA256_W[i - 2];
263
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
264
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
265
+ SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
266
+ }
267
+ // Compression function main loop, 64 rounds
268
+ let { A, B, C, D, E, F, G, H } = this;
269
+ for (let i = 0; i < 64; i++) {
270
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
271
+ const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
272
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
273
+ const T2 = (sigma0 + Maj(A, B, C)) | 0;
274
+ H = G;
275
+ G = F;
276
+ F = E;
277
+ E = (D + T1) | 0;
278
+ D = C;
279
+ C = B;
280
+ B = A;
281
+ A = (T1 + T2) | 0;
282
+ }
283
+ // Add the compressed chunk to the current hash value
284
+ A = (A + this.A) | 0;
285
+ B = (B + this.B) | 0;
286
+ C = (C + this.C) | 0;
287
+ D = (D + this.D) | 0;
288
+ E = (E + this.E) | 0;
289
+ F = (F + this.F) | 0;
290
+ G = (G + this.G) | 0;
291
+ H = (H + this.H) | 0;
292
+ this.set(A, B, C, D, E, F, G, H);
293
+ }
294
+ roundClean() {
295
+ SHA256_W.fill(0);
296
+ }
297
+ destroy() {
298
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
299
+ this.buffer.fill(0);
300
+ }
301
+ }
302
+ /**
303
+ * SHA2-256 hash function
304
+ * @param message - data that would be hashed
305
+ */
306
+ const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
307
+
308
+ const TAG_KEYSEND = "keysend";
309
+ const parseKeysendResponse = (data) => {
310
+ if (data.tag !== TAG_KEYSEND)
311
+ throw new Error("Invalid keysend params");
312
+ if (data.status !== "OK")
313
+ throw new Error("Keysend status not OK");
314
+ if (!data.pubkey)
315
+ throw new Error("Pubkey does not exist");
316
+ const destination = data.pubkey;
317
+ let customKey, customValue;
318
+ if (data.customData && data.customData[0]) {
319
+ customKey = data.customData[0].customKey;
320
+ customValue = data.customData[0].customValue;
321
+ }
322
+ return {
323
+ destination,
324
+ customKey,
325
+ customValue,
326
+ };
327
+ };
328
+ async function generateZapEvent({ satoshi, comment, p, e, relays }, options = {}) {
329
+ const nostr = options.nostr || globalThis.nostr;
330
+ if (!nostr) {
331
+ throw new Error("nostr option or window.nostr is not available");
332
+ }
333
+ const nostrTags = [
334
+ ["relays", ...relays],
335
+ ["amount", satoshi.toString()],
336
+ ];
337
+ if (p) {
338
+ nostrTags.push(["p", p]);
339
+ }
340
+ if (e) {
341
+ nostrTags.push(["e", e]);
342
+ }
343
+ const pubkey = await nostr.getPublicKey();
344
+ const nostrEvent = {
345
+ pubkey,
346
+ created_at: Math.floor(Date.now() / 1000),
347
+ kind: 9734,
348
+ tags: nostrTags,
349
+ content: comment ?? "",
350
+ };
351
+ nostrEvent.id = getEventHash(nostrEvent);
352
+ return await nostr.signEvent(nostrEvent);
353
+ }
354
+ function validateEvent(event) {
355
+ if (typeof event.content !== "string")
356
+ return false;
357
+ if (typeof event.created_at !== "number")
358
+ return false;
359
+ // ignore these checks because if the pubkey is not set we add it to the event. same for the ID.
360
+ // if (typeof event.pubkey !== "string") return false;
361
+ // if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false;
362
+ if (!Array.isArray(event.tags))
363
+ return false;
364
+ for (let i = 0; i < event.tags.length; i++) {
365
+ const tag = event.tags[i];
366
+ if (!Array.isArray(tag))
367
+ return false;
368
+ for (let j = 0; j < tag.length; j++) {
369
+ if (typeof tag[j] === "object")
370
+ return false;
371
+ }
372
+ }
373
+ return true;
374
+ }
375
+ function serializeEvent(evt) {
376
+ if (!validateEvent(evt))
377
+ throw new Error("can't serialize event with wrong or missing properties");
378
+ return JSON.stringify([
379
+ 0,
380
+ evt.pubkey,
381
+ evt.created_at,
382
+ evt.kind,
383
+ evt.tags,
384
+ evt.content,
385
+ ]);
386
+ }
387
+ function getEventHash(event) {
388
+ return bytesToHex(sha256(serializeEvent(event)));
389
+ }
390
+ function parseNostrResponse(nostrData, username) {
391
+ let nostrPubkey;
392
+ let nostrRelays;
393
+ if (username && nostrData) {
394
+ nostrPubkey = nostrData.names?.[username];
395
+ nostrRelays = nostrPubkey ? nostrData.relays?.[nostrPubkey] : undefined;
396
+ }
397
+ return [nostrData, nostrPubkey, nostrRelays];
398
+ }
399
+ const URL_REGEX = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/;
400
+ const isUrl = (url) => {
401
+ if (!url)
402
+ return false;
403
+ return URL_REGEX.test(url);
404
+ };
405
+ const isValidAmount = ({ amount, min, max, }) => {
406
+ return amount > 0 && amount >= min && amount <= max;
407
+ };
408
+ const TAG_PAY_REQUEST = "payRequest";
409
+ // From: https://github.com/dolcalmi/lnurl-pay/blob/main/src/request-pay-service-params.ts
410
+ const parseLnUrlPayResponse = async (data) => {
411
+ if (data.tag !== TAG_PAY_REQUEST)
412
+ throw new Error("Invalid pay service params");
413
+ const callback = (data.callback + "").trim();
414
+ if (!isUrl(callback))
415
+ throw new Error("Callback must be a valid url");
416
+ const min = Math.ceil(Number(data.minSendable || 0));
417
+ const max = Math.floor(Number(data.maxSendable));
418
+ if (!(min && max) || min > max)
419
+ throw new Error("Invalid pay service params");
420
+ let metadata;
421
+ let metadataHash;
422
+ try {
423
+ metadata = JSON.parse(data.metadata + "");
424
+ metadataHash = bytesToHex(sha256(data.metadata + ""));
425
+ }
426
+ catch {
427
+ metadata = [];
428
+ metadataHash = bytesToHex(sha256("[]"));
429
+ }
430
+ let email = "";
431
+ let image = "";
432
+ let description = "";
433
+ let identifier = "";
434
+ for (let i = 0; i < metadata.length; i++) {
435
+ const [k, v] = metadata[i];
436
+ switch (k) {
437
+ case "text/plain":
438
+ description = v;
439
+ break;
440
+ case "text/identifier":
441
+ identifier = v;
442
+ break;
443
+ case "text/email":
444
+ email = v;
445
+ break;
446
+ case "image/png;base64":
447
+ case "image/jpeg;base64":
448
+ image = "data:" + k + "," + v;
449
+ break;
450
+ }
451
+ }
452
+ const payerData = data.payerData;
453
+ let domain;
454
+ try {
455
+ domain = new URL(callback).hostname;
456
+ }
457
+ catch {
458
+ // fail silently and let domain remain undefined if callback is not a valid URL
459
+ }
460
+ return {
461
+ callback,
462
+ fixed: min === max,
463
+ min,
464
+ max,
465
+ domain,
466
+ metadata,
467
+ metadataHash,
468
+ identifier,
469
+ email,
470
+ description,
471
+ image,
472
+ payerData,
473
+ commentAllowed: Number(data.commentAllowed) || 0,
474
+ rawData: data,
475
+ allowsNostr: data.allowsNostr || false,
476
+ };
477
+ };
478
+
479
+ var lib = {};
480
+
481
+ var hasRequiredLib;
482
+
483
+ function requireLib () {
484
+ if (hasRequiredLib) return lib;
485
+ hasRequiredLib = 1;
486
+ (function (exports) {
487
+ /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
488
+ Object.defineProperty(exports, "__esModule", { value: true });
489
+ exports.bytes = exports.stringToBytes = exports.str = exports.bytesToString = exports.hex = exports.utf8 = exports.bech32m = exports.bech32 = exports.base58check = exports.base58xmr = exports.base58xrp = exports.base58flickr = exports.base58 = exports.base64url = exports.base64 = exports.base32crockford = exports.base32hex = exports.base32 = exports.base16 = exports.utils = exports.assertNumber = void 0;
490
+ function assertNumber(n) {
491
+ if (!Number.isSafeInteger(n))
492
+ throw new Error(`Wrong integer: ${n}`);
493
+ }
494
+ exports.assertNumber = assertNumber;
495
+ function chain(...args) {
496
+ const wrap = (a, b) => (c) => a(b(c));
497
+ const encode = Array.from(args)
498
+ .reverse()
499
+ .reduce((acc, i) => (acc ? wrap(acc, i.encode) : i.encode), undefined);
500
+ const decode = args.reduce((acc, i) => (acc ? wrap(acc, i.decode) : i.decode), undefined);
501
+ return { encode, decode };
502
+ }
503
+ function alphabet(alphabet) {
504
+ return {
505
+ encode: (digits) => {
506
+ if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))
507
+ throw new Error('alphabet.encode input should be an array of numbers');
508
+ return digits.map((i) => {
509
+ assertNumber(i);
510
+ if (i < 0 || i >= alphabet.length)
511
+ throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`);
512
+ return alphabet[i];
513
+ });
514
+ },
515
+ decode: (input) => {
516
+ if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))
517
+ throw new Error('alphabet.decode input should be array of strings');
518
+ return input.map((letter) => {
519
+ if (typeof letter !== 'string')
520
+ throw new Error(`alphabet.decode: not string element=${letter}`);
521
+ const index = alphabet.indexOf(letter);
522
+ if (index === -1)
523
+ throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet}`);
524
+ return index;
525
+ });
526
+ },
527
+ };
528
+ }
529
+ function join(separator = '') {
530
+ if (typeof separator !== 'string')
531
+ throw new Error('join separator should be string');
532
+ return {
533
+ encode: (from) => {
534
+ if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string'))
535
+ throw new Error('join.encode input should be array of strings');
536
+ for (let i of from)
537
+ if (typeof i !== 'string')
538
+ throw new Error(`join.encode: non-string input=${i}`);
539
+ return from.join(separator);
540
+ },
541
+ decode: (to) => {
542
+ if (typeof to !== 'string')
543
+ throw new Error('join.decode input should be string');
544
+ return to.split(separator);
545
+ },
546
+ };
547
+ }
548
+ function padding(bits, chr = '=') {
549
+ assertNumber(bits);
550
+ if (typeof chr !== 'string')
551
+ throw new Error('padding chr should be string');
552
+ return {
553
+ encode(data) {
554
+ if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string'))
555
+ throw new Error('padding.encode input should be array of strings');
556
+ for (let i of data)
557
+ if (typeof i !== 'string')
558
+ throw new Error(`padding.encode: non-string input=${i}`);
559
+ while ((data.length * bits) % 8)
560
+ data.push(chr);
561
+ return data;
562
+ },
563
+ decode(input) {
564
+ if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))
565
+ throw new Error('padding.encode input should be array of strings');
566
+ for (let i of input)
567
+ if (typeof i !== 'string')
568
+ throw new Error(`padding.decode: non-string input=${i}`);
569
+ let end = input.length;
570
+ if ((end * bits) % 8)
571
+ throw new Error('Invalid padding: string should have whole number of bytes');
572
+ for (; end > 0 && input[end - 1] === chr; end--) {
573
+ if (!(((end - 1) * bits) % 8))
574
+ throw new Error('Invalid padding: string has too much padding');
575
+ }
576
+ return input.slice(0, end);
577
+ },
578
+ };
579
+ }
580
+ function normalize(fn) {
581
+ if (typeof fn !== 'function')
582
+ throw new Error('normalize fn should be function');
583
+ return { encode: (from) => from, decode: (to) => fn(to) };
584
+ }
585
+ function convertRadix(data, from, to) {
586
+ if (from < 2)
587
+ throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`);
588
+ if (to < 2)
589
+ throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`);
590
+ if (!Array.isArray(data))
591
+ throw new Error('convertRadix: data should be array');
592
+ if (!data.length)
593
+ return [];
594
+ let pos = 0;
595
+ const res = [];
596
+ const digits = Array.from(data);
597
+ digits.forEach((d) => {
598
+ assertNumber(d);
599
+ if (d < 0 || d >= from)
600
+ throw new Error(`Wrong integer: ${d}`);
601
+ });
602
+ while (true) {
603
+ let carry = 0;
604
+ let done = true;
605
+ for (let i = pos; i < digits.length; i++) {
606
+ const digit = digits[i];
607
+ const digitBase = from * carry + digit;
608
+ if (!Number.isSafeInteger(digitBase) ||
609
+ (from * carry) / from !== carry ||
610
+ digitBase - digit !== from * carry) {
611
+ throw new Error('convertRadix: carry overflow');
612
+ }
613
+ carry = digitBase % to;
614
+ digits[i] = Math.floor(digitBase / to);
615
+ if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase)
616
+ throw new Error('convertRadix: carry overflow');
617
+ if (!done)
618
+ continue;
619
+ else if (!digits[i])
620
+ pos = i;
621
+ else
622
+ done = false;
623
+ }
624
+ res.push(carry);
625
+ if (done)
626
+ break;
627
+ }
628
+ for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
629
+ res.push(0);
630
+ return res.reverse();
631
+ }
632
+ const gcd = (a, b) => (!b ? a : gcd(b, a % b));
633
+ const radix2carry = (from, to) => from + (to - gcd(from, to));
634
+ function convertRadix2(data, from, to, padding) {
635
+ if (!Array.isArray(data))
636
+ throw new Error('convertRadix2: data should be array');
637
+ if (from <= 0 || from > 32)
638
+ throw new Error(`convertRadix2: wrong from=${from}`);
639
+ if (to <= 0 || to > 32)
640
+ throw new Error(`convertRadix2: wrong to=${to}`);
641
+ if (radix2carry(from, to) > 32) {
642
+ throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);
643
+ }
644
+ let carry = 0;
645
+ let pos = 0;
646
+ const mask = 2 ** to - 1;
647
+ const res = [];
648
+ for (const n of data) {
649
+ assertNumber(n);
650
+ if (n >= 2 ** from)
651
+ throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
652
+ carry = (carry << from) | n;
653
+ if (pos + from > 32)
654
+ throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
655
+ pos += from;
656
+ for (; pos >= to; pos -= to)
657
+ res.push(((carry >> (pos - to)) & mask) >>> 0);
658
+ carry &= 2 ** pos - 1;
659
+ }
660
+ carry = (carry << (to - pos)) & mask;
661
+ if (!padding && pos >= from)
662
+ throw new Error('Excess padding');
663
+ if (!padding && carry)
664
+ throw new Error(`Non-zero padding: ${carry}`);
665
+ if (padding && pos > 0)
666
+ res.push(carry >>> 0);
667
+ return res;
668
+ }
669
+ function radix(num) {
670
+ assertNumber(num);
671
+ return {
672
+ encode: (bytes) => {
673
+ if (!(bytes instanceof Uint8Array))
674
+ throw new Error('radix.encode input should be Uint8Array');
675
+ return convertRadix(Array.from(bytes), 2 ** 8, num);
676
+ },
677
+ decode: (digits) => {
678
+ if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))
679
+ throw new Error('radix.decode input should be array of strings');
680
+ return Uint8Array.from(convertRadix(digits, num, 2 ** 8));
681
+ },
682
+ };
683
+ }
684
+ function radix2(bits, revPadding = false) {
685
+ assertNumber(bits);
686
+ if (bits <= 0 || bits > 32)
687
+ throw new Error('radix2: bits should be in (0..32]');
688
+ if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
689
+ throw new Error('radix2: carry overflow');
690
+ return {
691
+ encode: (bytes) => {
692
+ if (!(bytes instanceof Uint8Array))
693
+ throw new Error('radix2.encode input should be Uint8Array');
694
+ return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
695
+ },
696
+ decode: (digits) => {
697
+ if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))
698
+ throw new Error('radix2.decode input should be array of strings');
699
+ return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
700
+ },
701
+ };
702
+ }
703
+ function unsafeWrapper(fn) {
704
+ if (typeof fn !== 'function')
705
+ throw new Error('unsafeWrapper fn should be function');
706
+ return function (...args) {
707
+ try {
708
+ return fn.apply(null, args);
709
+ }
710
+ catch (e) { }
711
+ };
712
+ }
713
+ function checksum(len, fn) {
714
+ assertNumber(len);
715
+ if (typeof fn !== 'function')
716
+ throw new Error('checksum fn should be function');
717
+ return {
718
+ encode(data) {
719
+ if (!(data instanceof Uint8Array))
720
+ throw new Error('checksum.encode: input should be Uint8Array');
721
+ const checksum = fn(data).slice(0, len);
722
+ const res = new Uint8Array(data.length + len);
723
+ res.set(data);
724
+ res.set(checksum, data.length);
725
+ return res;
726
+ },
727
+ decode(data) {
728
+ if (!(data instanceof Uint8Array))
729
+ throw new Error('checksum.decode: input should be Uint8Array');
730
+ const payload = data.slice(0, -len);
731
+ const newChecksum = fn(payload).slice(0, len);
732
+ const oldChecksum = data.slice(-len);
733
+ for (let i = 0; i < len; i++)
734
+ if (newChecksum[i] !== oldChecksum[i])
735
+ throw new Error('Invalid checksum');
736
+ return payload;
737
+ },
738
+ };
739
+ }
740
+ exports.utils = { alphabet, chain, checksum, radix, radix2, join, padding };
741
+ exports.base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));
742
+ exports.base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''));
743
+ exports.base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''));
744
+ exports.base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')));
745
+ exports.base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join(''));
746
+ exports.base64url = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join(''));
747
+ const genBase58 = (abc) => chain(radix(58), alphabet(abc), join(''));
748
+ exports.base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
749
+ exports.base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');
750
+ exports.base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz');
751
+ const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];
752
+ exports.base58xmr = {
753
+ encode(data) {
754
+ let res = '';
755
+ for (let i = 0; i < data.length; i += 8) {
756
+ const block = data.subarray(i, i + 8);
757
+ res += exports.base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');
758
+ }
759
+ return res;
760
+ },
761
+ decode(str) {
762
+ let res = [];
763
+ for (let i = 0; i < str.length; i += 11) {
764
+ const slice = str.slice(i, i + 11);
765
+ const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);
766
+ const block = exports.base58.decode(slice);
767
+ for (let j = 0; j < block.length - blockLen; j++) {
768
+ if (block[j] !== 0)
769
+ throw new Error('base58xmr: wrong padding');
770
+ }
771
+ res = res.concat(Array.from(block.slice(block.length - blockLen)));
772
+ }
773
+ return Uint8Array.from(res);
774
+ },
775
+ };
776
+ const base58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), exports.base58);
777
+ exports.base58check = base58check;
778
+ const BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));
779
+ const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
780
+ function bech32Polymod(pre) {
781
+ const b = pre >> 25;
782
+ let chk = (pre & 0x1ffffff) << 5;
783
+ for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
784
+ if (((b >> i) & 1) === 1)
785
+ chk ^= POLYMOD_GENERATORS[i];
786
+ }
787
+ return chk;
788
+ }
789
+ function bechChecksum(prefix, words, encodingConst = 1) {
790
+ const len = prefix.length;
791
+ let chk = 1;
792
+ for (let i = 0; i < len; i++) {
793
+ const c = prefix.charCodeAt(i);
794
+ if (c < 33 || c > 126)
795
+ throw new Error(`Invalid prefix (${prefix})`);
796
+ chk = bech32Polymod(chk) ^ (c >> 5);
797
+ }
798
+ chk = bech32Polymod(chk);
799
+ for (let i = 0; i < len; i++)
800
+ chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);
801
+ for (let v of words)
802
+ chk = bech32Polymod(chk) ^ v;
803
+ for (let i = 0; i < 6; i++)
804
+ chk = bech32Polymod(chk);
805
+ chk ^= encodingConst;
806
+ return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false));
807
+ }
808
+ function genBech32(encoding) {
809
+ const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;
810
+ const _words = radix2(5);
811
+ const fromWords = _words.decode;
812
+ const toWords = _words.encode;
813
+ const fromWordsUnsafe = unsafeWrapper(fromWords);
814
+ function encode(prefix, words, limit = 90) {
815
+ if (typeof prefix !== 'string')
816
+ throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`);
817
+ if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number'))
818
+ throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`);
819
+ const actualLength = prefix.length + 7 + words.length;
820
+ if (limit !== false && actualLength > limit)
821
+ throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
822
+ prefix = prefix.toLowerCase();
823
+ return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`;
824
+ }
825
+ function decode(str, limit = 90) {
826
+ if (typeof str !== 'string')
827
+ throw new Error(`bech32.decode input should be string, not ${typeof str}`);
828
+ if (str.length < 8 || (limit !== false && str.length > limit))
829
+ throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`);
830
+ const lowered = str.toLowerCase();
831
+ if (str !== lowered && str !== str.toUpperCase())
832
+ throw new Error(`String must be lowercase or uppercase`);
833
+ str = lowered;
834
+ const sepIndex = str.lastIndexOf('1');
835
+ if (sepIndex === 0 || sepIndex === -1)
836
+ throw new Error(`Letter "1" must be present between prefix and data only`);
837
+ const prefix = str.slice(0, sepIndex);
838
+ const _words = str.slice(sepIndex + 1);
839
+ if (_words.length < 6)
840
+ throw new Error('Data must be at least 6 characters long');
841
+ const words = BECH_ALPHABET.decode(_words).slice(0, -6);
842
+ const sum = bechChecksum(prefix, words, ENCODING_CONST);
843
+ if (!_words.endsWith(sum))
844
+ throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
845
+ return { prefix, words };
846
+ }
847
+ const decodeUnsafe = unsafeWrapper(decode);
848
+ function decodeToBytes(str) {
849
+ const { prefix, words } = decode(str, false);
850
+ return { prefix, words, bytes: fromWords(words) };
851
+ }
852
+ return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords };
853
+ }
854
+ exports.bech32 = genBech32('bech32');
855
+ exports.bech32m = genBech32('bech32m');
856
+ exports.utf8 = {
857
+ encode: (data) => new TextDecoder().decode(data),
858
+ decode: (str) => new TextEncoder().encode(str),
859
+ };
860
+ exports.hex = chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {
861
+ if (typeof s !== 'string' || s.length % 2)
862
+ throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
863
+ return s.toLowerCase();
864
+ }));
865
+ const CODERS = {
866
+ utf8: exports.utf8, hex: exports.hex, base16: exports.base16, base32: exports.base32, base64: exports.base64, base64url: exports.base64url, base58: exports.base58, base58xmr: exports.base58xmr
867
+ };
868
+ const coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(', ')}`;
869
+ const bytesToString = (type, bytes) => {
870
+ if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))
871
+ throw new TypeError(coderTypeError);
872
+ if (!(bytes instanceof Uint8Array))
873
+ throw new TypeError('bytesToString() expects Uint8Array');
874
+ return CODERS[type].encode(bytes);
875
+ };
876
+ exports.bytesToString = bytesToString;
877
+ exports.str = exports.bytesToString;
878
+ const stringToBytes = (type, str) => {
879
+ if (!CODERS.hasOwnProperty(type))
880
+ throw new TypeError(coderTypeError);
881
+ if (typeof str !== 'string')
882
+ throw new TypeError('stringToBytes() expects string');
883
+ return CODERS[type].decode(str);
884
+ };
885
+ exports.stringToBytes = stringToBytes;
886
+ exports.bytes = exports.stringToBytes;
887
+ } (lib));
888
+ return lib;
889
+ }
890
+
891
+ var bolt11;
892
+ var hasRequiredBolt11;
893
+
894
+ function requireBolt11 () {
895
+ if (hasRequiredBolt11) return bolt11;
896
+ hasRequiredBolt11 = 1;
897
+ const {bech32, hex, utf8} = requireLib();
898
+
899
+ // defaults for encode; default timestamp is current time at call
900
+ const DEFAULTNETWORK = {
901
+ // default network is bitcoin
902
+ bech32: 'bc',
903
+ pubKeyHash: 0x00,
904
+ scriptHash: 0x05,
905
+ validWitnessVersions: [0]
906
+ };
907
+ const TESTNETWORK = {
908
+ bech32: 'tb',
909
+ pubKeyHash: 0x6f,
910
+ scriptHash: 0xc4,
911
+ validWitnessVersions: [0]
912
+ };
913
+ const SIGNETNETWORK = {
914
+ bech32: 'tbs',
915
+ pubKeyHash: 0x6f,
916
+ scriptHash: 0xc4,
917
+ validWitnessVersions: [0]
918
+ };
919
+ const REGTESTNETWORK = {
920
+ bech32: 'bcrt',
921
+ pubKeyHash: 0x6f,
922
+ scriptHash: 0xc4,
923
+ validWitnessVersions: [0]
924
+ };
925
+ const SIMNETWORK = {
926
+ bech32: 'sb',
927
+ pubKeyHash: 0x3f,
928
+ scriptHash: 0x7b,
929
+ validWitnessVersions: [0]
930
+ };
931
+
932
+ const FEATUREBIT_ORDER = [
933
+ 'option_data_loss_protect',
934
+ 'initial_routing_sync',
935
+ 'option_upfront_shutdown_script',
936
+ 'gossip_queries',
937
+ 'var_onion_optin',
938
+ 'gossip_queries_ex',
939
+ 'option_static_remotekey',
940
+ 'payment_secret',
941
+ 'basic_mpp',
942
+ 'option_support_large_channel'
943
+ ];
944
+
945
+ const DIVISORS = {
946
+ m: BigInt(1e3),
947
+ u: BigInt(1e6),
948
+ n: BigInt(1e9),
949
+ p: BigInt(1e12)
950
+ };
951
+
952
+ const MAX_MILLISATS = BigInt('2100000000000000000');
953
+
954
+ const MILLISATS_PER_BTC = BigInt(1e11);
955
+
956
+ const TAGCODES = {
957
+ payment_hash: 1,
958
+ payment_secret: 16,
959
+ description: 13,
960
+ payee: 19,
961
+ description_hash: 23, // commit to longer descriptions (used by lnurl-pay)
962
+ expiry: 6, // default: 3600 (1 hour)
963
+ min_final_cltv_expiry: 24, // default: 9
964
+ fallback_address: 9,
965
+ route_hint: 3, // for extra routing info (private etc.)
966
+ feature_bits: 5,
967
+ metadata: 27
968
+ };
969
+
970
+ // reverse the keys and values of TAGCODES and insert into TAGNAMES
971
+ const TAGNAMES = {};
972
+ for (let i = 0, keys = Object.keys(TAGCODES); i < keys.length; i++) {
973
+ const currentName = keys[i];
974
+ const currentCode = TAGCODES[keys[i]].toString();
975
+ TAGNAMES[currentCode] = currentName;
976
+ }
977
+
978
+ const TAGPARSERS = {
979
+ 1: words => hex.encode(bech32.fromWordsUnsafe(words)), // 256 bits
980
+ 16: words => hex.encode(bech32.fromWordsUnsafe(words)), // 256 bits
981
+ 13: words => utf8.encode(bech32.fromWordsUnsafe(words)), // string variable length
982
+ 19: words => hex.encode(bech32.fromWordsUnsafe(words)), // 264 bits
983
+ 23: words => hex.encode(bech32.fromWordsUnsafe(words)), // 256 bits
984
+ 27: words => hex.encode(bech32.fromWordsUnsafe(words)), // variable
985
+ 6: wordsToIntBE, // default: 3600 (1 hour)
986
+ 24: wordsToIntBE, // default: 9
987
+ 3: routingInfoParser, // for extra routing info (private etc.)
988
+ 5: featureBitsParser // keep feature bits as array of 5 bit words
989
+ };
990
+
991
+ function getUnknownParser(tagCode) {
992
+ return words => ({
993
+ tagCode: parseInt(tagCode),
994
+ words: bech32.encode('unknown', words, Number.MAX_SAFE_INTEGER)
995
+ })
996
+ }
997
+
998
+ function wordsToIntBE(words) {
999
+ return words.reverse().reduce((total, item, index) => {
1000
+ return total + item * Math.pow(32, index)
1001
+ }, 0)
1002
+ }
1003
+
1004
+ // first convert from words to buffer, trimming padding where necessary
1005
+ // parse in 51 byte chunks. See encoder for details.
1006
+ function routingInfoParser(words) {
1007
+ const routes = [];
1008
+ let pubkey,
1009
+ shortChannelId,
1010
+ feeBaseMSats,
1011
+ feeProportionalMillionths,
1012
+ cltvExpiryDelta;
1013
+ let routesBuffer = bech32.fromWordsUnsafe(words);
1014
+ while (routesBuffer.length > 0) {
1015
+ pubkey = hex.encode(routesBuffer.slice(0, 33)); // 33 bytes
1016
+ shortChannelId = hex.encode(routesBuffer.slice(33, 41)); // 8 bytes
1017
+ feeBaseMSats = parseInt(hex.encode(routesBuffer.slice(41, 45)), 16); // 4 bytes
1018
+ feeProportionalMillionths = parseInt(
1019
+ hex.encode(routesBuffer.slice(45, 49)),
1020
+ 16
1021
+ ); // 4 bytes
1022
+ cltvExpiryDelta = parseInt(hex.encode(routesBuffer.slice(49, 51)), 16); // 2 bytes
1023
+
1024
+ routesBuffer = routesBuffer.slice(51);
1025
+
1026
+ routes.push({
1027
+ pubkey,
1028
+ short_channel_id: shortChannelId,
1029
+ fee_base_msat: feeBaseMSats,
1030
+ fee_proportional_millionths: feeProportionalMillionths,
1031
+ cltv_expiry_delta: cltvExpiryDelta
1032
+ });
1033
+ }
1034
+ return routes
1035
+ }
1036
+
1037
+ function featureBitsParser(words) {
1038
+ const bools = words
1039
+ .slice()
1040
+ .reverse()
1041
+ .map(word => [
1042
+ !!(word & 0b1),
1043
+ !!(word & 0b10),
1044
+ !!(word & 0b100),
1045
+ !!(word & 0b1000),
1046
+ !!(word & 0b10000)
1047
+ ])
1048
+ .reduce((finalArr, itemArr) => finalArr.concat(itemArr), []);
1049
+ while (bools.length < FEATUREBIT_ORDER.length * 2) {
1050
+ bools.push(false);
1051
+ }
1052
+
1053
+ const featureBits = {};
1054
+
1055
+ FEATUREBIT_ORDER.forEach((featureName, index) => {
1056
+ let status;
1057
+ if (bools[index * 2]) {
1058
+ status = 'required';
1059
+ } else if (bools[index * 2 + 1]) {
1060
+ status = 'supported';
1061
+ } else {
1062
+ status = 'unsupported';
1063
+ }
1064
+ featureBits[featureName] = status;
1065
+ });
1066
+
1067
+ const extraBits = bools.slice(FEATUREBIT_ORDER.length * 2);
1068
+ featureBits.extra_bits = {
1069
+ start_bit: FEATUREBIT_ORDER.length * 2,
1070
+ bits: extraBits,
1071
+ has_required: extraBits.reduce(
1072
+ (result, bit, index) =>
1073
+ index % 2 !== 0 ? result || false : result || bit,
1074
+ false
1075
+ )
1076
+ };
1077
+
1078
+ return featureBits
1079
+ }
1080
+
1081
+ function hrpToMillisat(hrpString, outputString) {
1082
+ let divisor, value;
1083
+ if (hrpString.slice(-1).match(/^[munp]$/)) {
1084
+ divisor = hrpString.slice(-1);
1085
+ value = hrpString.slice(0, -1);
1086
+ } else if (hrpString.slice(-1).match(/^[^munp0-9]$/)) {
1087
+ throw new Error('Not a valid multiplier for the amount')
1088
+ } else {
1089
+ value = hrpString;
1090
+ }
1091
+
1092
+ if (!value.match(/^\d+$/))
1093
+ throw new Error('Not a valid human readable amount')
1094
+
1095
+ const valueBN = BigInt(value);
1096
+
1097
+ const millisatoshisBN = divisor
1098
+ ? (valueBN * MILLISATS_PER_BTC) / DIVISORS[divisor]
1099
+ : valueBN * MILLISATS_PER_BTC;
1100
+
1101
+ if (
1102
+ (divisor === 'p' && !(valueBN % BigInt(10) === BigInt(0))) ||
1103
+ millisatoshisBN > MAX_MILLISATS
1104
+ ) {
1105
+ throw new Error('Amount is outside of valid range')
1106
+ }
1107
+
1108
+ return outputString ? millisatoshisBN.toString() : millisatoshisBN
1109
+ }
1110
+
1111
+ // decode will only have extra comments that aren't covered in encode comments.
1112
+ // also if anything is hard to read I'll comment.
1113
+ function decode(paymentRequest, network) {
1114
+ if (typeof paymentRequest !== 'string')
1115
+ throw new Error('Lightning Payment Request must be string')
1116
+ if (paymentRequest.slice(0, 2).toLowerCase() !== 'ln')
1117
+ throw new Error('Not a proper lightning payment request')
1118
+
1119
+ const sections = [];
1120
+ const decoded = bech32.decode(paymentRequest, Number.MAX_SAFE_INTEGER);
1121
+ paymentRequest = paymentRequest.toLowerCase();
1122
+ const prefix = decoded.prefix;
1123
+ let words = decoded.words;
1124
+ let letters = paymentRequest.slice(prefix.length + 1);
1125
+ let sigWords = words.slice(-104);
1126
+ words = words.slice(0, -104);
1127
+
1128
+ // Without reverse lookups, can't say that the multipier at the end must
1129
+ // have a number before it, so instead we parse, and if the second group
1130
+ // doesn't have anything, there's a good chance the last letter of the
1131
+ // coin type got captured by the third group, so just re-regex without
1132
+ // the number.
1133
+ let prefixMatches = prefix.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);
1134
+ if (prefixMatches && !prefixMatches[2])
1135
+ prefixMatches = prefix.match(/^ln(\S+)$/);
1136
+ if (!prefixMatches) {
1137
+ throw new Error('Not a proper lightning payment request')
1138
+ }
1139
+
1140
+ // "ln" section
1141
+ sections.push({
1142
+ name: 'lightning_network',
1143
+ letters: 'ln'
1144
+ });
1145
+
1146
+ // "bc" section
1147
+ const bech32Prefix = prefixMatches[1];
1148
+ let coinNetwork;
1149
+ if (!network) {
1150
+ switch (bech32Prefix) {
1151
+ case DEFAULTNETWORK.bech32:
1152
+ coinNetwork = DEFAULTNETWORK;
1153
+ break
1154
+ case TESTNETWORK.bech32:
1155
+ coinNetwork = TESTNETWORK;
1156
+ break
1157
+ case SIGNETNETWORK.bech32:
1158
+ coinNetwork = SIGNETNETWORK;
1159
+ break
1160
+ case REGTESTNETWORK.bech32:
1161
+ coinNetwork = REGTESTNETWORK;
1162
+ break
1163
+ case SIMNETWORK.bech32:
1164
+ coinNetwork = SIMNETWORK;
1165
+ break
1166
+ }
1167
+ } else {
1168
+ if (
1169
+ network.bech32 === undefined ||
1170
+ network.pubKeyHash === undefined ||
1171
+ network.scriptHash === undefined ||
1172
+ !Array.isArray(network.validWitnessVersions)
1173
+ )
1174
+ throw new Error('Invalid network')
1175
+ coinNetwork = network;
1176
+ }
1177
+ if (!coinNetwork || coinNetwork.bech32 !== bech32Prefix) {
1178
+ throw new Error('Unknown coin bech32 prefix')
1179
+ }
1180
+ sections.push({
1181
+ name: 'coin_network',
1182
+ letters: bech32Prefix,
1183
+ value: coinNetwork
1184
+ });
1185
+
1186
+ // amount section
1187
+ const value = prefixMatches[2];
1188
+ let millisatoshis;
1189
+ if (value) {
1190
+ const divisor = prefixMatches[3];
1191
+ millisatoshis = hrpToMillisat(value + divisor, true);
1192
+ sections.push({
1193
+ name: 'amount',
1194
+ letters: prefixMatches[2] + prefixMatches[3],
1195
+ value: millisatoshis
1196
+ });
1197
+ } else {
1198
+ millisatoshis = null;
1199
+ }
1200
+
1201
+ // "1" separator
1202
+ sections.push({
1203
+ name: 'separator',
1204
+ letters: '1'
1205
+ });
1206
+
1207
+ // timestamp
1208
+ const timestamp = wordsToIntBE(words.slice(0, 7));
1209
+ words = words.slice(7); // trim off the left 7 words
1210
+ sections.push({
1211
+ name: 'timestamp',
1212
+ letters: letters.slice(0, 7),
1213
+ value: timestamp
1214
+ });
1215
+ letters = letters.slice(7);
1216
+
1217
+ let tagName, parser, tagLength, tagWords;
1218
+ // we have no tag count to go on, so just keep hacking off words
1219
+ // until we have none.
1220
+ while (words.length > 0) {
1221
+ const tagCode = words[0].toString();
1222
+ tagName = TAGNAMES[tagCode] || 'unknown_tag';
1223
+ parser = TAGPARSERS[tagCode] || getUnknownParser(tagCode);
1224
+ words = words.slice(1);
1225
+
1226
+ tagLength = wordsToIntBE(words.slice(0, 2));
1227
+ words = words.slice(2);
1228
+
1229
+ tagWords = words.slice(0, tagLength);
1230
+ words = words.slice(tagLength);
1231
+
1232
+ sections.push({
1233
+ name: tagName,
1234
+ tag: letters[0],
1235
+ letters: letters.slice(0, 1 + 2 + tagLength),
1236
+ value: parser(tagWords) // see: parsers for more comments
1237
+ });
1238
+ letters = letters.slice(1 + 2 + tagLength);
1239
+ }
1240
+
1241
+ // signature
1242
+ sections.push({
1243
+ name: 'signature',
1244
+ letters: letters.slice(0, 104),
1245
+ value: hex.encode(bech32.fromWordsUnsafe(sigWords))
1246
+ });
1247
+ letters = letters.slice(104);
1248
+
1249
+ // checksum
1250
+ sections.push({
1251
+ name: 'checksum',
1252
+ letters: letters
1253
+ });
1254
+
1255
+ let result = {
1256
+ paymentRequest,
1257
+ sections,
1258
+
1259
+ get expiry() {
1260
+ let exp = sections.find(s => s.name === 'expiry');
1261
+ if (exp) return getValue('timestamp') + exp.value
1262
+ },
1263
+
1264
+ get route_hints() {
1265
+ return sections.filter(s => s.name === 'route_hint').map(s => s.value)
1266
+ }
1267
+ };
1268
+
1269
+ for (let name in TAGCODES) {
1270
+ if (name === 'route_hint') {
1271
+ // route hints can be multiple, so this won't work for them
1272
+ continue
1273
+ }
1274
+
1275
+ Object.defineProperty(result, name, {
1276
+ get() {
1277
+ return getValue(name)
1278
+ }
1279
+ });
1280
+ }
1281
+
1282
+ return result
1283
+
1284
+ function getValue(name) {
1285
+ let section = sections.find(s => s.name === name);
1286
+ return section ? section.value : undefined
1287
+ }
1288
+ }
1289
+
1290
+ bolt11 = {
1291
+ decode,
1292
+ hrpToMillisat
1293
+ };
1294
+ return bolt11;
1295
+ }
1296
+
1297
+ var bolt11Exports = requireBolt11();
1298
+
1299
+ // from https://stackoverflow.com/a/50868276
1300
+ const fromHexString = (hexString) => Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
1301
+ const decodeInvoice = (paymentRequest) => {
1302
+ if (!paymentRequest)
1303
+ return null;
1304
+ try {
1305
+ const decoded = bolt11Exports.decode(paymentRequest);
1306
+ if (!decoded || !decoded.sections)
1307
+ return null;
1308
+ const hashTag = decoded.sections.find((value) => value.name === "payment_hash");
1309
+ if (hashTag?.name !== "payment_hash" || !hashTag.value)
1310
+ return null;
1311
+ const paymentHash = hashTag.value;
1312
+ let satoshi = 0;
1313
+ const amountTag = decoded.sections.find((value) => value.name === "amount");
1314
+ if (amountTag?.name === "amount" && amountTag.value) {
1315
+ satoshi = parseInt(amountTag.value) / 1000; // millisats
1316
+ }
1317
+ const timestampTag = decoded.sections.find((value) => value.name === "timestamp");
1318
+ if (timestampTag?.name !== "timestamp" || !timestampTag.value)
1319
+ return null;
1320
+ const timestamp = timestampTag.value;
1321
+ let expiry;
1322
+ const expiryTag = decoded.sections.find((value) => value.name === "expiry");
1323
+ if (expiryTag?.name === "expiry") {
1324
+ expiry = expiryTag.value;
1325
+ }
1326
+ const descriptionTag = decoded.sections.find((value) => value.name === "description");
1327
+ const description = descriptionTag?.name === "description"
1328
+ ? descriptionTag?.value
1329
+ : undefined;
1330
+ return {
1331
+ paymentHash,
1332
+ satoshi,
1333
+ timestamp,
1334
+ expiry,
1335
+ description,
1336
+ };
1337
+ }
1338
+ catch {
1339
+ return null;
1340
+ }
1341
+ };
1342
+
1343
+ class Invoice {
1344
+ constructor(args) {
1345
+ this.paymentRequest = args.pr;
1346
+ if (!this.paymentRequest) {
1347
+ throw new Error("Invalid payment request");
1348
+ }
1349
+ const decodedInvoice = decodeInvoice(this.paymentRequest);
1350
+ if (!decodedInvoice) {
1351
+ throw new Error("Failed to decode payment request");
1352
+ }
1353
+ this.paymentHash = decodedInvoice.paymentHash;
1354
+ this.satoshi = decodedInvoice.satoshi;
1355
+ this.timestamp = decodedInvoice.timestamp;
1356
+ this.expiry = decodedInvoice.expiry;
1357
+ this.createdDate = new Date(this.timestamp * 1000);
1358
+ this.expiryDate = this.expiry
1359
+ ? new Date((this.timestamp + this.expiry) * 1000)
1360
+ : undefined;
1361
+ this.description = decodedInvoice.description ?? null;
1362
+ this.verify = args.verify ?? null;
1363
+ this.preimage = args.preimage ?? null;
1364
+ this.successAction = args.successAction ?? null;
1365
+ }
1366
+ async isPaid() {
1367
+ if (this.preimage)
1368
+ return this.validatePreimage(this.preimage);
1369
+ else if (this.verify) {
1370
+ return await this.verifyPayment();
1371
+ }
1372
+ else {
1373
+ throw new Error("Could not verify payment");
1374
+ }
1375
+ }
1376
+ validatePreimage(preimage) {
1377
+ if (!preimage || !this.paymentHash)
1378
+ return false;
1379
+ try {
1380
+ const preimageHash = bytesToHex(sha256(fromHexString(preimage)));
1381
+ return this.paymentHash === preimageHash;
1382
+ }
1383
+ catch {
1384
+ return false;
1385
+ }
1386
+ }
1387
+ async verifyPayment() {
1388
+ try {
1389
+ if (!this.verify) {
1390
+ throw new Error("LNURL verify not available");
1391
+ }
1392
+ const response = await fetch(this.verify);
1393
+ if (!response.ok) {
1394
+ throw new Error(`Verification request failed: ${response.status} ${response.statusText}`);
1395
+ }
1396
+ const json = await response.json();
1397
+ if (json.preimage) {
1398
+ this.preimage = json.preimage;
1399
+ }
1400
+ return json.settled;
1401
+ }
1402
+ catch (error) {
1403
+ console.error("Failed to check LNURL-verify", error);
1404
+ return false;
1405
+ }
1406
+ }
1407
+ hasExpired() {
1408
+ const { expiryDate } = this;
1409
+ if (expiryDate) {
1410
+ return expiryDate.getTime() < Date.now();
1411
+ }
1412
+ return false;
1413
+ }
1414
+ }
1415
+
1416
+ const sendBoostagram = async (args, options) => {
1417
+ const { boost } = args;
1418
+ if (!options) {
1419
+ options = {};
1420
+ }
1421
+ const webln = options.webln || globalThis.webln;
1422
+ if (!webln) {
1423
+ throw new Error("WebLN not available");
1424
+ }
1425
+ if (!webln.keysend) {
1426
+ throw new Error("Keysend not available in current WebLN provider");
1427
+ }
1428
+ const amount = args.amount || Math.floor(boost.value_msat / 1000);
1429
+ const weblnParams = {
1430
+ destination: args.destination,
1431
+ amount: amount,
1432
+ customRecords: {
1433
+ "7629169": JSON.stringify(boost),
1434
+ },
1435
+ };
1436
+ if (args.customKey && args.customValue) {
1437
+ weblnParams.customRecords[args.customKey] = args.customValue;
1438
+ }
1439
+ await webln.enable();
1440
+ const response = await webln.keysend(weblnParams);
1441
+ return response;
1442
+ };
1443
+
1444
+ const LN_ADDRESS_REGEX = /^((?:[^<>()[\]\\.,;:\s@"]+(?:\.[^<>()[\]\\.,;:\s@"]+)*)|(?:".+"))@((?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
1445
+ const DEFAULT_PROXY = "https://api.getalby.com/lnurl";
1446
+ class LightningAddress {
1447
+ constructor(address, options) {
1448
+ this.address = address;
1449
+ this.options = { proxy: DEFAULT_PROXY };
1450
+ this.options = Object.assign(this.options, options);
1451
+ this.parse();
1452
+ this.webln = this.options.webln;
1453
+ }
1454
+ parse() {
1455
+ const result = LN_ADDRESS_REGEX.exec(this.address.toLowerCase());
1456
+ if (result) {
1457
+ this.username = result[1];
1458
+ this.domain = result[2];
1459
+ }
1460
+ }
1461
+ getWebLN() {
1462
+ return this.webln || globalThis.webln;
1463
+ }
1464
+ async fetch() {
1465
+ if (this.options.proxy) {
1466
+ return this.fetchWithProxy();
1467
+ }
1468
+ else {
1469
+ return this.fetchWithoutProxy();
1470
+ }
1471
+ }
1472
+ async fetchWithProxy() {
1473
+ const response = await fetch(`${this.options.proxy}/lightning-address-details?${new URLSearchParams({
1474
+ ln: this.address,
1475
+ }).toString()}`);
1476
+ if (!response.ok) {
1477
+ throw new Error(`Failed to fetch lnurl info: ${response.status} ${response.statusText}`);
1478
+ }
1479
+ const json = await response.json();
1480
+ await this.parseLnUrlPayResponse(json.lnurlp);
1481
+ this.parseKeysendResponse(json.keysend);
1482
+ this.parseNostrResponse(json.nostr);
1483
+ }
1484
+ async fetchWithoutProxy() {
1485
+ if (!this.domain || !this.username) {
1486
+ return;
1487
+ }
1488
+ await Promise.all([
1489
+ this.fetchLnurlData(),
1490
+ this.fetchKeysendData(),
1491
+ this.fetchNostrData(),
1492
+ ]);
1493
+ }
1494
+ async fetchLnurlData() {
1495
+ const lnurlResult = await fetch(this.lnurlpUrl());
1496
+ if (lnurlResult.ok) {
1497
+ const lnurlData = await lnurlResult.json();
1498
+ await this.parseLnUrlPayResponse(lnurlData);
1499
+ }
1500
+ }
1501
+ async fetchKeysendData() {
1502
+ const keysendResult = await fetch(this.keysendUrl());
1503
+ if (keysendResult.ok) {
1504
+ const keysendData = await keysendResult.json();
1505
+ this.parseKeysendResponse(keysendData);
1506
+ }
1507
+ }
1508
+ async fetchNostrData() {
1509
+ const nostrResult = await fetch(this.nostrUrl());
1510
+ if (nostrResult.ok) {
1511
+ const nostrData = await nostrResult.json();
1512
+ this.parseNostrResponse(nostrData);
1513
+ }
1514
+ }
1515
+ lnurlpUrl() {
1516
+ return `https://${this.domain}/.well-known/lnurlp/${this.username}`;
1517
+ }
1518
+ keysendUrl() {
1519
+ return `https://${this.domain}/.well-known/keysend/${this.username}`;
1520
+ }
1521
+ nostrUrl() {
1522
+ return `https://${this.domain}/.well-known/nostr.json?name=${this.username}`;
1523
+ }
1524
+ async generateInvoice(params) {
1525
+ let data;
1526
+ if (this.options.proxy) {
1527
+ const invoiceResponse = await fetch(`${this.options.proxy}/generate-invoice?${new URLSearchParams({
1528
+ ln: this.address,
1529
+ ...params,
1530
+ }).toString()}`);
1531
+ if (!invoiceResponse.ok) {
1532
+ throw new Error(`Failed to generate invoice: ${invoiceResponse.status} ${invoiceResponse.statusText}`);
1533
+ }
1534
+ const json = await invoiceResponse.json();
1535
+ data = json.invoice;
1536
+ }
1537
+ else {
1538
+ if (!this.lnurlpData) {
1539
+ throw new Error("No lnurlpData available. Please call fetch() first.");
1540
+ }
1541
+ if (!this.lnurlpData.callback || !isUrl(this.lnurlpData.callback))
1542
+ throw new Error("Valid callback does not exist in lnurlpData");
1543
+ const callbackUrl = new URL(this.lnurlpData.callback);
1544
+ callbackUrl.search = new URLSearchParams(params).toString();
1545
+ const invoiceResponse = await fetch(callbackUrl.toString());
1546
+ if (!invoiceResponse.ok) {
1547
+ throw new Error(`Failed to generate invoice: ${invoiceResponse.status} ${invoiceResponse.statusText}`);
1548
+ }
1549
+ data = await invoiceResponse.json();
1550
+ }
1551
+ const paymentRequest = data && data.pr && data.pr.toString();
1552
+ if (!paymentRequest)
1553
+ throw new Error("Invalid pay service invoice");
1554
+ const invoiceArgs = { pr: paymentRequest };
1555
+ if (data && data.verify)
1556
+ invoiceArgs.verify = data.verify.toString();
1557
+ if (data && data.successAction && typeof data.successAction === "object") {
1558
+ const { tag, message, description, url } = data.successAction;
1559
+ if (tag === "message") {
1560
+ invoiceArgs.successAction = { tag, message };
1561
+ }
1562
+ else if (tag === "url") {
1563
+ invoiceArgs.successAction = { tag, description, url };
1564
+ }
1565
+ }
1566
+ return new Invoice(invoiceArgs);
1567
+ }
1568
+ async requestInvoice(args) {
1569
+ if (!this.lnurlpData) {
1570
+ throw new Error("No lnurlpData available. Please call fetch() first.");
1571
+ }
1572
+ const msat = args.satoshi * 1000;
1573
+ const { commentAllowed, min, max } = this.lnurlpData;
1574
+ if (!isValidAmount({ amount: msat, min, max }))
1575
+ throw new Error("Invalid amount");
1576
+ if (args.comment &&
1577
+ commentAllowed &&
1578
+ commentAllowed > 0 &&
1579
+ args.comment.length > commentAllowed)
1580
+ throw new Error(`The comment length must be ${commentAllowed} characters or fewer`);
1581
+ const invoiceParams = { amount: msat.toString() };
1582
+ if (args.comment)
1583
+ invoiceParams.comment = args.comment;
1584
+ if (args.payerdata)
1585
+ invoiceParams.payerdata = JSON.stringify(args.payerdata);
1586
+ return this.generateInvoice(invoiceParams);
1587
+ }
1588
+ async boost(boost, amount = 0) {
1589
+ if (!this.keysendData) {
1590
+ throw new Error("No keysendData available. Please call fetch() first.");
1591
+ }
1592
+ const { destination, customKey, customValue } = this.keysendData;
1593
+ const webln = this.getWebLN();
1594
+ if (!webln) {
1595
+ throw new Error("WebLN not available");
1596
+ }
1597
+ return sendBoostagram({
1598
+ destination,
1599
+ customKey,
1600
+ customValue,
1601
+ amount,
1602
+ boost,
1603
+ }, { webln });
1604
+ }
1605
+ async zapInvoice({ satoshi, comment, relays, e }, options = {}) {
1606
+ if (!this.lnurlpData) {
1607
+ throw new Error("No lnurlpData available. Please call fetch() first.");
1608
+ }
1609
+ if (!this.nostrPubkey) {
1610
+ throw new Error("Nostr Pubkey is missing");
1611
+ }
1612
+ const p = this.nostrPubkey;
1613
+ const msat = satoshi * 1000;
1614
+ const { allowsNostr, min, max } = this.lnurlpData;
1615
+ if (!isValidAmount({ amount: msat, min, max }))
1616
+ throw new Error("Invalid amount");
1617
+ if (!allowsNostr)
1618
+ throw new Error("Your provider does not support zaps");
1619
+ const event = await generateZapEvent({
1620
+ satoshi: msat,
1621
+ comment,
1622
+ p,
1623
+ e,
1624
+ relays,
1625
+ }, options);
1626
+ const zapParams = {
1627
+ amount: msat.toString(),
1628
+ nostr: JSON.stringify(event),
1629
+ };
1630
+ const invoice = await this.generateInvoice(zapParams);
1631
+ return invoice;
1632
+ }
1633
+ async zap(args, options = {}) {
1634
+ const invoice = this.zapInvoice(args, options);
1635
+ const webln = this.getWebLN();
1636
+ if (!webln) {
1637
+ throw new Error("WebLN not available");
1638
+ }
1639
+ await webln.enable();
1640
+ const response = webln.sendPayment((await invoice).paymentRequest);
1641
+ return response;
1642
+ }
1643
+ async parseLnUrlPayResponse(lnurlpData) {
1644
+ if (lnurlpData) {
1645
+ this.lnurlpData = await parseLnUrlPayResponse(lnurlpData);
1646
+ }
1647
+ }
1648
+ parseKeysendResponse(keysendData) {
1649
+ if (keysendData) {
1650
+ this.keysendData = parseKeysendResponse(keysendData);
1651
+ }
1652
+ }
1653
+ parseNostrResponse(nostrData) {
1654
+ if (nostrData) {
1655
+ [this.nostrData, this.nostrPubkey, this.nostrRelays] = parseNostrResponse(nostrData, this.username);
1656
+ }
1657
+ }
1658
+ }
1659
+
1660
+ export { DEFAULT_PROXY, LN_ADDRESS_REGEX, LightningAddress, generateZapEvent, getEventHash, isUrl, isValidAmount, parseKeysendResponse, parseLnUrlPayResponse, parseNostrResponse, serializeEvent, validateEvent };
1661
+ //# sourceMappingURL=lnurl.js.map