@tuwaio/nova-payments 0.2.0 → 0.3.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 CHANGED
@@ -156,7 +156,7 @@ export function PayPage({ token }: { token: string }) {
156
156
 
157
157
  The full integration with Satellite Connect, SIWX and Pulsar is in the **[Full-Stack React guide](https://docs.tuwa.io/guides/full-stack-react)**.
158
158
 
159
- Before an EVM payment the buyer's wallet sends itself (paying the gas, or a smart wallet with or without the merchant's paymaster), the wallet confirms the invoice: right after the wallet and the method are chosen, before the price, a step says that it is free and moves no money, sums up what the wallet signs (the invoice, the seller, the amount and the wallet) and opens the wallet's signature request (an EIP-4361 message from Quasar, signed with `personal_sign`; a smart wallet may ask for its passkey). Quasar credits the wallet's transfers to this invoice only once it signed; one signature per invoice and wallet, so a new price, token or network needs none. A refusal keeps the buyer on the step with the reason and the same button; "Back to methods" returns. A gasless USDC or EURC payment needs no extra window (the signed authorization confirms the wallet), and when the buyer pays the gas of such a method instead, the pay step asks for the confirmation first. Solana payments and automatic charges are unchanged. A chain adapter of your own adds `signMessage` for it.
159
+ Before an EVM payment the buyer's wallet sends itself (paying the gas, or a smart wallet with or without the merchant's paymaster), the wallet confirms the invoice: right after the wallet and the method are chosen, before the price, a step says that it is free and moves no money, sums up what the wallet signs (the invoice, the seller, the amount and the wallet) and opens the wallet's signature request (an EIP-4361 message from Quasar, signed with `personal_sign`; a smart wallet may ask for its passkey). Quasar credits the wallet's transfers to this invoice only once it signed; one signature per invoice and wallet, so a new price, token or network needs none. A refusal keeps the buyer on the step with the reason and the same button; "Back to methods" returns. A gasless USDC or EURC payment needs no extra window (the signed authorization confirms the wallet), and when the buyer pays the gas of such a method instead, the pay step asks for the confirmation first. The EVM adapter sends a gasless payment itself, from a one-time account: a key it makes in memory for the payment, delegated (EIP-7702) to `Simple7702Account`, whose one call is the transfer Quasar authorized for the signature, sponsored by the merchant's paymaster; the wallet signs only the authorization, and Quasar signs nothing. Solana payments and automatic charges are unchanged. A chain adapter of your own adds `signMessage` for it.
160
160
 
161
161
  After the payment the checkout shows its outcome: confirming, paid with the receipt and the way back to the invoice's `successUrl` (a visible countdown with "Stay here"; `autoReturnSeconds`, `0` for none). A payment that fails for good while the buyer watches (reverted, cancelled in the wallet, an expired Solana transaction) stays on the same screen as the `failed` step, with its transaction, the reason and "Pay again". Underpaid, held, refunded, expired, cancelled and corrected invoices get their own outcome with a "Contact" link to the seller (`onContact` replaces it). Every status screen has the same head in the same place (the mark, a chip that names the state, the heading and the amount), so one goes on into the next: the pixels of the Quasar loader fly into the check mark or the cross, the chip changes its color and word, the heading morphs, the steps run on, the fill of the main button comes in over "Close" and the receipt opens. On a phone, where the checkout is as tall as its step, its height glides from one status screen to the next instead of jumping. With `prefers-reduced-motion`, or `config.animation.disabled`, the screens just change. `onPaid` tells the page once the invoice is paid; fulfil orders from the `invoice.paid` webhook on your server. Closing the checkout before anything is sent asks first. The countdown to the invoice's deadline stays in the order through every step, also while the wallet signs and the payment confirms, and goes once the payment succeeded or the invoice has another outcome; when the deadline passes while the payment confirms, it stays at 00:00 and the confirm step says that a payment sent in time is being confirmed (from Quasar's word on that payment, else its `paymentCountsUntil`, else the page's clock), or that a payment arriving after the invoice closes waits for the seller to accept or return it. The buyer is never invited to pay twice: a page reopened while a payment of the invoice is on its way shows that payment confirming, and a payment Quasar could not confirm asks the buyer to check the wallet before paying again instead of offering the payment. The checkout says that Quasar checks the payment again for 24 hours and records it for the seller only while Quasar still reads it again (not found, no receipt in time, replaced); for a payment Quasar does not read again (a relay operation lost, an unknown failure, no result on chain within 24 hours, a hand-over the page gave up after an hour) it asks the buyer to contact the seller with the transaction hash, which it shows. A payment counts as sent once the wallet returned its hash: an invoice that expires or is cancelled while a payment may still arrive never says that nothing was charged, and a transaction that does not pay the invoice (a wrong amount or recipient) is named as such, with the seller to contact if money left the wallet. A QR code the checkout showed may have been paid from a phone, so an invoice that expires or is cancelled after it never says that nothing was charged either. A transaction the page of another invoice handed over first (EVM invoices share the seller's address) is credited by Quasar to the invoice the wallet that sent it confirmed: the checkout follows it, offers no payment meanwhile and shows its hash for the seller, and says that it pays another invoice if Quasar credits it there. A transfer from a wallet that did not confirm the invoice pays no invoice: the checkout says that the seller returns it to the wallet that sent it (a held invoice of that kind takes no other payment, so the buyer asks the seller for a new one), never that the seller checks it. A payment the network confirmed that Quasar has not recorded yet is named with its hash for the seller, never as a failure, and no payment is offered; the checkout says that Quasar tries again daily (for 30 days) only while Quasar says it does. On an expired or cancelled invoice the checkout says until when the page follows a payment on its way; later, a reload shows the outcome.
162
162
 
@@ -225,13 +225,13 @@ The checkout speaks the six languages of Quasar invoices: English, Ukrainian, Si
225
225
 
226
226
  ## 🗄️ Browser Storage
227
227
 
228
- The checkout and the refund window save nothing to `localStorage` or cookies. Until Quasar takes or refuses a payment transaction the wallet sent, the checkout store of `@tuwaio/quasar-sdk` keeps its hand-over in `sessionStorage` (the browser tab, until it closes) under `quasar-sdk:checkoutHandOvers:<checkout token>`: the transaction hash, the sending wallet, the wallet connector and when it was sent, so a page closed or reloaded before Quasar answered hands the payment over again (nothing is kept with your own `api`). A sponsored batch the wallet took has no hash yet: it is kept in `sessionStorage` under `nova-payments:sponsoredBatches` for 35 minutes or until its hash comes (the invoice ID, the batch ID, the wallet, the wallet connector, the method and what it pays), so a reload follows it instead of offering to pay next to it. Until Quasar takes it or refuses it for good, a refund transaction the wallet sent is kept by the refund store of `@tuwaio/quasar-sdk` in `sessionStorage` under `quasar-sdk:refundHandOvers`: the refund and invoice IDs, the refund's instructions, the transaction hash and the sending wallet, so a reload hands it over instead of having the wallet send the refund again. A payment it hands over to your Pulsar store is kept by that store (`createPulsarStore` persists its pool under its own name).
228
+ The checkout and the refund window save nothing to `localStorage` or cookies. Until Quasar takes or refuses a payment transaction the wallet sent, the checkout store of `@tuwaio/quasar-sdk` keeps its hand-over in `sessionStorage` (the browser tab, until it closes) under `quasar-sdk:checkoutHandOvers:<checkout token>`: the transaction hash, the sending wallet, the wallet connector and when it was sent, so a page closed or reloaded before Quasar answered hands the payment over again (nothing is kept with your own `api`). A sponsored batch the wallet took has no hash yet: it is kept in `sessionStorage` under `nova-payments:sponsoredBatches` for 35 minutes or until its hash comes (the invoice ID, the batch ID, the wallet, the wallet connector, the method and what it pays), so a reload follows it instead of offering to pay next to it. Until Quasar takes it or refuses it for good, a refund transaction the wallet sent is kept by the refund store of `@tuwaio/quasar-sdk` in `sessionStorage` under `quasar-sdk:refundHandOvers`: the refund and invoice IDs, the refund's instructions, the transaction hash and the sending wallet, so a reload hands it over instead of having the wallet send the refund again. A payment it hands over to your Pulsar store is kept by that store (`createPulsarStore` persists its pool under its own name). The key of the one-time account that sends a gasless payment stays in memory: it is never saved or sent.
229
229
 
230
230
  Nova's own connection (`ownConnection`) keeps the connected wallet in `sessionStorage` until the tab closes (`orbit-core:lastConnectedConnector` and `orbit-core:recentlyConnectedConnectorsListHelpers`, see [`@tuwaio/satellite-core`](https://satellite.docs.tuwa.io/packages/satellite-core)), and in `localStorage` with `rememberWallet: true` or, with `autoConnect`, when the buyer ticks "Remember this wallet" in its connect modal. Every Satellite store of the site shares these keys: connecting a wallet there that is not remembered moves `orbit-core:lastConnectedConnector` and that wallet's entry of the list out of `localStorage`, and disconnecting removes the last connection, so another Satellite app on the same origin forgets the wallet it remembered. wagmi keeps its own `wagmi.*` keys in `localStorage` unless the wagmi config uses `createStorage({ storage: noopStorage })`, as in the example above. Inside the app's connection, the app's stores keep them.
231
231
 
232
232
  ## 🌐 External Services
233
233
 
234
- The checkout routes of the Quasar API (`baseUrl`, Quasar Cloud by default): `GET /v1/payments/checkout/{token}`, its event stream and logo, and the `POST` routes of the steps (`buyer`, `locale`, `payer-proof/message`, `payer-proof`, `quote`, `submit`, `relay`; the wallet calls the `paymaster` route for sponsored calls). The EVM adapter reads balances and fee estimates through the RPC transports of your wagmi config, the Solana adapter through its `rpcUrls` (else the public endpoint of the cluster); links to transactions open the chain's block explorer (the explorer of the wagmi chain, the Solana Explorer). A refund calls only your server (the calls of its store); the adapters read the merchant wallet's balance and the fee the same way. Nova's own connection loads what its Satellite adapters and its Nova Connect modal load (see [`@tuwaio/nova-connect`](https://stories.tuwa.io/?path=/docs/packages-nova-connect-overview--docs)) through the RPC of its wagmi config and `rpcUrls`. The wallet asks the buyer, or the merchant for a refund, before every signature or transaction.
234
+ The checkout routes of the Quasar API (`baseUrl`, Quasar Cloud by default): `GET /v1/payments/checkout/{token}`, its event stream and logo, and the `POST` routes of the steps (`buyer`, `locale`, `payer-proof/message`, `payer-proof`, `quote`, `submit`, `relay/authorize`, `relay`; the wallet calls the `paymaster` route for sponsored calls, and so does the page's one-time account of a gasless payment). The EVM adapter reads balances and fee estimates through the RPC transports of your wagmi config (and the nonce and code of a one-time account), the Solana adapter through its `rpcUrls` (else the public endpoint of the cluster); links to transactions open the chain's block explorer (the explorer of the wagmi chain, the Solana Explorer). A refund calls only your server (the calls of its store); the adapters read the merchant wallet's balance and the fee the same way. Nova's own connection loads what its Satellite adapters and its Nova Connect modal load (see [`@tuwaio/nova-connect`](https://stories.tuwa.io/?path=/docs/packages-nova-connect-overview--docs)) through the RPC of its wagmi config and `rpcUrls`. The wallet asks the buyer, or the merchant for a refund, before every signature or transaction.
235
235
 
236
236
  ---
237
237
 
@@ -1 +1 @@
1
- 'use strict';var chunk7FQXTBOY_cjs=require('../chunk-7FQXTBOY.cjs'),orbitCore=require('@tuwaio/orbit-core'),pulsarCore=require('@tuwaio/pulsar-core'),core=require('@wagmi/core'),viem=require('viem');var R=18e4,U=30*6e4,G=15e3,V=25n;function h(t){let i=orbitCore.toEvmChainId(t);if(i===void 0)throw new Error(`${t} is not an EVM chain`);return i}function A(t){if(t.family!=="eip155")throw new Error(`${t.chainId} is not an EVM chain`);return t}function S(t){return t.token==="native"?{to:t.to,value:BigInt(t.amount)}:{to:t.token,data:viem.encodeFunctionData({abi:viem.erc20Abi,functionName:"transfer",args:[t.to,BigInt(t.amount)]})}}async function q(t,i,d){try{return {gas:(await core.estimateGas(t,{account:i,chainId:d.chainId,...S(d)})*(100n+V)+99n)/100n}}catch{return {}}}async function W(t){if(t?.type!=="walletConnect")return false;try{let i=await t.getProvider();return /^safe\b/i.test(i.session?.peer?.metadata?.name??"")}catch{return false}}function X(t){let i=async()=>{let a=core.getConnection(t).connector;if(a?.id==="safe"||a?.type==="safe"||await W(a))throw new chunk7FQXTBOY_cjs.a("unsupported","A Safe wallet cannot pay this checkout")},d=async a=>{let n;try{n=await core.getConnection(t).connector?.getChainId();}catch{return}if(!(n===void 0||n===a))try{await core.switchChain(t,{chainId:a});}catch(e){let s=chunk7FQXTBOY_cjs.b(e);throw s==="declined"?new chunk7FQXTBOY_cjs.a("declined",`The wallet declined the switch to ${a}`,{cause:e,step:"switch"}):s!=="failed"?e:new chunk7FQXTBOY_cjs.a("switchFailed",`The wallet did not switch to ${a}`,{cause:e,step:"switch"})}},f=async(a,n,e)=>{for(;Date.now()<n;){try{let s=await core.waitForCallsStatus(t,{id:a,timeout:n-Date.now()});if(s.status==="failure")return;let r=s.status==="success"?s.receipts?.at(-1)?.transactionHash:void 0;if(r)return e?.(r)}catch{}await orbitCore.delay(void 0,G);}};return {family:"eip155",getBalance:async({chainId:a,account:n,token:e})=>{let s=h(a);return e==="native"?(await core.getBalance(t,{address:n,chainId:s})).value:core.readContract(t,{address:e,abi:viem.erc20Abi,functionName:"balanceOf",args:[n],chainId:s})},estimateFee:async({instructions:a,account:n})=>{let e=A(a),s=await core.estimateGas(t,{account:n,chainId:e.chainId,...S(e)}),r=await core.estimateFeesPerGas(t,{chainId:e.chainId}),u=r.maxFeePerGas??r.gasPrice;if(u===void 0)return null;let l=t.chains.find(o=>o.id===e.chainId)?.nativeCurrency;return {amount:s*u,decimals:l?.decimals??18,symbol:l?.symbol??"ETH"}},canSponsorCalls:async({chainId:a,account:n})=>{try{return (await core.getCapabilities(t,{account:n,chainId:h(a)})).paymasterService?.supported===!0}catch{return false}},switchChain:async a=>{await core.switchChain(t,{chainId:h(a)});},sendTransfer:async({instructions:a,account:n})=>{let e=A(a);if(await i(),await d(e.chainId),e.token==="native"){let s=await q(t,n,e);return core.sendTransaction(t,{account:n,chainId:e.chainId,to:e.to,value:BigInt(e.amount),...s})}return core.writeContract(t,{account:n,chainId:e.chainId,address:e.token,abi:viem.erc20Abi,functionName:"transfer",args:[e.to,BigInt(e.amount)]})},signTransferAuthorization:async({typedData:a,account:n})=>{await i();let e=Number(a.domain.chainId);return await d(e),(await core.getConnectorClient(t,{chainId:e})).request({method:"eth_signTypedData_v4",params:[n,JSON.stringify(a)]})},signMessage:async({message:a,account:n,chainId:e})=>{await i();let s=orbitCore.toEvmChainId(e);return s!==void 0&&await d(s),core.signMessage(t,{account:n,message:a})},followSponsoredCalls:({batchId:a,until:n,onLate:e})=>{f(a,n,e).catch(()=>{});},sendSponsoredCalls:async({calls:a,paymasterUrl:n,chainId:e,account:s,onSent:r,onAccepted:u,onLate:l})=>{await i(),await d(h(e));let{id:o}=await core.sendCalls(t,{account:s,chainId:h(e),calls:a.map(c=>({to:c.to,value:BigInt(c.value),data:c.data})),capabilities:{paymasterService:{url:n}}});u?.(o),r?.();let w=c=>(f(o,Date.now()+U,l).catch(()=>{}),new chunk7FQXTBOY_cjs.a("sentUnconfirmed","The sponsored payment is not confirmed yet",{cause:c})),y=await core.waitForCallsStatus(t,{id:o,timeout:R}).catch(c=>{throw w(c)});if(y.status==="failure")throw new chunk7FQXTBOY_cjs.a("failed","The sponsored payment failed");let C=y.status==="success"?y.receipts?.at(-1)?.transactionHash:void 0;if(!C)throw w();return C},explorerUrl:({chainId:a,txKey:n})=>{let s=t.chains.find(r=>r.id===orbitCore.toEvmChainId(a))?.blockExplorers?.default.url;return s?`${s}/tx/${n}`:void 0},explorerAddressUrl:({chainId:a,address:n})=>{let s=t.chains.find(r=>r.id===orbitCore.toEvmChainId(a))?.blockExplorers?.default.url;return s?`${s}/address/${n}`:void 0},pulsarTransaction:({txKey:a,instructions:n,account:e,connectorType:s,title:r,description:u,payload:l})=>{let o=A(n);return {adapter:orbitCore.OrbitAdapter.EVM,tracker:pulsarCore.TransactionTracker.Ethereum,txKey:a,hash:a,chainId:o.chainId,from:e,to:o.token==="native"?o.to:o.token,type:"payment",connectorType:s,title:r,description:u,payload:l,pending:true,localTimestamp:Math.floor(Date.now()/1e3),isTrackedModalOpen:false}}}}exports.paymentsEVMAdapter=X;
1
+ 'use strict';var chunk7FQXTBOY_cjs=require('../chunk-7FQXTBOY.cjs'),orbitCore=require('@tuwaio/orbit-core'),pulsarCore=require('@tuwaio/pulsar-core'),core=require('@wagmi/core'),viem=require('viem'),accountAbstraction=require('viem/account-abstraction'),accounts=require('viem/accounts');var J=18e4,W=30*6e4,Q=15e3,X=25n;function w(t){let i=orbitCore.toEvmChainId(t);if(i===void 0)throw new Error(`${t} is not an EVM chain`);return i}function A(t){if(t.family!=="eip155")throw new Error(`${t.chainId} is not an EVM chain`);return t}function x(t){return t.token==="native"?{to:t.to,value:BigInt(t.amount)}:{to:t.token,data:viem.encodeFunctionData({abi:viem.erc20Abi,functionName:"transfer",args:[t.to,BigInt(t.amount)]})}}async function Y(t,i,u){try{return {gas:(await core.estimateGas(t,{account:i,chainId:u.chainId,...x(u)})*(100n+X)+99n)/100n}}catch{return {}}}async function Z(t){if(t?.type!=="walletConnect")return false;try{let i=await t.getProvider();return /^safe\b/i.test(i.session?.peer?.metadata?.name??"")}catch{return false}}var ee=1e4;async function te(t,i){let l=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:i,params:[]}),signal:AbortSignal.timeout(ee)})).json();if(l.error||l.result===void 0)throw new Error(l.error?.message??`${i} failed`);return l.result}function de(t){let i=async()=>{let a=core.getConnection(t).connector;if(a?.id==="safe"||a?.type==="safe"||await Z(a))throw new chunk7FQXTBOY_cjs.a("unsupported","A Safe wallet cannot pay this checkout")},u=async a=>{let n;try{n=await core.getConnection(t).connector?.getChainId();}catch{return}if(!(n===void 0||n===a))try{await core.switchChain(t,{chainId:a});}catch(e){let s=chunk7FQXTBOY_cjs.b(e);throw s==="declined"?new chunk7FQXTBOY_cjs.a("declined",`The wallet declined the switch to ${a}`,{cause:e,step:"switch"}):s!=="failed"?e:new chunk7FQXTBOY_cjs.a("switchFailed",`The wallet did not switch to ${a}`,{cause:e,step:"switch"})}},l=async(a,n,e)=>{for(;Date.now()<n;){try{let s=await core.waitForCallsStatus(t,{id:a,timeout:n-Date.now()});if(s.status==="failure")return;let r=s.status==="success"?s.receipts?.at(-1)?.transactionHash:void 0;if(r)return e?.(r)}catch{}await orbitCore.delay(void 0,Q);}};return {family:"eip155",getBalance:async({chainId:a,account:n,token:e})=>{let s=w(a);return e==="native"?(await core.getBalance(t,{address:n,chainId:s})).value:core.readContract(t,{address:e,abi:viem.erc20Abi,functionName:"balanceOf",args:[n],chainId:s})},estimateFee:async({instructions:a,account:n})=>{let e=A(a),s=await core.estimateGas(t,{account:n,chainId:e.chainId,...x(e)}),r=await core.estimateFeesPerGas(t,{chainId:e.chainId}),c=r.maxFeePerGas??r.gasPrice;if(c===void 0)return null;let d=t.chains.find(o=>o.id===e.chainId)?.nativeCurrency;return {amount:s*c,decimals:d?.decimals??18,symbol:d?.symbol??"ETH"}},canSponsorCalls:async({chainId:a,account:n})=>{try{return (await core.getCapabilities(t,{account:n,chainId:w(a)})).paymasterService?.supported===!0}catch{return false}},switchChain:async a=>{await core.switchChain(t,{chainId:w(a)});},sendTransfer:async({instructions:a,account:n})=>{let e=A(a);if(await i(),await u(e.chainId),e.token==="native"){let s=await Y(t,n,e);return core.sendTransaction(t,{account:n,chainId:e.chainId,to:e.to,value:BigInt(e.amount),...s})}return core.writeContract(t,{account:n,chainId:e.chainId,address:e.token,abi:viem.erc20Abi,functionName:"transfer",args:[e.to,BigInt(e.amount)]})},signTransferAuthorization:async({typedData:a,account:n})=>{await i();let e=Number(a.domain.chainId);return await u(e),(await core.getConnectorClient(t,{chainId:e})).request({method:"eth_signTypedData_v4",params:[n,JSON.stringify(a)]})},signMessage:async({message:a,account:n,chainId:e})=>{await i();let s=orbitCore.toEvmChainId(e);return s!==void 0&&await u(s),core.signMessage(t,{account:n,message:a})},followSponsoredCalls:({batchId:a,until:n,onLate:e})=>{l(a,n,e).catch(()=>{});},sendOneTimeRelay:async({chainId:a,call:n,paymasterUrl:e})=>{let s=orbitCore.toEvmChainId(a),r=s===void 0?void 0:core.getPublicClient(t,{chainId:s});if(s===void 0||!r)throw new chunk7FQXTBOY_cjs.a("unsupported",`The network ${a} is not configured`);let c=accounts.privateKeyToAccount(accounts.generatePrivateKey()),d=await accountAbstraction.toSimple7702SmartAccount({client:r,owner:c}),o=accountAbstraction.createBundlerClient({account:d,client:r,transport:viem.http(e),paymaster:accountAbstraction.createPaymasterClient({transport:viem.http(e)}),userOperation:{estimateFeesPerGas:async()=>{let p=await te(e,"pimlico_getUserOperationGasPrice");return {maxFeePerGas:viem.hexToBigInt(p.fast.maxFeePerGas),maxPriorityFeePerGas:viem.hexToBigInt(p.fast.maxPriorityFeePerGas)}}}}),f=await c.signAuthorization({chainId:s,contractAddress:d.authorization.address,nonce:0});return o.sendUserOperation({calls:[{to:n.to,data:n.data}],authorization:f})},sendSponsoredCalls:async({calls:a,paymasterUrl:n,chainId:e,account:s,onSent:r,onAccepted:c,onLate:d})=>{await i(),await u(w(e));let{id:o}=await core.sendCalls(t,{account:s,chainId:w(e),calls:a.map(m=>({to:m.to,value:BigInt(m.value),data:m.data})),capabilities:{paymasterService:{url:n}}});c?.(o),r?.();let f=m=>(l(o,Date.now()+W,d).catch(()=>{}),new chunk7FQXTBOY_cjs.a("sentUnconfirmed","The sponsored payment is not confirmed yet",{cause:m})),p=await core.waitForCallsStatus(t,{id:o,timeout:J}).catch(m=>{throw f(m)});if(p.status==="failure")throw new chunk7FQXTBOY_cjs.a("failed","The sponsored payment failed");let C=p.status==="success"?p.receipts?.at(-1)?.transactionHash:void 0;if(!C)throw f();return C},explorerUrl:({chainId:a,txKey:n})=>{let s=t.chains.find(r=>r.id===orbitCore.toEvmChainId(a))?.blockExplorers?.default.url;return s?`${s}/tx/${n}`:void 0},explorerAddressUrl:({chainId:a,address:n})=>{let s=t.chains.find(r=>r.id===orbitCore.toEvmChainId(a))?.blockExplorers?.default.url;return s?`${s}/address/${n}`:void 0},pulsarTransaction:({txKey:a,instructions:n,account:e,connectorType:s,title:r,description:c,payload:d})=>{let o=A(n);return {adapter:orbitCore.OrbitAdapter.EVM,tracker:pulsarCore.TransactionTracker.Ethereum,txKey:a,hash:a,chainId:o.chainId,from:e,to:o.token==="native"?o.to:o.token,type:"payment",connectorType:s,title:r,description:c,payload:d,pending:true,localTimestamp:Math.floor(Date.now()/1e3),isTrackedModalOpen:false}}}}exports.paymentsEVMAdapter=de;
@@ -11,15 +11,18 @@ import '@tuwaio/quasar-sdk/checkout';
11
11
  * gas of a token transfer, and of any transfer when that read fails),
12
12
  * signs the EIP-3009 authorization of a gasless quote with `eth_signTypedData_v4` exactly as Quasar issued it, signs
13
13
  * Quasar's message that confirms the paying wallet with `personal_sign`, and sends sponsored calls with
14
- * `wallet_sendCalls` and the checkout's ERC-7677 paymaster. Before each of these four requests, a wallet that reports
14
+ * `wallet_sendCalls` and the checkout's ERC-7677 paymaster. A gasless quote Quasar does not send itself is sent from a
15
+ * one-time account: a key made in memory for the payment, delegated (EIP-7702) to `Simple7702Account` of EntryPoint 0.8,
16
+ * whose user operation makes the one call Quasar authorized, through the checkout's paymaster route (the merchant's
17
+ * paymaster and bundler); the key is never stored or sent. Before each of the four wallet requests, a wallet that reports
15
18
  * another network than the request's is asked to switch (wagmi would refuse the request before the wallet saw it); a
16
19
  * switch that fails is a `PaymentWalletError` of the kind `switchFailed`, a refused one stays `declined`, both with
17
20
  * `step: 'switch'`. A Safe wallet
18
21
  * is refused: it returns a Safe transaction hash, not the transaction Quasar follows. Pass it in `adapters` of
19
22
  * `NovaPaymentsProvider`.
20
23
  *
21
- * Side effects: RPC reads through the wagmi transports (`eth_estimateGas` before each transfer); wallet prompts,
22
- * including a network switch.
24
+ * Side effects: RPC reads through the wagmi transports (`eth_estimateGas` before each transfer; the one-time account's
25
+ * nonce and code); wallet prompts, including a network switch; requests to the checkout's paymaster route.
23
26
  *
24
27
  * @param config - The wagmi config of the app.
25
28
  * @returns The EVM adapter.
@@ -11,15 +11,18 @@ import '@tuwaio/quasar-sdk/checkout';
11
11
  * gas of a token transfer, and of any transfer when that read fails),
12
12
  * signs the EIP-3009 authorization of a gasless quote with `eth_signTypedData_v4` exactly as Quasar issued it, signs
13
13
  * Quasar's message that confirms the paying wallet with `personal_sign`, and sends sponsored calls with
14
- * `wallet_sendCalls` and the checkout's ERC-7677 paymaster. Before each of these four requests, a wallet that reports
14
+ * `wallet_sendCalls` and the checkout's ERC-7677 paymaster. A gasless quote Quasar does not send itself is sent from a
15
+ * one-time account: a key made in memory for the payment, delegated (EIP-7702) to `Simple7702Account` of EntryPoint 0.8,
16
+ * whose user operation makes the one call Quasar authorized, through the checkout's paymaster route (the merchant's
17
+ * paymaster and bundler); the key is never stored or sent. Before each of the four wallet requests, a wallet that reports
15
18
  * another network than the request's is asked to switch (wagmi would refuse the request before the wallet saw it); a
16
19
  * switch that fails is a `PaymentWalletError` of the kind `switchFailed`, a refused one stays `declined`, both with
17
20
  * `step: 'switch'`. A Safe wallet
18
21
  * is refused: it returns a Safe transaction hash, not the transaction Quasar follows. Pass it in `adapters` of
19
22
  * `NovaPaymentsProvider`.
20
23
  *
21
- * Side effects: RPC reads through the wagmi transports (`eth_estimateGas` before each transfer); wallet prompts,
22
- * including a network switch.
24
+ * Side effects: RPC reads through the wagmi transports (`eth_estimateGas` before each transfer; the one-time account's
25
+ * nonce and code); wallet prompts, including a network switch; requests to the checkout's paymaster route.
23
26
  *
24
27
  * @param config - The wagmi config of the app.
25
28
  * @returns The EVM adapter.
package/dist/evm/index.js CHANGED
@@ -1 +1 @@
1
- import {a,b}from'../chunk-7HSDAUKN.js';import {OrbitAdapter,toEvmChainId,delay}from'@tuwaio/orbit-core';import {TransactionTracker}from'@tuwaio/pulsar-core';import {sendCalls,waitForCallsStatus,signMessage,getConnectorClient,sendTransaction,writeContract,switchChain,getCapabilities,estimateGas,estimateFeesPerGas,getBalance,readContract,getConnection}from'@wagmi/core';import {erc20Abi,encodeFunctionData}from'viem';var R=18e4,U=30*6e4,G=15e3,V=25n;function h(t){let i=toEvmChainId(t);if(i===void 0)throw new Error(`${t} is not an EVM chain`);return i}function A(t){if(t.family!=="eip155")throw new Error(`${t.chainId} is not an EVM chain`);return t}function S(t){return t.token==="native"?{to:t.to,value:BigInt(t.amount)}:{to:t.token,data:encodeFunctionData({abi:erc20Abi,functionName:"transfer",args:[t.to,BigInt(t.amount)]})}}async function q(t,i,d){try{return {gas:(await estimateGas(t,{account:i,chainId:d.chainId,...S(d)})*(100n+V)+99n)/100n}}catch{return {}}}async function W(t){if(t?.type!=="walletConnect")return false;try{let i=await t.getProvider();return /^safe\b/i.test(i.session?.peer?.metadata?.name??"")}catch{return false}}function X(t){let i=async()=>{let a$1=getConnection(t).connector;if(a$1?.id==="safe"||a$1?.type==="safe"||await W(a$1))throw new a("unsupported","A Safe wallet cannot pay this checkout")},d=async a$1=>{let n;try{n=await getConnection(t).connector?.getChainId();}catch{return}if(!(n===void 0||n===a$1))try{await switchChain(t,{chainId:a$1});}catch(e){let s=b(e);throw s==="declined"?new a("declined",`The wallet declined the switch to ${a$1}`,{cause:e,step:"switch"}):s!=="failed"?e:new a("switchFailed",`The wallet did not switch to ${a$1}`,{cause:e,step:"switch"})}},f=async(a,n,e)=>{for(;Date.now()<n;){try{let s=await waitForCallsStatus(t,{id:a,timeout:n-Date.now()});if(s.status==="failure")return;let r=s.status==="success"?s.receipts?.at(-1)?.transactionHash:void 0;if(r)return e?.(r)}catch{}await delay(void 0,G);}};return {family:"eip155",getBalance:async({chainId:a,account:n,token:e})=>{let s=h(a);return e==="native"?(await getBalance(t,{address:n,chainId:s})).value:readContract(t,{address:e,abi:erc20Abi,functionName:"balanceOf",args:[n],chainId:s})},estimateFee:async({instructions:a,account:n})=>{let e=A(a),s=await estimateGas(t,{account:n,chainId:e.chainId,...S(e)}),r=await estimateFeesPerGas(t,{chainId:e.chainId}),u=r.maxFeePerGas??r.gasPrice;if(u===void 0)return null;let l=t.chains.find(o=>o.id===e.chainId)?.nativeCurrency;return {amount:s*u,decimals:l?.decimals??18,symbol:l?.symbol??"ETH"}},canSponsorCalls:async({chainId:a,account:n})=>{try{return (await getCapabilities(t,{account:n,chainId:h(a)})).paymasterService?.supported===!0}catch{return false}},switchChain:async a=>{await switchChain(t,{chainId:h(a)});},sendTransfer:async({instructions:a,account:n})=>{let e=A(a);if(await i(),await d(e.chainId),e.token==="native"){let s=await q(t,n,e);return sendTransaction(t,{account:n,chainId:e.chainId,to:e.to,value:BigInt(e.amount),...s})}return writeContract(t,{account:n,chainId:e.chainId,address:e.token,abi:erc20Abi,functionName:"transfer",args:[e.to,BigInt(e.amount)]})},signTransferAuthorization:async({typedData:a,account:n})=>{await i();let e=Number(a.domain.chainId);return await d(e),(await getConnectorClient(t,{chainId:e})).request({method:"eth_signTypedData_v4",params:[n,JSON.stringify(a)]})},signMessage:async({message:a,account:n,chainId:e})=>{await i();let s=toEvmChainId(e);return s!==void 0&&await d(s),signMessage(t,{account:n,message:a})},followSponsoredCalls:({batchId:a,until:n,onLate:e})=>{f(a,n,e).catch(()=>{});},sendSponsoredCalls:async({calls:a$1,paymasterUrl:n,chainId:e,account:s,onSent:r,onAccepted:u,onLate:l})=>{await i(),await d(h(e));let{id:o}=await sendCalls(t,{account:s,chainId:h(e),calls:a$1.map(c=>({to:c.to,value:BigInt(c.value),data:c.data})),capabilities:{paymasterService:{url:n}}});u?.(o),r?.();let w=c=>(f(o,Date.now()+U,l).catch(()=>{}),new a("sentUnconfirmed","The sponsored payment is not confirmed yet",{cause:c})),y=await waitForCallsStatus(t,{id:o,timeout:R}).catch(c=>{throw w(c)});if(y.status==="failure")throw new a("failed","The sponsored payment failed");let C=y.status==="success"?y.receipts?.at(-1)?.transactionHash:void 0;if(!C)throw w();return C},explorerUrl:({chainId:a,txKey:n})=>{let s=t.chains.find(r=>r.id===toEvmChainId(a))?.blockExplorers?.default.url;return s?`${s}/tx/${n}`:void 0},explorerAddressUrl:({chainId:a,address:n})=>{let s=t.chains.find(r=>r.id===toEvmChainId(a))?.blockExplorers?.default.url;return s?`${s}/address/${n}`:void 0},pulsarTransaction:({txKey:a,instructions:n,account:e,connectorType:s,title:r,description:u,payload:l})=>{let o=A(n);return {adapter:OrbitAdapter.EVM,tracker:TransactionTracker.Ethereum,txKey:a,hash:a,chainId:o.chainId,from:e,to:o.token==="native"?o.to:o.token,type:"payment",connectorType:s,title:r,description:u,payload:l,pending:true,localTimestamp:Math.floor(Date.now()/1e3),isTrackedModalOpen:false}}}}export{X as paymentsEVMAdapter};
1
+ import {a,b}from'../chunk-7HSDAUKN.js';import {OrbitAdapter,toEvmChainId,delay}from'@tuwaio/orbit-core';import {TransactionTracker}from'@tuwaio/pulsar-core';import {sendCalls,waitForCallsStatus,getPublicClient,signMessage,getConnectorClient,sendTransaction,writeContract,switchChain,getCapabilities,estimateGas,estimateFeesPerGas,getBalance,readContract,getConnection}from'@wagmi/core';import {hexToBigInt,http,erc20Abi,encodeFunctionData}from'viem';import {toSimple7702SmartAccount,createBundlerClient,createPaymasterClient}from'viem/account-abstraction';import {privateKeyToAccount,generatePrivateKey}from'viem/accounts';var J=18e4,W=30*6e4,Q=15e3,X=25n;function w(t){let i=toEvmChainId(t);if(i===void 0)throw new Error(`${t} is not an EVM chain`);return i}function A(t){if(t.family!=="eip155")throw new Error(`${t.chainId} is not an EVM chain`);return t}function x(t){return t.token==="native"?{to:t.to,value:BigInt(t.amount)}:{to:t.token,data:encodeFunctionData({abi:erc20Abi,functionName:"transfer",args:[t.to,BigInt(t.amount)]})}}async function Y(t,i,u){try{return {gas:(await estimateGas(t,{account:i,chainId:u.chainId,...x(u)})*(100n+X)+99n)/100n}}catch{return {}}}async function Z(t){if(t?.type!=="walletConnect")return false;try{let i=await t.getProvider();return /^safe\b/i.test(i.session?.peer?.metadata?.name??"")}catch{return false}}var ee=1e4;async function te(t,i){let l=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:i,params:[]}),signal:AbortSignal.timeout(ee)})).json();if(l.error||l.result===void 0)throw new Error(l.error?.message??`${i} failed`);return l.result}function de(t){let i=async()=>{let a$1=getConnection(t).connector;if(a$1?.id==="safe"||a$1?.type==="safe"||await Z(a$1))throw new a("unsupported","A Safe wallet cannot pay this checkout")},u=async a$1=>{let n;try{n=await getConnection(t).connector?.getChainId();}catch{return}if(!(n===void 0||n===a$1))try{await switchChain(t,{chainId:a$1});}catch(e){let s=b(e);throw s==="declined"?new a("declined",`The wallet declined the switch to ${a$1}`,{cause:e,step:"switch"}):s!=="failed"?e:new a("switchFailed",`The wallet did not switch to ${a$1}`,{cause:e,step:"switch"})}},l=async(a,n,e)=>{for(;Date.now()<n;){try{let s=await waitForCallsStatus(t,{id:a,timeout:n-Date.now()});if(s.status==="failure")return;let r=s.status==="success"?s.receipts?.at(-1)?.transactionHash:void 0;if(r)return e?.(r)}catch{}await delay(void 0,Q);}};return {family:"eip155",getBalance:async({chainId:a,account:n,token:e})=>{let s=w(a);return e==="native"?(await getBalance(t,{address:n,chainId:s})).value:readContract(t,{address:e,abi:erc20Abi,functionName:"balanceOf",args:[n],chainId:s})},estimateFee:async({instructions:a,account:n})=>{let e=A(a),s=await estimateGas(t,{account:n,chainId:e.chainId,...x(e)}),r=await estimateFeesPerGas(t,{chainId:e.chainId}),c=r.maxFeePerGas??r.gasPrice;if(c===void 0)return null;let d=t.chains.find(o=>o.id===e.chainId)?.nativeCurrency;return {amount:s*c,decimals:d?.decimals??18,symbol:d?.symbol??"ETH"}},canSponsorCalls:async({chainId:a,account:n})=>{try{return (await getCapabilities(t,{account:n,chainId:w(a)})).paymasterService?.supported===!0}catch{return false}},switchChain:async a=>{await switchChain(t,{chainId:w(a)});},sendTransfer:async({instructions:a,account:n})=>{let e=A(a);if(await i(),await u(e.chainId),e.token==="native"){let s=await Y(t,n,e);return sendTransaction(t,{account:n,chainId:e.chainId,to:e.to,value:BigInt(e.amount),...s})}return writeContract(t,{account:n,chainId:e.chainId,address:e.token,abi:erc20Abi,functionName:"transfer",args:[e.to,BigInt(e.amount)]})},signTransferAuthorization:async({typedData:a,account:n})=>{await i();let e=Number(a.domain.chainId);return await u(e),(await getConnectorClient(t,{chainId:e})).request({method:"eth_signTypedData_v4",params:[n,JSON.stringify(a)]})},signMessage:async({message:a,account:n,chainId:e})=>{await i();let s=toEvmChainId(e);return s!==void 0&&await u(s),signMessage(t,{account:n,message:a})},followSponsoredCalls:({batchId:a,until:n,onLate:e})=>{l(a,n,e).catch(()=>{});},sendOneTimeRelay:async({chainId:a$1,call:n,paymasterUrl:e})=>{let s=toEvmChainId(a$1),r=s===void 0?void 0:getPublicClient(t,{chainId:s});if(s===void 0||!r)throw new a("unsupported",`The network ${a$1} is not configured`);let c=privateKeyToAccount(generatePrivateKey()),d=await toSimple7702SmartAccount({client:r,owner:c}),o=createBundlerClient({account:d,client:r,transport:http(e),paymaster:createPaymasterClient({transport:http(e)}),userOperation:{estimateFeesPerGas:async()=>{let p=await te(e,"pimlico_getUserOperationGasPrice");return {maxFeePerGas:hexToBigInt(p.fast.maxFeePerGas),maxPriorityFeePerGas:hexToBigInt(p.fast.maxPriorityFeePerGas)}}}}),f=await c.signAuthorization({chainId:s,contractAddress:d.authorization.address,nonce:0});return o.sendUserOperation({calls:[{to:n.to,data:n.data}],authorization:f})},sendSponsoredCalls:async({calls:a$1,paymasterUrl:n,chainId:e,account:s,onSent:r,onAccepted:c,onLate:d})=>{await i(),await u(w(e));let{id:o}=await sendCalls(t,{account:s,chainId:w(e),calls:a$1.map(m=>({to:m.to,value:BigInt(m.value),data:m.data})),capabilities:{paymasterService:{url:n}}});c?.(o),r?.();let f=m=>(l(o,Date.now()+W,d).catch(()=>{}),new a("sentUnconfirmed","The sponsored payment is not confirmed yet",{cause:m})),p=await waitForCallsStatus(t,{id:o,timeout:J}).catch(m=>{throw f(m)});if(p.status==="failure")throw new a("failed","The sponsored payment failed");let C=p.status==="success"?p.receipts?.at(-1)?.transactionHash:void 0;if(!C)throw f();return C},explorerUrl:({chainId:a,txKey:n})=>{let s=t.chains.find(r=>r.id===toEvmChainId(a))?.blockExplorers?.default.url;return s?`${s}/tx/${n}`:void 0},explorerAddressUrl:({chainId:a,address:n})=>{let s=t.chains.find(r=>r.id===toEvmChainId(a))?.blockExplorers?.default.url;return s?`${s}/address/${n}`:void 0},pulsarTransaction:({txKey:a,instructions:n,account:e,connectorType:s,title:r,description:c,payload:d})=>{let o=A(n);return {adapter:OrbitAdapter.EVM,tracker:TransactionTracker.Ethereum,txKey:a,hash:a,chainId:o.chainId,from:e,to:o.token==="native"?o.to:o.token,type:"payment",connectorType:s,title:r,description:c,payload:d,pending:true,localTimestamp:Math.floor(Date.now()/1e3),isTrackedModalOpen:false}}}}export{de as paymentsEVMAdapter};