@getalby/lightning-tools
Advanced tools
Comparing version 4.2.1 to 5.0.0
@@ -11,2 +11,1 @@ import fetchWithL402 from "./l402"; | ||
export * from "./types"; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -1,2 +0,1 @@ | ||
import t from"crypto-js/enc-hex.js";import e from"crypto-js/sha256.js";import{decode as a}from"light-bolt11-decoder";class r{constructor(t){this.storage=void 0,this.storage=t||{}}getItem(t){return this.storage[t]}setItem(t,e){this.storage[t]=e}}var n={__proto__:null,MemoryStorage:r,NoStorage:class{constructor(t){}getItem(t){return null}setItem(t,e){}},default:r};const s=new r,i=async(t,e,a)=>{a||(a={});const r=a.headerKey||"L402",n=a.webln||globalThis.webln;if(!n)throw new Error("WebLN is missing");const i=a.store||s;e||(e={}),e.cache="no-store",e.mode="cors",e.headers||(e.headers={});const o=i.getItem(t);if(o){const a=JSON.parse(o);return e.headers.Authorization=`${r} ${a.token}:${a.preimage}`,await fetch(t,e)}e.headers["Accept-Authenticate"]=r;const l=await fetch(t,e),c=l.headers.get("www-authenticate");if(!c)return l;const h=(t=>{const e=t.replace("L402","").replace("LSAT","").trim(),a={},r=/(\w+)=("([^"]*)"|'([^']*)'|([^,]*))/g;let n;for(;null!==(n=r.exec(e));)a[n[1]]=n[3]||n[4]||n[5];return a})(c),u=h.token||h.macaroon,m=h.invoice;await n.enable();const p=await n.sendPayment(m);return i.setItem(t,JSON.stringify({token:u,preimage:p.preimage})),e.headers.Authorization=`${r} ${u}:${p.preimage}`,await fetch(t,e)};var o={__proto__:null,storage:n,fetchWithL402:i,default:i};const l=async(t,e)=>{const{boost:a}=t;e||(e={});const r=e.webln||globalThis.webln;if(!r)throw new Error("WebLN not available");if(!r.keysend)throw new Error("Keysend not available in current WebLN provider");const n=t.amount||Math.floor(a.value_msat/1e3),s={destination:t.destination,amount:n,customRecords:{7629169:JSON.stringify(a)}};return t.customKey&&t.customValue&&(s.customRecords[t.customKey]=t.customValue),await r.enable(),await r.keysend(s)};var c={__proto__:null,boost:l,default:l};function h(){return h=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var a=arguments[e];for(var r in a)Object.prototype.hasOwnProperty.call(a,r)&&(t[r]=a[r])}return t},h.apply(this,arguments)}const u=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/,m=t=>!!t&&u.test(t),p=({amount:t,min:e,max:a})=>t>0&&t>=e&&t<=a;class d{constructor(t){var e,r,n;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.paymentRequest=t.pr,!this.paymentRequest)throw new Error("Invalid payment request");const s=(t=>{if(!t)return null;try{const e=a(t);if(!e||!e.sections)return null;const r=e.sections.find(t=>"payment_hash"===t.name);if("payment_hash"!==(null==r?void 0:r.name)||!r.value)return null;const n=r.value,s=e.sections.find(t=>"amount"===t.name);if("amount"!==(null==s?void 0:s.name)||void 0===s.value)return null;const i=parseInt(s.value)/1e3,o=e.sections.find(t=>"expiry"===t.name),l=e.sections.find(t=>"timestamp"===t.name);if("timestamp"!==(null==l?void 0:l.name)||!l.value)return null;const c=l.value;if("expiry"!==(null==o?void 0:o.name)||void 0===o.value)return null;const h=o.value,u=e.sections.find(t=>"description"===t.name);return{paymentHash:n,satoshi:i,timestamp:c,expiry:h,description:"description"===(null==u?void 0:u.name)?null==u?void 0:u.value:void 0}}catch(t){return null}})(this.paymentRequest);if(!s)throw new Error("Failed to decode payment request");this.paymentHash=s.paymentHash,this.satoshi=s.satoshi,this.timestamp=s.timestamp,this.expiry=s.expiry,this.createdDate=new Date(1e3*this.timestamp),this.expiryDate=new Date(1e3*(this.timestamp+this.expiry)),this.description=null!=(e=s.description)?e:null,this.verify=null!=(r=t.verify)?r:null,this.preimage=null!=(n=t.preimage)?n:null}async isPaid(){if(this.preimage)return this.validatePreimage(this.preimage);if(this.verify)return await this.verifyPayment();throw new Error("Could not verify payment")}validatePreimage(a){if(!a||!this.paymentHash)return!1;try{const r=e(t.parse(a)).toString(t);return this.paymentHash===r}catch(t){return!1}}async verifyPayment(){if(!this.verify)throw new Error("LNURL verify not available");const t=await fetch(this.verify),e=await t.json();return e.preimage&&(this.preimage=e.preimage),e.settled}}async function y({satoshi:t,comment:e,p:a,e:r,relays:n},s={}){const i=s.nostr||globalThis.nostr;if(!i)throw new Error("nostr option or window.nostr is not available");const o=[["relays",...n],["amount",t.toString()]];a&&o.push(["p",a]),r&&o.push(["e",r]);const l={pubkey:await i.getPublicKey(),created_at:Math.floor(Date.now()/1e3),kind:9734,tags:o,content:null!=e?e:""};return l.id=v(l),await i.signEvent(l)}function w(t){if("string"!=typeof t.content)return!1;if("number"!=typeof t.created_at)return!1;if(!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){const a=t.tags[e];if(!Array.isArray(a))return!1;for(let t=0;t<a.length;t++)if("object"==typeof a[t])return!1}return!0}function f(t){if(!w(t))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content])}function v(a){return e(f(a)).toString(t)}function g(t,e){let a,r;var n,s;return e&&t&&(a=null==(n=t.names)?void 0:n[e],r=a?null==(s=t.relays)?void 0:s[a]:void 0),[t,a,r]}var b={__proto__:null,generateZapEvent:y,validateEvent:w,serializeEvent:f,getEventHash:v,parseNostrResponse:g};const k=/^((?:[^<>()[\]\\.,;:\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,}))$/;class D{constructor(t,e){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=t,this.options={proxy:"https://api.getalby.com/lnurl"},this.options=Object.assign(this.options,e),this.parse(),this.webln=this.options.webln}parse(){const t=k.exec(this.address.toLowerCase());t&&(this.username=t[1],this.domain=t[2])}getWebLN(){return this.webln||globalThis.webln}async fetch(){return this.options.proxy?this.fetchWithProxy():this.fetchWithoutProxy()}async fetchWithProxy(){const t=await fetch(`${this.options.proxy}/lightning-address-details?${new URLSearchParams({ln:this.address}).toString()}`),e=await t.json();this.parseResponse(e.lnurlp,e.keysend,e.nostr)}async fetchWithoutProxy(){if(!this.domain||!this.username)return;const t=await fetch(this.lnurlpUrl()),e=await fetch(this.keysendUrl()),a=await fetch(this.nostrUrl());let r,n,s;t.ok&&(r=await t.json()),e.ok&&(n=await e.json()),a.ok&&(s=await a.json()),this.parseResponse(r,n,s)}lnurlpUrl(){return`https://${this.domain}/.well-known/lnurlp/${this.username}`}keysendUrl(){return`https://${this.domain}/.well-known/keysend/${this.username}`}nostrUrl(){return`https://${this.domain}/.well-known/nostr.json?name=${this.username}`}async generateInvoice(t){let e;if(this.options.proxy){const a=await fetch(`${this.options.proxy}/generate-invoice?${new URLSearchParams(h({ln:this.address},t)).toString()}`);e=(await a.json()).invoice}else{if(!this.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!this.lnurlpData.callback||!m(this.lnurlpData.callback))throw new Error("Valid callback does not exist in lnurlpData");const a=new URL(this.lnurlpData.callback);a.search=new URLSearchParams(t).toString();const r=await fetch(a.toString());e=await r.json()}const a=e&&e.pr&&e.pr.toString();if(!a)throw new Error("Invalid pay service invoice");const r={pr:a};return e&&e.verify&&(r.verify=e.verify.toString()),new d(r)}async requestInvoice(t){if(!this.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");const e=1e3*t.satoshi,{commentAllowed:a,min:r,max:n}=this.lnurlpData;if(!p({amount:e,min:r,max:n}))throw new Error("Invalid amount");if(t.comment&&a&&a>0&&t.comment.length>a)throw new Error(`The comment length must be ${a} characters or fewer`);const s={amount:e.toString()};return t.comment&&(s.comment=t.comment),t.payerdata&&(s.payerdata=JSON.stringify(t.payerdata)),this.generateInvoice(s)}async boost(t,e=0){if(!this.keysendData)throw new Error("No keysendData available. Please call fetch() first.");const{destination:a,customKey:r,customValue:n}=this.keysendData,s=this.getWebLN();if(!s)throw new Error("WebLN not available");return l({destination:a,customKey:r,customValue:n,amount:e,boost:t},{webln:s})}async zapInvoice({satoshi:t,comment:e,relays:a,e:r},n={}){if(!this.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!this.nostrPubkey)throw new Error("Nostr Pubkey is missing");const s=this.nostrPubkey,i=1e3*t,{allowsNostr:o,min:l,max:c}=this.lnurlpData;if(!p({amount:i,min:l,max:c}))throw new Error("Invalid amount");if(!o)throw new Error("Your provider does not support zaps");const h=await y({satoshi:i,comment:e,p:s,e:r,relays:a},n),u={amount:i.toString(),nostr:JSON.stringify(h)};return await this.generateInvoice(u)}async zap(t,e={}){const a=this.zapInvoice(t,e),r=this.getWebLN();if(!r)throw new Error("WebLN not available");return await r.enable(),r.sendPayment((await a).paymentRequest)}parseResponse(a,r,n){a&&(this.lnurlpData=(a=>{if("payRequest"!==a.tag)throw new Error("Invalid pay service params");const r=(a.callback+"").trim();if(!m(r))throw new Error("Callback must be a valid url");const n=Math.ceil(Number(a.minSendable||0)),s=Math.floor(Number(a.maxSendable));if(!n||!s||n>s)throw new Error("Invalid pay service params");let i,o;try{i=JSON.parse(a.metadata+""),o=e(a.metadata+"").toString(t)}catch(a){i=[],o=e("[]").toString(t)}let l="",c="",h="";for(let t=0;t<i.length;t++){const[e,a]=i[t];switch(e){case"text/plain":c=a;break;case"text/identifier":h=a;break;case"image/png;base64":case"image/jpeg;base64":l="data:"+e+","+a}}const u=a.payerData;let p;try{p=new URL(r).hostname}catch(t){}return{callback:r,fixed:n===s,min:n,max:s,domain:p,metadata:i,metadataHash:o,identifier:h,description:c,image:l,payerData:u,commentAllowed:Number(a.commentAllowed)||0,rawData:a,allowsNostr:a.allowsNostr||!1}})(a)),r&&(this.keysendData=(t=>{if("keysend"!==t.tag)throw new Error("Invalid keysend params");if("OK"!==t.status)throw new Error("Keysend status not OK");if(!("customKey"in t.customData[0])||"696969"!=t.customData[0].customKey)throw new Error("Unable to find customKey");if(!("customValue"in t.customData[0])||!t.customData[0].customValue)throw new Error("Unable to find customValue");if(!t.pubkey)throw new Error("Pubkey does not exist");return{destination:t.pubkey,customKey:t.customData[0].customKey,customValue:t.customData[0].customValue}})(r)),n&&([this.nostrData,this.nostrPubkey,this.nostrRelays]=g(n,this.username))}}const E=async t=>{const e="https://getalby.com/api/rates/"+t.toLowerCase()+".json",a=await fetch(e);return(await a.json()).rate_float/1e8},x=async({satoshi:t,currency:e})=>{const a=await E(e);return Number(t)*a};var N={__proto__:null,getFiatBtcRate:E,getFiatValue:x,getSatoshiValue:async({amount:t,currency:e})=>{const a=await E(e);return Math.floor(Number(t)/a)},getFormattedFiatValue:async({satoshi:t,currency:e,locale:a})=>(a||(a="en"),(await x({satoshi:t,currency:e})).toLocaleString(a,{style:"currency",currency:e}))};export{d as Invoice,D as LightningAddress,c as boostagrams,i as fetchWithL402,N as fiat,o as l402,b as nostr,l as sendBoostagram}; | ||
//# sourceMappingURL=index.modern.js.map | ||
class e{constructor(e){this.storage=void 0,this.storage=e||{}}getItem(e){return this.storage[e]}setItem(e,t){this.storage[e]=t}}var t={__proto__:null,MemoryStorage:e,NoStorage:class{constructor(e){}getItem(e){return null}setItem(e,t){}},default:e};const r=new e,n=async(e,t,n)=>{n||(n={});const o=n.headerKey||"L402",a=n.webln||globalThis.webln;if(!a)throw new Error("WebLN is missing");const s=n.store||r;t||(t={}),t.cache="no-store",t.mode="cors",t.headers||(t.headers={});const i=s.getItem(e);if(i){const r=JSON.parse(i);return t.headers.Authorization=`${o} ${r.token}:${r.preimage}`,await fetch(e,t)}t.headers["Accept-Authenticate"]=o;const c=await fetch(e,t),l=c.headers.get("www-authenticate");if(!l)return c;const h=(e=>{const t=e.replace("L402","").replace("LSAT","").trim(),r={},n=/(\w+)=("([^"]*)"|'([^']*)'|([^,]*))/g;let o;for(;null!==(o=n.exec(t));)r[o[1]]=o[3]||o[4]||o[5];return r})(l),u=h.token||h.macaroon,d=h.invoice;await a.enable();const f=await a.sendPayment(d);return s.setItem(e,JSON.stringify({token:u,preimage:f.preimage})),t.headers.Authorization=`${o} ${u}:${f.preimage}`,await fetch(e,t)};var o={__proto__:null,storage:t,fetchWithL402:n,default:n};const a=async(e,t)=>{const{boost:r}=e;t||(t={});const 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");const o=e.amount||Math.floor(r.value_msat/1e3),a={destination:e.destination,amount:o,customRecords:{7629169:JSON.stringify(r)}};return e.customKey&&e.customValue&&(a.customRecords[e.customKey]=e.customValue),await n.enable(),await n.keysend(a)};var s={__proto__:null,boost:a,default:a};function i(){return i=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},i.apply(this,arguments)}async function c(e){const t="string"==typeof e?(new TextEncoder).encode(e):e,r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}const l=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/,h=e=>!!e&&l.test(e),u=({amount:e,min:t,max:r})=>e>0&&e>=t&&e<=r;var d,f,p=(d=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 a(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 i(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 a=[],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 a=o;a<s.length;a++){const i=s[a],c=t*e+i;if(!Number.isSafeInteger(c)||t*e/t!==e||c-i!=t*e)throw new Error("convertRadix: carry overflow");if(e=c%n,s[a]=Math.floor(c/n),!Number.isSafeInteger(s[a])||s[a]*n+e!==c)throw new Error("convertRadix: carry overflow");r&&(s[a]?r=!1:o=a)}if(a.push(e),r)break}for(let t=0;t<e.length-1&&0===e[t];t++)a.push(0);return a.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 l=(e,t)=>t?l(t,e%t):e,h=(e,t)=>e+(t-l(e,t));function u(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 a=0,s=0;const i=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(a=a<<t|o,s+t>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${t}`);for(s+=t;s>=n;s-=n)c.push((a>>s-n&i)>>>0);a&=2**s-1}if(a=a<<n-s&i,!o&&s>=t)throw new Error("Excess padding");if(!o&&a)throw new Error(`Non-zero padding: ${a}`);return o&&s>0&&c.push(a>>>0),c}function d(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 f(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 u(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(u(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 w(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),a=r.slice(-e);for(let t=0;t<e;t++)if(o[t]!==a[t])throw new Error("Invalid checksum");return n}}}t.utils={alphabet:o,chain:n,checksum:w,radix:d,radix2:f,join:a,padding:s},t.base16=n(f(4),o("0123456789ABCDEF"),a("")),t.base32=n(f(5),o("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),s(5),a("")),t.base32hex=n(f(5),o("0123456789ABCDEFGHIJKLMNOPQRSTUV"),s(5),a("")),t.base32crockford=n(f(5),o("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),a(""),i(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),t.base64=n(f(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),s(6),a("")),t.base64url=n(f(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),s(6),a(""));const m=e=>n(d(58),o(e),a(""));t.base58=m("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.base58flickr=m("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),t.base58xrp=m("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const y=[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(y[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),a=y.indexOf(o.length),s=t.base58.decode(o);for(let e=0;e<s.length-a;e++)if(0!==s[e])throw new Error("base58xmr: wrong padding");r=r.concat(Array.from(s.slice(s.length-a)))}return Uint8Array.from(r)}},t.base58check=e=>n(w(4,t=>e(e(t))),t.base58);const g=n(o("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),a("")),b=[996825010,642813549,513874426,1027748829,705979059];function v(e){const t=e>>25;let r=(33554431&e)<<5;for(let e=0;e<b.length;e++)1==(t>>e&1)&&(r^=b[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=v(o)^r>>5}o=v(o);for(let t=0;t<n;t++)o=v(o)^31&e.charCodeAt(t);for(let e of t)o=v(o)^e;for(let e=0;e<6;e++)o=v(o);return o^=r,g.encode(u([o%2**30],30,5,!1))}function x(e){const t="bech32"===e?1:734539939,r=f(5),n=r.decode,o=r.encode,a=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 a=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 i=g.decode(s).slice(0,-6),c=E(a,i,t);if(!s.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:a,words:i}}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:a,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(f(4),o("0123456789abcdef"),a(""),i(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 _={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(_).join(", ")}`;t.bytesToString=(e,t)=>{if("string"!=typeof e||!_.hasOwnProperty(e))throw new TypeError(A);if(!(t instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return _[e].encode(t)},t.str=t.bytesToString,t.stringToBytes=(e,t)=>{if(!_.hasOwnProperty(e))throw new TypeError(A);if("string"!=typeof t)throw new TypeError("stringToBytes() expects string");return _[e].decode(t)},t.bytes=t.stringToBytes},d(f={exports:{}},f.exports),f.exports);const{bech32:w,hex:m,utf8:y}=p,g={bech32:"bc",pubKeyHash:0,scriptHash:5,validWitnessVersions:[0]},b={bech32:"tb",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},v={bech32:"bcrt",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},E={bech32:"sb",pubKeyHash:63,scriptHash:123,validWitnessVersions:[0]},x=["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"],_={m:BigInt(1e3),u:BigInt(1e6),n:BigInt(1e9),p:BigInt(1e12)},A=BigInt("2100000000000000000"),k=BigInt(1e11),$={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},N={};for(let e=0,t=Object.keys($);e<t.length;e++){const r=t[e],n=$[t[e]].toString();N[n]=r}const S={1:e=>m.encode(w.fromWordsUnsafe(e)),16:e=>m.encode(w.fromWordsUnsafe(e)),13:e=>y.encode(w.fromWordsUnsafe(e)),19:e=>m.encode(w.fromWordsUnsafe(e)),23:e=>m.encode(w.fromWordsUnsafe(e)),27:e=>m.encode(w.fromWordsUnsafe(e)),6:U,24:U,3:function(e){const t=[];let r,n,o,a,s,i=w.fromWordsUnsafe(e);for(;i.length>0;)r=m.encode(i.slice(0,33)),n=m.encode(i.slice(33,41)),o=parseInt(m.encode(i.slice(41,45)),16),a=parseInt(m.encode(i.slice(45,49)),16),s=parseInt(m.encode(i.slice(49,51)),16),i=i.slice(51),t.push({pubkey:r,short_channel_id:n,fee_base_msat:o,fee_proportional_millionths:a,cltv_expiry_delta:s});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*x.length;)t.push(!1);const r={};x.forEach((e,n)=>{let o;o=t[2*n]?"required":t[2*n+1]?"supported":"unsupported",r[e]=o});const n=t.slice(2*x.length);return r.extra_bits={start_bit:2*x.length,bits:n,has_required:n.reduce((e,t,r)=>r%2!=0?e||!1:e||t,!1)},r}};function I(e){return t=>({tagCode:parseInt(e),words:w.encode("unknown",t,Number.MAX_SAFE_INTEGER)})}function U(e){return e.reverse().reduce((e,t,r)=>e+t*Math.pow(32,r),0)}class D{constructor(e){var t,r,n;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.paymentRequest=e.pr,!this.paymentRequest)throw new Error("Invalid payment request");const o=(e=>{if(!e)return null;try{const 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 r=[],n=w.decode(e,Number.MAX_SAFE_INTEGER);e=e.toLowerCase();const o=n.prefix;let a=n.words,s=e.slice(o.length+1),i=a.slice(-104);a=a.slice(0,-104);let c=o.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);if(c&&!c[2]&&(c=o.match(/^ln(\S+)$/)),!c)throw new Error("Not a proper lightning payment request");r.push({name:"lightning_network",letters:"ln"});const l=c[1];let h;switch(l){case g.bech32:h=g;break;case b.bech32:h=b;break;case v.bech32:h=v;break;case E.bech32:h=E}if(!h||h.bech32!==l)throw new Error("Unknown coin bech32 prefix");r.push({name:"coin_network",letters:l,value:h});const u=c[2];let d;u?(d=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),a=r?o*k/_[r]:o*k;if("p"===r&&o%BigInt(10)!==BigInt(0)||a>A)throw new Error("Amount is outside of valid range");return a.toString()}(u+c[3]),r.push({name:"amount",letters:c[2]+c[3],value:d})):d=null,r.push({name:"separator",letters:"1"});const f=U(a.slice(0,7));let p,y,x,D;for(a=a.slice(7),r.push({name:"timestamp",letters:s.slice(0,7),value:f}),s=s.slice(7);a.length>0;){const e=a[0].toString();p=N[e]||"unknown_tag",y=S[e]||I(e),a=a.slice(1),x=U(a.slice(0,2)),a=a.slice(2),D=a.slice(0,x),a=a.slice(x),r.push({name:p,tag:s[0],letters:s.slice(0,3+x),value:y(D)}),s=s.slice(3+x)}r.push({name:"signature",letters:s.slice(0,104),value:m.encode(w.fromWordsUnsafe(i))}),s=s.slice(104),r.push({name:"checksum",letters:s});let R={paymentRequest:e,sections:r,get expiry(){let e=r.find(e=>"expiry"===e.name);if(e)return W("timestamp")+e.value},get route_hints(){return r.filter(e=>"route_hint"===e.name).map(e=>e.value)}};for(let e in $)"route_hint"!==e&&Object.defineProperty(R,e,{get:()=>W(e)});return R;function W(e){let t=r.find(t=>t.name===e);return t?t.value:void 0}}(e);if(!t||!t.sections)return null;const r=t.sections.find(e=>"payment_hash"===e.name);if("payment_hash"!==(null==r?void 0:r.name)||!r.value)return null;const n=r.value,o=t.sections.find(e=>"amount"===e.name);if("amount"!==(null==o?void 0:o.name)||void 0===o.value)return null;const a=parseInt(o.value)/1e3,s=t.sections.find(e=>"expiry"===e.name),i=t.sections.find(e=>"timestamp"===e.name);if("timestamp"!==(null==i?void 0:i.name)||!i.value)return null;const c=i.value;if("expiry"!==(null==s?void 0:s.name)||void 0===s.value)return null;const l=s.value,h=t.sections.find(e=>"description"===e.name);return{paymentHash:n,satoshi:a,timestamp:c,expiry:l,description:"description"===(null==h?void 0:h.name)?null==h?void 0:h.value:void 0}}catch(e){return null}})(this.paymentRequest);if(!o)throw new Error("Failed to decode payment request");this.paymentHash=o.paymentHash,this.satoshi=o.satoshi,this.timestamp=o.timestamp,this.expiry=o.expiry,this.createdDate=new Date(1e3*this.timestamp),this.expiryDate=new Date(1e3*(this.timestamp+this.expiry)),this.description=null!=(t=o.description)?t:null,this.verify=null!=(r=e.verify)?r:null,this.preimage=null!=(n=e.preimage)?n:null}async isPaid(){if(this.preimage)return this.validatePreimage(this.preimage);if(this.verify)return await this.verifyPayment();throw new Error("Could not verify payment")}async validatePreimage(e){if(!e||!this.paymentHash)return!1;try{const r=await c((t=e,Uint8Array.from(t.match(/.{1,2}/g).map(e=>parseInt(e,16)))));return this.paymentHash===r}catch(e){return!1}var t}async verifyPayment(){if(!this.verify)throw new Error("LNURL verify not available");const e=await fetch(this.verify),t=await e.json();return t.preimage&&(this.preimage=t.preimage),t.settled}}async function R({satoshi:e,comment:t,p:r,e:n,relays:o},a={}){const s=a.nostr||globalThis.nostr;if(!s)throw new Error("nostr option or window.nostr is not available");const i=[["relays",...o],["amount",e.toString()]];r&&i.push(["p",r]),n&&i.push(["e",n]);const c={pubkey:await s.getPublicKey(),created_at:Math.floor(Date.now()/1e3),kind:9734,tags:i,content:null!=t?t:""};return c.id=await L(c),await s.signEvent(c)}function W(e){if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if(!Array.isArray(e.tags))return!1;for(let t=0;t<e.tags.length;t++){const r=e.tags[t];if(!Array.isArray(r))return!1;for(let e=0;e<r.length;e++)if("object"==typeof r[e])return!1}return!0}function P(e){if(!W(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 L(e){return c(P(e))}function T(e,t){let r,n;var o,a;return t&&e&&(r=null==(o=e.names)?void 0:o[t],n=r?null==(a=e.relays)?void 0:a[r]:void 0),[e,r,n]}var j={__proto__:null,generateZapEvent:R,validateEvent:W,serializeEvent:P,getEventHash:L,parseNostrResponse:T};const O=/^((?:[^<>()[\]\\.,;:\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,}))$/;class K{constructor(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:"https://api.getalby.com/lnurl"},this.options=Object.assign(this.options,t),this.parse(),this.webln=this.options.webln}parse(){const e=O.exec(this.address.toLowerCase());e&&(this.username=e[1],this.domain=e[2])}getWebLN(){return this.webln||globalThis.webln}async fetch(){return this.options.proxy?this.fetchWithProxy():this.fetchWithoutProxy()}async fetchWithProxy(){const e=await fetch(`${this.options.proxy}/lightning-address-details?${new URLSearchParams({ln:this.address}).toString()}`),t=await e.json();await this.parseResponse(t.lnurlp,t.keysend,t.nostr)}async fetchWithoutProxy(){if(!this.domain||!this.username)return;const e=await fetch(this.lnurlpUrl()),t=await fetch(this.keysendUrl()),r=await fetch(this.nostrUrl());let n,o,a;e.ok&&(n=await e.json()),t.ok&&(o=await t.json()),r.ok&&(a=await r.json()),await this.parseResponse(n,o,a)}lnurlpUrl(){return`https://${this.domain}/.well-known/lnurlp/${this.username}`}keysendUrl(){return`https://${this.domain}/.well-known/keysend/${this.username}`}nostrUrl(){return`https://${this.domain}/.well-known/nostr.json?name=${this.username}`}async generateInvoice(e){let t;if(this.options.proxy){const r=await fetch(`${this.options.proxy}/generate-invoice?${new URLSearchParams(i({ln:this.address},e)).toString()}`);t=(await r.json()).invoice}else{if(!this.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!this.lnurlpData.callback||!h(this.lnurlpData.callback))throw new Error("Valid callback does not exist in lnurlpData");const r=new URL(this.lnurlpData.callback);r.search=new URLSearchParams(e).toString();const n=await fetch(r.toString());t=await n.json()}const r=t&&t.pr&&t.pr.toString();if(!r)throw new Error("Invalid pay service invoice");const n={pr:r};return t&&t.verify&&(n.verify=t.verify.toString()),new D(n)}async requestInvoice(e){if(!this.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");const t=1e3*e.satoshi,{commentAllowed:r,min:n,max:o}=this.lnurlpData;if(!u({amount:t,min:n,max:o}))throw new Error("Invalid amount");if(e.comment&&r&&r>0&&e.comment.length>r)throw new Error(`The comment length must be ${r} characters or fewer`);const a={amount:t.toString()};return e.comment&&(a.comment=e.comment),e.payerdata&&(a.payerdata=JSON.stringify(e.payerdata)),this.generateInvoice(a)}async boost(e,t=0){if(!this.keysendData)throw new Error("No keysendData available. Please call fetch() first.");const{destination:r,customKey:n,customValue:o}=this.keysendData,s=this.getWebLN();if(!s)throw new Error("WebLN not available");return a({destination:r,customKey:n,customValue:o,amount:t,boost:e},{webln:s})}async zapInvoice({satoshi:e,comment:t,relays:r,e:n},o={}){if(!this.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!this.nostrPubkey)throw new Error("Nostr Pubkey is missing");const a=this.nostrPubkey,s=1e3*e,{allowsNostr:i,min:c,max:l}=this.lnurlpData;if(!u({amount:s,min:c,max:l}))throw new Error("Invalid amount");if(!i)throw new Error("Your provider does not support zaps");const h=await R({satoshi:s,comment:t,p:a,e:n,relays:r},o),d={amount:s.toString(),nostr:JSON.stringify(h)};return await this.generateInvoice(d)}async zap(e,t={}){const r=this.zapInvoice(e,t),n=this.getWebLN();if(!n)throw new Error("WebLN not available");return await n.enable(),n.sendPayment((await r).paymentRequest)}async parseResponse(e,t,r){e&&(this.lnurlpData=await(async e=>{if("payRequest"!==e.tag)throw new Error("Invalid pay service params");const t=(e.callback+"").trim();if(!h(t))throw new Error("Callback must be a valid url");const r=Math.ceil(Number(e.minSendable||0)),n=Math.floor(Number(e.maxSendable));if(!r||!n||r>n)throw new Error("Invalid pay service params");let o,a;try{o=JSON.parse(e.metadata+""),a=await c(e.metadata+"")}catch(e){o=[],a=await c("[]")}let s="",i="",l="";for(let e=0;e<o.length;e++){const[t,r]=o[e];switch(t){case"text/plain":i=r;break;case"text/identifier":l=r;break;case"image/png;base64":case"image/jpeg;base64":s="data:"+t+","+r}}const u=e.payerData;let d;try{d=new URL(t).hostname}catch(e){}return{callback:t,fixed:r===n,min:r,max:n,domain:d,metadata:o,metadataHash:a,identifier:l,description:i,image:s,payerData:u,commentAllowed:Number(e.commentAllowed)||0,rawData:e,allowsNostr:e.allowsNostr||!1}})(e)),t&&(this.keysendData=(e=>{if("keysend"!==e.tag)throw new Error("Invalid keysend params");if("OK"!==e.status)throw new Error("Keysend status not OK");if(!("customKey"in e.customData[0])||"696969"!=e.customData[0].customKey)throw new Error("Unable to find customKey");if(!("customValue"in e.customData[0])||!e.customData[0].customValue)throw new Error("Unable to find customValue");if(!e.pubkey)throw new Error("Pubkey does not exist");return{destination:e.pubkey,customKey:e.customData[0].customKey,customValue:e.customData[0].customValue}})(t)),r&&([this.nostrData,this.nostrPubkey,this.nostrRelays]=T(r,this.username))}}const B=async e=>{const t="https://getalby.com/api/rates/"+e.toLowerCase()+".json",r=await fetch(t);return(await r.json()).rate_float/1e8},H=async({satoshi:e,currency:t})=>{const r=await B(t);return Number(e)*r};var V={__proto__:null,getFiatBtcRate:B,getFiatValue:H,getSatoshiValue:async({amount:e,currency:t})=>{const r=await B(t);return Math.floor(Number(e)/r)},getFormattedFiatValue:async({satoshi:e,currency:t,locale:r})=>(r||(r="en"),(await H({satoshi:e,currency:t})).toLocaleString(r,{style:"currency",currency:t}))};export{D as Invoice,K as LightningAddress,s as boostagrams,n as fetchWithL402,V as fiat,o as l402,j as nostr,a as sendBoostagram}; |
@@ -1,2 +0,1 @@ | ||
import e from"crypto-js/enc-hex.js";import t from"crypto-js/sha256.js";import{decode as r}from"light-bolt11-decoder";var n=/*#__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}(),o={__proto__:null,MemoryStorage:n,NoStorage:/*#__PURE__*/function(){function e(e){}var t=e.prototype;return t.getItem=function(e){return null},t.setItem=function(e,t){},e}(),default:n},i=new n,a=function(e,t,r){try{var n,o=function(r){return n?r:(t.headers["Accept-Authenticate"]=a,Promise.resolve(fetch(e,t)).then(function(r){var n=r.headers.get("www-authenticate");if(!n)return r;var o=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}(n),i=o.token||o.macaroon,l=o.invoice;return Promise.resolve(s.enable()).then(function(){return Promise.resolve(s.sendPayment(l)).then(function(r){return u.setItem(e,JSON.stringify({token:i,preimage:r.preimage})),t.headers.Authorization=a+" "+i+":"+r.preimage,Promise.resolve(fetch(e,t))})})}))};r||(r={});var a=r.headerKey||"L402",s=r.webln||globalThis.webln;if(!s)throw new Error("WebLN is missing");var u=r.store||i;t||(t={}),t.cache="no-store",t.mode="cors",t.headers||(t.headers={});var l=u.getItem(e),c=function(){if(l){var r=JSON.parse(l);return t.headers.Authorization=a+" "+r.token+":"+r.preimage,Promise.resolve(fetch(e,t)).then(function(e){return n=1,e})}}();return Promise.resolve(c&&c.then?c.then(o):o(c))}catch(e){return Promise.reject(e)}},s={__proto__:null,storage:o,fetchWithL402:a,default:a},u=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)}},l={__proto__:null,boost:u,default:u};function c(){return c=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},c.apply(this,arguments)}var h=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/,m=function(e){return!!e&&h.test(e)},v=function(e){var t=e.amount;return t>0&&t>=e.min&&t<=e.max},f=/*#__PURE__*/function(){function n(e){var t,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.paymentRequest=e.pr,!this.paymentRequest)throw new Error("Invalid payment request");var i=function(e){if(!e)return null;try{var t=r(e);if(!t||!t.sections)return null;var n=t.sections.find(function(e){return"payment_hash"===e.name});if("payment_hash"!==(null==n?void 0:n.name)||!n.value)return null;var o=n.value,i=t.sections.find(function(e){return"amount"===e.name});if("amount"!==(null==i?void 0:i.name)||void 0===i.value)return null;var a=parseInt(i.value)/1e3,s=t.sections.find(function(e){return"expiry"===e.name}),u=t.sections.find(function(e){return"timestamp"===e.name});if("timestamp"!==(null==u?void 0:u.name)||!u.value)return null;var l=u.value;if("expiry"!==(null==s?void 0:s.name)||void 0===s.value)return null;var c=s.value,h=t.sections.find(function(e){return"description"===e.name});return{paymentHash:o,satoshi:a,timestamp:l,expiry:c,description:"description"===(null==h?void 0:h.name)?null==h?void 0:h.value:void 0}}catch(e){return null}}(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=new Date(1e3*(this.timestamp+this.expiry)),this.description=null!=(t=i.description)?t:null,this.verify=null!=(n=e.verify)?n:null,this.preimage=null!=(o=e.preimage)?o:null}var o=n.prototype;return o.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)}},o.validatePreimage=function(r){if(!r||!this.paymentHash)return!1;try{var n=t(e.parse(r)).toString(e);return this.paymentHash===n}catch(e){return!1}},o.verifyPayment=function(){try{var e=this;if(!e.verify)throw new Error("LNURL verify not available");return Promise.resolve(fetch(e.verify)).then(function(t){return Promise.resolve(t.json()).then(function(t){return t.preimage&&(e.preimage=t.preimage),t.settled})})}catch(e){return Promise.reject(e)}},n}(),p=function(e,t){var r=e.satoshi,n=e.comment,o=e.p,i=e.e,a=e.relays;void 0===t&&(t={});try{var s=t.nostr||globalThis.nostr;if(!s)throw new Error("nostr option or window.nostr is not available");var u=[["relays"].concat(a),["amount",r.toString()]];return o&&u.push(["p",o]),i&&u.push(["e",i]),Promise.resolve(s.getPublicKey()).then(function(e){var t={pubkey:e,created_at:Math.floor(Date.now()/1e3),kind:9734,tags:u,content:null!=n?n:""};return t.id=w(t),Promise.resolve(s.signEvent(t))})}catch(i){return Promise.reject(i)}};function d(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 y(e){if(!d(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 w(r){return t(y(r)).toString(e)}function g(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 b={__proto__:null,generateZapEvent:p,validateEvent:d,serializeEvent:y,getEventHash:w,parseNostrResponse:g},P=/^((?:[^<>()[\]\\.,;:\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,}))$/,k=/*#__PURE__*/function(){function r(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:"https://api.getalby.com/lnurl"},this.options=Object.assign(this.options,t),this.parse(),this.webln=this.options.webln}var n=r.prototype;return n.parse=function(){var e=P.exec(this.address.toLowerCase());e&&(this.username=e[1],this.domain=e[2])},n.getWebLN=function(){return this.webln||globalThis.webln},n.fetch=function(){try{var e=this;return Promise.resolve(e.options.proxy?e.fetchWithProxy():e.fetchWithoutProxy())}catch(e){return Promise.reject(e)}},n.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){return Promise.resolve(t.json()).then(function(t){e.parseResponse(t.lnurlp,t.keysend,t.nostr)})})}catch(e){return Promise.reject(e)}},n.fetchWithoutProxy=function(){try{var e=this;return e.domain&&e.username?Promise.resolve(fetch(e.lnurlpUrl())).then(function(t){return Promise.resolve(fetch(e.keysendUrl())).then(function(r){return Promise.resolve(fetch(e.nostrUrl())).then(function(n){function o(){function t(){function t(){e.parseResponse(i,o,r)}var r,a=function(){if(n.ok)return Promise.resolve(n.json()).then(function(e){r=e})}();return a&&a.then?a.then(t):t()}var o,a=function(){if(r.ok)return Promise.resolve(r.json()).then(function(e){o=e})}();return a&&a.then?a.then(t):t()}var i,a=function(){if(t.ok)return Promise.resolve(t.json()).then(function(e){i=e})}();return a&&a.then?a.then(o):o()})})}):Promise.resolve()}catch(e){return Promise.reject(e)}},n.lnurlpUrl=function(){return"https://"+this.domain+"/.well-known/lnurlp/"+this.username},n.keysendUrl=function(){return"https://"+this.domain+"/.well-known/keysend/"+this.username},n.nostrUrl=function(){return"https://"+this.domain+"/.well-known/nostr.json?name="+this.username},n.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};return t&&t.verify&&(n.verify=t.verify.toString()),new f(n)},n=this,o=function(){if(n.options.proxy)return Promise.resolve(fetch(n.options.proxy+"/generate-invoice?"+new URLSearchParams(c({ln:n.address},e)).toString())).then(function(e){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||!m(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){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)}},n.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(!v({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)}},n.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,a=n.customValue,s=r.getWebLN();if(!s)throw new Error("WebLN not available");return Promise.resolve(u({destination:o,customKey:i,customValue:a,amount:t,boost:e},{webln:s}))}catch(e){return Promise.reject(e)}},n.zapInvoice=function(e,t){var r=e.satoshi,n=e.comment,o=e.relays,i=e.e;void 0===t&&(t={});try{var a=this;if(!a.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!a.nostrPubkey)throw new Error("Nostr Pubkey is missing");var s=a.nostrPubkey,u=1e3*r,l=a.lnurlpData,c=l.allowsNostr;if(!v({amount:u,min:l.min,max:l.max}))throw new Error("Invalid amount");if(!c)throw new Error("Your provider does not support zaps");return Promise.resolve(p({satoshi:u,comment:n,p:s,e:i,relays:o},t)).then(function(e){var t={amount:u.toString(),nostr:JSON.stringify(e)};return Promise.resolve(a.generateInvoice(t))})}catch(i){return Promise.reject(i)}},n.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)}},n.parseResponse=function(r,n,o){if(r&&(this.lnurlpData=function(r){if("payRequest"!==r.tag)throw new Error("Invalid pay service params");var n=(r.callback+"").trim();if(!m(n))throw new Error("Callback must be a valid url");var o,i,a=Math.ceil(Number(r.minSendable||0)),s=Math.floor(Number(r.maxSendable));if(!a||!s||a>s)throw new Error("Invalid pay service params");try{o=JSON.parse(r.metadata+""),i=t(r.metadata+"").toString(e)}catch(r){o=[],i=t("[]").toString(e)}for(var u="",l="",c="",h=0;h<o.length;h++){var v=o[h],f=v[0],p=v[1];switch(f){case"text/plain":l=p;break;case"text/identifier":c=p;break;case"image/png;base64":case"image/jpeg;base64":u="data:"+f+","+p}}var d,y=r.payerData;try{d=new URL(n).hostname}catch(e){}return{callback:n,fixed:a===s,min:a,max:s,domain:d,metadata:o,metadataHash:i,identifier:c,description:l,image:u,payerData:y,commentAllowed:Number(r.commentAllowed)||0,rawData:r,allowsNostr:r.allowsNostr||!1}}(r)),n&&(this.keysendData=function(e){if("keysend"!==e.tag)throw new Error("Invalid keysend params");if("OK"!==e.status)throw new Error("Keysend status not OK");if(!("customKey"in e.customData[0])||"696969"!=e.customData[0].customKey)throw new Error("Unable to find customKey");if(!("customValue"in e.customData[0])||!e.customData[0].customValue)throw new Error("Unable to find customValue");if(!e.pubkey)throw new Error("Pubkey does not exist");return{destination:e.pubkey,customKey:e.customData[0].customKey,customValue:e.customData[0].customValue}}(n)),o){var i=g(o,this.username);this.nostrData=i[0],this.nostrPubkey=i[1],this.nostrRelays=i[2]}},r}(),D=function(e){try{var t="https://getalby.com/api/rates/"+e.toLowerCase()+".json";return Promise.resolve(fetch(t)).then(function(e){return Promise.resolve(e.json()).then(function(e){return e.rate_float/1e8})})}catch(e){return Promise.reject(e)}},E=function(e){var t=e.satoshi;return Promise.resolve(D(e.currency)).then(function(e){return Number(t)*e})},j={__proto__:null,getFiatBtcRate:D,getFiatValue:E,getSatoshiValue:function(e){var t=e.amount;return Promise.resolve(D(e.currency)).then(function(e){return Math.floor(Number(t)/e)})},getFormattedFiatValue:function(e){var t=e.currency,r=e.locale;return r||(r="en"),Promise.resolve(E({satoshi:e.satoshi,currency:t})).then(function(e){return e.toLocaleString(r,{style:"currency",currency:t})})}};export{f as Invoice,k as LightningAddress,l as boostagrams,a as fetchWithL402,j as fiat,s as l402,b as nostr,u as sendBoostagram}; | ||
//# sourceMappingURL=index.module.js.map | ||
var e=/*#__PURE__*/function(){function e(e){this.storage=void 0,this.storage=e||{}}var r=e.prototype;return r.getItem=function(e){return this.storage[e]},r.setItem=function(e,r){this.storage[e]=r},e}(),r={__proto__:null,MemoryStorage:e,NoStorage:/*#__PURE__*/function(){function e(e){}var r=e.prototype;return r.getItem=function(e){return null},r.setItem=function(e,r){},e}(),default:e},t=new e,n=function(e,r,n){try{var o,i=function(t){return o?t:(r.headers["Accept-Authenticate"]=s,Promise.resolve(fetch(e,r)).then(function(t){var n=t.headers.get("www-authenticate");if(!n)return t;var o=function(e){for(var r,t=e.replace("L402","").replace("LSAT","").trim(),n={},o=/(\w+)=("([^"]*)"|'([^']*)'|([^,]*))/g;null!==(r=o.exec(t));)n[r[1]]=r[3]||r[4]||r[5];return n}(n),i=o.token||o.macaroon,u=o.invoice;return Promise.resolve(a.enable()).then(function(){return Promise.resolve(a.sendPayment(u)).then(function(t){return c.setItem(e,JSON.stringify({token:i,preimage:t.preimage})),r.headers.Authorization=s+" "+i+":"+t.preimage,Promise.resolve(fetch(e,r))})})}))};n||(n={});var s=n.headerKey||"L402",a=n.webln||globalThis.webln;if(!a)throw new Error("WebLN is missing");var c=n.store||t;r||(r={}),r.cache="no-store",r.mode="cors",r.headers||(r.headers={});var u=c.getItem(e),l=function(){if(u){var t=JSON.parse(u);return r.headers.Authorization=s+" "+t.token+":"+t.preimage,Promise.resolve(fetch(e,r)).then(function(e){return o=1,e})}}();return Promise.resolve(l&&l.then?l.then(i):i(l))}catch(e){return Promise.reject(e)}},o={__proto__:null,storage:r,fetchWithL402:n,default:n},i=function(e,r){try{var t=e.boost;r||(r={});var n=r.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(t.value_msat/1e3),i={destination:e.destination,amount:o,customRecords:{7629169:JSON.stringify(t)}};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)}},s={__proto__:null,boost:i,default:i};function a(){return a=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},a.apply(this,arguments)}var c,u,l=function(e){try{var r="string"==typeof e?(new TextEncoder).encode(e):e;return Promise.resolve(crypto.subtle.digest("SHA-256",r)).then(function(e){return Array.from(new Uint8Array(e)).map(function(e){return e.toString(16).padStart(2,"0")}).join("")})}catch(e){return Promise.reject(e)}},h=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/,f=function(e){return!!e&&h.test(e)},d=function(e){var r=e.amount;return r>0&&r>=e.min&&r<=e.max},m=(c=function(e,r){function t(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function n(...e){const r=(e,r)=>t=>e(r(t));return{encode:Array.from(e).reverse().reduce((e,t)=>e?r(e,t.encode):t.encode,void 0),decode:e.reduce((e,t)=>e?r(e,t.decode):t.decode,void 0)}}function o(e){return{encode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("alphabet.encode input should be an array of numbers");return r.map(r=>{if(t(r),r<0||r>=e.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${e.length})`);return e[r]})},decode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("alphabet.decode input should be array of strings");return r.map(r=>{if("string"!=typeof r)throw new Error(`alphabet.decode: not string element=${r}`);const t=e.indexOf(r);if(-1===t)throw new Error(`Unknown letter: "${r}". Allowed: ${e}`);return t})}}}function i(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("join.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return r.join(e)},decode:r=>{if("string"!=typeof r)throw new Error("join.decode input should be string");return r.split(e)}}}function s(e,r="="){if(t(e),"string"!=typeof r)throw new Error("padding chr should be string");return{encode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;t.length*e%8;)t.push(r);return t},decode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let n=t.length;if(n*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&t[n-1]===r;n--)if(!((n-1)*e%8))throw new Error("Invalid padding: string has too much padding");return t.slice(0,n)}}}function a(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:r=>e(r)}}function c(e,r,n){if(r<2)throw new Error(`convertRadix: wrong from=${r}, 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(t(e),e<0||e>=r)throw new Error(`Wrong integer: ${e}`)});;){let e=0,t=!0;for(let i=o;i<s.length;i++){const a=s[i],c=r*e+a;if(!Number.isSafeInteger(c)||r*e/r!==e||c-a!=r*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");t&&(s[i]?t=!1:o=i)}if(i.push(e),t)break}for(let r=0;r<e.length-1&&0===e[r];r++)i.push(0);return i.reverse()}Object.defineProperty(r,"__esModule",{value:!0}),r.bytes=r.stringToBytes=r.str=r.bytesToString=r.hex=r.utf8=r.bech32m=r.bech32=r.base58check=r.base58xmr=r.base58xrp=r.base58flickr=r.base58=r.base64url=r.base64=r.base32crockford=r.base32hex=r.base32=r.base16=r.utils=r.assertNumber=void 0,r.assertNumber=t;const u=(e,r)=>r?u(r,e%r):e,l=(e,r)=>e+(r-u(e,r));function h(e,r,n,o){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(r<=0||r>32)throw new Error(`convertRadix2: wrong from=${r}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(l(r,n)>32)throw new Error(`convertRadix2: carry overflow from=${r} to=${n} carryBits=${l(r,n)}`);let i=0,s=0;const a=2**n-1,c=[];for(const o of e){if(t(o),o>=2**r)throw new Error(`convertRadix2: invalid data word=${o} from=${r}`);if(i=i<<r|o,s+r>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${r}`);for(s+=r;s>=n;s-=n)c.push((i>>s-n&a)>>>0);i&=2**s-1}if(i=i<<n-s&a,!o&&s>=r)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 t(e),{encode:r=>{if(!(r instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return c(Array.from(r),256,e)},decode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(c(r,e,256))}}}function d(e,r=!1){if(t(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(l(8,e)>32||l(e,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return h(Array.from(t),8,e,!r)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(h(t,e,8,r))}}}function m(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...r){try{return e.apply(null,r)}catch(e){}}}function p(e,r){if(t(e),"function"!=typeof r)throw new Error("checksum fn should be function");return{encode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const n=r(t).slice(0,e),o=new Uint8Array(t.length+e);return o.set(t),o.set(n,t.length),o},decode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const n=t.slice(0,-e),o=r(n).slice(0,e),i=t.slice(-e);for(let r=0;r<e;r++)if(o[r]!==i[r])throw new Error("Invalid checksum");return n}}}r.utils={alphabet:o,chain:n,checksum:p,radix:f,radix2:d,join:i,padding:s},r.base16=n(d(4),o("0123456789ABCDEF"),i("")),r.base32=n(d(5),o("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),s(5),i("")),r.base32hex=n(d(5),o("0123456789ABCDEFGHIJKLMNOPQRSTUV"),s(5),i("")),r.base32crockford=n(d(5),o("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),i(""),a(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),r.base64=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),s(6),i("")),r.base64url=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),s(6),i(""));const y=e=>n(f(58),o(e),i(""));r.base58=y("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),r.base58flickr=y("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),r.base58xrp=y("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const v=[0,2,3,5,6,7,9,10,11];r.base58xmr={encode(e){let t="";for(let n=0;n<e.length;n+=8){const o=e.subarray(n,n+8);t+=r.base58.encode(o).padStart(v[o.length],"1")}return t},decode(e){let t=[];for(let n=0;n<e.length;n+=11){const o=e.slice(n,n+11),i=v.indexOf(o.length),s=r.base58.decode(o);for(let e=0;e<s.length-i;e++)if(0!==s[e])throw new Error("base58xmr: wrong padding");t=t.concat(Array.from(s.slice(s.length-i)))}return Uint8Array.from(t)}},r.base58check=e=>n(p(4,r=>e(e(r))),r.base58);const w=n(o("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),i("")),g=[996825010,642813549,513874426,1027748829,705979059];function b(e){const r=e>>25;let t=(33554431&e)<<5;for(let e=0;e<g.length;e++)1==(r>>e&1)&&(t^=g[e]);return t}function E(e,r,t=1){const n=e.length;let o=1;for(let r=0;r<n;r++){const t=e.charCodeAt(r);if(t<33||t>126)throw new Error(`Invalid prefix (${e})`);o=b(o)^t>>5}o=b(o);for(let r=0;r<n;r++)o=b(o)^31&e.charCodeAt(r);for(let e of r)o=b(o)^e;for(let e=0;e<6;e++)o=b(o);return o^=t,w.encode(h([o%2**30],30,5,!1))}function P(e){const r="bech32"===e?1:734539939,t=d(5),n=t.decode,o=t.encode,i=m(n);function s(e,t=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==t&&e.length>t)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${t})`);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=w.decode(s).slice(0,-6),c=E(i,a,r);if(!s.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:i,words:a}}return{encode:function(e,t,n=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof t);const o=e.length+7+t.length;if(!1!==n&&o>n)throw new TypeError(`Length ${o} exceeds limit ${n}`);return`${e=e.toLowerCase()}1${w.encode(t)}${E(e,t,r)}`},decode:s,decodeToBytes:function(e){const{prefix:r,words:t}=s(e,!1);return{prefix:r,words:t,bytes:n(t)}},decodeUnsafe:m(s),fromWords:n,fromWordsUnsafe:i,toWords:o}}r.bech32=P("bech32"),r.bech32m=P("bech32m"),r.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},r.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 x={utf8:r.utf8,hex:r.hex,base16:r.base16,base32:r.base32,base64:r.base64,base64url:r.base64url,base58:r.base58,base58xmr:r.base58xmr},_=`Invalid encoding type. Available types: ${Object.keys(x).join(", ")}`;r.bytesToString=(e,r)=>{if("string"!=typeof e||!x.hasOwnProperty(e))throw new TypeError(_);if(!(r instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return x[e].encode(r)},r.str=r.bytesToString,r.stringToBytes=(e,r)=>{if(!x.hasOwnProperty(e))throw new TypeError(_);if("string"!=typeof r)throw new TypeError("stringToBytes() expects string");return x[e].decode(r)},r.bytes=r.stringToBytes},c(u={exports:{}},u.exports),u.exports);const{bech32:p,hex:y,utf8:v}=m,w={bech32:"bc",pubKeyHash:0,scriptHash:5,validWitnessVersions:[0]},g={bech32:"tb",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},b={bech32:"bcrt",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},E={bech32:"sb",pubKeyHash:63,scriptHash:123,validWitnessVersions:[0]},P=["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"],x={m:BigInt(1e3),u:BigInt(1e6),n:BigInt(1e9),p:BigInt(1e12)},_=BigInt("2100000000000000000"),A=BigInt(1e11),k={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},N={};for(let e=0,r=Object.keys(k);e<r.length;e++){const t=r[e],n=k[r[e]].toString();N[n]=t}const S={1:e=>y.encode(p.fromWordsUnsafe(e)),16:e=>y.encode(p.fromWordsUnsafe(e)),13:e=>v.encode(p.fromWordsUnsafe(e)),19:e=>y.encode(p.fromWordsUnsafe(e)),23:e=>y.encode(p.fromWordsUnsafe(e)),27:e=>y.encode(p.fromWordsUnsafe(e)),6:I,24:I,3:function(e){const r=[];let t,n,o,i,s,a=p.fromWordsUnsafe(e);for(;a.length>0;)t=y.encode(a.slice(0,33)),n=y.encode(a.slice(33,41)),o=parseInt(y.encode(a.slice(41,45)),16),i=parseInt(y.encode(a.slice(45,49)),16),s=parseInt(y.encode(a.slice(49,51)),16),a=a.slice(51),r.push({pubkey:t,short_channel_id:n,fee_base_msat:o,fee_proportional_millionths:i,cltv_expiry_delta:s});return r},5:function(e){const r=e.slice().reverse().map(e=>[!!(1&e),!!(2&e),!!(4&e),!!(8&e),!!(16&e)]).reduce((e,r)=>e.concat(r),[]);for(;r.length<2*P.length;)r.push(!1);const t={};P.forEach((e,n)=>{let o;o=r[2*n]?"required":r[2*n+1]?"supported":"unsupported",t[e]=o});const n=r.slice(2*P.length);return t.extra_bits={start_bit:2*P.length,bits:n,has_required:n.reduce((e,r,t)=>t%2!=0?e||!1:e||r,!1)},t}};function j(e){return r=>({tagCode:parseInt(e),words:p.encode("unknown",r,Number.MAX_SAFE_INTEGER)})}function I(e){return e.reverse().reduce((e,r,t)=>e+r*Math.pow(32,t),0)}var U=/*#__PURE__*/function(){function e(e){var r,t,n;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.paymentRequest=e.pr,!this.paymentRequest)throw new Error("Invalid payment request");var o=function(e){if(!e)return null;try{var r=function(e,r){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 t=[],n=p.decode(e,Number.MAX_SAFE_INTEGER);e=e.toLowerCase();const o=n.prefix;let i=n.words,s=e.slice(o.length+1),a=i.slice(-104);i=i.slice(0,-104);let c=o.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);if(c&&!c[2]&&(c=o.match(/^ln(\S+)$/)),!c)throw new Error("Not a proper lightning payment request");t.push({name:"lightning_network",letters:"ln"});const u=c[1];let l;switch(u){case w.bech32:l=w;break;case g.bech32:l=g;break;case b.bech32:l=b;break;case E.bech32:l=E}if(!l||l.bech32!==u)throw new Error("Unknown coin bech32 prefix");t.push({name:"coin_network",letters:u,value:l});const h=c[2];let f;h?(f=function(e,r){let t,n;if(e.slice(-1).match(/^[munp]$/))t=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=t?o*A/x[t]:o*A;if("p"===t&&o%BigInt(10)!==BigInt(0)||i>_)throw new Error("Amount is outside of valid range");return i.toString()}(h+c[3]),t.push({name:"amount",letters:c[2]+c[3],value:f})):f=null,t.push({name:"separator",letters:"1"});const d=I(i.slice(0,7));let m,v,P,U;for(i=i.slice(7),t.push({name:"timestamp",letters:s.slice(0,7),value:d}),s=s.slice(7);i.length>0;){const e=i[0].toString();m=N[e]||"unknown_tag",v=S[e]||j(e),i=i.slice(1),P=I(i.slice(0,2)),i=i.slice(2),U=i.slice(0,P),i=i.slice(P),t.push({name:m,tag:s[0],letters:s.slice(0,3+P),value:v(U)}),s=s.slice(3+P)}t.push({name:"signature",letters:s.slice(0,104),value:y.encode(p.fromWordsUnsafe(a))}),s=s.slice(104),t.push({name:"checksum",letters:s});let D={paymentRequest:e,sections:t,get expiry(){let e=t.find(e=>"expiry"===e.name);if(e)return R("timestamp")+e.value},get route_hints(){return t.filter(e=>"route_hint"===e.name).map(e=>e.value)}};for(let e in k)"route_hint"!==e&&Object.defineProperty(D,e,{get:()=>R(e)});return D;function R(e){let r=t.find(r=>r.name===e);return r?r.value:void 0}}(e);if(!r||!r.sections)return null;var t=r.sections.find(function(e){return"payment_hash"===e.name});if("payment_hash"!==(null==t?void 0:t.name)||!t.value)return null;var n=t.value,o=r.sections.find(function(e){return"amount"===e.name});if("amount"!==(null==o?void 0:o.name)||void 0===o.value)return null;var i=parseInt(o.value)/1e3,s=r.sections.find(function(e){return"expiry"===e.name}),a=r.sections.find(function(e){return"timestamp"===e.name});if("timestamp"!==(null==a?void 0:a.name)||!a.value)return null;var c=a.value;if("expiry"!==(null==s?void 0:s.name)||void 0===s.value)return null;var u=s.value,l=r.sections.find(function(e){return"description"===e.name});return{paymentHash:n,satoshi:i,timestamp:c,expiry:u,description:"description"===(null==l?void 0:l.name)?null==l?void 0:l.value:void 0}}catch(e){return null}}(this.paymentRequest);if(!o)throw new Error("Failed to decode payment request");this.paymentHash=o.paymentHash,this.satoshi=o.satoshi,this.timestamp=o.timestamp,this.expiry=o.expiry,this.createdDate=new Date(1e3*this.timestamp),this.expiryDate=new Date(1e3*(this.timestamp+this.expiry)),this.description=null!=(r=o.description)?r:null,this.verify=null!=(t=e.verify)?t:null,this.preimage=null!=(n=e.preimage)?n:null}var r=e.prototype;return r.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)}},r.validatePreimage=function(e){try{var r=this;return Promise.resolve(!(!e||!r.paymentHash)&&function(t,n){try{var o=Promise.resolve(l((i=e,Uint8Array.from(i.match(/.{1,2}/g).map(function(e){return parseInt(e,16)}))))).then(function(e){return r.paymentHash===e})}catch(e){return!1}var i;return o&&o.then?o.then(void 0,function(){return!1}):o}())}catch(e){return Promise.reject(e)}},r.verifyPayment=function(){try{var e=this;if(!e.verify)throw new Error("LNURL verify not available");return Promise.resolve(fetch(e.verify)).then(function(r){return Promise.resolve(r.json()).then(function(r){return r.preimage&&(e.preimage=r.preimage),r.settled})})}catch(e){return Promise.reject(e)}},e}(),D=function(e,r){var t=e.satoshi,n=e.comment,o=e.p,i=e.e,s=e.relays;void 0===r&&(r={});try{var a=r.nostr||globalThis.nostr;if(!a)throw new Error("nostr option or window.nostr is not available");var c=[["relays"].concat(s),["amount",t.toString()]];return o&&c.push(["p",o]),i&&c.push(["e",i]),Promise.resolve(a.getPublicKey()).then(function(e){var r={pubkey:e,created_at:Math.floor(Date.now()/1e3),kind:9734,tags:c,content:null!=n?n:""};return Promise.resolve(W(r)).then(function(e){return r.id=e,Promise.resolve(a.signEvent(r))})})}catch(i){return Promise.reject(i)}};function R(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 r=0;r<e.tags.length;r++){var t=e.tags[r];if(!Array.isArray(t))return!1;for(var n=0;n<t.length;n++)if("object"==typeof t[n])return!1}return!0}function $(e){if(!R(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 W(e){return l($(e))}function L(e,r){var t,n,o,i;return r&&e&&(n=(t=null==(o=e.names)?void 0:o[r])?null==(i=e.relays)?void 0:i[t]:void 0),[e,t,n]}var T={__proto__:null,generateZapEvent:D,validateEvent:R,serializeEvent:$,getEventHash:W,parseNostrResponse:L},O=/^((?:[^<>()[\]\\.,;:\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,}))$/,K=/*#__PURE__*/function(){function e(e,r){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:"https://api.getalby.com/lnurl"},this.options=Object.assign(this.options,r),this.parse(),this.webln=this.options.webln}var r=e.prototype;return r.parse=function(){var e=O.exec(this.address.toLowerCase());e&&(this.username=e[1],this.domain=e[2])},r.getWebLN=function(){return this.webln||globalThis.webln},r.fetch=function(){try{var e=this;return Promise.resolve(e.options.proxy?e.fetchWithProxy():e.fetchWithoutProxy())}catch(e){return Promise.reject(e)}},r.fetchWithProxy=function(){try{var e=this;return Promise.resolve(fetch(e.options.proxy+"/lightning-address-details?"+new URLSearchParams({ln:e.address}).toString())).then(function(r){return Promise.resolve(r.json()).then(function(r){return Promise.resolve(e.parseResponse(r.lnurlp,r.keysend,r.nostr)).then(function(){})})})}catch(e){return Promise.reject(e)}},r.fetchWithoutProxy=function(){try{var e=this;return e.domain&&e.username?Promise.resolve(fetch(e.lnurlpUrl())).then(function(r){return Promise.resolve(fetch(e.keysendUrl())).then(function(t){return Promise.resolve(fetch(e.nostrUrl())).then(function(n){function o(){function r(){function r(){return Promise.resolve(e.parseResponse(i,o,t)).then(function(){})}var t,s=function(){if(n.ok)return Promise.resolve(n.json()).then(function(e){t=e})}();return s&&s.then?s.then(r):r()}var o,s=function(){if(t.ok)return Promise.resolve(t.json()).then(function(e){o=e})}();return s&&s.then?s.then(r):r()}var i,s=function(){if(r.ok)return Promise.resolve(r.json()).then(function(e){i=e})}();return s&&s.then?s.then(o):o()})})}):Promise.resolve()}catch(e){return Promise.reject(e)}},r.lnurlpUrl=function(){return"https://"+this.domain+"/.well-known/lnurlp/"+this.username},r.keysendUrl=function(){return"https://"+this.domain+"/.well-known/keysend/"+this.username},r.nostrUrl=function(){return"https://"+this.domain+"/.well-known/nostr.json?name="+this.username},r.generateInvoice=function(e){try{var r,t=function(e){var t=r&&r.pr&&r.pr.toString();if(!t)throw new Error("Invalid pay service invoice");var n={pr:t};return r&&r.verify&&(n.verify=r.verify.toString()),new U(n)},n=this,o=function(){if(n.options.proxy)return Promise.resolve(fetch(n.options.proxy+"/generate-invoice?"+new URLSearchParams(a({ln:n.address},e)).toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e.invoice})});if(!n.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!n.lnurlpData.callback||!f(n.lnurlpData.callback))throw new Error("Valid callback does not exist in lnurlpData");var t=new URL(n.lnurlpData.callback);return t.search=new URLSearchParams(e).toString(),Promise.resolve(fetch(t.toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e})})}();return Promise.resolve(o&&o.then?o.then(t):t())}catch(e){return Promise.reject(e)}},r.requestInvoice=function(e){try{var r=this;if(!r.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");var t=1e3*e.satoshi,n=r.lnurlpData,o=n.commentAllowed;if(!d({amount:t,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:t.toString()};return e.comment&&(i.comment=e.comment),e.payerdata&&(i.payerdata=JSON.stringify(e.payerdata)),Promise.resolve(r.generateInvoice(i))}catch(e){return Promise.reject(e)}},r.boost=function(e,r){void 0===r&&(r=0);try{var t=this;if(!t.keysendData)throw new Error("No keysendData available. Please call fetch() first.");var n=t.keysendData,o=n.destination,s=n.customKey,a=n.customValue,c=t.getWebLN();if(!c)throw new Error("WebLN not available");return Promise.resolve(i({destination:o,customKey:s,customValue:a,amount:r,boost:e},{webln:c}))}catch(e){return Promise.reject(e)}},r.zapInvoice=function(e,r){var t=e.satoshi,n=e.comment,o=e.relays,i=e.e;void 0===r&&(r={});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*t,u=s.lnurlpData,l=u.allowsNostr;if(!d({amount:c,min:u.min,max:u.max}))throw new Error("Invalid amount");if(!l)throw new Error("Your provider does not support zaps");return Promise.resolve(D({satoshi:c,comment:n,p:a,e:i,relays:o},r)).then(function(e){var r={amount:c.toString(),nostr:JSON.stringify(e)};return Promise.resolve(s.generateInvoice(r))})}catch(i){return Promise.reject(i)}},r.zap=function(e,r){void 0===r&&(r={});try{var t=this.zapInvoice(e,r),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(t).then(function(r){return e.call(n,r.paymentRequest)})})}catch(e){return Promise.reject(e)}},r.parseResponse=function(e,r,t){try{var n=function(){if(r&&(o.keysendData=function(e){if("keysend"!==e.tag)throw new Error("Invalid keysend params");if("OK"!==e.status)throw new Error("Keysend status not OK");if(!("customKey"in e.customData[0])||"696969"!=e.customData[0].customKey)throw new Error("Unable to find customKey");if(!("customValue"in e.customData[0])||!e.customData[0].customValue)throw new Error("Unable to find customValue");if(!e.pubkey)throw new Error("Pubkey does not exist");return{destination:e.pubkey,customKey:e.customData[0].customKey,customValue:e.customData[0].customValue}}(r)),t){var e=L(t,o.username);o.nostrData=e[0],o.nostrPubkey=e[1],o.nostrRelays=e[2]}},o=this,i=function(){if(e)return Promise.resolve(function(e){try{var r=function(){for(var r="",a="",c="",u=0;u<n.length;u++){var l=n[u],h=l[0],f=l[1];switch(h){case"text/plain":a=f;break;case"text/identifier":c=f;break;case"image/png;base64":case"image/jpeg;base64":r="data:"+h+","+f}}var d,m=e.payerData;try{d=new URL(t).hostname}catch(e){}return{callback:t,fixed:i===s,min:i,max:s,domain:d,metadata:n,metadataHash:o,identifier:c,description:a,image:r,payerData:m,commentAllowed:Number(e.commentAllowed)||0,rawData:e,allowsNostr:e.allowsNostr||!1}};if("payRequest"!==e.tag)throw new Error("Invalid pay service params");var t=(e.callback+"").trim();if(!f(t))throw new Error("Callback must be a valid url");var n,o,i=Math.ceil(Number(e.minSendable||0)),s=Math.floor(Number(e.maxSendable));if(!i||!s||i>s)throw new Error("Invalid pay service params");var a=function(r,t){try{var i=(n=JSON.parse(e.metadata+""),Promise.resolve(l(e.metadata+"")).then(function(e){o=e}))}catch(e){return t()}return i&&i.then?i.then(void 0,t):i}(0,function(){return n=[],Promise.resolve(l("[]")).then(function(e){o=e})});return Promise.resolve(a&&a.then?a.then(r):r())}catch(e){return Promise.reject(e)}}(e)).then(function(e){o.lnurlpData=e})}();return Promise.resolve(i&&i.then?i.then(n):n())}catch(e){return Promise.reject(e)}},e}(),B=function(e){try{var r="https://getalby.com/api/rates/"+e.toLowerCase()+".json";return Promise.resolve(fetch(r)).then(function(e){return Promise.resolve(e.json()).then(function(e){return e.rate_float/1e8})})}catch(e){return Promise.reject(e)}},H=function(e){var r=e.satoshi;return Promise.resolve(B(e.currency)).then(function(e){return Number(r)*e})},V={__proto__:null,getFiatBtcRate:B,getFiatValue:H,getSatoshiValue:function(e){var r=e.amount;return Promise.resolve(B(e.currency)).then(function(e){return Math.floor(Number(r)/e)})},getFormattedFiatValue:function(e){var r=e.currency,t=e.locale;return t||(t="en"),Promise.resolve(H({satoshi:e.satoshi,currency:r})).then(function(e){return e.toLocaleString(t,{style:"currency",currency:r})})}};export{U as Invoice,K as LightningAddress,s as boostagrams,n as fetchWithL402,V as fiat,o as l402,T as nostr,i as sendBoostagram}; |
@@ -1,2 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("crypto-js/enc-hex.js"),require("crypto-js/sha256.js"),require("light-bolt11-decoder")):"function"==typeof define&&define.amd?define(["exports","crypto-js/enc-hex.js","crypto-js/sha256.js","light-bolt11-decoder"],t):t((e||self).lightningTools={},e.Hex,e.sha256,e.lightBolt11Decoder)}(this,function(e,t,r,n){function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=/*#__PURE__*/o(t),a=/*#__PURE__*/o(r),s=/*#__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}(),u={__proto__:null,MemoryStorage:s,NoStorage:/*#__PURE__*/function(){function e(e){}var t=e.prototype;return t.getItem=function(e){return null},t.setItem=function(e,t){},e}(),default:s},l=new s,c=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=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}(n),u=o.token||o.macaroon,l=o.invoice;return Promise.resolve(a.enable()).then(function(){return Promise.resolve(a.sendPayment(l)).then(function(r){return s.setItem(e,JSON.stringify({token:u,preimage:r.preimage})),t.headers.Authorization=i+" "+u+":"+r.preimage,Promise.resolve(fetch(e,t))})})}))};r||(r={});var i=r.headerKey||"L402",a=r.webln||globalThis.webln;if(!a)throw new Error("WebLN is missing");var s=r.store||l;t||(t={}),t.cache="no-store",t.mode="cors",t.headers||(t.headers={});var u=s.getItem(e),c=function(){if(u){var r=JSON.parse(u);return t.headers.Authorization=i+" "+r.token+":"+r.preimage,Promise.resolve(fetch(e,t)).then(function(e){return n=1,e})}}();return Promise.resolve(c&&c.then?c.then(o):o(c))}catch(e){return Promise.reject(e)}},h={__proto__:null,storage:u,fetchWithL402:c,default:c},m=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)}},f={__proto__:null,boost:m,default:m};function v(){return v=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},v.apply(this,arguments)}var d=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/,p=function(e){return!!e&&d.test(e)},y=function(e){var t=e.amount;return t>0&&t>=e.min&&t<=e.max},w=/*#__PURE__*/function(){function e(e){var t,r,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.paymentRequest=e.pr,!this.paymentRequest)throw new Error("Invalid payment request");var i=function(e){if(!e)return null;try{var t=n.decode(e);if(!t||!t.sections)return null;var r=t.sections.find(function(e){return"payment_hash"===e.name});if("payment_hash"!==(null==r?void 0:r.name)||!r.value)return null;var o=r.value,i=t.sections.find(function(e){return"amount"===e.name});if("amount"!==(null==i?void 0:i.name)||void 0===i.value)return null;var a=parseInt(i.value)/1e3,s=t.sections.find(function(e){return"expiry"===e.name}),u=t.sections.find(function(e){return"timestamp"===e.name});if("timestamp"!==(null==u?void 0:u.name)||!u.value)return null;var l=u.value;if("expiry"!==(null==s?void 0:s.name)||void 0===s.value)return null;var c=s.value,h=t.sections.find(function(e){return"description"===e.name});return{paymentHash:o,satoshi:a,timestamp:l,expiry:c,description:"description"===(null==h?void 0:h.name)?null==h?void 0:h.value:void 0}}catch(e){return null}}(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=new Date(1e3*(this.timestamp+this.expiry)),this.description=null!=(t=i.description)?t:null,this.verify=null!=(r=e.verify)?r:null,this.preimage=null!=(o=e.preimage)?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=a.default(i.default.parse(e)).toString(i.default);return this.paymentHash===t}catch(e){return!1}},t.verifyPayment=function(){try{var e=this;if(!e.verify)throw new Error("LNURL verify not available");return Promise.resolve(fetch(e.verify)).then(function(t){return Promise.resolve(t.json()).then(function(t){return t.preimage&&(e.preimage=t.preimage),t.settled})})}catch(e){return Promise.reject(e)}},e}(),g=function(e,t){var r=e.satoshi,n=e.comment,o=e.p,i=e.e,a=e.relays;void 0===t&&(t={});try{var s=t.nostr||globalThis.nostr;if(!s)throw new Error("nostr option or window.nostr is not available");var u=[["relays"].concat(a),["amount",r.toString()]];return o&&u.push(["p",o]),i&&u.push(["e",i]),Promise.resolve(s.getPublicKey()).then(function(e){var t={pubkey:e,created_at:Math.floor(Date.now()/1e3),kind:9734,tags:u,content:null!=n?n:""};return t.id=k(t),Promise.resolve(s.signEvent(t))})}catch(i){return Promise.reject(i)}};function b(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 P(e){if(!b(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 a.default(P(e)).toString(i.default)}function j(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 x={__proto__:null,generateZapEvent:g,validateEvent:b,serializeEvent:P,getEventHash:k,parseNostrResponse:j},D=/^((?:[^<>()[\]\\.,;:\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,}))$/,E=/*#__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:"https://api.getalby.com/lnurl"},this.options=Object.assign(this.options,t),this.parse(),this.webln=this.options.webln}var t=e.prototype;return t.parse=function(){var e=D.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){return Promise.resolve(t.json()).then(function(t){e.parseResponse(t.lnurlp,t.keysend,t.nostr)})})}catch(e){return Promise.reject(e)}},t.fetchWithoutProxy=function(){try{var e=this;return e.domain&&e.username?Promise.resolve(fetch(e.lnurlpUrl())).then(function(t){return Promise.resolve(fetch(e.keysendUrl())).then(function(r){return Promise.resolve(fetch(e.nostrUrl())).then(function(n){function o(){function t(){function t(){e.parseResponse(i,o,r)}var r,a=function(){if(n.ok)return Promise.resolve(n.json()).then(function(e){r=e})}();return a&&a.then?a.then(t):t()}var o,a=function(){if(r.ok)return Promise.resolve(r.json()).then(function(e){o=e})}();return a&&a.then?a.then(t):t()}var i,a=function(){if(t.ok)return Promise.resolve(t.json()).then(function(e){i=e})}();return a&&a.then?a.then(o):o()})})}):Promise.resolve()}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};return t&&t.verify&&(n.verify=t.verify.toString()),new w(n)},n=this,o=function(){if(n.options.proxy)return Promise.resolve(fetch(n.options.proxy+"/generate-invoice?"+new URLSearchParams(v({ln:n.address},e)).toString())).then(function(e){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||!p(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){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(!y({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,a=n.customValue,s=r.getWebLN();if(!s)throw new Error("WebLN not available");return Promise.resolve(m({destination:o,customKey:i,customValue:a,amount:t,boost:e},{webln:s}))}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 a=this;if(!a.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!a.nostrPubkey)throw new Error("Nostr Pubkey is missing");var s=a.nostrPubkey,u=1e3*r,l=a.lnurlpData,c=l.allowsNostr;if(!y({amount:u,min:l.min,max:l.max}))throw new Error("Invalid amount");if(!c)throw new Error("Your provider does not support zaps");return Promise.resolve(g({satoshi:u,comment:n,p:s,e:i,relays:o},t)).then(function(e){var t={amount:u.toString(),nostr:JSON.stringify(e)};return Promise.resolve(a.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.parseResponse=function(e,t,r){if(e&&(this.lnurlpData=function(e){if("payRequest"!==e.tag)throw new Error("Invalid pay service params");var t=(e.callback+"").trim();if(!p(t))throw new Error("Callback must be a valid url");var r,n,o=Math.ceil(Number(e.minSendable||0)),s=Math.floor(Number(e.maxSendable));if(!o||!s||o>s)throw new Error("Invalid pay service params");try{r=JSON.parse(e.metadata+""),n=a.default(e.metadata+"").toString(i.default)}catch(e){r=[],n=a.default("[]").toString(i.default)}for(var u="",l="",c="",h=0;h<r.length;h++){var m=r[h],f=m[0],v=m[1];switch(f){case"text/plain":l=v;break;case"text/identifier":c=v;break;case"image/png;base64":case"image/jpeg;base64":u="data:"+f+","+v}}var d,y=e.payerData;try{d=new URL(t).hostname}catch(e){}return{callback:t,fixed:o===s,min:o,max:s,domain:d,metadata:r,metadataHash:n,identifier:c,description:l,image:u,payerData:y,commentAllowed:Number(e.commentAllowed)||0,rawData:e,allowsNostr:e.allowsNostr||!1}}(e)),t&&(this.keysendData=function(e){if("keysend"!==e.tag)throw new Error("Invalid keysend params");if("OK"!==e.status)throw new Error("Keysend status not OK");if(!("customKey"in e.customData[0])||"696969"!=e.customData[0].customKey)throw new Error("Unable to find customKey");if(!("customValue"in e.customData[0])||!e.customData[0].customValue)throw new Error("Unable to find customValue");if(!e.pubkey)throw new Error("Pubkey does not exist");return{destination:e.pubkey,customKey:e.customData[0].customKey,customValue:e.customData[0].customValue}}(t)),r){var n=j(r,this.username);this.nostrData=n[0],this.nostrPubkey=n[1],this.nostrRelays=n[2]}},e}(),N=function(e){try{var t="https://getalby.com/api/rates/"+e.toLowerCase()+".json";return Promise.resolve(fetch(t)).then(function(e){return Promise.resolve(e.json()).then(function(e){return e.rate_float/1e8})})}catch(e){return Promise.reject(e)}},S=function(e){var t=e.satoshi;return Promise.resolve(N(e.currency)).then(function(e){return Number(t)*e})},_={__proto__:null,getFiatBtcRate:N,getFiatValue:S,getSatoshiValue:function(e){var t=e.amount;return Promise.resolve(N(e.currency)).then(function(e){return Math.floor(Number(t)/e)})},getFormattedFiatValue:function(e){var t=e.currency,r=e.locale;return r||(r="en"),Promise.resolve(S({satoshi:e.satoshi,currency:t})).then(function(e){return e.toLocaleString(r,{style:"currency",currency:t})})}};e.Invoice=w,e.LightningAddress=E,e.boostagrams=f,e.fetchWithL402=c,e.fiat=_,e.l402=h,e.nostr=x,e.sendBoostagram=m}); | ||
//# sourceMappingURL=index.umd.js.map | ||
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e||self).lightningTools={})}(this,function(e){var r=/*#__PURE__*/function(){function e(e){this.storage=void 0,this.storage=e||{}}var r=e.prototype;return r.getItem=function(e){return this.storage[e]},r.setItem=function(e,r){this.storage[e]=r},e}(),t={__proto__:null,MemoryStorage:r,NoStorage:/*#__PURE__*/function(){function e(e){}var r=e.prototype;return r.getItem=function(e){return null},r.setItem=function(e,r){},e}(),default:r},n=new r,o=function(e,r,t){try{var o,i=function(t){return o?t:(r.headers["Accept-Authenticate"]=s,Promise.resolve(fetch(e,r)).then(function(t){var n=t.headers.get("www-authenticate");if(!n)return t;var o=function(e){for(var r,t=e.replace("L402","").replace("LSAT","").trim(),n={},o=/(\w+)=("([^"]*)"|'([^']*)'|([^,]*))/g;null!==(r=o.exec(t));)n[r[1]]=r[3]||r[4]||r[5];return n}(n),i=o.token||o.macaroon,u=o.invoice;return Promise.resolve(a.enable()).then(function(){return Promise.resolve(a.sendPayment(u)).then(function(t){return c.setItem(e,JSON.stringify({token:i,preimage:t.preimage})),r.headers.Authorization=s+" "+i+":"+t.preimage,Promise.resolve(fetch(e,r))})})}))};t||(t={});var s=t.headerKey||"L402",a=t.webln||globalThis.webln;if(!a)throw new Error("WebLN is missing");var c=t.store||n;r||(r={}),r.cache="no-store",r.mode="cors",r.headers||(r.headers={});var u=c.getItem(e),l=function(){if(u){var t=JSON.parse(u);return r.headers.Authorization=s+" "+t.token+":"+t.preimage,Promise.resolve(fetch(e,r)).then(function(e){return o=1,e})}}();return Promise.resolve(l&&l.then?l.then(i):i(l))}catch(e){return Promise.reject(e)}},i={__proto__:null,storage:t,fetchWithL402:o,default:o},s=function(e,r){try{var t=e.boost;r||(r={});var n=r.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(t.value_msat/1e3),i={destination:e.destination,amount:o,customRecords:{7629169:JSON.stringify(t)}};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)}},a={__proto__:null,boost:s,default:s};function c(){return c=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},c.apply(this,arguments)}var u=function(e){try{var r="string"==typeof e?(new TextEncoder).encode(e):e;return Promise.resolve(crypto.subtle.digest("SHA-256",r)).then(function(e){return Array.from(new Uint8Array(e)).map(function(e){return e.toString(16).padStart(2,"0")}).join("")})}catch(e){return Promise.reject(e)}},l=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/,h=function(e){return!!e&&l.test(e)},f=function(e){var r=e.amount;return r>0&&r>=e.min&&r<=e.max},d=function(e){var r={exports:{}};return function(e,r){function t(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function n(...e){const r=(e,r)=>t=>e(r(t));return{encode:Array.from(e).reverse().reduce((e,t)=>e?r(e,t.encode):t.encode,void 0),decode:e.reduce((e,t)=>e?r(e,t.decode):t.decode,void 0)}}function o(e){return{encode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("alphabet.encode input should be an array of numbers");return r.map(r=>{if(t(r),r<0||r>=e.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${e.length})`);return e[r]})},decode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("alphabet.decode input should be array of strings");return r.map(r=>{if("string"!=typeof r)throw new Error(`alphabet.decode: not string element=${r}`);const t=e.indexOf(r);if(-1===t)throw new Error(`Unknown letter: "${r}". Allowed: ${e}`);return t})}}}function i(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("join.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return r.join(e)},decode:r=>{if("string"!=typeof r)throw new Error("join.decode input should be string");return r.split(e)}}}function s(e,r="="){if(t(e),"string"!=typeof r)throw new Error("padding chr should be string");return{encode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;t.length*e%8;)t.push(r);return t},decode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let n=t.length;if(n*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&t[n-1]===r;n--)if(!((n-1)*e%8))throw new Error("Invalid padding: string has too much padding");return t.slice(0,n)}}}function a(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:r=>e(r)}}function c(e,r,n){if(r<2)throw new Error(`convertRadix: wrong from=${r}, 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(t(e),e<0||e>=r)throw new Error(`Wrong integer: ${e}`)});;){let e=0,t=!0;for(let i=o;i<s.length;i++){const a=s[i],c=r*e+a;if(!Number.isSafeInteger(c)||r*e/r!==e||c-a!=r*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");t&&(s[i]?t=!1:o=i)}if(i.push(e),t)break}for(let r=0;r<e.length-1&&0===e[r];r++)i.push(0);return i.reverse()}Object.defineProperty(r,"__esModule",{value:!0}),r.bytes=r.stringToBytes=r.str=r.bytesToString=r.hex=r.utf8=r.bech32m=r.bech32=r.base58check=r.base58xmr=r.base58xrp=r.base58flickr=r.base58=r.base64url=r.base64=r.base32crockford=r.base32hex=r.base32=r.base16=r.utils=r.assertNumber=void 0,r.assertNumber=t;const u=(e,r)=>r?u(r,e%r):e,l=(e,r)=>e+(r-u(e,r));function h(e,r,n,o){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(r<=0||r>32)throw new Error(`convertRadix2: wrong from=${r}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(l(r,n)>32)throw new Error(`convertRadix2: carry overflow from=${r} to=${n} carryBits=${l(r,n)}`);let i=0,s=0;const a=2**n-1,c=[];for(const o of e){if(t(o),o>=2**r)throw new Error(`convertRadix2: invalid data word=${o} from=${r}`);if(i=i<<r|o,s+r>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${r}`);for(s+=r;s>=n;s-=n)c.push((i>>s-n&a)>>>0);i&=2**s-1}if(i=i<<n-s&a,!o&&s>=r)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 t(e),{encode:r=>{if(!(r instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return c(Array.from(r),256,e)},decode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(c(r,e,256))}}}function d(e,r=!1){if(t(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(l(8,e)>32||l(e,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return h(Array.from(t),8,e,!r)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(h(t,e,8,r))}}}function m(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...r){try{return e.apply(null,r)}catch(e){}}}function p(e,r){if(t(e),"function"!=typeof r)throw new Error("checksum fn should be function");return{encode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const n=r(t).slice(0,e),o=new Uint8Array(t.length+e);return o.set(t),o.set(n,t.length),o},decode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const n=t.slice(0,-e),o=r(n).slice(0,e),i=t.slice(-e);for(let r=0;r<e;r++)if(o[r]!==i[r])throw new Error("Invalid checksum");return n}}}r.utils={alphabet:o,chain:n,checksum:p,radix:f,radix2:d,join:i,padding:s},r.base16=n(d(4),o("0123456789ABCDEF"),i("")),r.base32=n(d(5),o("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),s(5),i("")),r.base32hex=n(d(5),o("0123456789ABCDEFGHIJKLMNOPQRSTUV"),s(5),i("")),r.base32crockford=n(d(5),o("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),i(""),a(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),r.base64=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),s(6),i("")),r.base64url=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),s(6),i(""));const y=e=>n(f(58),o(e),i(""));r.base58=y("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),r.base58flickr=y("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),r.base58xrp=y("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const v=[0,2,3,5,6,7,9,10,11];r.base58xmr={encode(e){let t="";for(let n=0;n<e.length;n+=8){const o=e.subarray(n,n+8);t+=r.base58.encode(o).padStart(v[o.length],"1")}return t},decode(e){let t=[];for(let n=0;n<e.length;n+=11){const o=e.slice(n,n+11),i=v.indexOf(o.length),s=r.base58.decode(o);for(let e=0;e<s.length-i;e++)if(0!==s[e])throw new Error("base58xmr: wrong padding");t=t.concat(Array.from(s.slice(s.length-i)))}return Uint8Array.from(t)}},r.base58check=e=>n(p(4,r=>e(e(r))),r.base58);const w=n(o("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),i("")),g=[996825010,642813549,513874426,1027748829,705979059];function b(e){const r=e>>25;let t=(33554431&e)<<5;for(let e=0;e<g.length;e++)1==(r>>e&1)&&(t^=g[e]);return t}function E(e,r,t=1){const n=e.length;let o=1;for(let r=0;r<n;r++){const t=e.charCodeAt(r);if(t<33||t>126)throw new Error(`Invalid prefix (${e})`);o=b(o)^t>>5}o=b(o);for(let r=0;r<n;r++)o=b(o)^31&e.charCodeAt(r);for(let e of r)o=b(o)^e;for(let e=0;e<6;e++)o=b(o);return o^=t,w.encode(h([o%2**30],30,5,!1))}function P(e){const r="bech32"===e?1:734539939,t=d(5),n=t.decode,o=t.encode,i=m(n);function s(e,t=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==t&&e.length>t)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${t})`);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=w.decode(s).slice(0,-6),c=E(i,a,r);if(!s.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:i,words:a}}return{encode:function(e,t,n=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof t);const o=e.length+7+t.length;if(!1!==n&&o>n)throw new TypeError(`Length ${o} exceeds limit ${n}`);return`${e=e.toLowerCase()}1${w.encode(t)}${E(e,t,r)}`},decode:s,decodeToBytes:function(e){const{prefix:r,words:t}=s(e,!1);return{prefix:r,words:t,bytes:n(t)}},decodeUnsafe:m(s),fromWords:n,fromWordsUnsafe:i,toWords:o}}r.bech32=P("bech32"),r.bech32m=P("bech32m"),r.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},r.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 x={utf8:r.utf8,hex:r.hex,base16:r.base16,base32:r.base32,base64:r.base64,base64url:r.base64url,base58:r.base58,base58xmr:r.base58xmr},_=`Invalid encoding type. Available types: ${Object.keys(x).join(", ")}`;r.bytesToString=(e,r)=>{if("string"!=typeof e||!x.hasOwnProperty(e))throw new TypeError(_);if(!(r instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return x[e].encode(r)},r.str=r.bytesToString,r.stringToBytes=(e,r)=>{if(!x.hasOwnProperty(e))throw new TypeError(_);if("string"!=typeof r)throw new TypeError("stringToBytes() expects string");return x[e].decode(r)},r.bytes=r.stringToBytes}(0,r.exports),r.exports}();const{bech32:m,hex:p,utf8:y}=d,v={bech32:"bc",pubKeyHash:0,scriptHash:5,validWitnessVersions:[0]},w={bech32:"tb",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},g={bech32:"bcrt",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},b={bech32:"sb",pubKeyHash:63,scriptHash:123,validWitnessVersions:[0]},E=["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"],P={m:BigInt(1e3),u:BigInt(1e6),n:BigInt(1e9),p:BigInt(1e12)},x=BigInt("2100000000000000000"),_=BigInt(1e11),A={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},k={};for(let e=0,r=Object.keys(A);e<r.length;e++){const t=r[e],n=A[r[e]].toString();k[n]=t}const j={1:e=>p.encode(m.fromWordsUnsafe(e)),16:e=>p.encode(m.fromWordsUnsafe(e)),13:e=>y.encode(m.fromWordsUnsafe(e)),19:e=>p.encode(m.fromWordsUnsafe(e)),23:e=>p.encode(m.fromWordsUnsafe(e)),27:e=>p.encode(m.fromWordsUnsafe(e)),6:S,24:S,3:function(e){const r=[];let t,n,o,i,s,a=m.fromWordsUnsafe(e);for(;a.length>0;)t=p.encode(a.slice(0,33)),n=p.encode(a.slice(33,41)),o=parseInt(p.encode(a.slice(41,45)),16),i=parseInt(p.encode(a.slice(45,49)),16),s=parseInt(p.encode(a.slice(49,51)),16),a=a.slice(51),r.push({pubkey:t,short_channel_id:n,fee_base_msat:o,fee_proportional_millionths:i,cltv_expiry_delta:s});return r},5:function(e){const r=e.slice().reverse().map(e=>[!!(1&e),!!(2&e),!!(4&e),!!(8&e),!!(16&e)]).reduce((e,r)=>e.concat(r),[]);for(;r.length<2*E.length;)r.push(!1);const t={};E.forEach((e,n)=>{let o;o=r[2*n]?"required":r[2*n+1]?"supported":"unsupported",t[e]=o});const n=r.slice(2*E.length);return t.extra_bits={start_bit:2*E.length,bits:n,has_required:n.reduce((e,r,t)=>t%2!=0?e||!1:e||r,!1)},t}};function N(e){return r=>({tagCode:parseInt(e),words:m.encode("unknown",r,Number.MAX_SAFE_INTEGER)})}function S(e){return e.reverse().reduce((e,r,t)=>e+r*Math.pow(32,t),0)}var I=/*#__PURE__*/function(){function e(e){var r,t,n;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.paymentRequest=e.pr,!this.paymentRequest)throw new Error("Invalid payment request");var o=function(e){if(!e)return null;try{var r=function(e,r){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 t=[],n=m.decode(e,Number.MAX_SAFE_INTEGER);e=e.toLowerCase();const o=n.prefix;let i=n.words,s=e.slice(o.length+1),a=i.slice(-104);i=i.slice(0,-104);let c=o.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);if(c&&!c[2]&&(c=o.match(/^ln(\S+)$/)),!c)throw new Error("Not a proper lightning payment request");t.push({name:"lightning_network",letters:"ln"});const u=c[1];let l;switch(u){case v.bech32:l=v;break;case w.bech32:l=w;break;case g.bech32:l=g;break;case b.bech32:l=b}if(!l||l.bech32!==u)throw new Error("Unknown coin bech32 prefix");t.push({name:"coin_network",letters:u,value:l});const h=c[2];let f;h?(f=function(e,r){let t,n;if(e.slice(-1).match(/^[munp]$/))t=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=t?o*_/P[t]:o*_;if("p"===t&&o%BigInt(10)!==BigInt(0)||i>x)throw new Error("Amount is outside of valid range");return i.toString()}(h+c[3]),t.push({name:"amount",letters:c[2]+c[3],value:f})):f=null,t.push({name:"separator",letters:"1"});const d=S(i.slice(0,7));let y,E,I,U;for(i=i.slice(7),t.push({name:"timestamp",letters:s.slice(0,7),value:d}),s=s.slice(7);i.length>0;){const e=i[0].toString();y=k[e]||"unknown_tag",E=j[e]||N(e),i=i.slice(1),I=S(i.slice(0,2)),i=i.slice(2),U=i.slice(0,I),i=i.slice(I),t.push({name:y,tag:s[0],letters:s.slice(0,3+I),value:E(U)}),s=s.slice(3+I)}t.push({name:"signature",letters:s.slice(0,104),value:p.encode(m.fromWordsUnsafe(a))}),s=s.slice(104),t.push({name:"checksum",letters:s});let D={paymentRequest:e,sections:t,get expiry(){let e=t.find(e=>"expiry"===e.name);if(e)return R("timestamp")+e.value},get route_hints(){return t.filter(e=>"route_hint"===e.name).map(e=>e.value)}};for(let e in A)"route_hint"!==e&&Object.defineProperty(D,e,{get:()=>R(e)});return D;function R(e){let r=t.find(r=>r.name===e);return r?r.value:void 0}}(e);if(!r||!r.sections)return null;var t=r.sections.find(function(e){return"payment_hash"===e.name});if("payment_hash"!==(null==t?void 0:t.name)||!t.value)return null;var n=t.value,o=r.sections.find(function(e){return"amount"===e.name});if("amount"!==(null==o?void 0:o.name)||void 0===o.value)return null;var i=parseInt(o.value)/1e3,s=r.sections.find(function(e){return"expiry"===e.name}),a=r.sections.find(function(e){return"timestamp"===e.name});if("timestamp"!==(null==a?void 0:a.name)||!a.value)return null;var c=a.value;if("expiry"!==(null==s?void 0:s.name)||void 0===s.value)return null;var u=s.value,l=r.sections.find(function(e){return"description"===e.name});return{paymentHash:n,satoshi:i,timestamp:c,expiry:u,description:"description"===(null==l?void 0:l.name)?null==l?void 0:l.value:void 0}}catch(e){return null}}(this.paymentRequest);if(!o)throw new Error("Failed to decode payment request");this.paymentHash=o.paymentHash,this.satoshi=o.satoshi,this.timestamp=o.timestamp,this.expiry=o.expiry,this.createdDate=new Date(1e3*this.timestamp),this.expiryDate=new Date(1e3*(this.timestamp+this.expiry)),this.description=null!=(r=o.description)?r:null,this.verify=null!=(t=e.verify)?t:null,this.preimage=null!=(n=e.preimage)?n:null}var r=e.prototype;return r.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)}},r.validatePreimage=function(e){try{var r=this;return Promise.resolve(!(!e||!r.paymentHash)&&function(t,n){try{var o=Promise.resolve(u((i=e,Uint8Array.from(i.match(/.{1,2}/g).map(function(e){return parseInt(e,16)}))))).then(function(e){return r.paymentHash===e})}catch(e){return!1}var i;return o&&o.then?o.then(void 0,function(){return!1}):o}())}catch(e){return Promise.reject(e)}},r.verifyPayment=function(){try{var e=this;if(!e.verify)throw new Error("LNURL verify not available");return Promise.resolve(fetch(e.verify)).then(function(r){return Promise.resolve(r.json()).then(function(r){return r.preimage&&(e.preimage=r.preimage),r.settled})})}catch(e){return Promise.reject(e)}},e}(),U=function(e,r){var t=e.satoshi,n=e.comment,o=e.p,i=e.e,s=e.relays;void 0===r&&(r={});try{var a=r.nostr||globalThis.nostr;if(!a)throw new Error("nostr option or window.nostr is not available");var c=[["relays"].concat(s),["amount",t.toString()]];return o&&c.push(["p",o]),i&&c.push(["e",i]),Promise.resolve(a.getPublicKey()).then(function(e){var r={pubkey:e,created_at:Math.floor(Date.now()/1e3),kind:9734,tags:c,content:null!=n?n:""};return Promise.resolve($(r)).then(function(e){return r.id=e,Promise.resolve(a.signEvent(r))})})}catch(i){return Promise.reject(i)}};function D(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 r=0;r<e.tags.length;r++){var t=e.tags[r];if(!Array.isArray(t))return!1;for(var n=0;n<t.length;n++)if("object"==typeof t[n])return!1}return!0}function R(e){if(!D(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 $(e){return u(R(e))}function W(e,r){var t,n,o,i;return r&&e&&(n=(t=null==(o=e.names)?void 0:o[r])?null==(i=e.relays)?void 0:i[t]:void 0),[e,t,n]}var L={__proto__:null,generateZapEvent:U,validateEvent:D,serializeEvent:R,getEventHash:$,parseNostrResponse:W},T=/^((?:[^<>()[\]\\.,;:\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,}))$/,O=/*#__PURE__*/function(){function e(e,r){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:"https://api.getalby.com/lnurl"},this.options=Object.assign(this.options,r),this.parse(),this.webln=this.options.webln}var r=e.prototype;return r.parse=function(){var e=T.exec(this.address.toLowerCase());e&&(this.username=e[1],this.domain=e[2])},r.getWebLN=function(){return this.webln||globalThis.webln},r.fetch=function(){try{var e=this;return Promise.resolve(e.options.proxy?e.fetchWithProxy():e.fetchWithoutProxy())}catch(e){return Promise.reject(e)}},r.fetchWithProxy=function(){try{var e=this;return Promise.resolve(fetch(e.options.proxy+"/lightning-address-details?"+new URLSearchParams({ln:e.address}).toString())).then(function(r){return Promise.resolve(r.json()).then(function(r){return Promise.resolve(e.parseResponse(r.lnurlp,r.keysend,r.nostr)).then(function(){})})})}catch(e){return Promise.reject(e)}},r.fetchWithoutProxy=function(){try{var e=this;return e.domain&&e.username?Promise.resolve(fetch(e.lnurlpUrl())).then(function(r){return Promise.resolve(fetch(e.keysendUrl())).then(function(t){return Promise.resolve(fetch(e.nostrUrl())).then(function(n){function o(){function r(){function r(){return Promise.resolve(e.parseResponse(i,o,t)).then(function(){})}var t,s=function(){if(n.ok)return Promise.resolve(n.json()).then(function(e){t=e})}();return s&&s.then?s.then(r):r()}var o,s=function(){if(t.ok)return Promise.resolve(t.json()).then(function(e){o=e})}();return s&&s.then?s.then(r):r()}var i,s=function(){if(r.ok)return Promise.resolve(r.json()).then(function(e){i=e})}();return s&&s.then?s.then(o):o()})})}):Promise.resolve()}catch(e){return Promise.reject(e)}},r.lnurlpUrl=function(){return"https://"+this.domain+"/.well-known/lnurlp/"+this.username},r.keysendUrl=function(){return"https://"+this.domain+"/.well-known/keysend/"+this.username},r.nostrUrl=function(){return"https://"+this.domain+"/.well-known/nostr.json?name="+this.username},r.generateInvoice=function(e){try{var r,t=function(e){var t=r&&r.pr&&r.pr.toString();if(!t)throw new Error("Invalid pay service invoice");var n={pr:t};return r&&r.verify&&(n.verify=r.verify.toString()),new I(n)},n=this,o=function(){if(n.options.proxy)return Promise.resolve(fetch(n.options.proxy+"/generate-invoice?"+new URLSearchParams(c({ln:n.address},e)).toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e.invoice})});if(!n.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!n.lnurlpData.callback||!h(n.lnurlpData.callback))throw new Error("Valid callback does not exist in lnurlpData");var t=new URL(n.lnurlpData.callback);return t.search=new URLSearchParams(e).toString(),Promise.resolve(fetch(t.toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e})})}();return Promise.resolve(o&&o.then?o.then(t):t())}catch(e){return Promise.reject(e)}},r.requestInvoice=function(e){try{var r=this;if(!r.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");var t=1e3*e.satoshi,n=r.lnurlpData,o=n.commentAllowed;if(!f({amount:t,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:t.toString()};return e.comment&&(i.comment=e.comment),e.payerdata&&(i.payerdata=JSON.stringify(e.payerdata)),Promise.resolve(r.generateInvoice(i))}catch(e){return Promise.reject(e)}},r.boost=function(e,r){void 0===r&&(r=0);try{var t=this;if(!t.keysendData)throw new Error("No keysendData available. Please call fetch() first.");var n=t.keysendData,o=n.destination,i=n.customKey,a=n.customValue,c=t.getWebLN();if(!c)throw new Error("WebLN not available");return Promise.resolve(s({destination:o,customKey:i,customValue:a,amount:r,boost:e},{webln:c}))}catch(e){return Promise.reject(e)}},r.zapInvoice=function(e,r){var t=e.satoshi,n=e.comment,o=e.relays,i=e.e;void 0===r&&(r={});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*t,u=s.lnurlpData,l=u.allowsNostr;if(!f({amount:c,min:u.min,max:u.max}))throw new Error("Invalid amount");if(!l)throw new Error("Your provider does not support zaps");return Promise.resolve(U({satoshi:c,comment:n,p:a,e:i,relays:o},r)).then(function(e){var r={amount:c.toString(),nostr:JSON.stringify(e)};return Promise.resolve(s.generateInvoice(r))})}catch(i){return Promise.reject(i)}},r.zap=function(e,r){void 0===r&&(r={});try{var t=this.zapInvoice(e,r),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(t).then(function(r){return e.call(n,r.paymentRequest)})})}catch(e){return Promise.reject(e)}},r.parseResponse=function(e,r,t){try{var n=function(){if(r&&(o.keysendData=function(e){if("keysend"!==e.tag)throw new Error("Invalid keysend params");if("OK"!==e.status)throw new Error("Keysend status not OK");if(!("customKey"in e.customData[0])||"696969"!=e.customData[0].customKey)throw new Error("Unable to find customKey");if(!("customValue"in e.customData[0])||!e.customData[0].customValue)throw new Error("Unable to find customValue");if(!e.pubkey)throw new Error("Pubkey does not exist");return{destination:e.pubkey,customKey:e.customData[0].customKey,customValue:e.customData[0].customValue}}(r)),t){var e=W(t,o.username);o.nostrData=e[0],o.nostrPubkey=e[1],o.nostrRelays=e[2]}},o=this,i=function(){if(e)return Promise.resolve(function(e){try{var r=function(){for(var r="",a="",c="",u=0;u<n.length;u++){var l=n[u],h=l[0],f=l[1];switch(h){case"text/plain":a=f;break;case"text/identifier":c=f;break;case"image/png;base64":case"image/jpeg;base64":r="data:"+h+","+f}}var d,m=e.payerData;try{d=new URL(t).hostname}catch(e){}return{callback:t,fixed:i===s,min:i,max:s,domain:d,metadata:n,metadataHash:o,identifier:c,description:a,image:r,payerData:m,commentAllowed:Number(e.commentAllowed)||0,rawData:e,allowsNostr:e.allowsNostr||!1}};if("payRequest"!==e.tag)throw new Error("Invalid pay service params");var t=(e.callback+"").trim();if(!h(t))throw new Error("Callback must be a valid url");var n,o,i=Math.ceil(Number(e.minSendable||0)),s=Math.floor(Number(e.maxSendable));if(!i||!s||i>s)throw new Error("Invalid pay service params");var a=function(r,t){try{var i=(n=JSON.parse(e.metadata+""),Promise.resolve(u(e.metadata+"")).then(function(e){o=e}))}catch(e){return t()}return i&&i.then?i.then(void 0,t):i}(0,function(){return n=[],Promise.resolve(u("[]")).then(function(e){o=e})});return Promise.resolve(a&&a.then?a.then(r):r())}catch(e){return Promise.reject(e)}}(e)).then(function(e){o.lnurlpData=e})}();return Promise.resolve(i&&i.then?i.then(n):n())}catch(e){return Promise.reject(e)}},e}(),K=function(e){try{var r="https://getalby.com/api/rates/"+e.toLowerCase()+".json";return Promise.resolve(fetch(r)).then(function(e){return Promise.resolve(e.json()).then(function(e){return e.rate_float/1e8})})}catch(e){return Promise.reject(e)}},B=function(e){var r=e.satoshi;return Promise.resolve(K(e.currency)).then(function(e){return Number(r)*e})},H={__proto__:null,getFiatBtcRate:K,getFiatValue:B,getSatoshiValue:function(e){var r=e.amount;return Promise.resolve(K(e.currency)).then(function(e){return Math.floor(Number(r)/e)})},getFormattedFiatValue:function(e){var r=e.currency,t=e.locale;return t||(t="en"),Promise.resolve(B({satoshi:e.satoshi,currency:r})).then(function(e){return e.toLocaleString(t,{style:"currency",currency:r})})}};e.Invoice=I,e.LightningAddress=O,e.boostagrams=a,e.fetchWithL402=o,e.fiat=H,e.l402=i,e.nostr=L,e.sendBoostagram=s}); |
@@ -15,5 +15,4 @@ import { InvoiceArgs } from "./types"; | ||
isPaid(): Promise<boolean>; | ||
validatePreimage(preimage: string): boolean; | ||
validatePreimage(preimage: string): Promise<boolean>; | ||
verifyPayment(): Promise<boolean>; | ||
} | ||
//# sourceMappingURL=invoice.d.ts.map |
export {}; | ||
//# sourceMappingURL=invoice.test.d.ts.map |
@@ -9,2 +9,1 @@ import { WebLNProvider } from "@webbtc/webln-types"; | ||
export default fetchWithL402; | ||
//# sourceMappingURL=index.d.ts.map |
export declare const parseL402: (input: string) => Record<string, string>; | ||
//# sourceMappingURL=parse.d.ts.map |
export {}; | ||
//# sourceMappingURL=parse.test.d.ts.map |
@@ -40,2 +40,1 @@ import Invoice from "./invoice"; | ||
export {}; | ||
//# sourceMappingURL=lightning-address.d.ts.map |
export {}; | ||
//# sourceMappingURL=lightning-address.test.d.ts.map |
@@ -26,2 +26,1 @@ type BoostOptions = { | ||
export default boost; | ||
//# sourceMappingURL=boostagrams.d.ts.map |
@@ -100,2 +100,1 @@ export type KeysendResponse = { | ||
}; | ||
//# sourceMappingURL=types.d.ts.map |
@@ -15,2 +15,1 @@ export declare const getFiatBtcRate: (currency: string) => Promise<number>; | ||
}) => Promise<string>; | ||
//# sourceMappingURL=fiat.d.ts.map |
@@ -10,2 +10,1 @@ type DecodedInvoice = { | ||
export {}; | ||
//# sourceMappingURL=invoice.d.ts.map |
@@ -12,2 +12,1 @@ import type { KeysendResponse } from "../types"; | ||
export declare const parseKeysendResponse: (data: KeySendRawData) => KeysendResponse; | ||
//# sourceMappingURL=keysend.d.ts.map |
@@ -8,3 +8,2 @@ import type { LnUrlPayResponse, LnUrlRawData } from "../types"; | ||
}) => boolean; | ||
export declare const parseLnUrlPayResponse: (data: LnUrlRawData) => LnUrlPayResponse; | ||
//# sourceMappingURL=lnurl.d.ts.map | ||
export declare const parseLnUrlPayResponse: (data: LnUrlRawData) => Promise<LnUrlPayResponse>; |
export {}; | ||
//# sourceMappingURL=lnurl.test.d.ts.map |
@@ -5,4 +5,3 @@ import { Event, NostrResponse, ZapArgs, ZapOptions } from "../types"; | ||
export declare function serializeEvent(evt: Event): string; | ||
export declare function getEventHash(event: Event): string; | ||
export declare function getEventHash(event: Event): Promise<string>; | ||
export declare function parseNostrResponse(nostrData: NostrResponse, username: string | undefined): readonly [NostrResponse, string | undefined, string[] | undefined]; | ||
//# sourceMappingURL=nostr.d.ts.map |
@@ -13,2 +13,1 @@ export declare class MemoryStorage { | ||
export default MemoryStorage; | ||
//# sourceMappingURL=storage.d.ts.map |
{ | ||
"name": "@getalby/lightning-tools", | ||
"version": "4.2.1", | ||
"version": "5.0.0", | ||
"description": "Collection of helpful building blocks and tools to develop Bitcoin Lightning web apps", | ||
@@ -39,17 +39,12 @@ "type": "module", | ||
"format:fix": "prettier --loglevel silent --write '**/*.(md|json)' 'src/**/*.(js|ts)' 'examples/**/*.js'", | ||
"build:browser": "cp src/window.js dist && browserify dist/window.js > dist/index.browser.js", | ||
"test": "jest", | ||
"clean": "rm -rf dist", | ||
"build": "microbundle && yarn build:browser", | ||
"build": "microbundle --no-sourcemap", | ||
"dev": "microbundle watch", | ||
"prepare": "husky install" | ||
}, | ||
"dependencies": { | ||
"crypto-js": "^4.1.1", | ||
"light-bolt11-decoder": "^3.0.0" | ||
}, | ||
"dependencies": {}, | ||
"devDependencies": { | ||
"@commitlint/cli": "^17.7.1", | ||
"@commitlint/config-conventional": "^17.7.0", | ||
"@types/crypto-js": "^4.1.1", | ||
"@types/jest": "^29.4.0", | ||
@@ -66,2 +61,3 @@ "@types/node": "^20.8.2", | ||
"jest-fetch-mock": "^3.0.3", | ||
"light-bolt11-decoder": "^3.0.0", | ||
"lint-staged": "^14.0.0", | ||
@@ -68,0 +64,0 @@ "microbundle": "^0.15.1", |
@@ -23,6 +23,16 @@ <p align="center"> | ||
```html | ||
<script type="module"> | ||
import { LightningAddress } from "https://esm.sh/@getalby/lightning-tools@5.0.0"; // jsdelivr.net, skypack.dev also work | ||
// use LightningAddress normally... | ||
(async () => { | ||
const ln = new LightningAddress("hello@getalby.com"); | ||
// fetch the LNURL data | ||
await ln.fetch(); | ||
// get the LNURL-pay data: | ||
console.log(ln.lnurlpData); | ||
})(); | ||
</script> | ||
``` | ||
// lightning-tools now available at window.lightningTools | ||
<script src="https://cdn.jsdelivr.net/npm/@getalby/lightning-tools@latest/dist/index.browser.js"></script> | ||
``` | ||
@@ -183,3 +193,3 @@ **This library relies on a global `fetch()` function which will work in [browsers](https://caniuse.com/?search=fetch) and node v18 or newer.** (In older versions you have to use a polyfill.) | ||
{}, | ||
{ store: window.localStorage }, | ||
{ store: window.localStorage } | ||
) | ||
@@ -203,3 +213,3 @@ .then((res) => res.json()) | ||
{}, | ||
{ webln: nwc }, | ||
{ webln: nwc } | ||
) | ||
@@ -217,3 +227,3 @@ .then((res) => res.json()) | ||
{}, | ||
{ store: new l402.storage.NoStorage() }, | ||
{ store: new l402.storage.NoStorage() } | ||
); | ||
@@ -269,4 +279,16 @@ ``` | ||
```js | ||
const lightningAddress = new LightningAddress("hello@getalby.com", { | ||
proxy: false, | ||
}); | ||
``` | ||
const lightningAddress = new LightningAddress("hello@getalby.com", {proxy: false}); | ||
## crypto dependency | ||
If you get an `crypto is not defined` in NodeJS error you have to import it first: | ||
```js | ||
import * as crypto from 'crypto'; // or 'node:crypto' | ||
globalThis.crypto = crypto as any; | ||
//or: global.crypto = require('crypto'); | ||
``` | ||
@@ -276,3 +298,3 @@ | ||
This library relies on a global fetch object which will work in browsers and node v18.x or newer. In old version yoi can manually install a global fetch option or polyfill if needed. | ||
This library relies on a global fetch object which will work in browsers and node v18.x or newer. In old version you can manually install a global fetch option or polyfill if needed. | ||
@@ -279,0 +301,0 @@ For example: |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
0
1
325
1
45
134096
26
693
- Removedcrypto-js@^4.1.1
- Removedlight-bolt11-decoder@^3.0.0
- Removed@scure/base@1.1.1(transitive)
- Removedcrypto-js@4.2.0(transitive)
- Removedlight-bolt11-decoder@3.2.0(transitive)