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