@tuwaio/quasar-sdk 0.7.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ import {a,b}from'./chunk-KLHEH7HS.js';import {a as a$1}from'./chunk-ZSO6HC5H.js';import {createStore}from'zustand/vanilla';import {ofetch}from'ofetch';function _e(){try{return globalThis.sessionStorage??null}catch{return null}}function sn(t){return async(...s)=>{try{return await t(...s)}catch(c){if(!(c instanceof a)||!c.code)throw c;return {refused:{code:c.code,message:c.message,status:c.status}}}}}var Ae="quasar-sdk:refundHandOvers",gt=5*6e4,St=3e4,kt=new Set([401,403,408,425,429]),_t=({status:t})=>t!==void 0&&t>=400&&t<500&&!kt.has(t);function X(t){if(t&&typeof t=="object"&&"refused"in t)throw Object.assign(new Error(t.refused.message),t.refused);return t}function Z(t){if(t instanceof a){let c=t.details?.invoice;return {code:t.code??"request_failed",message:t.message,status:t.status,issues:t.issues,...typeof c=="string"?{otherInvoice:c}:{}}}let s=t;return {code:typeof s?.code=="string"?s.code:"request_failed",message:t instanceof Error?t.message:String(t),...typeof s?.status=="number"&&{status:s.status},...typeof s?.text=="string"&&{text:s.text}}}function an(t){let s=t.pollMs??5e3,c=null,y=t.handOverStorage!==void 0?t.handOverStorage:_e(),S=()=>{c&&clearTimeout(c),c=null;},v=()=>{try{let g=JSON.parse(y?.getItem(Ae)??"[]");return Array.isArray(g)?g:[]}catch{return []}},b=g=>{try{g.length>0?y?.setItem(Ae,JSON.stringify(g)):y?.removeItem(Ae);}catch{}},q=g=>b(v().filter(C=>C.refundId!==g));return createStore()((g,C)=>{let L=l=>{S();let m=Date.now(),P=()=>{let T=Date.now()-m<gt?s:Math.max(s,St),E=setTimeout(()=>{t.get(l).then(X).then(O=>{c!==E||C().refund?.id!==l||(O.status==="confirmed"||O.status==="failed"?(S(),g({refund:O,phase:O.status})):(g({refund:O}),P()));},O=>{if(c!==E)return;let{status:U}=Z(O);U===401||U===403||U===404?S():P();});},T);c=E;};P();};return {phase:"idle",refund:null,instructions:null,error:null,sentTransaction:null,preview:async(l,m={})=>{if(g({error:null}),!t.preview)return null;try{return X(await t.preview(l,m))}catch(P){return g({error:Z(P)}),null}},start:async(l,m={})=>{S(),g({phase:"requesting",error:null,refund:null,instructions:null,sentTransaction:null});let P=v().find(T=>T.invoiceId===l);if(P)try{let T=X(await t.get(P.refundId));if(T.status==="requested"){let{txHash:E,from:O,instructions:U}=P;return g({phase:"awaitingTransfer",refund:T,instructions:U,sentTransaction:{txHash:E,from:O}}),!0}if(q(P.refundId),T.status==="submitted")return g({phase:"confirming",refund:T}),L(T.id),!0}catch(T){let E=Z(T);if(E.status!==404)return g({phase:"idle",error:E}),false;q(P.refundId);}try{let{refund:T,instructions:E}=X(await t.request(l,m));return g({phase:"awaitingTransfer",refund:T,instructions:E}),!0}catch(T){return g({phase:"idle",error:Z(T)}),false}},resume:(l,m)=>{S();let P=v().find(E=>E.refundId===l.id),T=P?{txHash:P.txHash,from:P.from}:C().refund?.id===l.id?C().sentTransaction:null;g({phase:"awaitingTransfer",refund:l,instructions:m,error:null,sentTransaction:T});},recheck:async()=>{let l=C().refund;if(!l)return false;try{let m=X(await t.get(l.id));if(C().refund?.id!==l.id)return !1;if(m.status==="requested"){let P=C().instructions;return P&&m.cryptoAmount&&m.cryptoAmount!==P.amount&&!C().sentTransaction?(g({refund:m,instructions:{...P,amount:m.cryptoAmount},error:{code:"refund_repriced",message:"Quasar priced this refund again: check the new amount"}}),!1):(g({refund:m,error:null}),!C().sentTransaction)}return q(l.id),m.status==="submitted"?(g({phase:"confirming",refund:m,error:null,sentTransaction:null}),L(l.id)):g({phase:m.status,refund:m,error:null,sentTransaction:null}),!1}catch(m){return g({error:Z(m)}),false}},submit:async l=>{let m=C().refund;if(!m)return g({error:{code:"refund_required",message:"Ask for the refund first"}}),false;let P={txHash:l.txHash,from:l.from},T=C().instructions;T&&b([...v().filter(E=>E.refundId!==m.id),{refundId:m.id,invoiceId:m.invoiceId,instructions:T,...P}]),g({phase:"submitting",error:null,sentTransaction:P});try{let E=X(await t.submit(m.id,l));return q(m.id),g({phase:"confirming",refund:E,sentTransaction:null}),L(m.id),!0}catch(E){let O=Z(E);return _t(O)?(q(m.id),g({phase:"awaitingTransfer",error:O,sentTransaction:null})):g({phase:"awaitingTransfer",error:O}),false}},stopFollowing:S,keepFollowing:()=>{let{phase:l,refund:m}=C();l==="confirming"&&m&&!c&&L(m.id);},reset:()=>{S(),g({phase:"idle",refund:null,instructions:null,error:null,sentTransaction:null});}}})}var wt=45e3,vt=9e4,Qe=(t,s="")=>`/v1/payments/checkout/${encodeURIComponent(t)}${s?`/${s}`:""}`;function Ge(t,s=a$1){let c=async(y,S,v=wt)=>{try{return await ofetch(Qe(t,y),{baseURL:s,method:S?"POST":"GET",timeout:v,...S?{body:S}:{}})}catch(b$1){throw b(b$1)}};return {view:()=>c(""),quote:y=>c("quote",y),payerProofMessage:y=>c("payer-proof/message",y),payerProof:y=>c("payer-proof",y),buyer:y=>c("buyer",y),locale:y=>c("locale",{locale:y}),submit:async({methodId:y,...S})=>{if(!y)return c("submit",S);try{return await c("submit",{...S,methodId:y})}catch(v){if(!(v instanceof a)||v.status!==400)throw v;return c("submit",S)}},relay:y=>c("relay",{signature:y},vt),permission:y=>c("permission",y),permissionRevoked:()=>c("permission/revoked",{}),url:y=>`${s.replace(/\/+$/,"")}${Qe(t,y)}`}}var st=new Set(["paid","held","expired","cancelled","refunded","partially_refunded"]),ee=new Set(["paid","held","refunded","partially_refunded"]),Ke=new Set(["open","processing","underpaid","expired","cancelled"]),N=new Set(["expired","cancelled"]),V=new Set(["open","processing","underpaid"]),Pe=new Set(["loading","selectMethod","awaitingPayment","underpaid","unconfirmed"]),Et=25*6e4,Rt=35*6e4,Ct=35*6e4,xt=60*6e4,Be=2e4,bt=3*6e4,Ot=45e3,It=1e4,Ve=(t,s)=>t===s||Date.parse(t??"")===Date.parse(s??""),At=new Set(["quoting","submitting"]),Ye=new Set(["checkout_not_found","origin_not_allowed","payments_disabled"]),Kt=new Set(["nonce_spent_unexplained","no_matching_transfer","reference_missing","too_early","tx_already_used","payer_mismatch","payer_unconfirmed","already_paid","quote_changed","too_many_parts","too_many_transfers","below_minimum","native_from_contract_unverifiable","invoice_not_payable","settlement_failed"]),Me="settlement_failed",de="nonce_spent_unexplained",Te="tx_already_used",at="too_many_payments",qt=[6e4,5*6e4,15*6e4],it=new Set(["timeout","not_found","replaced","nonce_spent"]),Mt="quasar-sdk:checkoutHandOvers:",Lt=new Set(["payer_mismatch","payer_unconfirmed"]),Ut="quote_changed",ut=new Set(["eoa","authorization"]);function ve(t){let[s,c,y,...S]=t.split(":");return !s||!c||!y||S.length>0?null:{namespace:s,chainId:`${s}:${c}`,address:s==="eip155"?y.toLowerCase():y}}var $e="The wallet did not sign the confirmation. It is free and moves no funds: sign it to pay from this wallet, or choose another wallet or method.",Dt=new Set(["payer_chain_mismatch","too_many_payers","native_from_contract","payer_blocked","payer_not_expected"]);function Nt(t){let s=t?.code;return s!==void 0&&(s.startsWith("payer_proof_")||Dt.has(s))}function Ht(t,s){let c=ve(s);return c?t.some(y=>{let S=ve(y.payer);return !S||S.namespace!==c.namespace||S.address!==c.address?false:y.kind&&ut.has(y.kind)||y.chainId===c.chainId}):false}var Je=[2e3,4e3,8e3,16e3,3e4],Wt=60*6e4,Ft=new Set(["too_many_pending"]),ze=t=>t instanceof a&&t.code==="too_many_payments",Xe=t=>t instanceof a&&t.code===Te;function Ze(t){if(!(t instanceof a)||t.code&&Ft.has(t.code))return true;let{status:s}=t;return s===void 0||s===408||s===429||s>=500}var Q=t=>t.startsWith("0x")||t.startsWith("0X")?t.toLowerCase():t;function et(t){return t.rejectedPayments?t.rejectedPayments.map(({txKey:s,original:c,userOpHash:y,reason:S,final:v,movedMoney:b,rechecked:q,held:g,otherInvoice:C})=>({keys:[s,c,y].filter(L=>!!L).map(Q),reason:S,final:v,movedMoney:b===true||Kt.has(S),rechecked:q===true,held:g===true,...typeof C=="string"?{otherInvoice:C}:{}})):t.rejectedTxKeys?.map(s=>({keys:[Q(s)],final:true}))??null}var jt=(t,s)=>t!==null&&!(Date.parse(t.expiresAt??"")<=s),Qt=new Set([...st,"underpaid"]),Gt=new Set(["quoting","awaitingPayment","submitting","confirming","unconfirmed"]);function j(t){switch(t){case "processing":return "confirming";case "paid":case "partially_refunded":return "paid";case "refunded":case "underpaid":case "held":case "expired":return t;case "cancelled":return "cancelled";default:return "selectMethod"}}function tt(t,s){if(t.invoice.status!=="open")return j(t.invoice.status);if(t.buyer.required)return "buyer";let c=t.quote?.expiresAt?Date.parse(t.quote.expiresAt):Number.NaN;return t.quote&&!(c<=s)?"awaitingPayment":"selectMethod"}var nt={payer_blocked:"blocked",payer_not_expected:"blocked",buyer_required:"buyer",invoice_expired:"expired",invoice_processing:"confirming",payment_on_its_way:"confirming",payer_mismatch:"underpaid",rest_method_mismatch:"underpaid",too_many_payments:"selectMethod"},Bt=new Set(["invoice_expired","invoice_processing","payment_on_its_way"]);function Y(t){let s=t.reason?{reason:t.reason}:{};if(t.reason===Me)return $t(t.rechecked);if(t.reason===de)return t.otherInvoice?le():ct(t.keys?.[0]);if(t.reason===Ut)return {code:"payment_mismatch",message:"This payment was sent or charged under an earlier price of this invoice, so it does not pay it. The merchant holds it to return it to the wallet that sent it, and the invoice can still be paid.",...s,held:true};if(t.reason==="too_many_parts")return {code:"payment_mismatch",message:"This invoice has taken as many parts as it can, so this transfer does not pay it. The merchant holds it to return it to the wallet that sent it; send the whole rest at once.",...s,held:true};if(t.reason&&Lt.has(t.reason))return {code:"payment_mismatch",message:t.held?"This transaction came from a wallet that did not confirm this invoice, so it does not pay it. The merchant returns it to the wallet that sent it, and the invoice can still be paid from the wallet that confirmed it.":"This transaction came from a wallet that did not confirm this invoice, so it does not pay it. If money left your wallet, contact the merchant.",...s,...t.held?{held:true}:{}};let c=t.otherInvoice?{otherInvoice:t.otherInvoice}:{};return t.held?{code:"payment_mismatch",message:"This transaction is tied to another invoice, which holds it for a refund to the wallet that sent it. It does not count for this invoice. If it was your payment for this invoice, contact the merchant.",...s,held:true,...c}:t.movedMoney?{...c,code:"payment_mismatch",message:"This transaction does not pay the invoice. If money left your wallet, contact the merchant.",...s}:t.final?{code:"payment_failed",message:"The payment did not go through. Try again.",...s}:le(t.reason,t.rechecked)}function le(t,s=false){return {code:"payment_unconfirmed",message:s?"The payment is not confirmed yet; Quasar checks it again for up to 24 hours. Check your wallet before paying again.":t?"The payment could not be confirmed. If it left your wallet, contact the merchant with the transaction hash.":"The payment could not be confirmed. Check your wallet before paying again.",...t?{reason:t}:{},...s?{rechecked:true}:{}}}var Vt=()=>({code:"payment_unconfirmed",message:"The payment has not reached Quasar yet; this page keeps handing it over. Check your wallet before paying again.",reason:"submit_retrying"}),Yt=()=>({code:"payment_unconfirmed",message:"This invoice takes no more payments, and Quasar does not follow this one. If it left your wallet, contact the merchant with the transaction hash.",reason:at}),we=()=>({code:"payment_unconfirmed",message:"Quasar did not receive the payment. If it left your wallet, contact the merchant with the transaction hash.",reason:"submit_failed"}),$t=(t=false)=>({code:"payment_unconfirmed",message:t?"The payment reached the network, but Quasar has not recorded it yet; it tries again daily for up to 30 days. Do not pay again; contact the merchant with the transaction hash.":"The payment reached the network, but Quasar could not record it. Do not pay again; contact the merchant with the transaction hash.",reason:Me,...t?{rechecked:true}:{}}),ct=t=>({code:"payment_unconfirmed",...t?{txKey:t}:{},message:"The wallet used the number of this transaction for another one, which Quasar could not find, so money may have left the wallet. Do not pay again yet: name that transaction, or contact the merchant.",reason:de}),Jt=()=>({code:"payment_unconfirmed",message:"This transaction was handed over for another invoice first. Quasar credits it to the invoice that the wallet which sent it confirmed, and this page shows the result. Do not pay again meanwhile.",status:409,reason:Te}),zt=t=>t?.code==="payment_unconfirmed"&&(t.reason===Te||t.reason===Me||t.reason===de||t.reason===at),rt=t=>t.find(s=>s.reason===de&&!s.otherInvoice)??null,Xt=t=>t?.code==="payment_unconfirmed"&&t.reason===Te,te=t=>(t.unresolvedPayments??0)>0,Zt=(t,s)=>!t.final&&!t.movedMoney&&!t.rechecked&&it.has(t.reason??"")&&s.unresolvedPayments===0,ot=t=>(t.unresolvedPayments??t.pendingPayments??0)>0,qe=t=>({status:t.invoice.status,ledgerSeq:0,txHash:null,amountPaid:t.invoice.amountPaid,quoteExpiresAt:t.quote?.expiresAt??null,pendingPayments:t.invoice.pendingPayments,rejectedTxKeys:t.invoice.rejectedTxKeys,rejectedPayments:t.invoice.rejectedPayments,paymentCountsUntil:t.invoice.paymentCountsUntil,unresolvedPayments:t.invoice.unresolvedPayments,onTimeTxKeys:t.invoice.onTimeTxKeys});function ce(t){if(t instanceof a){let{reason:s,originWallet:c}=t.details??{};return {code:t.code??"request_failed",message:t.message,status:t.status,issues:t.issues,...typeof s=="string"?{reason:s}:{},...typeof c=="string"?{originWallet:c}:{}}}return {code:"request_failed",message:t instanceof Error?t.message:String(t)}}function Sn(t){let s=t.api??Ge(t.token,t.baseUrl??a$1),c=t.pollMs??5e3,y=t.EventSource===void 0?globalThis.EventSource??null:t.EventSource,S=null,v=null,b=null,q=null,g=false,C=null,L=c,l=false,m=[],P=false,T=[],E=null,O=new Set,U=0,Ee=0,H=null,G=null,Re=false,W=new Map,fe=false,x=null,ne=()=>({error:x?Y(x):ct()}),Ce=0,he=null,me=[],Le=new Set,re=t.handOverStorage!==void 0?t.handOverStorage:t.api?null:_e(),xe=`${Mt}${t.token}`,be=()=>{try{let _=JSON.parse(re?.getItem(xe)??"[]");return Array.isArray(_)?_.filter(o=>typeof o=="object"&&o!==null&&typeof o.txKey=="string"&&typeof o.at=="number"):[]}catch{return []}},Ue=_=>{try{_.length>0?re?.setItem(xe,JSON.stringify(_)):re?.removeItem(xe);}catch{}},lt=_=>{if(!re)return;let o=be(),a=o.find(({txKey:A})=>A===_.txKey);Ue([...o.filter(({txKey:A})=>A!==_.txKey),{txKey:_.txKey,..._.from?{from:_.from}:{},..._.connectorType?{connectorType:_.connectorType}:{},..._.methodId?{methodId:_.methodId}:{},at:a?.at??Date.now()}]);},F=_=>{if(!re)return;let o=be();o.some(({txKey:a})=>a===_)&&Ue(o.filter(({txKey:a})=>a!==_));},De=({quote:_,checkout:o})=>[...o?.payerProofs??[],...me,..._?.payerProof?.proven===true&&_.payer!==null?[{payer:_.payer,chainId:ve(_.payer)?.chainId??"",kind:_.payerProof.kind??void 0}]:[]],dt=_=>{let o=_.checkout?.methods.find(({id:M})=>M===_.methodId)?.chainId,a=o?.split(":")[0];if(!o)return [];let A=new Map;for(let M of De(_)){let D=ve(M.payer);!D||D.namespace!==a||(M.kind&&ut.has(M.kind)||M.chainId===o)&&(A.has(D.address)||A.set(D.address,M.payer));}return [...A.values()]},Ne=_=>{let{payer:o}=_,a=_.checkout?.methods.find(({id:D})=>D===_.methodId),M=o!==null&&Le.has(o)?"before_quote":a?.payerProof??"none";return M==="none"||!a?"not_needed":o&&Ht(De(_),o)?"confirmed":o!==null&&o===he&&M==="before_quote"?"confirming":M==="before_quote"?"required":"unless_relayed"};return createStore()((_,o)=>{let a$1=e=>{let r={...o(),...e};_({...e,receiptUrl:r.phase==="paid"||r.phase==="refunded"?s.url("receipt"):null,paymasterUrl:r.quote?.gasless?.paymaster?s.url("paymaster"):null,logoUrl:r.checkout?.merchant.logo?s.url("logo"):null,payerProof:Ne(r),confirmedWallets:dt(r)});},A=(e,r)=>{let n=ce(e),u=o().invoiceStatus;if(u&&(ee.has(u)||N.has(u))){a$1({error:n,...At.has(o().phase)?{phase:j(u)}:{}});return}a$1({error:n,phase:nt[n.code]??r});},M=()=>{G&&clearTimeout(G),G=null,H=null,Re=false,o().followingUntil!==null&&a$1({followingUntil:null});},D=()=>{S?.close(),S=null,v&&clearInterval(v),v=null,b&&clearTimeout(b),b=null,q&&clearTimeout(q),q=null,M();},oe=()=>(m=[],P=false,{paymentOnTheWay:false}),Oe=()=>{P=true,U=Date.now(),O=new Set(T);},ft=(e,r)=>{if(!r)return null;let n=r.find(({keys:u})=>u.some(i=>m.includes(i)));return n||(e.pendingPayments!==0?null:r.find(({keys:u})=>u.some(i=>!O.has(i)))??null)},pe=e=>e==="underpaid"?{phase:"underpaid"}:e&&!V.has(e)?{phase:j(e)}:jt(o().quote,Date.now())?{phase:"awaitingPayment"}:{phase:"selectMethod",quote:null},ht=()=>s.view().then(e=>{if(l)return;let r=e.invoice.status==="underpaid"&&e.quote;a$1({checkout:e,...r?{quote:r,methodId:r.methodId}:{}});}).catch(()=>{}),He=()=>{let{invoiceStatus:e,paymentOnTheWay:r}=o();return !st.has(e??"")||N.has(e??"")&&(r||P)},mt=e=>{let r=o().paymentOnTheWay||P;D(),a$1(r?{...oe(),error:we(),phase:"unconfirmed"}:{error:ce(e),phase:"error"});},se=()=>{if(v||l)return;L=H!==null||g&&!o().paymentOnTheWay&&!P?Math.max(c,Be):c;let r=false,n=setInterval(()=>{if(r)return;r=true;let u=Ee;s.view().then(i=>{if(l||v!==n)return;let p=i.invoice.status==="underpaid"&&i.quote;a$1({checkout:i,...p?{quote:p,methodId:p.methodId}:{}}),ye(qe(i),i,u===Ee),We(i.quote);}).catch(i=>{v===n&&i instanceof a&&i.code==="checkout_not_found"&&mt(i);}).finally(()=>{r=false;});},L);v=n;},We=e=>{let{phase:r,quote:n}=o();r!=="awaitingPayment"||!n||!e||Ve(e.expiresAt,n.expiresAt)||(e.payer===n.payer&&e.methodId===n.methodId?a$1({quote:e}):a$1({quote:null,phase:"selectMethod"}));},Ie=(e,r=false)=>{let n=Date.parse(o().checkout?.invoice.dueAt??""),u=e==="cancelled"?Math.max(Date.now(),U)+Ct:Number.isFinite(n)?Math.max(Math.min(n,Date.now()),U)+Rt:Date.now()+xt;(H===null||r&&u>H)&&(H=u,G&&clearTimeout(G),G=setTimeout(()=>{G=null,!l&&(a$1({...oe(),invoicePaymentOnTheWay:false,...o().invoicePaymentUnresolved&&!o().error?{error:le(void 0,fe)}:{}}),D());},Math.max(0,H-Date.now())),a$1({followingUntil:new Date(H).toISOString()})),v&&L<Be&&(clearInterval(v),v=null,se());},ye=(e,r,n=true)=>{if(l)return;let{invoiceStatus:u,phase:i,checkout:p,paymentOnTheWay:f}=o(),w=Xt(o().error),h=et(e),k=new Set(T);h&&(T=h.flatMap(({keys:I})=>I));let d={invoiceStatus:e.status,txHash:e.txHash??o().txHash};if(n&&e.pendingPayments!==void 0&&(d.invoicePaymentOnTheWay=e.pendingPayments>0),n&&e.paymentCountsUntil!==void 0&&(d.paymentCountsUntil=e.paymentCountsUntil),n&&(e.unresolvedPayments!==void 0||e.pendingPayments!==void 0)&&(d.invoicePaymentUnresolved=ot(e)),n&&e.unresolvedPayments!==void 0&&(fe=te(e)),n&&e.onTimeTxKeys&&m.length>0&&o().paymentSentInTime!==true){let I=new Set(e.onTimeTxKeys.map(Q));d.paymentSentInTime=m.some(z=>I.has(z));}!r&&p&&e.amountPaid!==void 0&&e.amountPaid!==p.invoice.amountPaid&&(d.checkout={...p,invoice:{...p.invoice,amountPaid:e.amountPaid}});let B=f||P,ae=e.pendingPayments??0,ie=e.amountPaid!==void 0&&e.amountPaid!==null&&e.amountPaid!==E;ie&&(E=e.amountPaid);let J=u==="underpaid"&&e.status==="underpaid"&&!ie,R=null;B&&n&&Ke.has(e.status)&&(R=ft(e,h),!R&&(e.status==="open"||J)&&e.pendingPayments===0&&e.rejectedPayments&&(P||Date.now()-U>=Et)&&!(w&&(e.unresolvedPayments??0)>0)&&(R={final:false,rechecked:te(e)})),!R&&e.status==="open"&&u==="processing"&&ae===0&&(R=e.rejectedPayments?h?.find(({keys:I})=>I.some(z=>!k.has(z)))??{final:false,rechecked:te(e)}:{final:true});let Se=x;if(h&&(x=rt(h)),R&&x&&(R=x),R?.final)Object.assign(d,oe(),{error:Y(R)},e.status==="open"||e.status==="processing"||e.status==="underpaid"?pe(e.status):{phase:j(e.status)});else if(R)Object.assign(d,oe(),{error:Y(R),phase:V.has(e.status)?"unconfirmed":j(e.status)});else if(e.status==="open")i==="loading"&&(d.phase="selectMethod");else if(!J||!Gt.has(i)||i==="awaitingPayment"&&r?.invoice.restPayable===false){d.phase=j(e.status);let I=o().error;e.status==="underpaid"&&u!=="underpaid"&&I&&I.code!=="payment_mismatch"&&!x&&(d.error=null);}if(B&&!R){let I=n&&e.pendingPayments===0,z=ee.has(e.status)||e.status==="underpaid"&&!J||N.has(e.status)&&r!==void 0&&I;z&&Object.assign(d,oe()),z&&N.has(e.status)&&(d.invoicePaymentUnresolved??o().invoicePaymentUnresolved)&&(d.error=le(void 0,fe));}if(n&&ae>0&&Ke.has(e.status)){!P&&!(d.paymentOnTheWay??f)&&Oe();let I=w&&d.error===void 0;V.has(e.status)&&Pe.has(d.phase??i)&&!I&&(d.phase="confirming");}w&&d.error===void 0&&(e.status==="processing"||e.status==="underpaid"&&!J||ee.has(e.status))&&(d.error=null),x&&V.has(e.status)&&Pe.has(d.phase??i)?Object.assign(d,ne(),{phase:"unconfirmed"}):Se&&!x&&o().error?.reason===de&&!d.error&&Object.assign(d,{error:null},V.has(e.status)?pe(e.status):{}),a$1(d),He()?N.has(e.status)&&(Re=(e.pendingPayments??0)>0,Ie(e.status),S&&e.pendingPayments===0&&(S.close(),S=null,se())):D(),!r&&e.status!==u&&Qt.has(e.status)&&ht();let ue=o().quote;!r&&o().phase==="awaitingPayment"&&ue&&e.quoteExpiresAt&&e.quoteExpiresAt!==C&&!Ve(e.quoteExpiresAt,ue.expiresAt)&&(C=e.quoteExpiresAt,s.view().then(I=>{l||We(I.quote);}).catch(()=>{}));},ge=()=>{if(l||S||v||!He())return;if(!y)return se();let e=new y(s.url("events"));S=e;let r=()=>{b&&clearTimeout(b),b=setTimeout(()=>{b=null,!(S!==e||l)&&(e.close(),S=null,s.view().then(n=>{l||ye(qe(n),n);}).catch(()=>{}),ge());},Ot);};r(),e.addEventListener("ping",r),e.addEventListener("status",n=>{r();try{ye(JSON.parse(n.data));}catch{}}),e.onerror=()=>{if(S!==e)return;let{invoiceStatus:n,paymentOnTheWay:u}=o(),i=u||P,p=e.readyState===2;(p||N.has(n??"")&&i&&!Re)&&(e.close(),S=null,b&&clearTimeout(b),b=null,g=p,se(),p&&!q&&(q=setTimeout(()=>{q=null,!(l||!v||H!==null)&&(clearInterval(v),v=null,g=false,ge());},bt)));};},$=(e,r,n,u=false)=>{if(ee.has(n??"")||ee.has(o().invoiceStatus??"")){let{error:f,txKey:w}=o();f?.reason?.startsWith("submit_")&&w&&e.includes(w)&&a$1({error:null}),s.view().then(h=>{l||ye(qe(h),h);}).catch(()=>{});return}Ee+=1,U=Date.now(),P=false,m=[...m,...e.filter(f=>!!f).map(Q)],O=new Set(T.map(Q));let{invoiceStatus:i}=o(),p=i&&N.has(i)?i:null;a$1({txKey:r,paymentOnTheWay:true,paymentSentInTime:null,error:u?Jt():null,phase:p?j(p):u?"unconfirmed":"confirming"}),p&&Ie(p,true),v&&g&&H===null&&L>c&&(clearInterval(v),v=null,se()),ge();},Fe=async(e,r)=>{let n={txKey:e.txKey,...e.from?{from:e.from}:{},...e.connectorType?{connectorType:e.connectorType}:{},...e.methodId?{methodId:e.methodId}:{}};lt(n);let u=()=>ee.has(o().invoiceStatus??""),i=()=>N.has(o().invoiceStatus??""),p=h=>{u()||a$1({txKey:h,error:Yt(),...i()?{}:{phase:"unconfirmed"}}),f(0);},f=h=>{let k=qt[h];if(k===void 0||l)return;let d=setTimeout(()=>{W.delete(n.txKey),!l&&s.submit(n).then(B=>{l||(F(n.txKey),$([n.txKey],n.txKey,B?.status));},()=>f(h+1));},k);W.set(n.txKey,d);},w=r==="unconfirmed";!u()&&!i()&&!w&&a$1({phase:"submitting",error:null}),clearTimeout(W.get(n.txKey)),W.delete(n.txKey);try{let h=await s.submit(n);return F(n.txKey),$([n.txKey],n.txKey,h?.status),!0}catch(h){if(Xe(h))return F(n.txKey),$([n.txKey],n.txKey,void 0,true),false;if(ze(h))return p(n.txKey),false;if(h instanceof a&&Ye.has(h.code??""))return u()||a$1({txKey:n.txKey,error:we(),...i()?{}:{phase:"unconfirmed"}}),false;if(!Ze(h))return F(n.txKey),w&&!x||(x&&!u()?a$1({...ne(),...i()?{}:{phase:"unconfirmed"}}):u()||A(h,r==="submitting"?"awaitingPayment":r)),false;u()||a$1({txKey:n.txKey,...x?ne():{error:Vt()},...i()?{}:{phase:"unconfirmed"}});let k=Date.now()+Wt,d=()=>(o().error?.reason==="submit_retrying"||!!x)&&o().txKey===n.txKey,B=ae=>{let ie=Je[Math.min(ae,Je.length-1)];if(l)return;if(Date.now()+ie>k){d()&&a$1(x?ne():{error:we()});return}let J=setTimeout(()=>{W.delete(n.txKey),!l&&s.submit(n).then(R=>{l||(F(n.txKey),$([n.txKey],n.txKey,R?.status));}).catch(R=>{if(l)return;if(Ze(R))return B(ae+1);if(R instanceof a&&Ye.has(R.code??"")){d()&&a$1({error:we()});return}if(ze(R)){d()?p(n.txKey):F(n.txKey);return}if(F(n.txKey),Xe(R)){d()&&$([n.txKey],n.txKey,void 0,true);return}if(!d())return;if(x){a$1(ne());return}let Se=ce(R),ue=nt[Se.code],I=o().phase;a$1({error:Se,...ue?{phase:ue}:I==="unconfirmed"?pe(o().invoiceStatus):{}});});},ie);W.set(n.txKey,J);};return B(0),false}},pt=e=>{let r=be();if(r.length===0)return;let n=new Set([...e.invoice.rejectedTxKeys??[],...e.invoice.onTimeTxKeys??[]].map(Q)),u=r.filter(({txKey:i})=>!n.has(Q(i))).sort((i,p)=>i.at-p.at);for(let{txKey:i}of r)n.has(Q(i))&&F(i);(async()=>{for(let i of u){if(l)return;await Fe(i,o().phase);}})();};return {phase:"loading",checkout:null,invoiceStatus:null,methodId:null,payer:null,consentGiven:false,payerProof:"not_needed",confirmedWallets:[],quote:null,locale:null,txKey:null,paymentOnTheWay:false,invoicePaymentOnTheWay:false,paymentCountsUntil:null,invoicePaymentUnresolved:false,paymentSentInTime:null,followingUntil:null,txHash:null,error:null,receiptUrl:null,clockSkewMs:0,paymasterUrl:null,logoUrl:null,load:async()=>{a$1({phase:"loading",error:null});try{let e=await s.view(),{invoice:r}=e,n=et(r);n&&(T=n.flatMap(({keys:k})=>k)),E=r.amountPaid;let u=tt(e,Date.now()),i=null,p=(r.pendingPayments??0)>0&&Ke.has(r.status);p&&!o().paymentOnTheWay&&Oe(),p&&V.has(r.status)&&Pe.has(u)&&(u="confirming");let f=n?.[0],w=ot(r),h=r.status==="open"||r.status==="underpaid"||N.has(r.status);if(n&&(x=rt(n)),!p&&!o().paymentOnTheWay&&h){let k=!1;x?(i=Y(x),k=!0):f&&!f.final&&!Zt(f,r)?(i=Y(f),it.has(f.reason??"")&&!f.rechecked&&te(r)&&(i={...i,stillRead:!0}),k=!0):f?.reason==="unresolved_after_24h"?(i=Y(f),k=!0):w?(i=le(void 0,te(r)),k=!0):f?.movedMoney&&(i=Y(f)),k&&Pe.has(u)&&(u="unconfirmed");}r.unresolvedPayments!==void 0&&(fe=te(r)),a$1({checkout:e,invoiceStatus:r.status,locale:r.locale,quote:e.quote,methodId:e.quote?.methodId??o().methodId,payer:e.quote?.payer??o().payer,invoicePaymentOnTheWay:(r.pendingPayments??0)>0,invoicePaymentUnresolved:w,paymentCountsUntil:r.paymentCountsUntil??null,phase:u,error:i}),P&&N.has(r.status)&&Ie(r.status),ge(),pt(e);}catch(e){a$1({phase:"error",error:ce(e)});}},selectMethod:(e,r)=>{let{quote:n,phase:u,error:i}=o(),p=n&&n.methodId!==e;a$1({methodId:e,error:r?.keepError?i:null,...p?{quote:null,phase:u==="awaitingPayment"?"selectMethod":u}:{}});},setPayer:e=>{let{quote:r,phase:n,invoiceStatus:u,checkout:i,error:p}=o(),f=r&&r.payer!==e,w=e!==o().payer&&Nt(p)?{error:null}:{},h=(u??i?.invoice.status)==="underpaid",k=n==="blocked"&&e!==null&&e!==o().payer?{phase:h?"underpaid":"selectMethod",quote:h?r:null}:{};if(f&&h){a$1({payer:e,...w,phase:n==="awaitingPayment"?"underpaid":n,...k});return}a$1({payer:e,...w,...f?{quote:null,phase:n==="awaitingPayment"?"selectMethod":n}:{},...k});},clearError:()=>a$1({error:null}),setConsentGiven:e=>a$1({consentGiven:e,error:null}),releaseQuote:()=>{let{phase:e,invoiceStatus:r,checkout:n}=o();e==="awaitingPayment"&&((r??n?.invoice.status)==="underpaid"?a$1({error:null,phase:"underpaid"}):a$1({quote:null,error:null,phase:"selectMethod"}));},requestQuote:async()=>{let{methodId:e,payer:r,phase:n,checkout:u,consentGiven:i,invoiceStatus:p}=o();if(!e)return a$1({error:{code:"method_required",message:"Choose a payment method first"}}),null;let f=(p??u?.invoice.status)==="underpaid";if(u?.consent?.required&&!i&&!f)return a$1({error:{code:"consent_required",message:"Tick the consent of the checkout first"}}),null;if(o().payerProof==="required"||o().payerProof==="confirming")return a$1({error:{code:"payer_proof_required",message:"Confirm the paying wallet with a free signature first"}}),null;a$1({phase:"quoting",error:null});let w=()=>{let k=o().invoiceStatus;return k!==null&&!V.has(k)},h=()=>{let k=o().invoiceStatus;return k&&a$1({phase:j(k),error:null}),null};try{let k=await s.quote({methodId:e,...r?{payer:r}:{},...u?.consent&&i&&!f?{consentGiven:!0}:{}});if(w())return h();if(o().payer!==r||o().methodId!==e)return a$1({phase:f?"underpaid":"selectMethod"}),null;let d=Date.now()-Date.parse(k.lockedAt??"");return a$1({quote:k,phase:o().invoicePaymentOnTheWay?"confirming":"awaitingPayment",clockSkewMs:Number.isFinite(d)&&Math.abs(d)>It?d:0}),k}catch(k){if(k instanceof a&&k.code==="payer_proof_required"&&r&&Le.add(r),w())return h();let d=ce(k);return d.code==="payment_on_its_way"&&Oe(),f&&!Bt.has(d.code)?a$1({error:d,phase:"underpaid"}):A(k,n==="quoting"?"selectMethod":n),null}},confirmPayer:async e=>{let{payer:r}=o();if(!r)return a$1({error:{code:"payer_required",message:"Connect the paying wallet first"}}),false;if(o().payerProof==="confirmed"||o().payerProof==="not_needed")return a$1({error:null}),true;let{payerProofMessage:n,payerProof:u}=s;if(!n||!u)return a$1({error:{code:"request_failed",message:"The checkout calls cannot confirm a wallet (payerProofMessage)"}}),false;let i=++Ce;he=r,a$1({error:null});let p=(f,w)=>{f&&me.push(f);let h=i===Ce;h&&(he=null),!l&&(w===void 0||!h||o().payer!==r||Ne(o())==="confirmed"?a$1({}):w instanceof Error&&w.name==="PayerProofDeclined"?a$1({error:{code:"payer_proof_declined",message:$e}}):A(w,o().phase));};try{let f=await n({payer:r});if(f.proven)return p({payer:f.payer,chainId:f.chainId}),!0;let w;try{w=await e(f.message,f);}catch(k){let d=new Error(k instanceof Error?k.message:String(k));throw d.name="PayerProofDeclined",d}let h=await u({payer:r,message:f.message,signature:w});return p(h),!0}catch(f){return p(null,f),false}},abandonConfirmation:()=>{Ce++,he=null,a$1({});},setBuyer:async(e,r={})=>{a$1({error:null});try{let n=await s.buyer({buyer:e,...r.company?{company:!0}:{}});return a$1({checkout:n,phase:tt(n,Date.now())}),!0}catch(n){return A(n,o().phase),false}},setLocale:async e=>{let r=o().locale;a$1({locale:e});try{return await s.locale(e),!0}catch{return a$1({locale:r}),false}},submit:e=>Fe(e,o().phase),relay:async e=>{let r=o().phase;a$1({phase:"submitting",error:null});try{let n=await s.relay(e);return $([n.userOpHash,n.txHash],n.txHash??null),!0}catch(n){return A(n,r==="submitting"?"awaitingPayment":r),false}},grantPermission:async(e,r)=>{a$1({error:null});let n=async()=>{let{autoCharge:u}=await s.permission(e),i=o().checkout;return i&&a$1({checkout:{...i,autoCharge:u}}),true};try{try{return await n()}catch(u){let{payerProofMessage:i,payerProof:p}=s;if(!(u instanceof a&&u.code==="payer_proof_required")||!r||!i||!p)throw u;let w=await i({payer:e.payer});if(w.proven)me.push({payer:w.payer,chainId:w.chainId});else {let h;try{h=await r(w.message,w);}catch{return a$1({error:{code:"payer_proof_declined",message:$e}}),!1}me.push(await p({payer:e.payer,message:w.message,signature:h}));}return await n()}}catch(u){return A(u,o().phase),false}},permissionRevoked:async()=>{try{let{autoCharge:e}=await s.permissionRevoked(),r=o().checkout;return r&&a$1({checkout:{...r,autoCharge:e}}),e?.status!=="active"}catch{return null}},payAgain:()=>{o().phase!=="unconfirmed"||zt(o().error)||x||a$1({error:null,...pe(o().invoiceStatus)});},destroy:()=>{l=true;for(let e of W.values())clearTimeout(e);W.clear(),D();}}})}export{Sn as createCheckoutStore,an as createRefundStore,sn as refundAction};
@@ -1,2 +1,2 @@
1
- 'use strict';var o="https://api.tuwa.io",t="/v1/engine/pulsar/sync",s="/v1/engine/pulsar/history",e=n=>`${t}/${encodeURIComponent(n)}/hash`;
2
- exports.a=o;exports.b=t;exports.c=s;exports.d=e;
1
+ 'use strict';var o="https://api.tuwa.io",t="/v1/engine/pulsar/sync",s="/v1/engine/pulsar/history",e=n=>`${t}/${encodeURIComponent(n)}/hash`,p="/v1/payments";
2
+ exports.a=o;exports.b=t;exports.c=s;exports.d=e;exports.e=p;
@@ -0,0 +1 @@
1
+ var u=class extends Error{status;originalError;code;issues;details;constructor(e,n,s,r={}){super(e),this.name="QuasarSDKError",this.status=n,this.originalError=s,this.code=r.code,this.issues=r.issues,this.details=r.details;}};function g(t){let e=t,n=e.statusCode??e.response?.status,s=l(e.data??e.response?._data),r=s?.error,o=e.message??"Unknown Error",i={};if(typeof r=="string")o=typeof s?.statusCode=="number"&&typeof s.message=="string"?s.message:r,typeof s?.code=="string"&&(i={code:s.code});else if(typeof r=="object"&&r!==null){let{code:a,message:d,issues:c,...f}=r;typeof d=="string"&&(o=d),i={code:typeof a=="string"?a:void 0,issues:Array.isArray(c)?c:void 0,details:Object.keys(f).length>0?f:void 0};}else typeof s?.message=="string"&&(o=s.message);return (n===401||n===403)&&!i.code&&console.error("\u{1F6A8} [Quasar SDK] Auth Error. Check your Secret Key and scopes."),new u(`[Quasar SDK] Request Failed (${n}): ${o}`,n,e,i)}function l(t){let e=t;if(e instanceof ArrayBuffer||e instanceof Uint8Array)try{e=JSON.parse(new TextDecoder().decode(e));}catch{return}return typeof e=="object"&&e!==null?e:void 0}export{u as a,g as b};
@@ -0,0 +1 @@
1
+ 'use strict';var u=class extends Error{status;originalError;code;issues;details;constructor(e,n,s,r={}){super(e),this.name="QuasarSDKError",this.status=n,this.originalError=s,this.code=r.code,this.issues=r.issues,this.details=r.details;}};function g(t){let e=t,n=e.statusCode??e.response?.status,s=l(e.data??e.response?._data),r=s?.error,o=e.message??"Unknown Error",i={};if(typeof r=="string")o=typeof s?.statusCode=="number"&&typeof s.message=="string"?s.message:r,typeof s?.code=="string"&&(i={code:s.code});else if(typeof r=="object"&&r!==null){let{code:a,message:d,issues:c,...f}=r;typeof d=="string"&&(o=d),i={code:typeof a=="string"?a:void 0,issues:Array.isArray(c)?c:void 0,details:Object.keys(f).length>0?f:void 0};}else typeof s?.message=="string"&&(o=s.message);return (n===401||n===403)&&!i.code&&console.error("\u{1F6A8} [Quasar SDK] Auth Error. Check your Secret Key and scopes."),new u(`[Quasar SDK] Request Failed (${n}): ${o}`,n,e,i)}function l(t){let e=t;if(e instanceof ArrayBuffer||e instanceof Uint8Array)try{e=JSON.parse(new TextDecoder().decode(e));}catch{return}return typeof e=="object"&&e!==null?e:void 0}exports.a=u;exports.b=g;
@@ -0,0 +1,2 @@
1
+ var o="https://api.tuwa.io",t="/v1/engine/pulsar/sync",s="/v1/engine/pulsar/history",e=n=>`${t}/${encodeURIComponent(n)}/hash`,p="/v1/payments";
2
+ export{o as a,t as b,s as c,e as d,p as e};
package/dist/cli.cjs CHANGED
@@ -48,11 +48,11 @@ var path = __toESM(require("path"), 1);
48
48
  // package.json
49
49
  var package_default = {
50
50
  name: "@tuwaio/quasar-sdk",
51
- version: "0.7.3",
51
+ version: "0.8.0",
52
52
  private: false,
53
53
  author: "Oleksandr Tkach",
54
54
  license: "Apache-2.0",
55
- description: "L5 client of Quasar (TUWA): the Quasar API client for Quasar Cloud and self-hosted Quasar nodes (transaction sync and history for Pulsar), and the quasar-sdk CLI that relays webhooks to localhost.",
55
+ description: "L5 client of Quasar (TUWA): the Quasar API client for Quasar Cloud and self-hosted Quasar nodes (transaction sync and history for Pulsar, Payments invoices, refunds and subscriptions, webhook verification), and the quasar-sdk CLI that relays webhooks to localhost.",
56
56
  type: "module",
57
57
  main: "./dist/index.cjs",
58
58
  module: "./dist/index.js",
@@ -63,12 +63,23 @@ var package_default = {
63
63
  import: "./dist/index.js",
64
64
  require: "./dist/index.cjs"
65
65
  },
66
+ "./pulsar": {
67
+ types: "./dist/pulsar.d.ts",
68
+ import: "./dist/pulsar.js",
69
+ require: "./dist/pulsar.cjs"
70
+ },
66
71
  "./react": {
67
72
  types: "./dist/react.d.ts",
68
73
  import: "./dist/react.js",
69
74
  require: "./dist/react.cjs"
75
+ },
76
+ "./checkout": {
77
+ types: "./dist/checkout.d.ts",
78
+ import: "./dist/checkout.js",
79
+ require: "./dist/checkout.cjs"
70
80
  }
71
81
  },
82
+ sideEffects: false,
72
83
  publishConfig: {
73
84
  access: "public"
74
85
  },
@@ -105,12 +116,12 @@ var package_default = {
105
116
  ],
106
117
  repository: {
107
118
  type: "git",
108
- url: "git+https://github.com/TuwaIO/sdk.git",
119
+ url: "git+https://github.com/TuwaIO/quasar-client.git",
109
120
  directory: "packages/quasar-sdk"
110
121
  },
111
- homepage: "https://github.com/TuwaIO/sdk",
122
+ homepage: "https://github.com/TuwaIO/quasar-client",
112
123
  bugs: {
113
- url: "https://github.com/TuwaIO/sdk/issues"
124
+ url: "https://github.com/TuwaIO/quasar-client/issues"
114
125
  },
115
126
  contributors: [
116
127
  {
@@ -123,18 +134,26 @@ var package_default = {
123
134
  },
124
135
  peerDependencies: {
125
136
  "@tuwaio/pulsar-core": ">=0.10",
126
- "@tuwaio/siwx-react": ">=0.5"
137
+ "@tuwaio/siwx-react": ">=0.5",
138
+ zustand: "5.x.x"
127
139
  },
128
140
  peerDependenciesMeta: {
141
+ "@tuwaio/pulsar-core": {
142
+ optional: true
143
+ },
129
144
  "@tuwaio/siwx-react": {
130
145
  optional: true
146
+ },
147
+ zustand: {
148
+ optional: true
131
149
  }
132
150
  },
133
151
  devDependencies: {
134
- "@tuwaio/pulsar-core": "^0.11.1",
135
- "@tuwaio/siwx-react": "^0.6.5",
152
+ "@tuwaio/pulsar-core": "^0.12.4",
153
+ "@tuwaio/siwx-react": "^0.6.6",
136
154
  tsup: "^9.0.0",
137
- typescript: "6.0.3"
155
+ typescript: "6.0.3",
156
+ zustand: "^5.0.15"
138
157
  }
139
158
  };
140
159