@tuwaio/quasar-sdk 0.8.0 → 0.9.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.
- package/README.md +4 -1
- package/dist/checkout.cjs +1 -1
- package/dist/checkout.d.cts +40 -6
- package/dist/checkout.d.ts +40 -6
- package/dist/checkout.js +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/{errors-BCdisviA.d.cts → errors-4kLHVSws.d.cts} +6 -5
- package/dist/{errors-BCdisviA.d.ts → errors-4kLHVSws.d.ts} +6 -5
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +14 -7
- package/dist/index.d.ts +14 -7
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -84,6 +84,9 @@ const stop = watchBatchHashes(pulsarStore, (tx) => syncBatchHash(tx.txKey, tx.ha
|
|
|
84
84
|
|
|
85
85
|
### Payments
|
|
86
86
|
|
|
87
|
+
> [!IMPORTANT]
|
|
88
|
+
> Docs only, not live in production: Quasar Payments is still being built, so what this page describes is not available yet and may change.
|
|
89
|
+
|
|
87
90
|
A Payments app (chosen when the app is created, on a node that runs Payments) issues invoices that buyers pay in crypto on its payment page; Quasar checks the payment on-chain, issues the receipt and sends `payments.v1` webhooks.
|
|
88
91
|
|
|
89
92
|
```ts
|
|
@@ -129,7 +132,7 @@ export async function POST(request: Request) {
|
|
|
129
132
|
|
|
130
133
|
`verifyWebhook` refuses a delivery sent further from now than `toleranceSeconds` (default 300) as `stale`, so a captured webhook cannot be replayed later. It reads `sentAt`, set on every delivery attempt; a transaction webhook from an engine that does not send `sentAt` yet is checked by its `timestamp`, the time it was created, which its retries reuse: raise `toleranceSeconds` (1200 covers the retries) until the engine is updated. `toleranceSeconds: false` turns the check off.
|
|
131
134
|
|
|
132
|
-
`invoice.held` carries `data.hold`: why (`reason`: `late`, `aml`, `quote_expired`), its `txHash` and `senders`. A transfer that reached an invoice without being tied to it by proof never holds the invoice: Quasar records it as a held transfer of its own and sends `invoice.transfer_held` (`data.heldTransfer`: its `id`, `txHash`, `amount` in base units, `senders`, `reason`: `payer_mismatch`, `payer_unconfirmed`, `already_paid`, `quote_changed` or `too_many_parts`). List them with `listHeldTransfers` (`{ status: 'held' }` for those still to refund, `{ invoice }` for one invoice) and refund one as a whole to the wallet that sent it with `refundHeldTransfer(id)`, then `submitRefund` like any refund; the refund's `heldTransfer` names it. `invoice.transfer_hold_voided` tells you that the same transaction was proven to pay another invoice of yours since (`data.heldTransfer.paidInvoice`): nothing to refund. `payment.unverified` tells you that a smart wallet sent a native coin inside its own call, which no receipt shows: nothing was credited, so check the transaction yourself; a smart wallet is offered tokens only.
|
|
135
|
+
`invoice.held` carries `data.hold`: why (`reason`: `late`, `aml`, `quote_expired`), its `txHash` and `senders`. A transfer that reached an invoice without being tied to it by proof never holds the invoice: Quasar records it as a held transfer of its own and sends `invoice.transfer_held` (`data.heldTransfer`: its `id`, `txHash`, `amount` in base units, `senders`, `reason`: `payer_mismatch`, `payer_unconfirmed`, `reference_missing` (a Solana Pay transfer without the invoice's reference whose amount alone does not tie it to the invoice), `already_paid`, `quote_changed` or `too_many_parts`). List them with `listHeldTransfers` (`{ status: 'held' }` for those still to refund, `{ invoice }` for one invoice) and refund one as a whole to the wallet that sent it with `refundHeldTransfer(id)`, then `submitRefund` like any refund; the refund's `heldTransfer` names it. `invoice.transfer_hold_voided` tells you that the same transaction was proven to pay another invoice of yours since (`data.heldTransfer.paidInvoice`): nothing to refund. `payment.unverified` tells you that a smart wallet sent a native coin inside its own call, which no receipt shows: nothing was credited, so check the transaction yourself; a smart wallet is offered tokens only.
|
|
133
136
|
|
|
134
137
|
### Checkout in the browser
|
|
135
138
|
|
package/dist/checkout.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var chunkLGJMFD5H_cjs=require('./chunk-LGJMFD5H.cjs'),chunk2LAAWGEK_cjs=require('./chunk-2LAAWGEK.cjs'),vanilla=require('zustand/vanilla'),ofetch=require('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 chunkLGJMFD5H_cjs.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 chunkLGJMFD5H_cjs.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 vanilla.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=chunk2LAAWGEK_cjs.a){let c=async(y,S,v=wt)=>{try{return await ofetch.ofetch(Qe(t,y),{baseURL:s,method:S?"POST":"GET",timeout:v,...S?{body:S}:{}})}catch(b){throw chunkLGJMFD5H_cjs.b(b)}};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 chunkLGJMFD5H_cjs.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 chunkLGJMFD5H_cjs.a&&t.code==="too_many_payments",Xe=t=>t instanceof chunkLGJMFD5H_cjs.a&&t.code===Te;function Ze(t){if(!(t instanceof chunkLGJMFD5H_cjs.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 chunkLGJMFD5H_cjs.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??chunk2LAAWGEK_cjs.a),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 vanilla.createStore()((_,o)=>{let a=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({error:n,...At.has(o().phase)?{phase:j(u)}:{}});return}a({error:n,phase:nt[n.code]??r});},M=()=>{G&&clearTimeout(G),G=null,H=null,Re=false,o().followingUntil!==null&&a({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({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(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({checkout:i,...p?{quote:p,methodId:p.methodId}:{}}),ye(qe(i),i,u===Ee),We(i.quote);}).catch(i=>{v===n&&i instanceof chunkLGJMFD5H_cjs.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({quote:e}):a({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({...oe(),invoicePaymentOnTheWay:false,...o().invoicePaymentUnresolved&&!o().error?{error:le(void 0,fe)}:{}}),D());},Math.max(0,H-Date.now())),a({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(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({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({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({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({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 chunkLGJMFD5H_cjs.a&&Ye.has(h.code??""))return u()||a({txKey:n.txKey,error:we(),...i()?{}:{phase:"unconfirmed"}}),false;if(!Ze(h))return F(n.txKey),w&&!x||(x&&!u()?a({...ne(),...i()?{}:{phase:"unconfirmed"}}):u()||A(h,r==="submitting"?"awaitingPayment":r)),false;u()||a({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(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 chunkLGJMFD5H_cjs.a&&Ye.has(R.code??"")){d()&&a({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(ne());return}let Se=ce(R),ue=nt[Se.code],I=o().phase;a({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({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({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({phase:"error",error:ce(e)});}},selectMethod:(e,r)=>{let{quote:n,phase:u,error:i}=o(),p=n&&n.methodId!==e;a({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({payer:e,...w,phase:n==="awaitingPayment"?"underpaid":n,...k});return}a({payer:e,...w,...f?{quote:null,phase:n==="awaitingPayment"?"selectMethod":n}:{},...k});},clearError:()=>a({error:null}),setConsentGiven:e=>a({consentGiven:e,error:null}),releaseQuote:()=>{let{phase:e,invoiceStatus:r,checkout:n}=o();e==="awaitingPayment"&&((r??n?.invoice.status)==="underpaid"?a({error:null,phase:"underpaid"}):a({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({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({error:{code:"consent_required",message:"Tick the consent of the checkout first"}}),null;if(o().payerProof==="required"||o().payerProof==="confirming")return a({error:{code:"payer_proof_required",message:"Confirm the paying wallet with a free signature first"}}),null;a({phase:"quoting",error:null});let w=()=>{let k=o().invoiceStatus;return k!==null&&!V.has(k)},h=()=>{let k=o().invoiceStatus;return k&&a({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({phase:f?"underpaid":"selectMethod"}),null;let d=Date.now()-Date.parse(k.lockedAt??"");return a({quote:k,phase:o().invoicePaymentOnTheWay?"confirming":"awaitingPayment",clockSkewMs:Number.isFinite(d)&&Math.abs(d)>It?d:0}),k}catch(k){if(k instanceof chunkLGJMFD5H_cjs.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({error:d,phase:"underpaid"}):A(k,n==="quoting"?"selectMethod":n),null}},confirmPayer:async e=>{let{payer:r}=o();if(!r)return a({error:{code:"payer_required",message:"Connect the paying wallet first"}}),false;if(o().payerProof==="confirmed"||o().payerProof==="not_needed")return a({error:null}),true;let{payerProofMessage:n,payerProof:u}=s;if(!n||!u)return a({error:{code:"request_failed",message:"The checkout calls cannot confirm a wallet (payerProofMessage)"}}),false;let i=++Ce;he=r,a({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({}):w instanceof Error&&w.name==="PayerProofDeclined"?a({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({});},setBuyer:async(e,r={})=>{a({error:null});try{let n=await s.buyer({buyer:e,...r.company?{company:!0}:{}});return a({checkout:n,phase:tt(n,Date.now())}),!0}catch(n){return A(n,o().phase),false}},setLocale:async e=>{let r=o().locale;a({locale:e});try{return await s.locale(e),!0}catch{return a({locale:r}),false}},submit:e=>Fe(e,o().phase),relay:async e=>{let r=o().phase;a({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({error:null});let n=async()=>{let{autoCharge:u}=await s.permission(e),i=o().checkout;return i&&a({checkout:{...i,autoCharge:u}}),true};try{try{return await n()}catch(u){let{payerProofMessage:i,payerProof:p}=s;if(!(u instanceof chunkLGJMFD5H_cjs.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({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({checkout:{...r,autoCharge:e}}),e?.status!=="active"}catch{return null}},payAgain:()=>{o().phase!=="unconfirmed"||zt(o().error)||x||a({error:null,...pe(o().invoiceStatus)});},destroy:()=>{l=true;for(let e of W.values())clearTimeout(e);W.clear(),D();}}})}exports.createCheckoutStore=Sn;exports.createRefundStore=an;exports.refundAction=sn;
|
|
1
|
+
'use strict';var chunkLGJMFD5H_cjs=require('./chunk-LGJMFD5H.cjs'),chunk2LAAWGEK_cjs=require('./chunk-2LAAWGEK.cjs'),vanilla=require('zustand/vanilla'),ofetch=require('ofetch');function _e(){try{return globalThis.sessionStorage??null}catch{return null}}function ln(e){return async(...s)=>{try{return await e(...s)}catch(c){if(!(c instanceof chunkLGJMFD5H_cjs.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:e})=>e!==void 0&&e>=400&&e<500&&!kt.has(e);function X(e){if(e&&typeof e=="object"&&"refused"in e)throw Object.assign(new Error(e.refused.message),e.refused);return e}function Z(e){if(e instanceof chunkLGJMFD5H_cjs.a){let c=e.details?.invoice;return {code:e.code??"request_failed",message:e.message,status:e.status,issues:e.issues,...typeof c=="string"?{otherInvoice:c}:{}}}let s=e;return {code:typeof s?.code=="string"?s.code:"request_failed",message:e instanceof Error?e.message:String(e),...typeof s?.status=="number"&&{status:s.status},...typeof s?.text=="string"&&{text:s.text}}}function dn(e){let s=e.pollMs??5e3,c=null,y=e.handOverStorage!==void 0?e.handOverStorage:_e(),S=()=>{c&&clearTimeout(c),c=null;},v=()=>{try{let g=JSON.parse(y?.getItem(Ae)??"[]");return Array.isArray(g)?g:[]}catch{return []}},O=g=>{try{g.length>0?y?.setItem(Ae,JSON.stringify(g)):y?.removeItem(Ae);}catch{}},M=g=>O(v().filter(C=>C.refundId!==g));return vanilla.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(()=>{e.get(l).then(X).then(b=>{c!==E||C().refund?.id!==l||(b.status==="confirmed"||b.status==="failed"?(S(),g({refund:b,phase:b.status})):(g({refund:b}),P()));},b=>{if(c!==E)return;let{status:U}=Z(b);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}),!e.preview)return null;try{return X(await e.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 e.get(P.refundId));if(T.status==="requested"){let{txHash:E,from:b,instructions:U}=P;return g({phase:"awaitingTransfer",refund:T,instructions:U,sentTransaction:{txHash:E,from:b}}),!0}if(M(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;M(P.refundId);}try{let{refund:T,instructions:E}=X(await e.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 e.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 M(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&&O([...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 e.submit(m.id,l));return M(m.id),g({phase:"confirming",refund:E,sentTransaction:null}),L(m.id),!0}catch(E){let b=Z(E);return _t(b)?(M(m.id),g({phase:"awaitingTransfer",error:b,sentTransaction:null})):g({phase:"awaitingTransfer",error:b}),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=(e,s="")=>`/v1/payments/checkout/${encodeURIComponent(e)}${s?`/${s}`:""}`;function Ge(e,s=chunk2LAAWGEK_cjs.a){let c=async(y,S,v=wt)=>{try{return await ofetch.ofetch(Qe(e,y),{baseURL:s,method:S?"POST":"GET",timeout:v,...S?{body:S}:{}})}catch(O){throw chunkLGJMFD5H_cjs.b(O)}};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 chunkLGJMFD5H_cjs.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(e,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"]),D=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,Ot=3*6e4,bt=45e3,It=1e4,Ve=(e,s)=>e===s||Date.parse(e??"")===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"]),qe="settlement_failed",de="nonce_spent_unexplained",Te="tx_already_used",at="too_many_payments",Mt=[6e4,5*6e4,15*6e4],it=new Set(["timeout","not_found","replaced","nonce_spent"]),qt="quasar-sdk:checkoutHandOvers:",Lt=new Set(["payer_mismatch","payer_unconfirmed"]),Ut="reference_missing",Nt="quote_changed",ut=new Set(["eoa","authorization"]);function ve(e){let[s,c,y,...S]=e.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 Ht(e){let s=e?.code;return s!==void 0&&(s.startsWith("payer_proof_")||Dt.has(s))}function Wt(e,s){let c=ve(s);return c?e.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],Ft=60*6e4,jt=new Set(["too_many_pending"]),ze=e=>e instanceof chunkLGJMFD5H_cjs.a&&e.code==="too_many_payments",Xe=e=>e instanceof chunkLGJMFD5H_cjs.a&&e.code===Te;function Ze(e){if(!(e instanceof chunkLGJMFD5H_cjs.a)||e.code&&jt.has(e.code))return true;let{status:s}=e;return s===void 0||s===408||s===429||s>=500}var Q=e=>e.startsWith("0x")||e.startsWith("0X")?e.toLowerCase():e;function et(e){return e.rejectedPayments?e.rejectedPayments.map(({txKey:s,original:c,userOpHash:y,reason:S,final:v,movedMoney:O,rechecked:M,held:g,otherInvoice:C})=>({keys:[s,c,y].filter(L=>!!L).map(Q),reason:S,final:v,movedMoney:O===true||Kt.has(S),rechecked:M===true,held:g===true,...typeof C=="string"?{otherInvoice:C}:{}})):e.rejectedTxKeys?.map(s=>({keys:[Q(s)],final:true}))??null}var Qt=(e,s)=>e!==null&&!(Date.parse(e.expiresAt??"")<=s),Gt=new Set([...st,"underpaid"]),Bt=new Set(["quoting","awaitingPayment","submitting","confirming","unconfirmed"]);function j(e){switch(e){case "processing":return "confirming";case "paid":case "partially_refunded":return "paid";case "refunded":case "underpaid":case "held":case "expired":return e;case "cancelled":return "cancelled";default:return "selectMethod"}}function tt(e,s){if(e.invoice.status!=="open")return j(e.invoice.status);if(e.buyer.required)return "buyer";let c=e.quote?.expiresAt?Date.parse(e.quote.expiresAt):Number.NaN;return e.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"},Vt=new Set(["invoice_expired","invoice_processing","payment_on_its_way"]);function Y(e){return {...Jt(e),...$t(e)}}var Yt=new Set(["reverted"]);function $t(e){let s=e.keys?.[0];return s?e.movedMoney||e.reason!==void 0&&Yt.has(e.reason)?{txKey:s}:{}:{}}function Jt(e){let s=e.reason?{reason:e.reason}:{};if(e.reason===qe)return Zt(e.rechecked);if(e.reason===de)return e.otherInvoice?le():ct(e.keys?.[0]);if(e.reason===Nt)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(e.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(e.reason&&Lt.has(e.reason))return {code:"payment_mismatch",message:e.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,...e.held?{held:true}:{}};if(e.reason===Ut&&e.held)return {code:"payment_mismatch",message:"This transfer arrived without the Solana Pay reference of this invoice, and its amount alone does not tie it to the invoice, so it does not pay it. The merchant returns it to the wallet that sent it, and the invoice can still be paid.",...s,held:true};let c=e.otherInvoice?{otherInvoice:e.otherInvoice}:{};return e.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}:e.movedMoney?{...c,code:"payment_mismatch",message:"This transaction does not pay the invoice. If money left your wallet, contact the merchant.",...s}:e.final?{code:"payment_failed",message:"The payment did not go through. Try again.",...s}:le(e.reason,e.rechecked)}function le(e,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.":e?"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.",...e?{reason:e}:{},...s?{rechecked:true}:{}}}var zt=()=>({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"}),Xt=()=>({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"}),Zt=(e=false)=>({code:"payment_unconfirmed",message:e?"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:qe,...e?{rechecked:true}:{}}),ct=e=>({code:"payment_unconfirmed",...e?{txKey:e}:{},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}),en=()=>({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}),tn=e=>e?.code==="payment_unconfirmed"&&(e.reason===Te||e.reason===qe||e.reason===de||e.reason===at),rt=e=>e.find(s=>s.reason===de&&!s.otherInvoice)??null,nn=e=>e?.code==="payment_unconfirmed"&&e.reason===Te,te=e=>(e.unresolvedPayments??0)>0,rn=(e,s)=>!e.final&&!e.movedMoney&&!e.rechecked&&it.has(e.reason??"")&&s.unresolvedPayments===0,ot=e=>(e.unresolvedPayments??e.pendingPayments??0)>0,Me=e=>({status:e.invoice.status,ledgerSeq:0,txHash:null,amountPaid:e.invoice.amountPaid,quoteExpiresAt:e.quote?.expiresAt??null,pendingPayments:e.invoice.pendingPayments,rejectedTxKeys:e.invoice.rejectedTxKeys,rejectedPayments:e.invoice.rejectedPayments,paymentCountsUntil:e.invoice.paymentCountsUntil,unresolvedPayments:e.invoice.unresolvedPayments,onTimeTxKeys:e.invoice.onTimeTxKeys});function ce(e){if(e instanceof chunkLGJMFD5H_cjs.a){let{reason:s,originWallet:c}=e.details??{};return {code:e.code??"request_failed",message:e.message,status:e.status,issues:e.issues,...typeof s=="string"?{reason:s}:{},...typeof c=="string"?{originWallet:c}:{}}}return {code:"request_failed",message:e instanceof Error?e.message:String(e)}}function wn(e){let s=e.api??Ge(e.token,e.baseUrl??chunk2LAAWGEK_cjs.a),c=e.pollMs??5e3,y=e.EventSource===void 0?globalThis.EventSource??null:e.EventSource,S=null,v=null,O=null,M=null,g=false,C=null,L=c,l=false,m=[],P=false,T=[],E=null,b=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=e.handOverStorage!==void 0?e.handOverStorage:e.api?null:_e(),xe=`${qt}${e.token}`,Oe=()=>{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=Oe(),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=Oe();o.some(({txKey:a})=>a===_)&&Ue(o.filter(({txKey:a})=>a!==_));},Ne=({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:q})=>q===_.methodId)?.chainId,a=o?.split(":")[0];if(!o)return [];let A=new Map;for(let q of Ne(_)){let N=ve(q.payer);!N||N.namespace!==a||(q.kind&&ut.has(q.kind)||q.chainId===o)&&(A.has(N.address)||A.set(N.address,q.payer));}return [...A.values()]},De=_=>{let{payer:o}=_,a=_.checkout?.methods.find(({id:N})=>N===_.methodId),q=o!==null&&Le.has(o)?"before_quote":a?.payerProof??"none";return q==="none"||!a?"not_needed":o&&Wt(Ne(_),o)?"confirmed":o!==null&&o===he&&q==="before_quote"?"confirming":q==="before_quote"?"required":"unless_relayed"};return vanilla.createStore()((_,o)=>{let a=t=>{let r={...o(),...t};_({...t,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:De(r),confirmedWallets:dt(r)});},A=(t,r)=>{let n=ce(t),u=o().invoiceStatus;if(u&&(ee.has(u)||D.has(u))){a({error:n,...At.has(o().phase)?{phase:j(u)}:{}});return}a({error:n,phase:nt[n.code]??r});},q=()=>{G&&clearTimeout(G),G=null,H=null,Re=false,o().followingUntil!==null&&a({followingUntil:null});},N=()=>{S?.close(),S=null,v&&clearInterval(v),v=null,O&&clearTimeout(O),O=null,M&&clearTimeout(M),M=null,q();},oe=()=>(m=[],P=false,{paymentOnTheWay:false}),be=()=>{P=true,U=Date.now(),b=new Set(T);},ft=(t,r)=>{if(!r)return null;let n=r.find(({keys:u})=>u.some(i=>m.includes(i)));return n||(t.pendingPayments!==0?null:r.find(({keys:u})=>u.some(i=>!b.has(i)))??null)},pe=t=>t==="underpaid"?{phase:"underpaid"}:t&&!V.has(t)?{phase:j(t)}:Qt(o().quote,Date.now())?{phase:"awaitingPayment"}:{phase:"selectMethod",quote:null},ht=()=>s.view().then(t=>{if(l)return;let r=t.invoice.status==="underpaid"&&t.quote;a({checkout:t,...r?{quote:r,methodId:r.methodId}:{}});}).catch(()=>{}),He=()=>{let{invoiceStatus:t,paymentOnTheWay:r}=o();return !st.has(t??"")||D.has(t??"")&&(r||P)},mt=t=>{let r=o().paymentOnTheWay||P;N(),a(r?{...oe(),error:we(),phase:"unconfirmed"}:{error:ce(t),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({checkout:i,...p?{quote:p,methodId:p.methodId}:{}}),ye(Me(i),i,u===Ee),We(i.quote);}).catch(i=>{v===n&&i instanceof chunkLGJMFD5H_cjs.a&&i.code==="checkout_not_found"&&mt(i);}).finally(()=>{r=false;});},L);v=n;},We=t=>{let{phase:r,quote:n}=o();r!=="awaitingPayment"||!n||!t||Ve(t.expiresAt,n.expiresAt)||(t.payer===n.payer&&t.methodId===n.methodId?a({quote:t}):a({quote:null,phase:"selectMethod"}));},Ie=(t,r=false)=>{let n=Date.parse(o().checkout?.invoice.dueAt??""),u=t==="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({...oe(),invoicePaymentOnTheWay:false,...o().invoicePaymentUnresolved&&!o().error?{error:le(void 0,fe)}:{}}),N());},Math.max(0,H-Date.now())),a({followingUntil:new Date(H).toISOString()})),v&&L<Be&&(clearInterval(v),v=null,se());},ye=(t,r,n=true)=>{if(l)return;let{invoiceStatus:u,phase:i,checkout:p,paymentOnTheWay:f}=o(),w=nn(o().error),h=et(t),k=new Set(T);h&&(T=h.flatMap(({keys:I})=>I));let d={invoiceStatus:t.status,txHash:t.txHash??o().txHash};if(n&&t.pendingPayments!==void 0&&(d.invoicePaymentOnTheWay=t.pendingPayments>0),n&&t.paymentCountsUntil!==void 0&&(d.paymentCountsUntil=t.paymentCountsUntil),n&&(t.unresolvedPayments!==void 0||t.pendingPayments!==void 0)&&(d.invoicePaymentUnresolved=ot(t)),n&&t.unresolvedPayments!==void 0&&(fe=te(t)),n&&t.onTimeTxKeys&&m.length>0&&o().paymentSentInTime!==true){let I=new Set(t.onTimeTxKeys.map(Q));d.paymentSentInTime=m.some(z=>I.has(z));}!r&&p&&t.amountPaid!==void 0&&t.amountPaid!==p.invoice.amountPaid&&(d.checkout={...p,invoice:{...p.invoice,amountPaid:t.amountPaid}});let B=f||P,ae=t.pendingPayments??0,ie=t.amountPaid!==void 0&&t.amountPaid!==null&&t.amountPaid!==E;ie&&(E=t.amountPaid);let J=u==="underpaid"&&t.status==="underpaid"&&!ie,R=null;B&&n&&Ke.has(t.status)&&(R=ft(t,h),!R&&(t.status==="open"||J)&&t.pendingPayments===0&&t.rejectedPayments&&(P||Date.now()-U>=Et)&&!(w&&(t.unresolvedPayments??0)>0)&&(R={final:false,rechecked:te(t)})),!R&&t.status==="open"&&u==="processing"&&ae===0&&(R=t.rejectedPayments?h?.find(({keys:I})=>I.some(z=>!k.has(z)))??{final:false,rechecked:te(t)}:{final:true});let Se=x;if(h&&(x=rt(h)),R&&x&&(R=x),R?.final)Object.assign(d,oe(),{error:Y(R)},t.status==="open"||t.status==="processing"||t.status==="underpaid"?pe(t.status):{phase:j(t.status)});else if(R)Object.assign(d,oe(),{error:Y(R),phase:V.has(t.status)?"unconfirmed":j(t.status)});else if(t.status==="open")i==="loading"&&(d.phase="selectMethod");else if(!J||!Bt.has(i)||i==="awaitingPayment"&&r?.invoice.restPayable===false){d.phase=j(t.status);let I=o().error;t.status==="underpaid"&&u!=="underpaid"&&I&&I.code!=="payment_mismatch"&&!x&&(d.error=null);}if(B&&!R){let I=n&&t.pendingPayments===0,z=ee.has(t.status)||t.status==="underpaid"&&!J||D.has(t.status)&&r!==void 0&&I;z&&Object.assign(d,oe()),z&&D.has(t.status)&&(d.invoicePaymentUnresolved??o().invoicePaymentUnresolved)&&(d.error=le(void 0,fe));}if(n&&ae>0&&Ke.has(t.status)){!P&&!(d.paymentOnTheWay??f)&&be();let I=w&&d.error===void 0;V.has(t.status)&&Pe.has(d.phase??i)&&!I&&(d.phase="confirming");}w&&d.error===void 0&&(t.status==="processing"||t.status==="underpaid"&&!J||ee.has(t.status))&&(d.error=null),x&&V.has(t.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(t.status)?pe(t.status):{}),a(d),He()?D.has(t.status)&&(Re=(t.pendingPayments??0)>0,Ie(t.status),S&&t.pendingPayments===0&&(S.close(),S=null,se())):N(),!r&&t.status!==u&&Gt.has(t.status)&&ht();let ue=o().quote;!r&&o().phase==="awaitingPayment"&&ue&&t.quoteExpiresAt&&t.quoteExpiresAt!==C&&!Ve(t.quoteExpiresAt,ue.expiresAt)&&(C=t.quoteExpiresAt,s.view().then(I=>{l||We(I.quote);}).catch(()=>{}));},ge=()=>{if(l||S||v||!He())return;if(!y)return se();let t=new y(s.url("events"));S=t;let r=()=>{O&&clearTimeout(O),O=setTimeout(()=>{O=null,!(S!==t||l)&&(t.close(),S=null,s.view().then(n=>{l||ye(Me(n),n);}).catch(()=>{}),ge());},bt);};r(),t.addEventListener("ping",r),t.addEventListener("status",n=>{r();try{ye(JSON.parse(n.data));}catch{}}),t.onerror=()=>{if(S!==t)return;let{invoiceStatus:n,paymentOnTheWay:u}=o(),i=u||P,p=t.readyState===2;(p||D.has(n??"")&&i&&!Re)&&(t.close(),S=null,O&&clearTimeout(O),O=null,g=p,se(),p&&!M&&(M=setTimeout(()=>{M=null,!(l||!v||H!==null)&&(clearInterval(v),v=null,g=false,ge());},Ot)));};},$=(t,r,n,u=false)=>{if(ee.has(n??"")||ee.has(o().invoiceStatus??"")){let{error:f,txKey:w}=o();f?.reason?.startsWith("submit_")&&w&&t.includes(w)&&a({error:null}),s.view().then(h=>{l||ye(Me(h),h);}).catch(()=>{});return}Ee+=1,U=Date.now(),P=false,m=[...m,...t.filter(f=>!!f).map(Q)],b=new Set(T.map(Q));let{invoiceStatus:i}=o(),p=i&&D.has(i)?i:null;a({txKey:r,paymentOnTheWay:true,paymentSentInTime:null,error:u?en():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(t,r)=>{let n={txKey:t.txKey,...t.from?{from:t.from}:{},...t.connectorType?{connectorType:t.connectorType}:{},...t.methodId?{methodId:t.methodId}:{}};lt(n);let u=()=>ee.has(o().invoiceStatus??""),i=()=>D.has(o().invoiceStatus??""),p=h=>{u()||a({txKey:h,error:Xt(),...i()?{}:{phase:"unconfirmed"}}),f(0);},f=h=>{let k=Mt[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({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 chunkLGJMFD5H_cjs.a&&Ye.has(h.code??""))return u()||a({txKey:n.txKey,error:we(),...i()?{}:{phase:"unconfirmed"}}),false;if(!Ze(h))return F(n.txKey),w&&!x||(x&&!u()?a({...ne(),...i()?{}:{phase:"unconfirmed"}}):u()||A(h,r==="submitting"?"awaitingPayment":r)),false;u()||a({txKey:n.txKey,...x?ne():{error:zt()},...i()?{}:{phase:"unconfirmed"}});let k=Date.now()+Ft,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(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 chunkLGJMFD5H_cjs.a&&Ye.has(R.code??"")){d()&&a({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(ne());return}let Se=ce(R),ue=nt[Se.code],I=o().phase;a({error:Se,...ue?{phase:ue}:I==="unconfirmed"?pe(o().invoiceStatus):{}});});},ie);W.set(n.txKey,J);};return B(0),false}},pt=t=>{let r=Oe();if(r.length===0)return;let n=new Set([...t.invoice.rejectedTxKeys??[],...t.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({phase:"loading",error:null});try{let t=await s.view(),{invoice:r}=t,n=et(r);n&&(T=n.flatMap(({keys:k})=>k)),E=r.amountPaid;let u=tt(t,Date.now()),i=null,p=(r.pendingPayments??0)>0&&Ke.has(r.status);p&&!o().paymentOnTheWay&&be(),p&&V.has(r.status)&&Pe.has(u)&&(u="confirming");let f=n?.[0],w=ot(r),h=r.status==="open"||r.status==="underpaid"||D.has(r.status);if(n&&(x=rt(n)),!p&&!o().paymentOnTheWay&&h){let k=!1;x?(i=Y(x),k=!0):f&&!f.final&&!rn(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({checkout:t,invoiceStatus:r.status,locale:r.locale,quote:t.quote,methodId:t.quote?.methodId??o().methodId,payer:t.quote?.payer??o().payer,invoicePaymentOnTheWay:(r.pendingPayments??0)>0,invoicePaymentUnresolved:w,paymentCountsUntil:r.paymentCountsUntil??null,phase:u,error:i}),P&&D.has(r.status)&&Ie(r.status),ge(),pt(t);}catch(t){a({phase:"error",error:ce(t)});}},selectMethod:(t,r)=>{let{quote:n,phase:u,error:i}=o(),p=n&&n.methodId!==t;a({methodId:t,error:r?.keepError?i:null,...p?{quote:null,phase:u==="awaitingPayment"?"selectMethod":u}:{}});},setPayer:t=>{let{quote:r,phase:n,invoiceStatus:u,checkout:i,error:p}=o(),f=r&&r.payer!==t,w=t!==o().payer&&Ht(p)?{error:null}:{},h=(u??i?.invoice.status)==="underpaid",k=n==="blocked"&&t!==null&&t!==o().payer?{phase:h?"underpaid":"selectMethod",quote:h?r:null}:{};if(f&&h){a({payer:t,...w,phase:n==="awaitingPayment"?"underpaid":n,...k});return}a({payer:t,...w,...f?{quote:null,phase:n==="awaitingPayment"?"selectMethod":n}:{},...k});},clearError:()=>a({error:null}),setConsentGiven:t=>a({consentGiven:t,error:null}),releaseQuote:()=>{let{phase:t,invoiceStatus:r,checkout:n}=o();t==="awaitingPayment"&&((r??n?.invoice.status)==="underpaid"?a({error:null,phase:"underpaid"}):a({quote:null,error:null,phase:"selectMethod"}));},requestQuote:async()=>{let{methodId:t,payer:r,phase:n,checkout:u,consentGiven:i,invoiceStatus:p}=o();if(!t)return a({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({error:{code:"consent_required",message:"Tick the consent of the checkout first"}}),null;if(o().payerProof==="required"||o().payerProof==="confirming")return a({error:{code:"payer_proof_required",message:"Confirm the paying wallet with a free signature first"}}),null;a({phase:"quoting",error:null});let w=()=>{let k=o().invoiceStatus;return k!==null&&!V.has(k)},h=()=>{let k=o().invoiceStatus;return k&&a({phase:j(k),error:null}),null};try{let k=await s.quote({methodId:t,...r?{payer:r}:{},...u?.consent&&i&&!f?{consentGiven:!0}:{}});if(w())return h();if(o().payer!==r||o().methodId!==t)return a({phase:f?"underpaid":"selectMethod"}),null;let d=Date.now()-Date.parse(k.lockedAt??"");return a({quote:k,phase:o().invoicePaymentOnTheWay?"confirming":"awaitingPayment",clockSkewMs:Number.isFinite(d)&&Math.abs(d)>It?d:0}),k}catch(k){if(k instanceof chunkLGJMFD5H_cjs.a&&k.code==="payer_proof_required"&&r&&Le.add(r),w())return h();let d=ce(k);return d.code==="payment_on_its_way"&&be(),f&&!Vt.has(d.code)?a({error:d,phase:"underpaid"}):A(k,n==="quoting"?"selectMethod":n),null}},confirmPayer:async t=>{let{payer:r}=o();if(!r)return a({error:{code:"payer_required",message:"Connect the paying wallet first"}}),false;if(o().payerProof==="confirmed"||o().payerProof==="not_needed")return a({error:null}),true;let{payerProofMessage:n,payerProof:u}=s;if(!n||!u)return a({error:{code:"request_failed",message:"The checkout calls cannot confirm a wallet (payerProofMessage)"}}),false;let i=++Ce;he=r,a({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||De(o())==="confirmed"?a({}):w instanceof Error&&w.name==="PayerProofDeclined"?a({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 t(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({});},setBuyer:async(t,r={})=>{a({error:null});try{let n=await s.buyer({buyer:t,...r.company?{company:!0}:{}});return a({checkout:n,phase:tt(n,Date.now())}),!0}catch(n){return A(n,o().phase),false}},setLocale:async t=>{let r=o().locale;a({locale:t});try{return await s.locale(t),!0}catch{return a({locale:r}),false}},submit:t=>Fe(t,o().phase),relay:async t=>{let r=o().phase;a({phase:"submitting",error:null});try{let n=await s.relay(t);return $([n.userOpHash,n.txHash],n.txHash??null),!0}catch(n){return A(n,r==="submitting"?"awaitingPayment":r),false}},grantPermission:async(t,r)=>{a({error:null});let n=async()=>{let{autoCharge:u}=await s.permission(t),i=o().checkout;return i&&a({checkout:{...i,autoCharge:u}}),true};try{try{return await n()}catch(u){let{payerProofMessage:i,payerProof:p}=s;if(!(u instanceof chunkLGJMFD5H_cjs.a&&u.code==="payer_proof_required")||!r||!i||!p)throw u;let w=await i({payer:t.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({error:{code:"payer_proof_declined",message:$e}}),!1}me.push(await p({payer:t.payer,message:w.message,signature:h}));}return await n()}}catch(u){return A(u,o().phase),false}},permissionRevoked:async()=>{try{let{autoCharge:t}=await s.permissionRevoked(),r=o().checkout;return r&&a({checkout:{...r,autoCharge:t}}),t?.status!=="active"}catch{return null}},payAgain:()=>{o().phase!=="unconfirmed"||tn(o().error)||x||a({error:null,...pe(o().invoiceStatus)});},destroy:()=>{l=true;for(let t of W.values())clearTimeout(t);W.clear(),N();}}})}exports.createCheckoutStore=wn;exports.createRefundStore=dn;exports.refundAction=ln;
|
package/dist/checkout.d.cts
CHANGED
|
@@ -70,6 +70,13 @@ interface CheckoutInvoice {
|
|
|
70
70
|
refundedTotalMinor: string | null;
|
|
71
71
|
/** When the invoice was paid; `null` until then, and absent from an engine that does not send it yet. */
|
|
72
72
|
paidAt?: string | null;
|
|
73
|
+
/**
|
|
74
|
+
* Every transfer credited to the invoice, oldest first ({@link CheckoutPayment}): an invoice paid in parts has
|
|
75
|
+
* several, and the replacement of a corrected paid invoice lists the transfers of the invoice it replaced. Empty until
|
|
76
|
+
* something is credited. Quasar versions before November 13, 2026 leave it out: such a page names only the
|
|
77
|
+
* transaction it handed over itself.
|
|
78
|
+
*/
|
|
79
|
+
payments?: CheckoutPayment[];
|
|
73
80
|
/**
|
|
74
81
|
* Payments of the invoice handed over and still on their way, whoever handed them over: tracked transactions
|
|
75
82
|
* settlement has not verified or rejected yet (recorded within the last 25 minutes: Quasar stops counting a stuck
|
|
@@ -137,6 +144,23 @@ interface CheckoutInvoice {
|
|
|
137
144
|
type CheckoutReview = {
|
|
138
145
|
reason: 'screening' | 'late' | 'overpaid' | 'quote_expired';
|
|
139
146
|
};
|
|
147
|
+
/** A transfer credited to the invoice, as the checkout lists it ({@link CheckoutInvoice.payments}). */
|
|
148
|
+
interface CheckoutPayment {
|
|
149
|
+
/** The transaction: its hash, or its Solana signature. */
|
|
150
|
+
txKey: string;
|
|
151
|
+
/** CAIP-2 chain of the transfer; `null` when the record of the payment names none. */
|
|
152
|
+
chainId: string | null;
|
|
153
|
+
/** What it credited to the invoice, in base units of the token. */
|
|
154
|
+
amount: string;
|
|
155
|
+
/** The token it was paid in; `null` when the merchant no longer has that payment method. */
|
|
156
|
+
symbol: string | null;
|
|
157
|
+
/** The decimals of that token; `null` like `symbol`. */
|
|
158
|
+
decimals: number | null;
|
|
159
|
+
/** The address that sent it (the first one, when a Solana transfer names several); `null` when none is on record. */
|
|
160
|
+
from: string | null;
|
|
161
|
+
/** When the network included it (ISO), or when Quasar verified it if the network named no time. */
|
|
162
|
+
at: string;
|
|
163
|
+
}
|
|
140
164
|
/** A payment of the invoice that failed, as the checkout lists it ({@link CheckoutInvoice.rejectedPayments}). */
|
|
141
165
|
interface CheckoutRejectedPayment {
|
|
142
166
|
/** The transaction's `txKey`, or the `userOpHash` of a gasless relay that failed before it had a transaction. */
|
|
@@ -146,7 +170,9 @@ interface CheckoutRejectedPayment {
|
|
|
146
170
|
* recipient), `tx_already_used` (the transaction pays another invoice of the merchant: the one the wallet that sent
|
|
147
171
|
* it confirmed, or whose mark it carries, also when this invoice's page handed it over first or claimed it; with
|
|
148
172
|
* `held`, another invoice holds it for a refund only and it pays none),
|
|
149
|
-
* `reference_missing
|
|
173
|
+
* `reference_missing` (a Solana Pay transfer without the invoice's reference whose amount alone does not tie it to
|
|
174
|
+
* the invoice: some wallets drop the reference; with `held` this invoice holds it for a refund), `too_early`,
|
|
175
|
+
* `not_found` (the network never returned the transaction), `timeout` (no receipt
|
|
150
176
|
* in time), `replaced`, `payer_mismatch` (a transfer from another wallet to an invoice paid or held already; one to a
|
|
151
177
|
* payable invoice is held for a refund only: {@link CheckoutReview}), `payer_unconfirmed` (the same from a wallet that
|
|
152
178
|
* never confirmed the invoice: it pays no invoice; final; a refund only when held, a transfer credited to another
|
|
@@ -194,8 +220,9 @@ interface CheckoutRejectedPayment {
|
|
|
194
220
|
/**
|
|
195
221
|
* `true` when Quasar records the transfer as a held transfer, which the merchant returns to the wallet that sent it:
|
|
196
222
|
* a `payer_mismatch` or `payer_unconfirmed` rejection (the invoice stays payable from the wallet that confirmed it),
|
|
197
|
-
*
|
|
198
|
-
*
|
|
223
|
+
* a `reference_missing` one (held on this invoice, which stays payable), or a `tx_already_used` one whose transfer
|
|
224
|
+
* is held at another invoice of the merchant (`otherInvoice`; say that it is tied to another invoice, never that it
|
|
225
|
+
* pays one). Quasar versions before October 29, 2026 leave it out.
|
|
199
226
|
*/
|
|
200
227
|
held?: true;
|
|
201
228
|
/** The invoice of the merchant the transaction is credited to or held on, when Quasar names it. */
|
|
@@ -789,7 +816,8 @@ interface CheckoutError {
|
|
|
789
816
|
*
|
|
790
817
|
* `payment_mismatch` with `payer_mismatch` or `payer_unconfirmed`: the transfer came from another wallet than the
|
|
791
818
|
* quoted one, or from one that never confirmed the invoice; it pays no invoice and the merchant returns it to the
|
|
792
|
-
* wallet that sent it.
|
|
819
|
+
* wallet that sent it. With `reference_missing` and `held`: a Solana Pay transfer without the invoice's reference
|
|
820
|
+
* whose amount alone does not tie it to the invoice, held on this invoice for a refund to its sender.
|
|
793
821
|
*/
|
|
794
822
|
reason?: string;
|
|
795
823
|
/**
|
|
@@ -818,7 +846,13 @@ interface CheckoutError {
|
|
|
818
846
|
* prices the rest of an underpaid invoice only for that wallet, so the buyer pays the rest from it.
|
|
819
847
|
*/
|
|
820
848
|
originWallet?: string;
|
|
821
|
-
/**
|
|
849
|
+
/**
|
|
850
|
+
* The transaction the error is about, when the network has it to look at: one that reverted (`payment_failed` with
|
|
851
|
+
* the reason `reverted`), one that succeeded without paying the invoice (`payment_mismatch`), and the transaction
|
|
852
|
+
* whose nonce nothing explains, on `nonce_spent_unexplained` (not always the one the page handed over last). A page
|
|
853
|
+
* links to it in the explorer next to what it says. Absent for a payment that never reached the network (a relay
|
|
854
|
+
* operation lost, a transaction that expired or was replaced).
|
|
855
|
+
*/
|
|
822
856
|
txKey?: string;
|
|
823
857
|
/**
|
|
824
858
|
* Set on `payment_unconfirmed` for a payment past the first day Quasar still reads, as a node still shows it or nothing could
|
|
@@ -1414,4 +1448,4 @@ type RefundStore = StoreApi<RefundState>;
|
|
|
1414
1448
|
declare function createRefundStore(options: RefundStoreOptions): RefundStore;
|
|
1415
1449
|
|
|
1416
1450
|
export { createCheckoutStore, createRefundStore, refundAction };
|
|
1417
|
-
export type { AutoChargeOffer, CheckoutApi, CheckoutConsent, CheckoutError, CheckoutHandOverStorage, CheckoutInvoice, CheckoutLine, CheckoutMerchant, CheckoutMethod, CheckoutPayerProof, CheckoutPhase, CheckoutQuote, CheckoutRejectedPayment, CheckoutReview, CheckoutState, CheckoutStatusEvent, CheckoutStore, CheckoutStoreOptions, CheckoutSubscription, CheckoutTheme, CheckoutView, EventSourceConstructor, EventSourceLike, GaslessOffer, GrantPermissionParams, PayerProofConfirmation, PayerProofKind, PayerProofMessage, PayerProofNeed, PayerProofSigner, PayerProofStatus, PaymentInstructions, PermissionRequest, RefundPhase, RefundState, RefundStore, RefundStoreOptions, RefusedRefundCall, SentRefundTransaction, TransferAuthorizationTypedData };
|
|
1451
|
+
export type { AutoChargeOffer, CheckoutApi, CheckoutConsent, CheckoutError, CheckoutHandOverStorage, CheckoutInvoice, CheckoutLine, CheckoutMerchant, CheckoutMethod, CheckoutPayerProof, CheckoutPayment, CheckoutPhase, CheckoutQuote, CheckoutRejectedPayment, CheckoutReview, CheckoutState, CheckoutStatusEvent, CheckoutStore, CheckoutStoreOptions, CheckoutSubscription, CheckoutTheme, CheckoutView, EventSourceConstructor, EventSourceLike, GaslessOffer, GrantPermissionParams, PayerProofConfirmation, PayerProofKind, PayerProofMessage, PayerProofNeed, PayerProofSigner, PayerProofStatus, PaymentInstructions, PermissionRequest, RefundPhase, RefundState, RefundStore, RefundStoreOptions, RefusedRefundCall, SentRefundTransaction, TransferAuthorizationTypedData };
|
package/dist/checkout.d.ts
CHANGED
|
@@ -70,6 +70,13 @@ interface CheckoutInvoice {
|
|
|
70
70
|
refundedTotalMinor: string | null;
|
|
71
71
|
/** When the invoice was paid; `null` until then, and absent from an engine that does not send it yet. */
|
|
72
72
|
paidAt?: string | null;
|
|
73
|
+
/**
|
|
74
|
+
* Every transfer credited to the invoice, oldest first ({@link CheckoutPayment}): an invoice paid in parts has
|
|
75
|
+
* several, and the replacement of a corrected paid invoice lists the transfers of the invoice it replaced. Empty until
|
|
76
|
+
* something is credited. Quasar versions before November 13, 2026 leave it out: such a page names only the
|
|
77
|
+
* transaction it handed over itself.
|
|
78
|
+
*/
|
|
79
|
+
payments?: CheckoutPayment[];
|
|
73
80
|
/**
|
|
74
81
|
* Payments of the invoice handed over and still on their way, whoever handed them over: tracked transactions
|
|
75
82
|
* settlement has not verified or rejected yet (recorded within the last 25 minutes: Quasar stops counting a stuck
|
|
@@ -137,6 +144,23 @@ interface CheckoutInvoice {
|
|
|
137
144
|
type CheckoutReview = {
|
|
138
145
|
reason: 'screening' | 'late' | 'overpaid' | 'quote_expired';
|
|
139
146
|
};
|
|
147
|
+
/** A transfer credited to the invoice, as the checkout lists it ({@link CheckoutInvoice.payments}). */
|
|
148
|
+
interface CheckoutPayment {
|
|
149
|
+
/** The transaction: its hash, or its Solana signature. */
|
|
150
|
+
txKey: string;
|
|
151
|
+
/** CAIP-2 chain of the transfer; `null` when the record of the payment names none. */
|
|
152
|
+
chainId: string | null;
|
|
153
|
+
/** What it credited to the invoice, in base units of the token. */
|
|
154
|
+
amount: string;
|
|
155
|
+
/** The token it was paid in; `null` when the merchant no longer has that payment method. */
|
|
156
|
+
symbol: string | null;
|
|
157
|
+
/** The decimals of that token; `null` like `symbol`. */
|
|
158
|
+
decimals: number | null;
|
|
159
|
+
/** The address that sent it (the first one, when a Solana transfer names several); `null` when none is on record. */
|
|
160
|
+
from: string | null;
|
|
161
|
+
/** When the network included it (ISO), or when Quasar verified it if the network named no time. */
|
|
162
|
+
at: string;
|
|
163
|
+
}
|
|
140
164
|
/** A payment of the invoice that failed, as the checkout lists it ({@link CheckoutInvoice.rejectedPayments}). */
|
|
141
165
|
interface CheckoutRejectedPayment {
|
|
142
166
|
/** The transaction's `txKey`, or the `userOpHash` of a gasless relay that failed before it had a transaction. */
|
|
@@ -146,7 +170,9 @@ interface CheckoutRejectedPayment {
|
|
|
146
170
|
* recipient), `tx_already_used` (the transaction pays another invoice of the merchant: the one the wallet that sent
|
|
147
171
|
* it confirmed, or whose mark it carries, also when this invoice's page handed it over first or claimed it; with
|
|
148
172
|
* `held`, another invoice holds it for a refund only and it pays none),
|
|
149
|
-
* `reference_missing
|
|
173
|
+
* `reference_missing` (a Solana Pay transfer without the invoice's reference whose amount alone does not tie it to
|
|
174
|
+
* the invoice: some wallets drop the reference; with `held` this invoice holds it for a refund), `too_early`,
|
|
175
|
+
* `not_found` (the network never returned the transaction), `timeout` (no receipt
|
|
150
176
|
* in time), `replaced`, `payer_mismatch` (a transfer from another wallet to an invoice paid or held already; one to a
|
|
151
177
|
* payable invoice is held for a refund only: {@link CheckoutReview}), `payer_unconfirmed` (the same from a wallet that
|
|
152
178
|
* never confirmed the invoice: it pays no invoice; final; a refund only when held, a transfer credited to another
|
|
@@ -194,8 +220,9 @@ interface CheckoutRejectedPayment {
|
|
|
194
220
|
/**
|
|
195
221
|
* `true` when Quasar records the transfer as a held transfer, which the merchant returns to the wallet that sent it:
|
|
196
222
|
* a `payer_mismatch` or `payer_unconfirmed` rejection (the invoice stays payable from the wallet that confirmed it),
|
|
197
|
-
*
|
|
198
|
-
*
|
|
223
|
+
* a `reference_missing` one (held on this invoice, which stays payable), or a `tx_already_used` one whose transfer
|
|
224
|
+
* is held at another invoice of the merchant (`otherInvoice`; say that it is tied to another invoice, never that it
|
|
225
|
+
* pays one). Quasar versions before October 29, 2026 leave it out.
|
|
199
226
|
*/
|
|
200
227
|
held?: true;
|
|
201
228
|
/** The invoice of the merchant the transaction is credited to or held on, when Quasar names it. */
|
|
@@ -789,7 +816,8 @@ interface CheckoutError {
|
|
|
789
816
|
*
|
|
790
817
|
* `payment_mismatch` with `payer_mismatch` or `payer_unconfirmed`: the transfer came from another wallet than the
|
|
791
818
|
* quoted one, or from one that never confirmed the invoice; it pays no invoice and the merchant returns it to the
|
|
792
|
-
* wallet that sent it.
|
|
819
|
+
* wallet that sent it. With `reference_missing` and `held`: a Solana Pay transfer without the invoice's reference
|
|
820
|
+
* whose amount alone does not tie it to the invoice, held on this invoice for a refund to its sender.
|
|
793
821
|
*/
|
|
794
822
|
reason?: string;
|
|
795
823
|
/**
|
|
@@ -818,7 +846,13 @@ interface CheckoutError {
|
|
|
818
846
|
* prices the rest of an underpaid invoice only for that wallet, so the buyer pays the rest from it.
|
|
819
847
|
*/
|
|
820
848
|
originWallet?: string;
|
|
821
|
-
/**
|
|
849
|
+
/**
|
|
850
|
+
* The transaction the error is about, when the network has it to look at: one that reverted (`payment_failed` with
|
|
851
|
+
* the reason `reverted`), one that succeeded without paying the invoice (`payment_mismatch`), and the transaction
|
|
852
|
+
* whose nonce nothing explains, on `nonce_spent_unexplained` (not always the one the page handed over last). A page
|
|
853
|
+
* links to it in the explorer next to what it says. Absent for a payment that never reached the network (a relay
|
|
854
|
+
* operation lost, a transaction that expired or was replaced).
|
|
855
|
+
*/
|
|
822
856
|
txKey?: string;
|
|
823
857
|
/**
|
|
824
858
|
* Set on `payment_unconfirmed` for a payment past the first day Quasar still reads, as a node still shows it or nothing could
|
|
@@ -1414,4 +1448,4 @@ type RefundStore = StoreApi<RefundState>;
|
|
|
1414
1448
|
declare function createRefundStore(options: RefundStoreOptions): RefundStore;
|
|
1415
1449
|
|
|
1416
1450
|
export { createCheckoutStore, createRefundStore, refundAction };
|
|
1417
|
-
export type { AutoChargeOffer, CheckoutApi, CheckoutConsent, CheckoutError, CheckoutHandOverStorage, CheckoutInvoice, CheckoutLine, CheckoutMerchant, CheckoutMethod, CheckoutPayerProof, CheckoutPhase, CheckoutQuote, CheckoutRejectedPayment, CheckoutReview, CheckoutState, CheckoutStatusEvent, CheckoutStore, CheckoutStoreOptions, CheckoutSubscription, CheckoutTheme, CheckoutView, EventSourceConstructor, EventSourceLike, GaslessOffer, GrantPermissionParams, PayerProofConfirmation, PayerProofKind, PayerProofMessage, PayerProofNeed, PayerProofSigner, PayerProofStatus, PaymentInstructions, PermissionRequest, RefundPhase, RefundState, RefundStore, RefundStoreOptions, RefusedRefundCall, SentRefundTransaction, TransferAuthorizationTypedData };
|
|
1451
|
+
export type { AutoChargeOffer, CheckoutApi, CheckoutConsent, CheckoutError, CheckoutHandOverStorage, CheckoutInvoice, CheckoutLine, CheckoutMerchant, CheckoutMethod, CheckoutPayerProof, CheckoutPayment, CheckoutPhase, CheckoutQuote, CheckoutRejectedPayment, CheckoutReview, CheckoutState, CheckoutStatusEvent, CheckoutStore, CheckoutStoreOptions, CheckoutSubscription, CheckoutTheme, CheckoutView, EventSourceConstructor, EventSourceLike, GaslessOffer, GrantPermissionParams, PayerProofConfirmation, PayerProofKind, PayerProofMessage, PayerProofNeed, PayerProofSigner, PayerProofStatus, PaymentInstructions, PermissionRequest, RefundPhase, RefundState, RefundStore, RefundStoreOptions, RefusedRefundCall, SentRefundTransaction, TransferAuthorizationTypedData };
|
package/dist/checkout.js
CHANGED
|
@@ -1 +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
|
+
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 ln(e){return async(...s)=>{try{return await e(...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:e})=>e!==void 0&&e>=400&&e<500&&!kt.has(e);function X(e){if(e&&typeof e=="object"&&"refused"in e)throw Object.assign(new Error(e.refused.message),e.refused);return e}function Z(e){if(e instanceof a){let c=e.details?.invoice;return {code:e.code??"request_failed",message:e.message,status:e.status,issues:e.issues,...typeof c=="string"?{otherInvoice:c}:{}}}let s=e;return {code:typeof s?.code=="string"?s.code:"request_failed",message:e instanceof Error?e.message:String(e),...typeof s?.status=="number"&&{status:s.status},...typeof s?.text=="string"&&{text:s.text}}}function dn(e){let s=e.pollMs??5e3,c=null,y=e.handOverStorage!==void 0?e.handOverStorage:_e(),S=()=>{c&&clearTimeout(c),c=null;},v=()=>{try{let g=JSON.parse(y?.getItem(Ae)??"[]");return Array.isArray(g)?g:[]}catch{return []}},O=g=>{try{g.length>0?y?.setItem(Ae,JSON.stringify(g)):y?.removeItem(Ae);}catch{}},M=g=>O(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(()=>{e.get(l).then(X).then(b=>{c!==E||C().refund?.id!==l||(b.status==="confirmed"||b.status==="failed"?(S(),g({refund:b,phase:b.status})):(g({refund:b}),P()));},b=>{if(c!==E)return;let{status:U}=Z(b);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}),!e.preview)return null;try{return X(await e.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 e.get(P.refundId));if(T.status==="requested"){let{txHash:E,from:b,instructions:U}=P;return g({phase:"awaitingTransfer",refund:T,instructions:U,sentTransaction:{txHash:E,from:b}}),!0}if(M(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;M(P.refundId);}try{let{refund:T,instructions:E}=X(await e.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 e.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 M(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&&O([...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 e.submit(m.id,l));return M(m.id),g({phase:"confirming",refund:E,sentTransaction:null}),L(m.id),!0}catch(E){let b=Z(E);return _t(b)?(M(m.id),g({phase:"awaitingTransfer",error:b,sentTransaction:null})):g({phase:"awaitingTransfer",error:b}),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=(e,s="")=>`/v1/payments/checkout/${encodeURIComponent(e)}${s?`/${s}`:""}`;function Ge(e,s=a$1){let c=async(y,S,v=wt)=>{try{return await ofetch(Qe(e,y),{baseURL:s,method:S?"POST":"GET",timeout:v,...S?{body:S}:{}})}catch(O){throw b(O)}};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(e,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"]),D=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,Ot=3*6e4,bt=45e3,It=1e4,Ve=(e,s)=>e===s||Date.parse(e??"")===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"]),qe="settlement_failed",de="nonce_spent_unexplained",Te="tx_already_used",at="too_many_payments",Mt=[6e4,5*6e4,15*6e4],it=new Set(["timeout","not_found","replaced","nonce_spent"]),qt="quasar-sdk:checkoutHandOvers:",Lt=new Set(["payer_mismatch","payer_unconfirmed"]),Ut="reference_missing",Nt="quote_changed",ut=new Set(["eoa","authorization"]);function ve(e){let[s,c,y,...S]=e.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 Ht(e){let s=e?.code;return s!==void 0&&(s.startsWith("payer_proof_")||Dt.has(s))}function Wt(e,s){let c=ve(s);return c?e.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],Ft=60*6e4,jt=new Set(["too_many_pending"]),ze=e=>e instanceof a&&e.code==="too_many_payments",Xe=e=>e instanceof a&&e.code===Te;function Ze(e){if(!(e instanceof a)||e.code&&jt.has(e.code))return true;let{status:s}=e;return s===void 0||s===408||s===429||s>=500}var Q=e=>e.startsWith("0x")||e.startsWith("0X")?e.toLowerCase():e;function et(e){return e.rejectedPayments?e.rejectedPayments.map(({txKey:s,original:c,userOpHash:y,reason:S,final:v,movedMoney:O,rechecked:M,held:g,otherInvoice:C})=>({keys:[s,c,y].filter(L=>!!L).map(Q),reason:S,final:v,movedMoney:O===true||Kt.has(S),rechecked:M===true,held:g===true,...typeof C=="string"?{otherInvoice:C}:{}})):e.rejectedTxKeys?.map(s=>({keys:[Q(s)],final:true}))??null}var Qt=(e,s)=>e!==null&&!(Date.parse(e.expiresAt??"")<=s),Gt=new Set([...st,"underpaid"]),Bt=new Set(["quoting","awaitingPayment","submitting","confirming","unconfirmed"]);function j(e){switch(e){case "processing":return "confirming";case "paid":case "partially_refunded":return "paid";case "refunded":case "underpaid":case "held":case "expired":return e;case "cancelled":return "cancelled";default:return "selectMethod"}}function tt(e,s){if(e.invoice.status!=="open")return j(e.invoice.status);if(e.buyer.required)return "buyer";let c=e.quote?.expiresAt?Date.parse(e.quote.expiresAt):Number.NaN;return e.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"},Vt=new Set(["invoice_expired","invoice_processing","payment_on_its_way"]);function Y(e){return {...Jt(e),...$t(e)}}var Yt=new Set(["reverted"]);function $t(e){let s=e.keys?.[0];return s?e.movedMoney||e.reason!==void 0&&Yt.has(e.reason)?{txKey:s}:{}:{}}function Jt(e){let s=e.reason?{reason:e.reason}:{};if(e.reason===qe)return Zt(e.rechecked);if(e.reason===de)return e.otherInvoice?le():ct(e.keys?.[0]);if(e.reason===Nt)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(e.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(e.reason&&Lt.has(e.reason))return {code:"payment_mismatch",message:e.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,...e.held?{held:true}:{}};if(e.reason===Ut&&e.held)return {code:"payment_mismatch",message:"This transfer arrived without the Solana Pay reference of this invoice, and its amount alone does not tie it to the invoice, so it does not pay it. The merchant returns it to the wallet that sent it, and the invoice can still be paid.",...s,held:true};let c=e.otherInvoice?{otherInvoice:e.otherInvoice}:{};return e.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}:e.movedMoney?{...c,code:"payment_mismatch",message:"This transaction does not pay the invoice. If money left your wallet, contact the merchant.",...s}:e.final?{code:"payment_failed",message:"The payment did not go through. Try again.",...s}:le(e.reason,e.rechecked)}function le(e,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.":e?"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.",...e?{reason:e}:{},...s?{rechecked:true}:{}}}var zt=()=>({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"}),Xt=()=>({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"}),Zt=(e=false)=>({code:"payment_unconfirmed",message:e?"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:qe,...e?{rechecked:true}:{}}),ct=e=>({code:"payment_unconfirmed",...e?{txKey:e}:{},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}),en=()=>({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}),tn=e=>e?.code==="payment_unconfirmed"&&(e.reason===Te||e.reason===qe||e.reason===de||e.reason===at),rt=e=>e.find(s=>s.reason===de&&!s.otherInvoice)??null,nn=e=>e?.code==="payment_unconfirmed"&&e.reason===Te,te=e=>(e.unresolvedPayments??0)>0,rn=(e,s)=>!e.final&&!e.movedMoney&&!e.rechecked&&it.has(e.reason??"")&&s.unresolvedPayments===0,ot=e=>(e.unresolvedPayments??e.pendingPayments??0)>0,Me=e=>({status:e.invoice.status,ledgerSeq:0,txHash:null,amountPaid:e.invoice.amountPaid,quoteExpiresAt:e.quote?.expiresAt??null,pendingPayments:e.invoice.pendingPayments,rejectedTxKeys:e.invoice.rejectedTxKeys,rejectedPayments:e.invoice.rejectedPayments,paymentCountsUntil:e.invoice.paymentCountsUntil,unresolvedPayments:e.invoice.unresolvedPayments,onTimeTxKeys:e.invoice.onTimeTxKeys});function ce(e){if(e instanceof a){let{reason:s,originWallet:c}=e.details??{};return {code:e.code??"request_failed",message:e.message,status:e.status,issues:e.issues,...typeof s=="string"?{reason:s}:{},...typeof c=="string"?{originWallet:c}:{}}}return {code:"request_failed",message:e instanceof Error?e.message:String(e)}}function wn(e){let s=e.api??Ge(e.token,e.baseUrl??a$1),c=e.pollMs??5e3,y=e.EventSource===void 0?globalThis.EventSource??null:e.EventSource,S=null,v=null,O=null,M=null,g=false,C=null,L=c,l=false,m=[],P=false,T=[],E=null,b=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=e.handOverStorage!==void 0?e.handOverStorage:e.api?null:_e(),xe=`${qt}${e.token}`,Oe=()=>{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=Oe(),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=Oe();o.some(({txKey:a})=>a===_)&&Ue(o.filter(({txKey:a})=>a!==_));},Ne=({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:q})=>q===_.methodId)?.chainId,a=o?.split(":")[0];if(!o)return [];let A=new Map;for(let q of Ne(_)){let N=ve(q.payer);!N||N.namespace!==a||(q.kind&&ut.has(q.kind)||q.chainId===o)&&(A.has(N.address)||A.set(N.address,q.payer));}return [...A.values()]},De=_=>{let{payer:o}=_,a=_.checkout?.methods.find(({id:N})=>N===_.methodId),q=o!==null&&Le.has(o)?"before_quote":a?.payerProof??"none";return q==="none"||!a?"not_needed":o&&Wt(Ne(_),o)?"confirmed":o!==null&&o===he&&q==="before_quote"?"confirming":q==="before_quote"?"required":"unless_relayed"};return createStore()((_,o)=>{let a$1=t=>{let r={...o(),...t};_({...t,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:De(r),confirmedWallets:dt(r)});},A=(t,r)=>{let n=ce(t),u=o().invoiceStatus;if(u&&(ee.has(u)||D.has(u))){a$1({error:n,...At.has(o().phase)?{phase:j(u)}:{}});return}a$1({error:n,phase:nt[n.code]??r});},q=()=>{G&&clearTimeout(G),G=null,H=null,Re=false,o().followingUntil!==null&&a$1({followingUntil:null});},N=()=>{S?.close(),S=null,v&&clearInterval(v),v=null,O&&clearTimeout(O),O=null,M&&clearTimeout(M),M=null,q();},oe=()=>(m=[],P=false,{paymentOnTheWay:false}),be=()=>{P=true,U=Date.now(),b=new Set(T);},ft=(t,r)=>{if(!r)return null;let n=r.find(({keys:u})=>u.some(i=>m.includes(i)));return n||(t.pendingPayments!==0?null:r.find(({keys:u})=>u.some(i=>!b.has(i)))??null)},pe=t=>t==="underpaid"?{phase:"underpaid"}:t&&!V.has(t)?{phase:j(t)}:Qt(o().quote,Date.now())?{phase:"awaitingPayment"}:{phase:"selectMethod",quote:null},ht=()=>s.view().then(t=>{if(l)return;let r=t.invoice.status==="underpaid"&&t.quote;a$1({checkout:t,...r?{quote:r,methodId:r.methodId}:{}});}).catch(()=>{}),He=()=>{let{invoiceStatus:t,paymentOnTheWay:r}=o();return !st.has(t??"")||D.has(t??"")&&(r||P)},mt=t=>{let r=o().paymentOnTheWay||P;N(),a$1(r?{...oe(),error:we(),phase:"unconfirmed"}:{error:ce(t),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(Me(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=t=>{let{phase:r,quote:n}=o();r!=="awaitingPayment"||!n||!t||Ve(t.expiresAt,n.expiresAt)||(t.payer===n.payer&&t.methodId===n.methodId?a$1({quote:t}):a$1({quote:null,phase:"selectMethod"}));},Ie=(t,r=false)=>{let n=Date.parse(o().checkout?.invoice.dueAt??""),u=t==="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)}:{}}),N());},Math.max(0,H-Date.now())),a$1({followingUntil:new Date(H).toISOString()})),v&&L<Be&&(clearInterval(v),v=null,se());},ye=(t,r,n=true)=>{if(l)return;let{invoiceStatus:u,phase:i,checkout:p,paymentOnTheWay:f}=o(),w=nn(o().error),h=et(t),k=new Set(T);h&&(T=h.flatMap(({keys:I})=>I));let d={invoiceStatus:t.status,txHash:t.txHash??o().txHash};if(n&&t.pendingPayments!==void 0&&(d.invoicePaymentOnTheWay=t.pendingPayments>0),n&&t.paymentCountsUntil!==void 0&&(d.paymentCountsUntil=t.paymentCountsUntil),n&&(t.unresolvedPayments!==void 0||t.pendingPayments!==void 0)&&(d.invoicePaymentUnresolved=ot(t)),n&&t.unresolvedPayments!==void 0&&(fe=te(t)),n&&t.onTimeTxKeys&&m.length>0&&o().paymentSentInTime!==true){let I=new Set(t.onTimeTxKeys.map(Q));d.paymentSentInTime=m.some(z=>I.has(z));}!r&&p&&t.amountPaid!==void 0&&t.amountPaid!==p.invoice.amountPaid&&(d.checkout={...p,invoice:{...p.invoice,amountPaid:t.amountPaid}});let B=f||P,ae=t.pendingPayments??0,ie=t.amountPaid!==void 0&&t.amountPaid!==null&&t.amountPaid!==E;ie&&(E=t.amountPaid);let J=u==="underpaid"&&t.status==="underpaid"&&!ie,R=null;B&&n&&Ke.has(t.status)&&(R=ft(t,h),!R&&(t.status==="open"||J)&&t.pendingPayments===0&&t.rejectedPayments&&(P||Date.now()-U>=Et)&&!(w&&(t.unresolvedPayments??0)>0)&&(R={final:false,rechecked:te(t)})),!R&&t.status==="open"&&u==="processing"&&ae===0&&(R=t.rejectedPayments?h?.find(({keys:I})=>I.some(z=>!k.has(z)))??{final:false,rechecked:te(t)}:{final:true});let Se=x;if(h&&(x=rt(h)),R&&x&&(R=x),R?.final)Object.assign(d,oe(),{error:Y(R)},t.status==="open"||t.status==="processing"||t.status==="underpaid"?pe(t.status):{phase:j(t.status)});else if(R)Object.assign(d,oe(),{error:Y(R),phase:V.has(t.status)?"unconfirmed":j(t.status)});else if(t.status==="open")i==="loading"&&(d.phase="selectMethod");else if(!J||!Bt.has(i)||i==="awaitingPayment"&&r?.invoice.restPayable===false){d.phase=j(t.status);let I=o().error;t.status==="underpaid"&&u!=="underpaid"&&I&&I.code!=="payment_mismatch"&&!x&&(d.error=null);}if(B&&!R){let I=n&&t.pendingPayments===0,z=ee.has(t.status)||t.status==="underpaid"&&!J||D.has(t.status)&&r!==void 0&&I;z&&Object.assign(d,oe()),z&&D.has(t.status)&&(d.invoicePaymentUnresolved??o().invoicePaymentUnresolved)&&(d.error=le(void 0,fe));}if(n&&ae>0&&Ke.has(t.status)){!P&&!(d.paymentOnTheWay??f)&&be();let I=w&&d.error===void 0;V.has(t.status)&&Pe.has(d.phase??i)&&!I&&(d.phase="confirming");}w&&d.error===void 0&&(t.status==="processing"||t.status==="underpaid"&&!J||ee.has(t.status))&&(d.error=null),x&&V.has(t.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(t.status)?pe(t.status):{}),a$1(d),He()?D.has(t.status)&&(Re=(t.pendingPayments??0)>0,Ie(t.status),S&&t.pendingPayments===0&&(S.close(),S=null,se())):N(),!r&&t.status!==u&&Gt.has(t.status)&&ht();let ue=o().quote;!r&&o().phase==="awaitingPayment"&&ue&&t.quoteExpiresAt&&t.quoteExpiresAt!==C&&!Ve(t.quoteExpiresAt,ue.expiresAt)&&(C=t.quoteExpiresAt,s.view().then(I=>{l||We(I.quote);}).catch(()=>{}));},ge=()=>{if(l||S||v||!He())return;if(!y)return se();let t=new y(s.url("events"));S=t;let r=()=>{O&&clearTimeout(O),O=setTimeout(()=>{O=null,!(S!==t||l)&&(t.close(),S=null,s.view().then(n=>{l||ye(Me(n),n);}).catch(()=>{}),ge());},bt);};r(),t.addEventListener("ping",r),t.addEventListener("status",n=>{r();try{ye(JSON.parse(n.data));}catch{}}),t.onerror=()=>{if(S!==t)return;let{invoiceStatus:n,paymentOnTheWay:u}=o(),i=u||P,p=t.readyState===2;(p||D.has(n??"")&&i&&!Re)&&(t.close(),S=null,O&&clearTimeout(O),O=null,g=p,se(),p&&!M&&(M=setTimeout(()=>{M=null,!(l||!v||H!==null)&&(clearInterval(v),v=null,g=false,ge());},Ot)));};},$=(t,r,n,u=false)=>{if(ee.has(n??"")||ee.has(o().invoiceStatus??"")){let{error:f,txKey:w}=o();f?.reason?.startsWith("submit_")&&w&&t.includes(w)&&a$1({error:null}),s.view().then(h=>{l||ye(Me(h),h);}).catch(()=>{});return}Ee+=1,U=Date.now(),P=false,m=[...m,...t.filter(f=>!!f).map(Q)],b=new Set(T.map(Q));let{invoiceStatus:i}=o(),p=i&&D.has(i)?i:null;a$1({txKey:r,paymentOnTheWay:true,paymentSentInTime:null,error:u?en():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(t,r)=>{let n={txKey:t.txKey,...t.from?{from:t.from}:{},...t.connectorType?{connectorType:t.connectorType}:{},...t.methodId?{methodId:t.methodId}:{}};lt(n);let u=()=>ee.has(o().invoiceStatus??""),i=()=>D.has(o().invoiceStatus??""),p=h=>{u()||a$1({txKey:h,error:Xt(),...i()?{}:{phase:"unconfirmed"}}),f(0);},f=h=>{let k=Mt[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:zt()},...i()?{}:{phase:"unconfirmed"}});let k=Date.now()+Ft,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=t=>{let r=Oe();if(r.length===0)return;let n=new Set([...t.invoice.rejectedTxKeys??[],...t.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 t=await s.view(),{invoice:r}=t,n=et(r);n&&(T=n.flatMap(({keys:k})=>k)),E=r.amountPaid;let u=tt(t,Date.now()),i=null,p=(r.pendingPayments??0)>0&&Ke.has(r.status);p&&!o().paymentOnTheWay&&be(),p&&V.has(r.status)&&Pe.has(u)&&(u="confirming");let f=n?.[0],w=ot(r),h=r.status==="open"||r.status==="underpaid"||D.has(r.status);if(n&&(x=rt(n)),!p&&!o().paymentOnTheWay&&h){let k=!1;x?(i=Y(x),k=!0):f&&!f.final&&!rn(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:t,invoiceStatus:r.status,locale:r.locale,quote:t.quote,methodId:t.quote?.methodId??o().methodId,payer:t.quote?.payer??o().payer,invoicePaymentOnTheWay:(r.pendingPayments??0)>0,invoicePaymentUnresolved:w,paymentCountsUntil:r.paymentCountsUntil??null,phase:u,error:i}),P&&D.has(r.status)&&Ie(r.status),ge(),pt(t);}catch(t){a$1({phase:"error",error:ce(t)});}},selectMethod:(t,r)=>{let{quote:n,phase:u,error:i}=o(),p=n&&n.methodId!==t;a$1({methodId:t,error:r?.keepError?i:null,...p?{quote:null,phase:u==="awaitingPayment"?"selectMethod":u}:{}});},setPayer:t=>{let{quote:r,phase:n,invoiceStatus:u,checkout:i,error:p}=o(),f=r&&r.payer!==t,w=t!==o().payer&&Ht(p)?{error:null}:{},h=(u??i?.invoice.status)==="underpaid",k=n==="blocked"&&t!==null&&t!==o().payer?{phase:h?"underpaid":"selectMethod",quote:h?r:null}:{};if(f&&h){a$1({payer:t,...w,phase:n==="awaitingPayment"?"underpaid":n,...k});return}a$1({payer:t,...w,...f?{quote:null,phase:n==="awaitingPayment"?"selectMethod":n}:{},...k});},clearError:()=>a$1({error:null}),setConsentGiven:t=>a$1({consentGiven:t,error:null}),releaseQuote:()=>{let{phase:t,invoiceStatus:r,checkout:n}=o();t==="awaitingPayment"&&((r??n?.invoice.status)==="underpaid"?a$1({error:null,phase:"underpaid"}):a$1({quote:null,error:null,phase:"selectMethod"}));},requestQuote:async()=>{let{methodId:t,payer:r,phase:n,checkout:u,consentGiven:i,invoiceStatus:p}=o();if(!t)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:t,...r?{payer:r}:{},...u?.consent&&i&&!f?{consentGiven:!0}:{}});if(w())return h();if(o().payer!==r||o().methodId!==t)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"&&be(),f&&!Vt.has(d.code)?a$1({error:d,phase:"underpaid"}):A(k,n==="quoting"?"selectMethod":n),null}},confirmPayer:async t=>{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||De(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 t(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(t,r={})=>{a$1({error:null});try{let n=await s.buyer({buyer:t,...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 t=>{let r=o().locale;a$1({locale:t});try{return await s.locale(t),!0}catch{return a$1({locale:r}),false}},submit:t=>Fe(t,o().phase),relay:async t=>{let r=o().phase;a$1({phase:"submitting",error:null});try{let n=await s.relay(t);return $([n.userOpHash,n.txHash],n.txHash??null),!0}catch(n){return A(n,r==="submitting"?"awaitingPayment":r),false}},grantPermission:async(t,r)=>{a$1({error:null});let n=async()=>{let{autoCharge:u}=await s.permission(t),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:t.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:t.payer,message:w.message,signature:h}));}return await n()}}catch(u){return A(u,o().phase),false}},permissionRevoked:async()=>{try{let{autoCharge:t}=await s.permissionRevoked(),r=o().checkout;return r&&a$1({checkout:{...r,autoCharge:t}}),t?.status!=="active"}catch{return null}},payAgain:()=>{o().phase!=="unconfirmed"||tn(o().error)||x||a$1({error:null,...pe(o().invoiceStatus)});},destroy:()=>{l=true;for(let t of W.values())clearTimeout(t);W.clear(),N();}}})}export{wn as createCheckoutStore,dn as createRefundStore,ln as refundAction};
|
package/dist/cli.cjs
CHANGED
|
@@ -608,10 +608,11 @@ interface Refund {
|
|
|
608
608
|
type HeldTransferStatus = 'held' | 'refunding' | 'refunded' | 'voided';
|
|
609
609
|
/**
|
|
610
610
|
* A transfer that reached the address of one of your invoices without being tied to it by proof: from another wallet
|
|
611
|
-
* than the one the quote was for (`payer_mismatch`),
|
|
612
|
-
* (`payer_unconfirmed`)
|
|
613
|
-
*
|
|
614
|
-
*
|
|
611
|
+
* than the one the quote was for (`payer_mismatch`), from the quoted wallet that never confirmed the invoice
|
|
612
|
+
* (`payer_unconfirmed`), or a Solana Pay transfer without the invoice's reference whose amount alone does not tie it to
|
|
613
|
+
* the invoice (`reference_missing`). It paid nothing and the invoice stays as it was; refund it as a whole to the wallet
|
|
614
|
+
* that sent it with {@link PaymentsModule.refundHeldTransfer}. When the same transaction is proven to pay an invoice,
|
|
615
|
+
* Quasar voids the record (`voided`, `voidedBy`).
|
|
615
616
|
*/
|
|
616
617
|
interface HeldTransfer {
|
|
617
618
|
/** Held transfer ID. */
|
|
@@ -621,7 +622,7 @@ interface HeldTransfer {
|
|
|
621
622
|
/** Where it is. */
|
|
622
623
|
status: HeldTransferStatus;
|
|
623
624
|
/** Why it is tied to no invoice. */
|
|
624
|
-
reason: 'payer_mismatch' | 'payer_unconfirmed' | 'already_paid' | 'quote_changed' | 'too_many_parts';
|
|
625
|
+
reason: 'payer_mismatch' | 'payer_unconfirmed' | 'reference_missing' | 'already_paid' | 'quote_changed' | 'too_many_parts';
|
|
625
626
|
/** Whether it arrived after the invoice expired or was cancelled. */
|
|
626
627
|
late: boolean;
|
|
627
628
|
/** CAIP-2 chain. */
|
|
@@ -608,10 +608,11 @@ interface Refund {
|
|
|
608
608
|
type HeldTransferStatus = 'held' | 'refunding' | 'refunded' | 'voided';
|
|
609
609
|
/**
|
|
610
610
|
* A transfer that reached the address of one of your invoices without being tied to it by proof: from another wallet
|
|
611
|
-
* than the one the quote was for (`payer_mismatch`),
|
|
612
|
-
* (`payer_unconfirmed`)
|
|
613
|
-
*
|
|
614
|
-
*
|
|
611
|
+
* than the one the quote was for (`payer_mismatch`), from the quoted wallet that never confirmed the invoice
|
|
612
|
+
* (`payer_unconfirmed`), or a Solana Pay transfer without the invoice's reference whose amount alone does not tie it to
|
|
613
|
+
* the invoice (`reference_missing`). It paid nothing and the invoice stays as it was; refund it as a whole to the wallet
|
|
614
|
+
* that sent it with {@link PaymentsModule.refundHeldTransfer}. When the same transaction is proven to pay an invoice,
|
|
615
|
+
* Quasar voids the record (`voided`, `voidedBy`).
|
|
615
616
|
*/
|
|
616
617
|
interface HeldTransfer {
|
|
617
618
|
/** Held transfer ID. */
|
|
@@ -621,7 +622,7 @@ interface HeldTransfer {
|
|
|
621
622
|
/** Where it is. */
|
|
622
623
|
status: HeldTransferStatus;
|
|
623
624
|
/** Why it is tied to no invoice. */
|
|
624
|
-
reason: 'payer_mismatch' | 'payer_unconfirmed' | 'already_paid' | 'quote_changed' | 'too_many_parts';
|
|
625
|
+
reason: 'payer_mismatch' | 'payer_unconfirmed' | 'reference_missing' | 'already_paid' | 'quote_changed' | 'too_many_parts';
|
|
625
626
|
/** Whether it arrived after the invoice expired or was cancelled. */
|
|
626
627
|
late: boolean;
|
|
627
628
|
/** CAIP-2 chain. */
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var chunkLGJMFD5H_cjs=require('./chunk-LGJMFD5H.cjs'),chunk2LAAWGEK_cjs=require('./chunk-2LAAWGEK.cjs'),ofetch=require('ofetch');var s=
|
|
1
|
+
'use strict';var chunkLGJMFD5H_cjs=require('./chunk-LGJMFD5H.cjs'),chunk2LAAWGEK_cjs=require('./chunk-2LAAWGEK.cjs'),ofetch=require('ofetch');var s=n=>encodeURIComponent(n),d=n=>n instanceof Date?n.toISOString():n,p=n=>n?.idempotencyKey?{"Idempotency-Key":n.idempotencyKey}:{},$=n=>Array.isArray(n)?n.join(","):n,c=n=>Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0)),m=class{constructor(e){this.client=e;}client;async createInvoice(e,t){return this.client.request(`${chunk2LAAWGEK_cjs.e}/invoices`,{method:"POST",body:{...e,dueAt:d(e.dueAt),supplyDate:d(e.supplyDate)},headers:p(t)})}async getInvoice(e){return this.client.request(`${chunk2LAAWGEK_cjs.e}/invoices/${s(e)}`,{method:"GET"})}async listInvoiceRefunds(e,t={}){return this.client.request(`${chunk2LAAWGEK_cjs.e}/invoices/${s(e)}/refunds`,{method:"GET",query:c({limit:t.limit,cursor:t.cursor})})}async listInvoiceDocuments(e,t={}){return this.client.request(`${chunk2LAAWGEK_cjs.e}/invoices/${s(e)}/documents`,{method:"GET",query:c({limit:t.limit,cursor:t.cursor})})}async listInvoices(e={}){return this.client.request(`${chunk2LAAWGEK_cjs.e}/invoices`,{method:"GET",query:c({status:$(e.status),environment:e.environment,externalId:e.externalId,createdAfter:d(e.createdAfter),createdBefore:d(e.createdBefore),limit:e.limit,cursor:e.cursor})})}async cancelInvoice(e,t={}){return this.client.request(`${chunk2LAAWGEK_cjs.e}/invoices/${s(e)}/cancel`,{method:"POST",body:t})}async releaseInvoice(e,t){return this.client.request(`${chunk2LAAWGEK_cjs.e}/invoices/${s(e)}/release`,{method:"POST",body:t})}async correctInvoice(e,t){return this.client.request(`${chunk2LAAWGEK_cjs.e}/invoices/${s(e)}/correct`,{method:"POST",body:t})}async replacePayLink(e){return this.client.request(`${chunk2LAAWGEK_cjs.e}/invoices/${s(e)}/checkout`,{method:"POST",body:{}})}async getEvents(e,t={}){return this.client.request(`${chunk2LAAWGEK_cjs.e}/invoices/${s(e)}/events`,{method:"GET",query:c({verify:t.verify?"true":void 0,limit:t.limit,cursor:t.cursor})})}async previewRefund(e,t={}){return this.client.request(`${chunk2LAAWGEK_cjs.e}/invoices/${s(e)}/refunds/preview`,{method:"POST",body:t})}async refund(e,t={},i){return this.client.request(`${chunk2LAAWGEK_cjs.e}/invoices/${s(e)}/refunds`,{method:"POST",body:t,headers:p(i)})}async withdrawRefund(e){return this.client.request(`${chunk2LAAWGEK_cjs.e}/refunds/${s(e)}/withdraw`,{method:"POST",body:{}})}async getRefund(e){return this.client.request(`${chunk2LAAWGEK_cjs.e}/refunds/${s(e)}`,{method:"GET"})}async submitRefund(e,t){return this.client.request(`${chunk2LAAWGEK_cjs.e}/refunds/${s(e)}/submit`,{method:"POST",body:t})}async listHeldTransfers(e={}){let t=e.invoice?`${chunk2LAAWGEK_cjs.e}/invoices/${s(e.invoice)}/held-transfers`:`${chunk2LAAWGEK_cjs.e}/held-transfers`,i=await this.client.request(t,{method:"GET",query:e.invoice?{}:c({status:e.status})});return e.invoice&&e.status?i.heldTransfers.filter(o=>o.status===e.status):i.heldTransfers}async refundHeldTransfer(e){return this.client.request(`${chunk2LAAWGEK_cjs.e}/held-transfers/${s(e)}/refund`,{method:"POST",body:{}})}async getDocument(e,t){return this.client.requestFile(`${chunk2LAAWGEK_cjs.e}/invoices/${s(e)}/documents/${t}`)}async getCreditNote(e,t,i="pdf"){let o=`${s(t)}${i==="ubl"?".xml":""}`;return this.client.requestFile(`${chunk2LAAWGEK_cjs.e}/invoices/${s(e)}/documents/credit-note/${o}`)}async quote(e){return this.client.request(`${chunk2LAAWGEK_cjs.e}/quotes`,{method:"POST",body:e})}async listMethods(){return this.client.request(`${chunk2LAAWGEK_cjs.e}/methods`,{method:"GET"})}async createSubscription(e,t){return this.client.request(`${chunk2LAAWGEK_cjs.e}/subscriptions`,{method:"POST",body:{...e,endsAt:d(e.endsAt)},headers:p(t)})}async listSubscriptions(e={}){return this.client.request(`${chunk2LAAWGEK_cjs.e}/subscriptions`,{method:"GET",query:c({status:$(e.status),limit:e.limit,cursor:e.cursor})})}async getSubscription(e){return this.client.request(`${chunk2LAAWGEK_cjs.e}/subscriptions/${s(e)}`,{method:"GET"})}async listSubscriptionInvoices(e,t={}){return this.client.request(`${chunk2LAAWGEK_cjs.e}/subscriptions/${s(e)}/invoices`,{method:"GET",query:c({limit:t.limit,cursor:t.cursor})})}async listSubscriptionCharges(e,t={}){return this.client.request(`${chunk2LAAWGEK_cjs.e}/subscriptions/${s(e)}/charges`,{method:"GET",query:c({limit:t.limit,cursor:t.cursor})})}async cancelSubscription(e,t={}){return this.client.request(`${chunk2LAAWGEK_cjs.e}/subscriptions/${s(e)}/cancel`,{method:"POST",body:t})}async undoSubscriptionCancel(e){return this.client.request(`${chunk2LAAWGEK_cjs.e}/subscriptions/${s(e)}/cancel/undo`,{method:"POST",body:{}})}async endSubscriptionPermission(e){return this.client.request(`${chunk2LAAWGEK_cjs.e}/subscriptions/${s(e)}/permission/end`,{method:"POST",body:{}})}async pauseSubscription(e){return this.client.request(`${chunk2LAAWGEK_cjs.e}/subscriptions/${s(e)}/pause`,{method:"POST",body:{}})}async resumeSubscription(e){return this.client.request(`${chunk2LAAWGEK_cjs.e}/subscriptions/${s(e)}/resume`,{method:"POST",body:{}})}};var l=class{constructor(e){this.client=e;}client;async syncCreate(e,t){return this.client.request(chunk2LAAWGEK_cjs.b,{method:"POST",body:{...e,appName:t}})}async syncHash(e,t){return this.client.request(chunk2LAAWGEK_cjs.d(e),{method:"POST",body:{hash:t}})}async getHistory(e={}){return this.client.request(chunk2LAAWGEK_cjs.c,{method:"GET",query:{page:e.page??1,limit:e.limit??10,chainId:e.chainId,status:e.status,txKey:e.txKey,appName:e.appName,walletAddress:e.walletAddress}})}};var y=class{secretKey;internalSecret;baseUrl;timeout;constructor(e){if(!e.secretKey)throw new Error("[Quasar SDK] Missing API Key. Provide the secretKey of your Quasar app (sk_live_ or sk_test_).");this.secretKey=e.secretKey,this.internalSecret=e.internalSecret,this.baseUrl=e.baseUrl||chunk2LAAWGEK_cjs.a,this.timeout=e.timeout||1e4;}async request(e,t={}){try{return await ofetch.ofetch(e,{baseURL:this.baseUrl,timeout:this.timeout,...t,headers:{"Content-Type":"application/json","x-tuwa-secret-key":this.secretKey,...this.internalSecret?{"x-internal-secret":this.internalSecret}:{},...t.headers}})}catch(i){throw chunkLGJMFD5H_cjs.b(i)}}async requestFile(e){try{let t=await ofetch.ofetch.raw(e,{baseURL:this.baseUrl,timeout:this.timeout,method:"GET",responseType:"arrayBuffer",headers:{"x-tuwa-secret-key":this.secretKey,...this.internalSecret?{"x-internal-secret":this.internalSecret}:{}}}),i=t.headers.get("content-disposition")??"";return {bytes:new Uint8Array(t._data??new ArrayBuffer(0)),contentType:t.headers.get("content-type"),filename:/filename="([^"]*)"/.exec(i)?.[1]??null}}catch(t){throw chunkLGJMFD5H_cjs.b(t)}}};var f=class{client;pulsar;payments;constructor(e){this.client=new y(e),this.pulsar=new l(this.client),this.payments=new m(this.client);}};var C="x-quasar-signature",O="payments.v1",a=class extends Error{code;constructor(e,t){super(t),this.name="QuasarWebhookError",this.code=e;}},k=300;async function A(n,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},false,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",t,e));return Array.from(i,o=>o.toString(16).padStart(2,"0")).join("")}function R(n,e){if(n.length!==e.length)return false;let t=0;for(let i=0;i<n.length;i++)t|=n.charCodeAt(i)^e.charCodeAt(i);return t===0}function W(n){if(H(n)||n.sentAt!=null)return {field:"sentAt",time:typeof n.sentAt=="string"?Date.parse(n.sentAt):NaN};let{timestamp:e}=n;return {field:"timestamp",time:typeof e=="number"&&Number.isFinite(e)?e*1e3:NaN}}function H(n){return n.apiVersion===O}async function Y(n){let{body:e,signature:t,secret:i,toleranceSeconds:o=k,now:E=new Date}=n;if(o!==false&&(typeof o!="number"||!Number.isFinite(o)||o<=0))throw new a("invalid_options","toleranceSeconds must be a finite number above 0, or false");if(!i)throw new a("missing_secret","No signing secret to verify the webhook with");if(!t)throw new a("missing_signature",`The ${C} header is missing`);let x=typeof e=="string"?new TextEncoder().encode(e):e,_=await A(i,x);if(!R(t.trim().toLowerCase(),_))throw new a("invalid_signature","The signature does not match the body");let u;try{u=JSON.parse(typeof e=="string"?e:new TextDecoder().decode(e));}catch{throw new a("invalid_body","The body is not JSON")}if(typeof u!="object"||u===null||Array.isArray(u))throw new a("invalid_body","The body is not a webhook");let b=u;if(o!==false){let{field:P,time:g}=W(b);if(Number.isNaN(g))throw new a("stale",`The event carries no valid send time (${P})`);if(Math.abs(E.getTime()-g)>o*1e3)throw new a("stale",`The event was sent outside the ${o} s tolerance (${P})`)}return b}Object.defineProperty(exports,"QuasarSDKError",{enumerable:true,get:function(){return chunkLGJMFD5H_cjs.a}});Object.defineProperty(exports,"BASE_API_URL",{enumerable:true,get:function(){return chunk2LAAWGEK_cjs.a}});Object.defineProperty(exports,"PAYMENTS_ENDPOINT",{enumerable:true,get:function(){return chunk2LAAWGEK_cjs.e}});Object.defineProperty(exports,"PULSAR_HISTORY_ENDPOINT",{enumerable:true,get:function(){return chunk2LAAWGEK_cjs.c}});Object.defineProperty(exports,"PULSAR_SYNC_ENDPOINT",{enumerable:true,get:function(){return chunk2LAAWGEK_cjs.b}});Object.defineProperty(exports,"pulsarSyncHashEndpoint",{enumerable:true,get:function(){return chunk2LAAWGEK_cjs.d}});exports.PAYMENT_WEBHOOK_VERSION=O;exports.PaymentsModule=m;exports.PulsarModule=l;exports.Quasar=f;exports.QuasarWebhookError=a;exports.WEBHOOK_SIGNATURE_HEADER=C;exports.isPaymentWebhookEvent=H;exports.verifyWebhook=Y;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as CreateInvoiceParams, i as CreateOptions, j as InvoiceWithCheckout, k as InvoiceDetails, L as ListInvoiceItemsParams, l as PaymentsList, R as Refund, m as InvoiceDocumentRef, n as ListInvoicesParams, o as Invoice, p as CorrectInvoiceParams, q as InvoiceCorrection, G as GetEventsParams, r as InvoiceLedger, f as RefundParams, g as RefundPreview, e as RefundStart, h as SubmitRefundParams, s as ListHeldTransfersParams, H as HeldTransfer, t as PaymentDocumentKind, u as PaymentDocument, v as QuoteParams, w as PaymentQuote, x as PaymentMethod, y as CreateSubscriptionParams, z as SubscriptionStart, A as ListSubscriptionsParams, D as Subscription, E as ListSubscriptionItemsParams, F as SubscriptionCharge, J as CancelSubscriptionParams, P as PaymentsEnvironment, K as InvoiceSettlement, M as InvoicePayment } from './errors-
|
|
2
|
-
export { B as Buyer, N as HeldTransferStatus, O as InvoiceAml, U as InvoiceAttempt, V as InvoiceLine, W as InvoiceLineInput, X as InvoiceLinesInput, b as InvoiceLocale, Y as InvoiceQuote, Z as InvoiceSeller, I as InvoiceStatus, _ as InvoiceTermsInput, $ as InvoiceWalletConfirmation, a0 as LedgerEvent, a1 as LedgerSummary, a2 as LedgerVerification, a as PaymentsCurrency, Q as QuasarRequestIssue, a3 as QuasarSDKError, a4 as RefundMode, d as SubscriptionInterval, S as SubscriptionPermission, c as SubscriptionStatus, T as TaxCategory } from './errors-
|
|
1
|
+
import { C as CreateInvoiceParams, i as CreateOptions, j as InvoiceWithCheckout, k as InvoiceDetails, L as ListInvoiceItemsParams, l as PaymentsList, R as Refund, m as InvoiceDocumentRef, n as ListInvoicesParams, o as Invoice, p as CorrectInvoiceParams, q as InvoiceCorrection, G as GetEventsParams, r as InvoiceLedger, f as RefundParams, g as RefundPreview, e as RefundStart, h as SubmitRefundParams, s as ListHeldTransfersParams, H as HeldTransfer, t as PaymentDocumentKind, u as PaymentDocument, v as QuoteParams, w as PaymentQuote, x as PaymentMethod, y as CreateSubscriptionParams, z as SubscriptionStart, A as ListSubscriptionsParams, D as Subscription, E as ListSubscriptionItemsParams, F as SubscriptionCharge, J as CancelSubscriptionParams, P as PaymentsEnvironment, K as InvoiceSettlement, M as InvoicePayment } from './errors-4kLHVSws.cjs';
|
|
2
|
+
export { B as Buyer, N as HeldTransferStatus, O as InvoiceAml, U as InvoiceAttempt, V as InvoiceLine, W as InvoiceLineInput, X as InvoiceLinesInput, b as InvoiceLocale, Y as InvoiceQuote, Z as InvoiceSeller, I as InvoiceStatus, _ as InvoiceTermsInput, $ as InvoiceWalletConfirmation, a0 as LedgerEvent, a1 as LedgerSummary, a2 as LedgerVerification, a as PaymentsCurrency, Q as QuasarRequestIssue, a3 as QuasarSDKError, a4 as RefundMode, d as SubscriptionInterval, S as SubscriptionPermission, c as SubscriptionStatus, T as TaxCategory } from './errors-4kLHVSws.cjs';
|
|
3
3
|
import { FetchOptions } from 'ofetch';
|
|
4
4
|
import { Transaction } from '@tuwaio/pulsar-core';
|
|
5
5
|
export { Transaction, TransactionStatus, TransactionTracker, UpdatableTransactionFields } from '@tuwaio/pulsar-core';
|
|
@@ -652,8 +652,8 @@ declare const PAYMENT_WEBHOOK_VERSION = "payments.v1";
|
|
|
652
652
|
type PaymentWebhookEventType = 'invoice.issued' | 'invoice.processing' | 'invoice.paid' | 'invoice.underpaid' | 'invoice.held' | 'invoice.transfer_held' | 'invoice.transfer_hold_voided' | 'invoice.released' | 'invoice.expired' | 'invoice.cancelled' | 'invoice.refunded' | 'invoice.partially_refunded' | 'invoice.replaced' | 'refund.confirmed' | 'refund.failed' | 'payment.reverted' | 'payment.unverified' | 'subscription.created' | 'subscription.renewed' | 'subscription.past_due' | 'subscription.paused' | 'subscription.resumed' | 'subscription.cancel_scheduled' | 'subscription.cancel_unscheduled' | 'subscription.canceled' | 'subscription.ended' | 'subscription.permission_granted' | 'subscription.charge_failed' | 'subscription.permission_revoked' | 'subscription.invoice_refused';
|
|
653
653
|
/**
|
|
654
654
|
* What a hold is about (`data.hold` of `invoice.held`): an invoice paid in a way that waits for your decision. `reason`
|
|
655
|
-
* (`late`, `aml`, `quote_expired`), its transaction (`txHash`), the wallets that sent it
|
|
656
|
-
* late (`late`). Release it with {@link PaymentsModule.releaseInvoice} or refund it; a refund to a wallet AML blocks now
|
|
655
|
+
* (`late`, `aml`, `quote_expired`), its transaction (`txHash`) and network (`chainId`), the wallets that sent it
|
|
656
|
+
* (`senders`) and whether it came late (`late`). Release it with {@link PaymentsModule.releaseInvoice} or refund it; a refund to a wallet AML blocks now
|
|
657
657
|
* is refused (`sender_blocked`).
|
|
658
658
|
*/
|
|
659
659
|
interface PaymentWebhookHold {
|
|
@@ -661,6 +661,8 @@ interface PaymentWebhookHold {
|
|
|
661
661
|
reason: 'late' | 'aml' | 'quote_expired' | null;
|
|
662
662
|
/** The transaction of the held payment. */
|
|
663
663
|
txHash: string | null;
|
|
664
|
+
/** CAIP-2 chain of the transaction; Quasar versions before November 10, 2026 leave it out. */
|
|
665
|
+
chainId?: string | null;
|
|
664
666
|
/** The wallets that sent it. */
|
|
665
667
|
senders?: string[];
|
|
666
668
|
/** It arrived after the invoice expired or was cancelled, or was handed over after `dueAt`. */
|
|
@@ -670,8 +672,9 @@ interface PaymentWebhookHold {
|
|
|
670
672
|
* A transfer that reached the invoice's address without being tied to it by proof (`data.heldTransfer` of
|
|
671
673
|
* `invoice.transfer_held`): it paid nothing and the invoice stays as it was. It is a record of its own, which you
|
|
672
674
|
* refund as a whole to the wallet that sent it ({@link PaymentsModule.refundHeldTransfer}): `reason` is
|
|
673
|
-
* `payer_mismatch` (another wallet than the one the quote was for)
|
|
674
|
-
* confirmed the invoice)
|
|
675
|
+
* `payer_mismatch` (another wallet than the one the quote was for), `payer_unconfirmed` (the quoted wallet never
|
|
676
|
+
* confirmed the invoice), `reference_missing` (a Solana Pay transfer without the invoice's reference whose amount does
|
|
677
|
+
* not tie it to the invoice either), `already_paid`, `quote_changed` or `too_many_parts`.
|
|
675
678
|
*/
|
|
676
679
|
interface PaymentWebhookHeldTransfer {
|
|
677
680
|
/** Not set: the transfer is held. */
|
|
@@ -680,12 +683,14 @@ interface PaymentWebhookHeldTransfer {
|
|
|
680
683
|
id: string | null;
|
|
681
684
|
/** Its transaction. */
|
|
682
685
|
txHash: string | null;
|
|
686
|
+
/** CAIP-2 chain of the transaction; Quasar versions before November 10, 2026 leave it out. */
|
|
687
|
+
chainId?: string | null;
|
|
683
688
|
/** What it carried, in base units of its token. */
|
|
684
689
|
amount: string | null;
|
|
685
690
|
/** The wallets that sent it. */
|
|
686
691
|
senders: string[];
|
|
687
692
|
/** Why it is tied to no invoice. */
|
|
688
|
-
reason: 'payer_mismatch' | 'payer_unconfirmed' | 'already_paid' | 'quote_changed' | 'too_many_parts' | null;
|
|
693
|
+
reason: 'payer_mismatch' | 'payer_unconfirmed' | 'reference_missing' | 'already_paid' | 'quote_changed' | 'too_many_parts' | null;
|
|
689
694
|
/** It arrived after the invoice expired or was cancelled. */
|
|
690
695
|
late?: true;
|
|
691
696
|
/** Set when AML blocked its sender: Quasar refunds it to no one. */
|
|
@@ -705,6 +710,8 @@ interface PaymentWebhookHeldTransferVoided {
|
|
|
705
710
|
voided: true;
|
|
706
711
|
/** Its transaction. */
|
|
707
712
|
txHash: string | null;
|
|
713
|
+
/** CAIP-2 chain of the transaction; Quasar versions before November 10, 2026 leave it out. */
|
|
714
|
+
chainId?: string | null;
|
|
708
715
|
/** The invoice the transaction paid instead. */
|
|
709
716
|
paidInvoice: string | null;
|
|
710
717
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as CreateInvoiceParams, i as CreateOptions, j as InvoiceWithCheckout, k as InvoiceDetails, L as ListInvoiceItemsParams, l as PaymentsList, R as Refund, m as InvoiceDocumentRef, n as ListInvoicesParams, o as Invoice, p as CorrectInvoiceParams, q as InvoiceCorrection, G as GetEventsParams, r as InvoiceLedger, f as RefundParams, g as RefundPreview, e as RefundStart, h as SubmitRefundParams, s as ListHeldTransfersParams, H as HeldTransfer, t as PaymentDocumentKind, u as PaymentDocument, v as QuoteParams, w as PaymentQuote, x as PaymentMethod, y as CreateSubscriptionParams, z as SubscriptionStart, A as ListSubscriptionsParams, D as Subscription, E as ListSubscriptionItemsParams, F as SubscriptionCharge, J as CancelSubscriptionParams, P as PaymentsEnvironment, K as InvoiceSettlement, M as InvoicePayment } from './errors-
|
|
2
|
-
export { B as Buyer, N as HeldTransferStatus, O as InvoiceAml, U as InvoiceAttempt, V as InvoiceLine, W as InvoiceLineInput, X as InvoiceLinesInput, b as InvoiceLocale, Y as InvoiceQuote, Z as InvoiceSeller, I as InvoiceStatus, _ as InvoiceTermsInput, $ as InvoiceWalletConfirmation, a0 as LedgerEvent, a1 as LedgerSummary, a2 as LedgerVerification, a as PaymentsCurrency, Q as QuasarRequestIssue, a3 as QuasarSDKError, a4 as RefundMode, d as SubscriptionInterval, S as SubscriptionPermission, c as SubscriptionStatus, T as TaxCategory } from './errors-
|
|
1
|
+
import { C as CreateInvoiceParams, i as CreateOptions, j as InvoiceWithCheckout, k as InvoiceDetails, L as ListInvoiceItemsParams, l as PaymentsList, R as Refund, m as InvoiceDocumentRef, n as ListInvoicesParams, o as Invoice, p as CorrectInvoiceParams, q as InvoiceCorrection, G as GetEventsParams, r as InvoiceLedger, f as RefundParams, g as RefundPreview, e as RefundStart, h as SubmitRefundParams, s as ListHeldTransfersParams, H as HeldTransfer, t as PaymentDocumentKind, u as PaymentDocument, v as QuoteParams, w as PaymentQuote, x as PaymentMethod, y as CreateSubscriptionParams, z as SubscriptionStart, A as ListSubscriptionsParams, D as Subscription, E as ListSubscriptionItemsParams, F as SubscriptionCharge, J as CancelSubscriptionParams, P as PaymentsEnvironment, K as InvoiceSettlement, M as InvoicePayment } from './errors-4kLHVSws.js';
|
|
2
|
+
export { B as Buyer, N as HeldTransferStatus, O as InvoiceAml, U as InvoiceAttempt, V as InvoiceLine, W as InvoiceLineInput, X as InvoiceLinesInput, b as InvoiceLocale, Y as InvoiceQuote, Z as InvoiceSeller, I as InvoiceStatus, _ as InvoiceTermsInput, $ as InvoiceWalletConfirmation, a0 as LedgerEvent, a1 as LedgerSummary, a2 as LedgerVerification, a as PaymentsCurrency, Q as QuasarRequestIssue, a3 as QuasarSDKError, a4 as RefundMode, d as SubscriptionInterval, S as SubscriptionPermission, c as SubscriptionStatus, T as TaxCategory } from './errors-4kLHVSws.js';
|
|
3
3
|
import { FetchOptions } from 'ofetch';
|
|
4
4
|
import { Transaction } from '@tuwaio/pulsar-core';
|
|
5
5
|
export { Transaction, TransactionStatus, TransactionTracker, UpdatableTransactionFields } from '@tuwaio/pulsar-core';
|
|
@@ -652,8 +652,8 @@ declare const PAYMENT_WEBHOOK_VERSION = "payments.v1";
|
|
|
652
652
|
type PaymentWebhookEventType = 'invoice.issued' | 'invoice.processing' | 'invoice.paid' | 'invoice.underpaid' | 'invoice.held' | 'invoice.transfer_held' | 'invoice.transfer_hold_voided' | 'invoice.released' | 'invoice.expired' | 'invoice.cancelled' | 'invoice.refunded' | 'invoice.partially_refunded' | 'invoice.replaced' | 'refund.confirmed' | 'refund.failed' | 'payment.reverted' | 'payment.unverified' | 'subscription.created' | 'subscription.renewed' | 'subscription.past_due' | 'subscription.paused' | 'subscription.resumed' | 'subscription.cancel_scheduled' | 'subscription.cancel_unscheduled' | 'subscription.canceled' | 'subscription.ended' | 'subscription.permission_granted' | 'subscription.charge_failed' | 'subscription.permission_revoked' | 'subscription.invoice_refused';
|
|
653
653
|
/**
|
|
654
654
|
* What a hold is about (`data.hold` of `invoice.held`): an invoice paid in a way that waits for your decision. `reason`
|
|
655
|
-
* (`late`, `aml`, `quote_expired`), its transaction (`txHash`), the wallets that sent it
|
|
656
|
-
* late (`late`). Release it with {@link PaymentsModule.releaseInvoice} or refund it; a refund to a wallet AML blocks now
|
|
655
|
+
* (`late`, `aml`, `quote_expired`), its transaction (`txHash`) and network (`chainId`), the wallets that sent it
|
|
656
|
+
* (`senders`) and whether it came late (`late`). Release it with {@link PaymentsModule.releaseInvoice} or refund it; a refund to a wallet AML blocks now
|
|
657
657
|
* is refused (`sender_blocked`).
|
|
658
658
|
*/
|
|
659
659
|
interface PaymentWebhookHold {
|
|
@@ -661,6 +661,8 @@ interface PaymentWebhookHold {
|
|
|
661
661
|
reason: 'late' | 'aml' | 'quote_expired' | null;
|
|
662
662
|
/** The transaction of the held payment. */
|
|
663
663
|
txHash: string | null;
|
|
664
|
+
/** CAIP-2 chain of the transaction; Quasar versions before November 10, 2026 leave it out. */
|
|
665
|
+
chainId?: string | null;
|
|
664
666
|
/** The wallets that sent it. */
|
|
665
667
|
senders?: string[];
|
|
666
668
|
/** It arrived after the invoice expired or was cancelled, or was handed over after `dueAt`. */
|
|
@@ -670,8 +672,9 @@ interface PaymentWebhookHold {
|
|
|
670
672
|
* A transfer that reached the invoice's address without being tied to it by proof (`data.heldTransfer` of
|
|
671
673
|
* `invoice.transfer_held`): it paid nothing and the invoice stays as it was. It is a record of its own, which you
|
|
672
674
|
* refund as a whole to the wallet that sent it ({@link PaymentsModule.refundHeldTransfer}): `reason` is
|
|
673
|
-
* `payer_mismatch` (another wallet than the one the quote was for)
|
|
674
|
-
* confirmed the invoice)
|
|
675
|
+
* `payer_mismatch` (another wallet than the one the quote was for), `payer_unconfirmed` (the quoted wallet never
|
|
676
|
+
* confirmed the invoice), `reference_missing` (a Solana Pay transfer without the invoice's reference whose amount does
|
|
677
|
+
* not tie it to the invoice either), `already_paid`, `quote_changed` or `too_many_parts`.
|
|
675
678
|
*/
|
|
676
679
|
interface PaymentWebhookHeldTransfer {
|
|
677
680
|
/** Not set: the transfer is held. */
|
|
@@ -680,12 +683,14 @@ interface PaymentWebhookHeldTransfer {
|
|
|
680
683
|
id: string | null;
|
|
681
684
|
/** Its transaction. */
|
|
682
685
|
txHash: string | null;
|
|
686
|
+
/** CAIP-2 chain of the transaction; Quasar versions before November 10, 2026 leave it out. */
|
|
687
|
+
chainId?: string | null;
|
|
683
688
|
/** What it carried, in base units of its token. */
|
|
684
689
|
amount: string | null;
|
|
685
690
|
/** The wallets that sent it. */
|
|
686
691
|
senders: string[];
|
|
687
692
|
/** Why it is tied to no invoice. */
|
|
688
|
-
reason: 'payer_mismatch' | 'payer_unconfirmed' | 'already_paid' | 'quote_changed' | 'too_many_parts' | null;
|
|
693
|
+
reason: 'payer_mismatch' | 'payer_unconfirmed' | 'reference_missing' | 'already_paid' | 'quote_changed' | 'too_many_parts' | null;
|
|
689
694
|
/** It arrived after the invoice expired or was cancelled. */
|
|
690
695
|
late?: true;
|
|
691
696
|
/** Set when AML blocked its sender: Quasar refunds it to no one. */
|
|
@@ -705,6 +710,8 @@ interface PaymentWebhookHeldTransferVoided {
|
|
|
705
710
|
voided: true;
|
|
706
711
|
/** Its transaction. */
|
|
707
712
|
txHash: string | null;
|
|
713
|
+
/** CAIP-2 chain of the transaction; Quasar versions before November 10, 2026 leave it out. */
|
|
714
|
+
chainId?: string | null;
|
|
708
715
|
/** The invoice the transaction paid instead. */
|
|
709
716
|
paidInvoice: string | null;
|
|
710
717
|
}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b as b$1}from'./chunk-KLHEH7HS.js';export{a as QuasarSDKError}from'./chunk-KLHEH7HS.js';import {e,b,d as d$1,c as c$1,a as a$1}from'./chunk-ZSO6HC5H.js';export{a as BASE_API_URL,e as PAYMENTS_ENDPOINT,c as PULSAR_HISTORY_ENDPOINT,b as PULSAR_SYNC_ENDPOINT,d as pulsarSyncHashEndpoint}from'./chunk-ZSO6HC5H.js';import {ofetch}from'ofetch';var s=
|
|
1
|
+
import {b as b$1}from'./chunk-KLHEH7HS.js';export{a as QuasarSDKError}from'./chunk-KLHEH7HS.js';import {e,b,d as d$1,c as c$1,a as a$1}from'./chunk-ZSO6HC5H.js';export{a as BASE_API_URL,e as PAYMENTS_ENDPOINT,c as PULSAR_HISTORY_ENDPOINT,b as PULSAR_SYNC_ENDPOINT,d as pulsarSyncHashEndpoint}from'./chunk-ZSO6HC5H.js';import {ofetch}from'ofetch';var s=n=>encodeURIComponent(n),d=n=>n instanceof Date?n.toISOString():n,p=n=>n?.idempotencyKey?{"Idempotency-Key":n.idempotencyKey}:{},$=n=>Array.isArray(n)?n.join(","):n,c=n=>Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0)),m=class{constructor(e){this.client=e;}client;async createInvoice(e$1,t){return this.client.request(`${e}/invoices`,{method:"POST",body:{...e$1,dueAt:d(e$1.dueAt),supplyDate:d(e$1.supplyDate)},headers:p(t)})}async getInvoice(e$1){return this.client.request(`${e}/invoices/${s(e$1)}`,{method:"GET"})}async listInvoiceRefunds(e$1,t={}){return this.client.request(`${e}/invoices/${s(e$1)}/refunds`,{method:"GET",query:c({limit:t.limit,cursor:t.cursor})})}async listInvoiceDocuments(e$1,t={}){return this.client.request(`${e}/invoices/${s(e$1)}/documents`,{method:"GET",query:c({limit:t.limit,cursor:t.cursor})})}async listInvoices(e$1={}){return this.client.request(`${e}/invoices`,{method:"GET",query:c({status:$(e$1.status),environment:e$1.environment,externalId:e$1.externalId,createdAfter:d(e$1.createdAfter),createdBefore:d(e$1.createdBefore),limit:e$1.limit,cursor:e$1.cursor})})}async cancelInvoice(e$1,t={}){return this.client.request(`${e}/invoices/${s(e$1)}/cancel`,{method:"POST",body:t})}async releaseInvoice(e$1,t){return this.client.request(`${e}/invoices/${s(e$1)}/release`,{method:"POST",body:t})}async correctInvoice(e$1,t){return this.client.request(`${e}/invoices/${s(e$1)}/correct`,{method:"POST",body:t})}async replacePayLink(e$1){return this.client.request(`${e}/invoices/${s(e$1)}/checkout`,{method:"POST",body:{}})}async getEvents(e$1,t={}){return this.client.request(`${e}/invoices/${s(e$1)}/events`,{method:"GET",query:c({verify:t.verify?"true":void 0,limit:t.limit,cursor:t.cursor})})}async previewRefund(e$1,t={}){return this.client.request(`${e}/invoices/${s(e$1)}/refunds/preview`,{method:"POST",body:t})}async refund(e$1,t={},i){return this.client.request(`${e}/invoices/${s(e$1)}/refunds`,{method:"POST",body:t,headers:p(i)})}async withdrawRefund(e$1){return this.client.request(`${e}/refunds/${s(e$1)}/withdraw`,{method:"POST",body:{}})}async getRefund(e$1){return this.client.request(`${e}/refunds/${s(e$1)}`,{method:"GET"})}async submitRefund(e$1,t){return this.client.request(`${e}/refunds/${s(e$1)}/submit`,{method:"POST",body:t})}async listHeldTransfers(e$1={}){let t=e$1.invoice?`${e}/invoices/${s(e$1.invoice)}/held-transfers`:`${e}/held-transfers`,i=await this.client.request(t,{method:"GET",query:e$1.invoice?{}:c({status:e$1.status})});return e$1.invoice&&e$1.status?i.heldTransfers.filter(o=>o.status===e$1.status):i.heldTransfers}async refundHeldTransfer(e$1){return this.client.request(`${e}/held-transfers/${s(e$1)}/refund`,{method:"POST",body:{}})}async getDocument(e$1,t){return this.client.requestFile(`${e}/invoices/${s(e$1)}/documents/${t}`)}async getCreditNote(e$1,t,i="pdf"){let o=`${s(t)}${i==="ubl"?".xml":""}`;return this.client.requestFile(`${e}/invoices/${s(e$1)}/documents/credit-note/${o}`)}async quote(e$1){return this.client.request(`${e}/quotes`,{method:"POST",body:e$1})}async listMethods(){return this.client.request(`${e}/methods`,{method:"GET"})}async createSubscription(e$1,t){return this.client.request(`${e}/subscriptions`,{method:"POST",body:{...e$1,endsAt:d(e$1.endsAt)},headers:p(t)})}async listSubscriptions(e$1={}){return this.client.request(`${e}/subscriptions`,{method:"GET",query:c({status:$(e$1.status),limit:e$1.limit,cursor:e$1.cursor})})}async getSubscription(e$1){return this.client.request(`${e}/subscriptions/${s(e$1)}`,{method:"GET"})}async listSubscriptionInvoices(e$1,t={}){return this.client.request(`${e}/subscriptions/${s(e$1)}/invoices`,{method:"GET",query:c({limit:t.limit,cursor:t.cursor})})}async listSubscriptionCharges(e$1,t={}){return this.client.request(`${e}/subscriptions/${s(e$1)}/charges`,{method:"GET",query:c({limit:t.limit,cursor:t.cursor})})}async cancelSubscription(e$1,t={}){return this.client.request(`${e}/subscriptions/${s(e$1)}/cancel`,{method:"POST",body:t})}async undoSubscriptionCancel(e$1){return this.client.request(`${e}/subscriptions/${s(e$1)}/cancel/undo`,{method:"POST",body:{}})}async endSubscriptionPermission(e$1){return this.client.request(`${e}/subscriptions/${s(e$1)}/permission/end`,{method:"POST",body:{}})}async pauseSubscription(e$1){return this.client.request(`${e}/subscriptions/${s(e$1)}/pause`,{method:"POST",body:{}})}async resumeSubscription(e$1){return this.client.request(`${e}/subscriptions/${s(e$1)}/resume`,{method:"POST",body:{}})}};var l=class{constructor(e){this.client=e;}client;async syncCreate(e,t){return this.client.request(b,{method:"POST",body:{...e,appName:t}})}async syncHash(e,t){return this.client.request(d$1(e),{method:"POST",body:{hash:t}})}async getHistory(e={}){return this.client.request(c$1,{method:"GET",query:{page:e.page??1,limit:e.limit??10,chainId:e.chainId,status:e.status,txKey:e.txKey,appName:e.appName,walletAddress:e.walletAddress}})}};var y=class{secretKey;internalSecret;baseUrl;timeout;constructor(e){if(!e.secretKey)throw new Error("[Quasar SDK] Missing API Key. Provide the secretKey of your Quasar app (sk_live_ or sk_test_).");this.secretKey=e.secretKey,this.internalSecret=e.internalSecret,this.baseUrl=e.baseUrl||a$1,this.timeout=e.timeout||1e4;}async request(e,t={}){try{return await ofetch(e,{baseURL:this.baseUrl,timeout:this.timeout,...t,headers:{"Content-Type":"application/json","x-tuwa-secret-key":this.secretKey,...this.internalSecret?{"x-internal-secret":this.internalSecret}:{},...t.headers}})}catch(i){throw b$1(i)}}async requestFile(e){try{let t=await ofetch.raw(e,{baseURL:this.baseUrl,timeout:this.timeout,method:"GET",responseType:"arrayBuffer",headers:{"x-tuwa-secret-key":this.secretKey,...this.internalSecret?{"x-internal-secret":this.internalSecret}:{}}}),i=t.headers.get("content-disposition")??"";return {bytes:new Uint8Array(t._data??new ArrayBuffer(0)),contentType:t.headers.get("content-type"),filename:/filename="([^"]*)"/.exec(i)?.[1]??null}}catch(t){throw b$1(t)}}};var f=class{client;pulsar;payments;constructor(e){this.client=new y(e),this.pulsar=new l(this.client),this.payments=new m(this.client);}};var C="x-quasar-signature",O="payments.v1",a=class extends Error{code;constructor(e,t){super(t),this.name="QuasarWebhookError",this.code=e;}},k=300;async function A(n,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},false,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",t,e));return Array.from(i,o=>o.toString(16).padStart(2,"0")).join("")}function R(n,e){if(n.length!==e.length)return false;let t=0;for(let i=0;i<n.length;i++)t|=n.charCodeAt(i)^e.charCodeAt(i);return t===0}function W(n){if(H(n)||n.sentAt!=null)return {field:"sentAt",time:typeof n.sentAt=="string"?Date.parse(n.sentAt):NaN};let{timestamp:e}=n;return {field:"timestamp",time:typeof e=="number"&&Number.isFinite(e)?e*1e3:NaN}}function H(n){return n.apiVersion===O}async function Y(n){let{body:e,signature:t,secret:i,toleranceSeconds:o=k,now:E=new Date}=n;if(o!==false&&(typeof o!="number"||!Number.isFinite(o)||o<=0))throw new a("invalid_options","toleranceSeconds must be a finite number above 0, or false");if(!i)throw new a("missing_secret","No signing secret to verify the webhook with");if(!t)throw new a("missing_signature",`The ${C} header is missing`);let x=typeof e=="string"?new TextEncoder().encode(e):e,_=await A(i,x);if(!R(t.trim().toLowerCase(),_))throw new a("invalid_signature","The signature does not match the body");let u;try{u=JSON.parse(typeof e=="string"?e:new TextDecoder().decode(e));}catch{throw new a("invalid_body","The body is not JSON")}if(typeof u!="object"||u===null||Array.isArray(u))throw new a("invalid_body","The body is not a webhook");let b=u;if(o!==false){let{field:P,time:g}=W(b);if(Number.isNaN(g))throw new a("stale",`The event carries no valid send time (${P})`);if(Math.abs(E.getTime()-g)>o*1e3)throw new a("stale",`The event was sent outside the ${o} s tolerance (${P})`)}return b}export{O as PAYMENT_WEBHOOK_VERSION,m as PaymentsModule,l as PulsarModule,f as Quasar,a as QuasarWebhookError,C as WEBHOOK_SIGNATURE_HEADER,H as isPaymentWebhookEvent,Y as verifyWebhook};
|