UNPKG

@getalby/lightning-tools

Version:

Collection of helpful building blocks and tools to develop Bitcoin Lightning web apps

2 lines (1 loc) 35.1 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e||self).lightningTools={})}(this,function(e){var t=function(e){var t={exports:{}};return function(e,t){function r(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function n(...e){const t=(e,t)=>r=>e(t(r));return{encode:Array.from(e).reverse().reduce((e,r)=>e?t(e,r.encode):r.encode,void 0),decode:e.reduce((e,r)=>e?t(e,r.decode):r.decode,void 0)}}function o(e){return{encode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("alphabet.encode input should be an array of numbers");return t.map(t=>{if(r(t),t<0||t>=e.length)throw new Error(`Digit index outside alphabet: ${t} (alphabet: ${e.length})`);return e[t]})},decode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("alphabet.decode input should be array of strings");return t.map(t=>{if("string"!=typeof t)throw new Error(`alphabet.decode: not string element=${t}`);const r=e.indexOf(t);if(-1===r)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return r})}}}function i(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("join.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return t.join(e)},decode:t=>{if("string"!=typeof t)throw new Error("join.decode input should be string");return t.split(e)}}}function s(e,t="="){if(r(e),"string"!=typeof t)throw new Error("padding chr should be string");return{encode(r){if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("padding.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;r.length*e%8;)r.push(t);return r},decode(r){if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("padding.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let n=r.length;if(n*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&r[n-1]===t;n--)if(!((n-1)*e%8))throw new Error("Invalid padding: string has too much padding");return r.slice(0,n)}}}function a(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:t=>e(t)}}function c(e,t,n){if(t<2)throw new Error(`convertRadix: wrong from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let o=0;const i=[],s=Array.from(e);for(s.forEach(e=>{if(r(e),e<0||e>=t)throw new Error(`Wrong integer: ${e}`)});;){let e=0,r=!0;for(let i=o;i<s.length;i++){const a=s[i],c=t*e+a;if(!Number.isSafeInteger(c)||t*e/t!==e||c-a!=t*e)throw new Error("convertRadix: carry overflow");if(e=c%n,s[i]=Math.floor(c/n),!Number.isSafeInteger(s[i])||s[i]*n+e!==c)throw new Error("convertRadix: carry overflow");r&&(s[i]?r=!1:o=i)}if(i.push(e),r)break}for(let t=0;t<e.length-1&&0===e[t];t++)i.push(0);return i.reverse()}Object.defineProperty(t,"__esModule",{value:!0}),t.bytes=t.stringToBytes=t.str=t.bytesToString=t.hex=t.utf8=t.bech32m=t.bech32=t.base58check=t.base58xmr=t.base58xrp=t.base58flickr=t.base58=t.base64url=t.base64=t.base32crockford=t.base32hex=t.base32=t.base16=t.utils=t.assertNumber=void 0,t.assertNumber=r;const u=(e,t)=>t?u(t,e%t):e,h=(e,t)=>e+(t-u(e,t));function l(e,t,n,o){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(h(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${h(t,n)}`);let i=0,s=0;const a=2**n-1,c=[];for(const o of e){if(r(o),o>=2**t)throw new Error(`convertRadix2: invalid data word=${o} from=${t}`);if(i=i<<t|o,s+t>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${t}`);for(s+=t;s>=n;s-=n)c.push((i>>s-n&a)>>>0);i&=2**s-1}if(i=i<<n-s&a,!o&&s>=t)throw new Error("Excess padding");if(!o&&i)throw new Error(`Non-zero padding: ${i}`);return o&&s>0&&c.push(i>>>0),c}function f(e){return r(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return c(Array.from(t),256,e)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(c(t,e,256))}}}function d(e,t=!1){if(r(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(h(8,e)>32||h(e,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!(r instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return l(Array.from(r),8,e,!t)},decode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(l(r,e,8,t))}}}function p(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch(e){}}}function m(e,t){if(r(e),"function"!=typeof t)throw new Error("checksum fn should be function");return{encode(r){if(!(r instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const n=t(r).slice(0,e),o=new Uint8Array(r.length+e);return o.set(r),o.set(n,r.length),o},decode(r){if(!(r instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const n=r.slice(0,-e),o=t(n).slice(0,e),i=r.slice(-e);for(let t=0;t<e;t++)if(o[t]!==i[t])throw new Error("Invalid checksum");return n}}}t.utils={alphabet:o,chain:n,checksum:m,radix:f,radix2:d,join:i,padding:s},t.base16=n(d(4),o("0123456789ABCDEF"),i("")),t.base32=n(d(5),o("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),s(5),i("")),t.base32hex=n(d(5),o("0123456789ABCDEFGHIJKLMNOPQRSTUV"),s(5),i("")),t.base32crockford=n(d(5),o("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),i(""),a(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),t.base64=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),s(6),i("")),t.base64url=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),s(6),i(""));const y=e=>n(f(58),o(e),i(""));t.base58=y("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.base58flickr=y("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),t.base58xrp=y("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const w=[0,2,3,5,6,7,9,10,11];t.base58xmr={encode(e){let r="";for(let n=0;n<e.length;n+=8){const o=e.subarray(n,n+8);r+=t.base58.encode(o).padStart(w[o.length],"1")}return r},decode(e){let r=[];for(let n=0;n<e.length;n+=11){const o=e.slice(n,n+11),i=w.indexOf(o.length),s=t.base58.decode(o);for(let e=0;e<s.length-i;e++)if(0!==s[e])throw new Error("base58xmr: wrong padding");r=r.concat(Array.from(s.slice(s.length-i)))}return Uint8Array.from(r)}},t.base58check=e=>n(m(4,t=>e(e(t))),t.base58);const g=n(o("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),i("")),v=[996825010,642813549,513874426,1027748829,705979059];function b(e){const t=e>>25;let r=(33554431&e)<<5;for(let e=0;e<v.length;e++)1==(t>>e&1)&&(r^=v[e]);return r}function E(e,t,r=1){const n=e.length;let o=1;for(let t=0;t<n;t++){const r=e.charCodeAt(t);if(r<33||r>126)throw new Error(`Invalid prefix (${e})`);o=b(o)^r>>5}o=b(o);for(let t=0;t<n;t++)o=b(o)^31&e.charCodeAt(t);for(let e of t)o=b(o)^e;for(let e=0;e<6;e++)o=b(o);return o^=r,g.encode(l([o%2**30],30,5,!1))}function x(e){const t="bech32"===e?1:734539939,r=d(5),n=r.decode,o=r.encode,i=p(n);function s(e,r=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==r&&e.length>r)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${r})`);const n=e.toLowerCase();if(e!==n&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const o=(e=n).lastIndexOf("1");if(0===o||-1===o)throw new Error('Letter "1" must be present between prefix and data only');const i=e.slice(0,o),s=e.slice(o+1);if(s.length<6)throw new Error("Data must be at least 6 characters long");const a=g.decode(s).slice(0,-6),c=E(i,a,t);if(!s.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:i,words:a}}return{encode:function(e,r,n=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof r);const o=e.length+7+r.length;if(!1!==n&&o>n)throw new TypeError(`Length ${o} exceeds limit ${n}`);return`${e=e.toLowerCase()}1${g.encode(r)}${E(e,r,t)}`},decode:s,decodeToBytes:function(e){const{prefix:t,words:r}=s(e,!1);return{prefix:t,words:r,bytes:n(r)}},decodeUnsafe:p(s),fromWords:n,fromWordsUnsafe:i,toWords:o}}t.bech32=x("bech32"),t.bech32m=x("bech32m"),t.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},t.hex=n(d(4),o("0123456789abcdef"),i(""),a(e=>{if("string"!=typeof e||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));const P={utf8:t.utf8,hex:t.hex,base16:t.base16,base32:t.base32,base64:t.base64,base64url:t.base64url,base58:t.base58,base58xmr:t.base58xmr},A=`Invalid encoding type. Available types: ${Object.keys(P).join(", ")}`;t.bytesToString=(e,t)=>{if("string"!=typeof e||!P.hasOwnProperty(e))throw new TypeError(A);if(!(t instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return P[e].encode(t)},t.str=t.bytesToString,t.stringToBytes=(e,t)=>{if(!P.hasOwnProperty(e))throw new TypeError(A);if("string"!=typeof t)throw new TypeError("stringToBytes() expects string");return P[e].decode(t)},t.bytes=t.stringToBytes}(0,t.exports),t.exports}();const{bech32:r,hex:n,utf8:o}=t,i={bech32:"bc",pubKeyHash:0,scriptHash:5,validWitnessVersions:[0]},s={bech32:"tb",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},a={bech32:"tbs",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},c={bech32:"bcrt",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},u={bech32:"sb",pubKeyHash:63,scriptHash:123,validWitnessVersions:[0]},h=["option_data_loss_protect","initial_routing_sync","option_upfront_shutdown_script","gossip_queries","var_onion_optin","gossip_queries_ex","option_static_remotekey","payment_secret","basic_mpp","option_support_large_channel"],l={m:BigInt(1e3),u:BigInt(1e6),n:BigInt(1e9),p:BigInt(1e12)},f=BigInt("2100000000000000000"),d=BigInt(1e11),p={payment_hash:1,payment_secret:16,description:13,payee:19,description_hash:23,expiry:6,min_final_cltv_expiry:24,fallback_address:9,route_hint:3,feature_bits:5,metadata:27},m={};for(let e=0,t=Object.keys(p);e<t.length;e++){const r=t[e],n=p[t[e]].toString();m[n]=r}const y={1:e=>n.encode(r.fromWordsUnsafe(e)),16:e=>n.encode(r.fromWordsUnsafe(e)),13:e=>o.encode(r.fromWordsUnsafe(e)),19:e=>n.encode(r.fromWordsUnsafe(e)),23:e=>n.encode(r.fromWordsUnsafe(e)),27:e=>n.encode(r.fromWordsUnsafe(e)),6:g,24:g,3:function(e){const t=[];let o,i,s,a,c,u=r.fromWordsUnsafe(e);for(;u.length>0;)o=n.encode(u.slice(0,33)),i=n.encode(u.slice(33,41)),s=parseInt(n.encode(u.slice(41,45)),16),a=parseInt(n.encode(u.slice(45,49)),16),c=parseInt(n.encode(u.slice(49,51)),16),u=u.slice(51),t.push({pubkey:o,short_channel_id:i,fee_base_msat:s,fee_proportional_millionths:a,cltv_expiry_delta:c});return t},5:function(e){const t=e.slice().reverse().map(e=>[!!(1&e),!!(2&e),!!(4&e),!!(8&e),!!(16&e)]).reduce((e,t)=>e.concat(t),[]);for(;t.length<2*h.length;)t.push(!1);const r={};h.forEach((e,n)=>{let o;o=t[2*n]?"required":t[2*n+1]?"supported":"unsupported",r[e]=o});const n=t.slice(2*h.length);return r.extra_bits={start_bit:2*h.length,bits:n,has_required:n.reduce((e,t,r)=>r%2!=0?e||!1:e||t,!1)},r}};function w(e){return t=>({tagCode:parseInt(e),words:r.encode("unknown",t,Number.MAX_SAFE_INTEGER)})}function g(e){return e.reverse().reduce((e,t,r)=>e+t*Math.pow(32,r),0)}var v=function(e){return Uint8Array.from(e.match(/.{1,2}/g).map(function(e){return parseInt(e,16)}))},b=function(e){if(!e)return null;try{var t=function(e,t){if("string"!=typeof e)throw new Error("Lightning Payment Request must be string");if("ln"!==e.slice(0,2).toLowerCase())throw new Error("Not a proper lightning payment request");const o=[],h=r.decode(e,Number.MAX_SAFE_INTEGER);e=e.toLowerCase();const v=h.prefix;let b=h.words,E=e.slice(v.length+1),x=b.slice(-104);b=b.slice(0,-104);let P=v.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);if(P&&!P[2]&&(P=v.match(/^ln(\S+)$/)),!P)throw new Error("Not a proper lightning payment request");o.push({name:"lightning_network",letters:"ln"});const A=P[1];let k;switch(A){case i.bech32:k=i;break;case s.bech32:k=s;break;case a.bech32:k=a;break;case c.bech32:k=c;break;case u.bech32:k=u}if(!k||k.bech32!==A)throw new Error("Unknown coin bech32 prefix");o.push({name:"coin_network",letters:A,value:k});const _=P[2];let U;_?(U=function(e,t){let r,n;if(e.slice(-1).match(/^[munp]$/))r=e.slice(-1),n=e.slice(0,-1);else{if(e.slice(-1).match(/^[^munp0-9]$/))throw new Error("Not a valid multiplier for the amount");n=e}if(!n.match(/^\d+$/))throw new Error("Not a valid human readable amount");const o=BigInt(n),i=r?o*d/l[r]:o*d;if("p"===r&&o%BigInt(10)!==BigInt(0)||i>f)throw new Error("Amount is outside of valid range");return i.toString()}(_+P[3]),o.push({name:"amount",letters:P[2]+P[3],value:U})):U=null,o.push({name:"separator",letters:"1"});const L=g(b.slice(0,7));let N,D,I,S;for(b=b.slice(7),o.push({name:"timestamp",letters:E.slice(0,7),value:L}),E=E.slice(7);b.length>0;){const e=b[0].toString();N=m[e]||"unknown_tag",D=y[e]||w(e),b=b.slice(1),I=g(b.slice(0,2)),b=b.slice(2),S=b.slice(0,I),b=b.slice(I),o.push({name:N,tag:E[0],letters:E.slice(0,3+I),value:D(S)}),E=E.slice(3+I)}o.push({name:"signature",letters:E.slice(0,104),value:n.encode(r.fromWordsUnsafe(x))}),E=E.slice(104),o.push({name:"checksum",letters:E});let R={paymentRequest:e,sections:o,get expiry(){let e=o.find(e=>"expiry"===e.name);if(e)return j("timestamp")+e.value},get route_hints(){return o.filter(e=>"route_hint"===e.name).map(e=>e.value)}};for(let e in p)"route_hint"!==e&&Object.defineProperty(R,e,{get:()=>j(e)});return R;function j(e){let t=o.find(t=>t.name===e);return t?t.value:void 0}}(e);if(!t||!t.sections)return null;var o=t.sections.find(function(e){return"payment_hash"===e.name});if("payment_hash"!==(null==o?void 0:o.name)||!o.value)return null;var h=o.value,v=0,b=t.sections.find(function(e){return"amount"===e.name});"amount"===(null==b?void 0:b.name)&&b.value&&(v=parseInt(b.value)/1e3);var E=t.sections.find(function(e){return"timestamp"===e.name});if("timestamp"!==(null==E?void 0:E.name)||!E.value)return null;var x,P=E.value,A=t.sections.find(function(e){return"expiry"===e.name});"expiry"===(null==A?void 0:A.name)&&(x=A.value);var k=t.sections.find(function(e){return"description"===e.name});return{paymentHash:h,satoshi:v,timestamp:P,expiry:x,description:"description"===(null==k?void 0:k.name)?null==k?void 0:k.value:void 0}}catch(e){return null}};function E(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const x=e=>e instanceof Uint8Array,P=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),A=(e,t)=>e<<32-t|e>>>t;if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");const k=/* @__PURE__ */Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function _(e){if(!x(e))throw new Error("Uint8Array expected");let t="";for(let r=0;r<e.length;r++)t+=k[e[r]];return t}function U(e){if("string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),!x(e))throw new Error("expected Uint8Array, got "+typeof e);return e}class L{clone(){return this._cloneInto()}}function N(e){const t=t=>e().update(U(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}class D extends L{constructor(e,t,r,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=P(this.buffer)}update(e){E(this);const{view:t,buffer:r,blockLen:n}=this,o=(e=U(e)).length;for(let i=0;i<o;){const s=Math.min(n-this.pos,o-i);if(s!==n)r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n&&(this.process(t,0),this.pos=0);else{const t=P(e);for(;n<=o-i;i+=n)this.process(t,i)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){E(this),function(e,t){!function(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}(e);const r=t.outputLen;if(e.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:o}=this;let{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>n-i&&(this.process(r,0),i=0);for(let e=i;e<n;e++)t[e]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),c=n?0:4;e.setUint32(t+(n?4:0),s,n),e.setUint32(t+c,a,n)}(r,n-8,BigInt(8*this.length),o),this.process(r,0);const s=P(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)s.setUint32(4*e,u[e],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:o,destroyed:i,pos:s}=this;return e.length=n,e.pos=s,e.finished=o,e.destroyed=i,n%t&&e.buffer.set(r),e}}const I=(e,t,r)=>e&t^e&r^t&r,S=/* @__PURE__ */new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),R=/* @__PURE__ */new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),j=/* @__PURE__ */new Uint32Array(64);class $ extends D{constructor(){super(64,32,8,!1),this.A=0|R[0],this.B=0|R[1],this.C=0|R[2],this.D=0|R[3],this.E=0|R[4],this.F=0|R[5],this.G=0|R[6],this.H=0|R[7]}get(){const{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|o,this.F=0|i,this.G=0|s,this.H=0|a}process(e,t){for(let r=0;r<16;r++,t+=4)j[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=j[e-15],r=j[e-2],n=A(t,7)^A(t,18)^t>>>3,o=A(r,17)^A(r,19)^r>>>10;j[e]=o+j[e-7]+n+j[e-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+(A(s,6)^A(s,11)^A(s,25))+((h=s)&a^~h&c)+S[e]+j[e]|0,l=(A(r,2)^A(r,13)^A(r,22))+I(r,n,o)|0;u=c,c=a,a=s,s=i+t|0,i=o,o=n,n=r,r=t+l|0}var h;r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,o,i,s,a,c,u)}roundClean(){j.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const T=/* @__PURE__ */N(()=>new $);var W=/*#__PURE__*/function(){function e(e){var t,r,n,o;if(this.paymentRequest=void 0,this.paymentHash=void 0,this.preimage=void 0,this.verify=void 0,this.satoshi=void 0,this.expiry=void 0,this.timestamp=void 0,this.createdDate=void 0,this.expiryDate=void 0,this.description=void 0,this.successAction=void 0,this.paymentRequest=e.pr,!this.paymentRequest)throw new Error("Invalid payment request");var i=b(this.paymentRequest);if(!i)throw new Error("Failed to decode payment request");this.paymentHash=i.paymentHash,this.satoshi=i.satoshi,this.timestamp=i.timestamp,this.expiry=i.expiry,this.createdDate=new Date(1e3*this.timestamp),this.expiryDate=this.expiry?new Date(1e3*(this.timestamp+this.expiry)):void 0,this.description=null!=(t=i.description)?t:null,this.verify=null!=(r=e.verify)?r:null,this.preimage=null!=(n=e.preimage)?n:null,this.successAction=null!=(o=e.successAction)?o:null}var t=e.prototype;return t.isPaid=function(){try{var e=this;if(e.preimage)return Promise.resolve(e.validatePreimage(e.preimage));if(e.verify)return Promise.resolve(e.verifyPayment());throw new Error("Could not verify payment")}catch(e){return Promise.reject(e)}},t.validatePreimage=function(e){if(!e||!this.paymentHash)return!1;try{var t=_(T(v(e)));return this.paymentHash===t}catch(e){return!1}},t.verifyPayment=function(){try{var e=this;return Promise.resolve(function(t,r){try{var n=function(){if(!e.verify)throw new Error("LNURL verify not available");return Promise.resolve(fetch(e.verify)).then(function(t){if(!t.ok)throw new Error("Verification request failed: "+t.status+" "+t.statusText);return Promise.resolve(t.json()).then(function(t){return t.preimage&&(e.preimage=t.preimage),t.settled})})}()}catch(e){return r(e)}return n&&n.then?n.then(void 0,r):n}(0,function(e){return console.error("Failed to check LNURL-verify",e),!1}))}catch(e){return Promise.reject(e)}},t.hasExpired=function(){var e=this.expiryDate;return!!e&&e.getTime()<Date.now()},e}(),B=function(e,t){var r=e.satoshi,n=e.comment,o=e.p,i=e.e,s=e.relays;void 0===t&&(t={});try{var a=t.nostr||globalThis.nostr;if(!a)throw new Error("nostr option or window.nostr is not available");var c=[["relays"].concat(s),["amount",r.toString()]];return o&&c.push(["p",o]),i&&c.push(["e",i]),Promise.resolve(a.getPublicKey()).then(function(e){var t={pubkey:e,created_at:Math.floor(Date.now()/1e3),kind:9734,tags:c,content:null!=n?n:""};return t.id=K(t),Promise.resolve(a.signEvent(t))})}catch(i){return Promise.reject(i)}},H=function(e){if("keysend"!==e.tag)throw new Error("Invalid keysend params");if("OK"!==e.status)throw new Error("Keysend status not OK");if(!e.pubkey)throw new Error("Pubkey does not exist");var t,r;return e.customData&&e.customData[0]&&(t=e.customData[0].customKey,r=e.customData[0].customValue),{destination:e.pubkey,customKey:t,customValue:r}};function O(e){if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if(!Array.isArray(e.tags))return!1;for(var t=0;t<e.tags.length;t++){var r=e.tags[t];if(!Array.isArray(r))return!1;for(var n=0;n<r.length;n++)if("object"==typeof r[n])return!1}return!0}function F(e){if(!O(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function K(e){return _(T(F(e)))}function C(e,t){var r,n,o,i;return t&&e&&(n=(r=null==(o=e.names)?void 0:o[t])?null==(i=e.relays)?void 0:i[r]:void 0),[e,r,n]}var V=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/,q=function(e){return!!e&&V.test(e)},z=function(e){var t=e.amount;return t>0&&t>=e.min&&t<=e.max},M=function(e){try{if("payRequest"!==e.tag)throw new Error("Invalid pay service params");var t=(e.callback+"").trim();if(!q(t))throw new Error("Callback must be a valid url");var r,n,o=Math.ceil(Number(e.minSendable||0)),i=Math.floor(Number(e.maxSendable));if(!o||!i||o>i)throw new Error("Invalid pay service params");try{r=JSON.parse(e.metadata+""),n=_(T(e.metadata+""))}catch(e){r=[],n=_(T("[]"))}for(var s="",a="",c="",u="",h=0;h<r.length;h++){var l=r[h],f=l[0],d=l[1];switch(f){case"text/plain":c=d;break;case"text/identifier":u=d;break;case"text/email":s=d;break;case"image/png;base64":case"image/jpeg;base64":a="data:"+f+","+d}}var p,m=e.payerData;try{p=new URL(t).hostname}catch(e){}return Promise.resolve({callback:t,fixed:o===i,min:o,max:i,domain:p,metadata:r,metadataHash:n,identifier:u,email:s,description:c,image:a,payerData:m,commentAllowed:Number(e.commentAllowed)||0,rawData:e,allowsNostr:e.allowsNostr||!1})}catch(e){return Promise.reject(e)}};function G(){return G=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},G.apply(this,arguments)}var J=function(e,t){try{var r=e.boost;t||(t={});var n=t.webln||globalThis.webln;if(!n)throw new Error("WebLN not available");if(!n.keysend)throw new Error("Keysend not available in current WebLN provider");var o=e.amount||Math.floor(r.value_msat/1e3),i={destination:e.destination,amount:o,customRecords:{7629169:JSON.stringify(r)}};return e.customKey&&e.customValue&&(i.customRecords[e.customKey]=e.customValue),Promise.resolve(n.enable()).then(function(){return Promise.resolve(n.keysend(i))})}catch(e){return Promise.reject(e)}},Z=/^((?:[^<>()[\]\\.,;:\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,}))$/,X="https://api.getalby.com/lnurl",Y=/*#__PURE__*/function(){function e(e,t){this.address=void 0,this.options=void 0,this.username=void 0,this.domain=void 0,this.pubkey=void 0,this.lnurlpData=void 0,this.keysendData=void 0,this.nostrData=void 0,this.nostrPubkey=void 0,this.nostrRelays=void 0,this.webln=void 0,this.address=e,this.options={proxy:X},this.options=Object.assign(this.options,t),this.parse(),this.webln=this.options.webln}var t=e.prototype;return t.parse=function(){var e=Z.exec(this.address.toLowerCase());e&&(this.username=e[1],this.domain=e[2])},t.getWebLN=function(){return this.webln||globalThis.webln},t.fetch=function(){try{var e=this;return Promise.resolve(e.options.proxy?e.fetchWithProxy():e.fetchWithoutProxy())}catch(e){return Promise.reject(e)}},t.fetchWithProxy=function(){try{var e=this;return Promise.resolve(fetch(e.options.proxy+"/lightning-address-details?"+new URLSearchParams({ln:e.address}).toString())).then(function(t){if(!t.ok)throw new Error("Failed to fetch lnurl info: "+t.status+" "+t.statusText);return Promise.resolve(t.json()).then(function(t){return Promise.resolve(e.parseLnUrlPayResponse(t.lnurlp)).then(function(){e.parseKeysendResponse(t.keysend),e.parseNostrResponse(t.nostr)})})})}catch(e){return Promise.reject(e)}},t.fetchWithoutProxy=function(){try{var e=this;return e.domain&&e.username?Promise.resolve(Promise.all([e.fetchLnurlData(),e.fetchKeysendData(),e.fetchNostrData()])).then(function(){}):Promise.resolve()}catch(e){return Promise.reject(e)}},t.fetchLnurlData=function(){try{var e=this;return Promise.resolve(fetch(e.lnurlpUrl())).then(function(t){var r=function(){if(t.ok)return Promise.resolve(t.json()).then(function(t){return Promise.resolve(e.parseLnUrlPayResponse(t)).then(function(){})})}();if(r&&r.then)return r.then(function(){})})}catch(e){return Promise.reject(e)}},t.fetchKeysendData=function(){try{var e=this;return Promise.resolve(fetch(e.keysendUrl())).then(function(t){var r=function(){if(t.ok)return Promise.resolve(t.json()).then(function(t){e.parseKeysendResponse(t)})}();if(r&&r.then)return r.then(function(){})})}catch(e){return Promise.reject(e)}},t.fetchNostrData=function(){try{var e=this;return Promise.resolve(fetch(e.nostrUrl())).then(function(t){var r=function(){if(t.ok)return Promise.resolve(t.json()).then(function(t){e.parseNostrResponse(t)})}();if(r&&r.then)return r.then(function(){})})}catch(e){return Promise.reject(e)}},t.lnurlpUrl=function(){return"https://"+this.domain+"/.well-known/lnurlp/"+this.username},t.keysendUrl=function(){return"https://"+this.domain+"/.well-known/keysend/"+this.username},t.nostrUrl=function(){return"https://"+this.domain+"/.well-known/nostr.json?name="+this.username},t.generateInvoice=function(e){try{var t,r=function(e){var r=t&&t.pr&&t.pr.toString();if(!r)throw new Error("Invalid pay service invoice");var n={pr:r};if(t&&t.verify&&(n.verify=t.verify.toString()),t&&t.successAction&&"object"==typeof t.successAction){var o=t.successAction,i=o.tag,s=o.description,a=o.url;"message"===i?n.successAction={tag:i,message:o.message}:"url"===i&&(n.successAction={tag:i,description:s,url:a})}return new W(n)},n=this,o=function(){if(n.options.proxy)return Promise.resolve(fetch(n.options.proxy+"/generate-invoice?"+new URLSearchParams(G({ln:n.address},e)).toString())).then(function(e){if(!e.ok)throw new Error("Failed to generate invoice: "+e.status+" "+e.statusText);return Promise.resolve(e.json()).then(function(e){t=e.invoice})});if(!n.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!n.lnurlpData.callback||!q(n.lnurlpData.callback))throw new Error("Valid callback does not exist in lnurlpData");var r=new URL(n.lnurlpData.callback);return r.search=new URLSearchParams(e).toString(),Promise.resolve(fetch(r.toString())).then(function(e){if(!e.ok)throw new Error("Failed to generate invoice: "+e.status+" "+e.statusText);return Promise.resolve(e.json()).then(function(e){t=e})})}();return Promise.resolve(o&&o.then?o.then(r):r())}catch(e){return Promise.reject(e)}},t.requestInvoice=function(e){try{var t=this;if(!t.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");var r=1e3*e.satoshi,n=t.lnurlpData,o=n.commentAllowed;if(!z({amount:r,min:n.min,max:n.max}))throw new Error("Invalid amount");if(e.comment&&o&&o>0&&e.comment.length>o)throw new Error("The comment length must be "+o+" characters or fewer");var i={amount:r.toString()};return e.comment&&(i.comment=e.comment),e.payerdata&&(i.payerdata=JSON.stringify(e.payerdata)),Promise.resolve(t.generateInvoice(i))}catch(e){return Promise.reject(e)}},t.boost=function(e,t){void 0===t&&(t=0);try{var r=this;if(!r.keysendData)throw new Error("No keysendData available. Please call fetch() first.");var n=r.keysendData,o=n.destination,i=n.customKey,s=n.customValue,a=r.getWebLN();if(!a)throw new Error("WebLN not available");return Promise.resolve(J({destination:o,customKey:i,customValue:s,amount:t,boost:e},{webln:a}))}catch(e){return Promise.reject(e)}},t.zapInvoice=function(e,t){var r=e.satoshi,n=e.comment,o=e.relays,i=e.e;void 0===t&&(t={});try{var s=this;if(!s.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!s.nostrPubkey)throw new Error("Nostr Pubkey is missing");var a=s.nostrPubkey,c=1e3*r,u=s.lnurlpData,h=u.allowsNostr;if(!z({amount:c,min:u.min,max:u.max}))throw new Error("Invalid amount");if(!h)throw new Error("Your provider does not support zaps");return Promise.resolve(B({satoshi:c,comment:n,p:a,e:i,relays:o},t)).then(function(e){var t={amount:c.toString(),nostr:JSON.stringify(e)};return Promise.resolve(s.generateInvoice(t))})}catch(i){return Promise.reject(i)}},t.zap=function(e,t){void 0===t&&(t={});try{var r=this.zapInvoice(e,t),n=this.getWebLN();if(!n)throw new Error("WebLN not available");return Promise.resolve(n.enable()).then(function(){var e=n.sendPayment;return Promise.resolve(r).then(function(t){return e.call(n,t.paymentRequest)})})}catch(e){return Promise.reject(e)}},t.parseLnUrlPayResponse=function(e){try{var t=this,r=function(){if(e)return Promise.resolve(M(e)).then(function(e){t.lnurlpData=e})}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},t.parseKeysendResponse=function(e){e&&(this.keysendData=H(e))},t.parseNostrResponse=function(e){if(e){var t=C(e,this.username);this.nostrData=t[0],this.nostrPubkey=t[1],this.nostrRelays=t[2]}},e}(),Q=/*#__PURE__*/function(){function e(e){this.storage=void 0,this.storage=e||{}}var t=e.prototype;return t.getItem=function(e){return this.storage[e]},t.setItem=function(e,t){this.storage[e]=t},e}(),ee=/*#__PURE__*/function(){function e(e){}var t=e.prototype;return t.getItem=function(e){return null},t.setItem=function(e,t){},e}(),te=function(e){for(var t,r=e.replace("L402","").replace("LSAT","").trim(),n={},o=/(\w+)=("([^"]*)"|'([^']*)'|([^,]*))/g;null!==(t=o.exec(r));)n[t[1]]=t[3]||t[4]||t[5];return n},re=new Q,ne=function(e,t,r){try{var n,o=function(r){return n?r:(t.headers["Accept-Authenticate"]=i,Promise.resolve(fetch(e,t)).then(function(r){var n=r.headers.get("www-authenticate");if(!n)return r;var o=te(n),c=o.token||o.macaroon,u=o.invoice;return Promise.resolve(s.enable()).then(function(){return Promise.resolve(s.sendPayment(u)).then(function(r){return a.setItem(e,JSON.stringify({token:c,preimage:r.preimage})),t.headers.Authorization=i+" "+c+":"+r.preimage,Promise.resolve(fetch(e,t))})})}))};r||(r={});var i=r.headerKey||"L402",s=r.webln||globalThis.webln;if(!s)throw new Error("WebLN is missing");var a=r.store||re;t||(t={}),t.cache="no-store",t.mode="cors",t.headers||(t.headers={});var c=a.getItem(e),u=function(){if(c){var r=JSON.parse(c);return t.headers.Authorization=i+" "+r.token+":"+r.preimage,Promise.resolve(fetch(e,t)).then(function(e){return n=1,e})}}();return Promise.resolve(u&&u.then?u.then(o):o(u))}catch(e){return Promise.reject(e)}},oe={__proto__:null,fetchWithL402:ne,MemoryStorage:Q,NoStorage:ee,parseL402:te},ie=function(e){try{var t="https://getalby.com/api/rates/"+e.toLowerCase()+".json";return Promise.resolve(fetch(t)).then(function(e){if(!e.ok)throw new Error("Failed to fetch rate: "+e.status+" "+e.statusText);return Promise.resolve(e.json()).then(function(e){return e.rate_float/1e8})})}catch(e){return Promise.reject(e)}},se=function(e){var t=e.satoshi;return Promise.resolve(ie(e.currency)).then(function(e){return Number(t)*e})},ae=function(e){var t=e.amount;return Promise.resolve(ie(e.currency)).then(function(e){return Math.floor(Number(t)/e)})},ce=function(e){var t=e.currency,r=e.locale;return r||(r="en"),Promise.resolve(se({satoshi:e.satoshi,currency:t})).then(function(e){return e.toLocaleString(r,{style:"currency",currency:t})})},ue={__proto__:null,getFiatBtcRate:ie,getFiatValue:se,getSatoshiValue:ae,getFormattedFiatValue:ce};e.DEFAULT_PROXY=X,e.Invoice=W,e.LightningAddress=Y,e.MemoryStorage=Q,e.NoStorage=ee,e.decodeInvoice=b,e.fetchWithL402=ne,e.fiat=ue,e.fromHexString=v,e.generateZapEvent=B,e.getEventHash=K,e.getFiatBtcRate=ie,e.getFiatValue=se,e.getFormattedFiatValue=ce,e.getSatoshiValue=ae,e.isUrl=q,e.isValidAmount=z,e.l402=oe,e.parseKeysendResponse=H,e.parseL402=te,e.parseLnUrlPayResponse=M,e.parseNostrResponse=C,e.sendBoostagram=J,e.serializeEvent=F,e.validateEvent=O});