@dexterai/x402 5.4.2 → 6.0.0-rc.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 +19 -4
- package/REFERENCE.md +79 -8
- package/dist/adapters/index.d.cts +3 -3
- package/dist/adapters/index.d.ts +3 -3
- package/dist/batch-settlement/index.d.cts +3 -3
- package/dist/batch-settlement/index.d.ts +3 -3
- package/dist/batch-settlement/seller/index.d.cts +4 -4
- package/dist/batch-settlement/seller/index.d.ts +4 -4
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +6 -6
- package/dist/client/index.d.ts +6 -6
- package/dist/client/index.js +1 -1
- package/dist/{constants-Icc4CXNG.d.cts → constants-BLvApMMl.d.cts} +1 -1
- package/dist/{constants-Icc4CXNG.d.ts → constants-BLvApMMl.d.ts} +1 -1
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.cts +4 -4
- package/dist/react/index.d.ts +4 -4
- package/dist/react/index.js +1 -1
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.d.cts +5 -5
- package/dist/server/index.d.ts +5 -5
- package/dist/server/index.js +1 -1
- package/dist/{sessions-BG2OYLBi.d.cts → sessions-rPdO1CgK.d.cts} +35 -3
- package/dist/{sessions-BG2OYLBi.d.ts → sessions-rPdO1CgK.d.ts} +35 -3
- package/dist/tab/adapters/solana/index.cjs +1 -1
- package/dist/tab/adapters/solana/index.d.cts +178 -26
- package/dist/tab/adapters/solana/index.d.ts +178 -26
- package/dist/tab/adapters/solana/index.js +1 -1
- package/dist/tab/index.cjs +5 -5
- package/dist/tab/index.d.cts +117 -16
- package/dist/tab/index.d.ts +117 -16
- package/dist/tab/index.js +4 -4
- package/dist/tab/seller/index.cjs +3 -3
- package/dist/tab/seller/index.d.cts +4 -4
- package/dist/tab/seller/index.d.ts +4 -4
- package/dist/tab/seller/index.js +3 -3
- package/dist/{types-CSuISjXA.d.cts → types-45M9fb5M.d.cts} +109 -6
- package/dist/{types-CSuISjXA.d.ts → types-45M9fb5M.d.ts} +109 -6
- package/dist/{types-BdS_uvNs.d.cts → types-BbvuPNXl.d.cts} +2 -2
- package/dist/{types-Co5YYhVB.d.ts → types-BhXu7cgi.d.ts} +3 -3
- package/dist/{types-xQu1U4xk.d.cts → types-BvQpNtFw.d.cts} +9 -1
- package/dist/{types-xQu1U4xk.d.ts → types-BvQpNtFw.d.ts} +9 -1
- package/dist/{types-CZHPdVkg.d.cts → types-C6z04Mxr.d.cts} +3 -3
- package/dist/{types-DY8xKheW.d.ts → types-CkcNYx1Q.d.ts} +2 -2
- package/dist/{types-_wdHzVG-.d.ts → types-DwVhPqOZ.d.ts} +2 -2
- package/dist/{types-WMqs5xII.d.cts → types-JpkrtFbZ.d.cts} +2 -2
- package/dist/utils/index.d.cts +1 -1
- package/dist/utils/index.d.ts +1 -1
- package/dist/{x402-client-BQKDeNxq.d.cts → x402-client-B8zdDeat.d.cts} +2 -2
- package/dist/{x402-client-BQKDeNxq.d.ts → x402-client-B8zdDeat.d.ts} +2 -2
- package/package.json +7 -6
package/dist/react/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useState as le,useCallback as Qe,useEffect as vt,useMemo as We}from"react";var F="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Re="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Ke="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",ee=F,we=Re,_e=Ke,K="eip155:8453",me="eip155:84532",fe="eip155:42161",ge="eip155:137",he="eip155:10",Ae="eip155:43114",ye="eip155:56",te="eip155:480",ne="eip155:143",re="eip155:4663",se="eip155:1187947933",oe="eip155:324705682",Ee="eip155:1",ae=K,qe=me,be=fe,Ne=ge,Pe=he,Ie=Ae,Ce=ye,ve=te,Oe=ne,Be=re,De=se,Me=oe,Ue=Ee,Le="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",ct="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",Fe="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",et="0x55d398326f99059fF775485246999027B3197955",je="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",tt="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",He={[ye]:je,[K]:Fe,[me]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[fe]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[ge]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[he]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[Ae]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[te]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[ne]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[re]:tt,[se]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[oe]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[Ee]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},Xe={[et]:{symbol:"USDT",decimals:18},[je]:{symbol:"USDC",decimals:18}};var Ve={[te]:{name:"USDC",version:"2"},[ne]:{name:"USDC",version:"2"},[re]:{name:"Global Dollar",version:"1"},[se]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[oe]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}},z="0x000000000022D473030F116dDEE9F6B43aC78BA3",ke="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",nt={[ye]:56,[K]:8453,[me]:84532,[fe]:42161,[ge]:137,[he]:10,[Ae]:43114,[te]:480,[ne]:143,[re]:4663,[se]:1187947933,[oe]:324705682,[Ee]:1},ie={[F]:"https://api.dexter.cash/api/solana/rpc",[Re]:"https://api.devnet.solana.com",[Ke]:"https://api.testnet.solana.com"},M={[ye]:"https://api.dexter.cash/api/evm/bsc/rpc",[K]:"https://api.dexter.cash/api/base/rpc",[me]:"https://sepolia.base.org",[fe]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[ge]:"https://api.dexter.cash/api/evm/polygon/rpc",[he]:"https://api.dexter.cash/api/evm/optimism/rpc",[Ae]:"https://api.dexter.cash/api/evm/avalanche/rpc",[te]:"https://worldchain-mainnet.g.alchemy.com/public",[ne]:"https://rpc.monad.xyz",[re]:"https://rpc.mainnet.chain.robinhood.com",[se]:"https://skale-base.skalenodes.com/v1/base",[oe]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[Ee]:"https://eth.llamarpc.com"};var b=class r extends Error{code;details;constructor(e,t,n){super(t),this.name="X402Error",this.code=e,this.details=n,Object.setPrototypeOf(this,r.prototype)}};import{PublicKey as ce,Connection as rt,TransactionMessage as yt,VersionedTransaction as Et,ComputeBudgetProgram as lt}from"@solana/web3.js";import{getAssociatedTokenAddress as st,getAccount as St,createTransferCheckedInstruction as Tt,getMint as xt,TOKEN_PROGRAM_ID as pt,TOKEN_2022_PROGRAM_ID as Je}from"@solana/spl-token";var Rt=12e3,wt=1;function j(r){if(!r||typeof r!="object")return!1;let e=r;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var Ge=class{name="Solana";networks=[ee,we,_e];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:solana]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="solana"||e==="solana-devnet"||e==="solana-testnet"||e.startsWith("solana:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:ie[e]?ie[e]:e==="solana"?ie[ee]:e==="solana-devnet"?ie[we]:e==="solana-testnet"?ie[_e]:ie[ee]}getAddress(e){return j(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return j(e)?e.publicKey!==null:!1}async getBalance(e,t,n){if(!j(t)||!t.publicKey)return 0;let o=n||this.getDefaultRpcUrl(e.network),s=new rt(o,"confirmed"),p=new ce(t.publicKey.toBase58()),a=new ce(e.asset);try{let d=(await s.getAccountInfo(a,"confirmed"))?.owner.toBase58()===Je.toBase58()?Je:pt,E=await st(a,p,!1,d),w=await St(s,E,void 0,d),A=e.extra?.decimals??6;return Number(w.amount)/Math.pow(10,A)}catch(c){if(c&&typeof c=="object"&&"name"in c&&(c.name==="TokenAccountNotFoundError"||c.name==="TokenInvalidAccountOwnerError"))return 0;throw c}}async buildTransaction(e,t,n){if(!j(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let o=n||this.getDefaultRpcUrl(e.network),s=new rt(o,"confirmed"),p=new ce(t.publicKey.toBase58()),{payTo:a,asset:c,extra:d}=e,E=e.amount??e.maxAmountRequired;if(!E)throw new Error("Missing amount in payment requirements");if(!d?.feePayer)throw new Error("Missing feePayer in payment requirements");let w=new ce(d.feePayer),A=new ce(c),N=new ce(a);this.log("Building transaction:",{from:p.toBase58(),to:a,amount:E,asset:c,feePayer:d.feePayer});let l=[];l.push(lt.setComputeUnitLimit({units:Rt})),l.push(lt.setComputeUnitPrice({microLamports:wt}));let P=await s.getAccountInfo(A,"confirmed");if(!P)throw new Error(`Token mint ${c} not found`);let I=P.owner.toBase58()===Je.toBase58()?Je:pt,k=await xt(s,A,void 0,I);typeof d?.decimals=="number"&&k.decimals!==d.decimals&&this.log(`Decimals mismatch: requirements say ${d.decimals}, mint says ${k.decimals}`);let W=await st(A,p,!1,I),R=await st(A,N,!0,I);if(!await s.getAccountInfo(W,"confirmed"))throw new Error(`No token account found for ${c}. Please ensure you have USDC in your wallet.`);if(!await s.getAccountInfo(R,"confirmed"))throw new Error(`Seller token account not found. The seller (${a}) must have a USDC account.`);let B=BigInt(E);l.push(Tt(W,A,R,p,B,k.decimals,[],I));let{blockhash:U}=await s.getLatestBlockhash("confirmed"),$=new yt({payerKey:w,recentBlockhash:U,instructions:l}).compileToV0Message(),D=new Et($),f=await t.signTransaction(D);return this.log("Transaction signed successfully"),{serialized:Buffer.from(f.serialize()).toString("base64"),settlementProbe:{kind:"solana",sourceAta:W.toBase58(),destinationAta:R.toBase58(),asset:c,amount:E,blockhash:U}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let n=new rt(t,"confirmed"),o=new ce(e.destinationAta),s=await n.getSignaturesForAddress(o,{limit:25});if(s.length===0)return{settled:!1};let p=BigInt(e.amount);for(let a of s){if(a.err)continue;let c=await n.getTransaction(a.signature,{commitment:"confirmed",maxSupportedTransactionVersion:0});if(!c?.meta)continue;let d=c.transaction.message.getAccountKeys().keySegments().flat(),E=c.meta.preTokenBalances??[],w=c.meta.postTokenBalances??[];for(let A of w){if(A.mint!==e.asset)continue;let N=d[A.accountIndex];if(!N||!N.equals(o))continue;let l=E.find(k=>k.accountIndex===A.accountIndex),P=BigInt(l?.uiTokenAmount.amount??"0");if(BigInt(A.uiTokenAmount.amount??"0")-P===p)return{settled:!0,txSignature:a.signature}}}return{settled:!1}}};function Se(r){return new Ge(r)}var _t={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"validAfter",type:"uint256"}]},dt=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function H(r){if(!r||typeof r!="object")return!1;let e=r;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var Ye=class{name="EVM";networks=[Ce,ae,qe,Ue,be,Ne,Pe,Ie,ve,Oe,Be,De,Me];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:evm]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="base"||e==="bsc"||e==="ethereum"||e==="arbitrum"||e==="polygon"||e==="optimism"||e==="avalanche"||e==="world"||e==="monad"||e==="robinhood"||e==="skale-base"||e==="skale-base-sepolia"||e.startsWith("eip155:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:M[e]?M[e]:e==="base"?M[ae]:e==="bsc"?M[Ce]:e==="ethereum"?M[Ue]:e==="arbitrum"?M[be]:e==="polygon"?M[Ne]:e==="optimism"?M[Pe]:e==="avalanche"?M[Ie]:e==="world"?M[ve]:e==="monad"?M[Oe]:e==="robinhood"?M[Be]:e==="skale-base"?M[De]:e==="skale-base-sepolia"?M[Me]:M[ae]}getAddress(e){return H(e)?e.address:null}isConnected(e){return H(e)?!!e.address:!1}getChainId(e){if(nt[e])return nt[e];if(e.startsWith("eip155:")){let t=e.split(":")[1];return parseInt(t,10)}return e==="base"?8453:e==="bsc"?56:e==="ethereum"?1:e==="arbitrum"?42161:e==="polygon"?137:e==="optimism"?10:e==="avalanche"?43114:e==="world"?480:e==="monad"?143:e==="robinhood"?4663:e==="skale-base"?1187947933:e==="skale-base-sepolia"?324705682:8453}async getBalance(e,t,n){if(!H(t)||!t.address)return 0;let o=n||this.getDefaultRpcUrl(e.network);try{let s=this.encodeBalanceOf(t.address),p=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:e.asset,data:s},"latest"]})});if(!p.ok)throw new Error(`RPC request failed: ${p.status}`);let a=await p.json();if(a.error)throw new Error(`RPC error: ${JSON.stringify(a.error)}`);if(!a.result||a.result==="0x")return 0;let c=BigInt(a.result),d=e.extra?.decimals??6;return Number(c)/Math.pow(10,d)}catch(s){throw s}}encodeBalanceOf(e){let t="0x70a08231",n=e.slice(2).toLowerCase().padStart(64,"0");return t+n}async confirmSettlement(e,t){if(e.kind==="eip3009"){let n="0xe94a0102",o=e.from.slice(2).toLowerCase().padStart(64,"0"),s=e.nonce.slice(2).toLowerCase().padStart(64,"0"),p=n+o+s,a=await this.ethCall(t,e.asset,p);return{settled:BigInt(a)!==0n}}if(e.kind==="permit2"){let n="0x4fe02b44",o=BigInt(e.nonce),s=o>>8n,p=o&0xffn,a=e.from.slice(2).toLowerCase().padStart(64,"0"),c=s.toString(16).padStart(64,"0"),d=n+a+c,E=await this.ethCall(t,z,d);return{settled:(BigInt(E)>>p&1n)===1n}}throw new Error(`EvmAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`)}async ethCall(e,t,n){let o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:n},"latest"]})});if(!o.ok)throw new Error(`RPC request failed: ${o.status}`);let s=await o.json();if(s.error)throw new Error(`RPC error: ${JSON.stringify(s.error)}`);if(!s.result||s.result==="0x")throw new Error("RPC returned an empty result");return s.result}async buildTransaction(e,t,n){if(!H(t))throw new Error("Invalid EVM wallet");if(!t.address)throw new Error("Wallet not connected");if(e.scheme==="exact-approval")return this.buildApprovalTransaction(e,t,n);if(e.extra?.assetTransferMethod==="permit2")return this.buildPermit2Transaction(e,t,n);let{payTo:o,asset:s,extra:p}=e,a=e.amount??e.maxAmountRequired;if(!a)throw new Error("Missing amount in payment requirements");this.log("Building EVM transaction:",{from:t.address,to:o,amount:a,asset:s,network:e.network});let c=this.getChainId(e.network),d=Ve[`eip155:${c}`],E={name:p?.name??d?.name??"USD Coin",version:p?.version??d?.version??"2",chainId:BigInt(c),verifyingContract:s},w={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},A=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(A);let N="0x"+[...A].map(R=>R.toString(16).padStart(2,"0")).join(""),l=Math.floor(Date.now()/1e3),P={from:t.address,to:o,value:a,validAfter:String(l-600),validBefore:String(l+(e.maxTimeoutSeconds||60)),nonce:N},I={from:t.address,to:o,value:BigInt(a),validAfter:BigInt(l-600),validBefore:BigInt(l+(e.maxTimeoutSeconds||60)),nonce:N};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let k=await t.signTypedData({domain:E,types:w,primaryType:"TransferWithAuthorization",message:I});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:P,signature:k}),signature:k,settlementProbe:{kind:"eip3009",from:t.address,nonce:N,asset:s,chainId:c}}}async buildApprovalTransaction(e,t,n){let{payTo:o,asset:s,extra:p}=e,a=e.amount??e.maxAmountRequired;if(!a)throw new Error("Missing amount in payment requirements");let c=p?.facilitatorContract;if(!c)throw new Error("exact-approval scheme requires extra.facilitatorContract from the facilitator. The /supported endpoint should provide this.");if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building approval-based transaction:",{from:t.address,to:o,amount:a,asset:s,network:e.network,facilitatorContract:c});let d=n||this.getDefaultRpcUrl(e.network),E=p?.fee??"0",w=BigInt(a)+BigInt(E),A=await this.readAllowance(d,s,t.address,c);if(A<w){if(!t.sendTransaction)throw new Error("BSC payments require a wallet that supports sendTransaction for the one-time token approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.");let D=this.calculateApprovalAmount(a,E,p?.approvalStrategy);this.log(`Approving ${D} for ${c} (current allowance: ${A})`);let f=await t.sendTransaction({to:s,data:this.encodeApprove(c,D),value:0n});this.log(`Approval tx sent: ${f}`),await this.waitForReceipt(d,f),this.log("Approval confirmed")}else this.log("Sufficient allowance, skipping approval");let N=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(N);let l=[...N].reduce((D,f)=>D*256n+BigInt(f),0n).toString(),P=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(P);let I="0x"+[...P].map(D=>D.toString(16).padStart(2,"0")).join(""),W=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),R=p?.eip712Domain,O=R?{name:R.name,version:R.version,chainId:BigInt(R.chainId),verifyingContract:R.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:c},x=p?.eip712Types??{Payment:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"token",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"paymentId",type:"bytes32"}]},B={from:t.address,to:o,token:s,amount:BigInt(a),fee:BigInt(E),nonce:BigInt(l),deadline:BigInt(W),paymentId:I},U=await t.signTypedData({domain:O,types:x,primaryType:"Payment",message:B});this.log("EIP-712 Payment signature obtained");let $={from:t.address,to:o,token:s,amount:a,fee:E,nonce:l,deadline:W,paymentId:I,signature:U};return{serialized:JSON.stringify($),signature:U}}async buildPermit2Transaction(e,t,n){let{payTo:o,asset:s}=e,p=e.amount??e.maxAmountRequired;if(!p)throw new Error("Missing amount in payment requirements");if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building Permit2 transaction:",{from:t.address,to:o,amount:p,asset:s,network:e.network});let a=n||this.getDefaultRpcUrl(e.network),c=await this.readAllowance(a,s,t.address,z),d;if(c<BigInt(p)){let O=this.encodeApprove(z,dt);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${c})`);let x=this.getChainId(e.network),B=await this.readGasPrice(a),U=await this.readNonce(a,t.address),$=await t.signTransaction({to:s,data:O,chainId:x,gas:50000n,gasPrice:B,nonce:U});d={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:s,spender:z,amount:dt.toString(),signedTransaction:$,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${c})`);let x=await t.sendTransaction({to:s,data:O,value:0n});this.log(`Permit2 approval tx sent: ${x}`),await this.waitForReceipt(a,x),this.log("Permit2 approval confirmed")}else throw new Error("Permit2 payments require a wallet that supports signTransaction or sendTransaction for the one-time Permit2 approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.")}else this.log("Sufficient Permit2 allowance, skipping approval");let E=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(E);let w=[...E].reduce((O,x)=>O*256n+BigInt(x),0n),A=Math.floor(Date.now()/1e3),N=A-600,l=A+(e.maxTimeoutSeconds||300),P=this.getChainId(e.network),I={name:"Permit2",chainId:BigInt(P),verifyingContract:z},k={permitted:{token:s,amount:BigInt(p)},spender:ke,nonce:w,deadline:BigInt(l),witness:{to:o,validAfter:BigInt(N)}},W=await t.signTypedData({domain:I,types:_t,primaryType:"PermitWitnessTransferFrom",message:k});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let R={signature:W,permit2Authorization:{from:t.address,permitted:{token:s,amount:p},spender:ke,nonce:w.toString(),deadline:String(l),witness:{to:o,validAfter:String(N)}}};return{serialized:JSON.stringify(R),signature:W,extensions:d,settlementProbe:{kind:"permit2",from:t.address,nonce:w.toString(),chainId:P}}}async readAllowance(e,t,n,o){let s="0xdd62ed3e",p=n.slice(2).toLowerCase().padStart(64,"0"),a=o.slice(2).toLowerCase().padStart(64,"0"),c=s+p+a;try{let E=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:c},"latest"]})})).json();return E.error||!E.result||E.result==="0x"?0n:BigInt(E.result)}catch{return 0n}}encodeApprove(e,t){let n="0x095ea7b3",o=e.slice(2).toLowerCase().padStart(64,"0"),s=t.toString(16).padStart(64,"0");return n+o+s}async waitForReceipt(e,t,n=3e4){let o=Date.now();for(;Date.now()-o<n;){try{let p=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionReceipt",params:[t]})})).json();if(p.result){if(p.result.status==="0x0")throw new Error(`Approval transaction reverted: ${t}`);return}}catch(s){if(s instanceof Error&&s.message.includes("reverted"))throw s}await new Promise(s=>setTimeout(s,2e3))}throw new Error(`Approval transaction receipt timeout after ${n}ms: ${t}`)}async readGasPrice(e){try{let n=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_gasPrice",params:[]})})).json();return n.result?BigInt(n.result):50000000n}catch{return 50000000n}}async readNonce(e,t){try{let o=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionCount",params:[t,"latest"]})})).json();return o.result?parseInt(o.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,n){let o=BigInt(e)+BigInt(t);if(!n||n.mode==="exact")return o;let s=BigInt(n.defaultMultiple??10),p=o*s;if(n.maxCapUsd){let a=this.inferDecimals(e),c=BigInt(Math.floor(n.maxCapUsd*Math.pow(10,a)));if(p>c)return c}if(n.exactAboveUsd){let a=this.inferDecimals(e),c=BigInt(Math.floor(n.exactAboveUsd*Math.pow(10,a)));if(BigInt(e)>c)return o}return p}inferDecimals(e){return e.length>12?18:6}};function Te(r){return new Ye(r)}function ot(r){if(r===Le||r===ct)return!0;let e=r.toLowerCase();for(let t of Object.values(He))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(Xe))if(t.toLowerCase()===e)return!0;return!1}function bt(r){return r.startsWith("solana:")||r==="solana"}var Nt=["base","base-sepolia","ethereum","arbitrum","polygon","optimism","avalanche","bsc","world","monad","robinhood","skale-base","skale-base-sepolia"];function Pt(r){return r.startsWith("eip155:")||Nt.includes(r)}function It(r){return bt(r)?"solana":Pt(r)?"evm":"unknown"}function ze(r){return{[F]:"Solana",[Re]:"Solana Devnet",[Ke]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[K]:"Base",[me]:"Base Sepolia",[Ee]:"Ethereum",[fe]:"Arbitrum",[ge]:"Polygon",[he]:"Optimism",[Ae]:"Avalanche",[ye]:"BSC",[te]:"World Chain",[ne]:"Monad",[re]:"Robinhood Chain",[se]:"SKALE Base",[oe]:"SKALE Base Sepolia",base:"Base","base-sepolia":"Base Sepolia",ethereum:"Ethereum",arbitrum:"Arbitrum",polygon:"Polygon",optimism:"Optimism",avalanche:"Avalanche",bsc:"BSC",world:"World Chain",monad:"Monad",robinhood:"Robinhood Chain","skale-base":"SKALE Base","skale-base-sepolia":"SKALE Base Sepolia"}[r]||r}function ut(r,e){let t=ze(r);return t===r?e:t}function mt(r,e){let t=It(e);if(t==="solana")return e.includes("devnet")||e===Re?`https://solscan.io/tx/${r}?cluster=devnet`:`https://www.orbmarkets.io/tx/${r}`;if(t==="evm"){let n="8453";switch(e.startsWith("eip155:")?n=e.split(":")[1]:e==="ethereum"?n="1":e==="arbitrum"?n="42161":e==="polygon"?n="137":e==="optimism"?n="10":e==="avalanche"?n="43114":e==="bsc"?n="56":e==="world"?n="480":e==="monad"?n="143":e==="robinhood"?n="4663":e==="skale-base"?n="1187947933":e==="skale-base-sepolia"&&(n="324705682"),n){case"8453":return`https://basescan.org/tx/${r}`;case"84532":return`https://sepolia.basescan.org/tx/${r}`;case"1":return`https://etherscan.io/tx/${r}`;case"42161":return`https://arbiscan.io/tx/${r}`;case"137":return`https://polygonscan.com/tx/${r}`;case"10":return`https://optimistic.etherscan.io/tx/${r}`;case"43114":return`https://snowtrace.io/tx/${r}`;case"56":return`https://bscscan.com/tx/${r}`;case"480":return`https://worldscan.org/tx/${r}`;case"143":return`https://monadvision.com/tx/${r}`;case"4663":return`https://robinhoodchain.blockscout.com/tx/${r}`;case"1187947933":return`https://elated-tan-skat.explorer.mainnet.skalenodes.com/tx/${r}`;case"324705682":return`https://base-sepolia-testnet.explorer.skalenodes.com/tx/${r}`;default:return`https://basescan.org/tx/${r}`}}return`https://solscan.io/tx/${r}`}async function Ct(r,e){if(typeof r=="string")return[r,e];if(r instanceof URL)return[r.href,e];let t=r,n=new Headers(t.headers);e?.headers&&new Headers(e.headers).forEach((p,a)=>n.set(a,p));let o={method:e?.method??t.method,headers:n,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},s=(o.method??"GET").toUpperCase();return e&&"body"in e?o.body=e.body:s!=="GET"&&s!=="HEAD"&&t.body&&(o.body=await t.arrayBuffer()),[t.url,o]}var ft=new WeakMap;function gt(r){return ft.get(r)}function ht(r){let{adapters:e=[Se({verbose:r.verbose}),Te({verbose:r.verbose})],wallets:t,wallet:n,preferredNetwork:o,rpcUrls:s={},maxAmountAtomic:p,fetch:a=globalThis.fetch,verbose:c=!1,accessPass:d,onPaymentRequired:E,onPaymentDispatched:w,maxRetries:A=0,retryDelayMs:N=500}=r,l=c?console.log.bind(console,"[x402]"):()=>{};async function P(f,y){let T;for(let h=0;h<=A;h++)try{let u=await a(f,y);if(u.status>=502&&u.status<=504&&h<A){l(`Retry ${h+1}/${A}: server returned ${u.status}`),await new Promise(g=>setTimeout(g,N*Math.pow(2,h)));continue}return u}catch(u){T=u,h<A&&(l(`Retry ${h+1}/${A}: ${u instanceof Error?u.message:"network error"}`),await new Promise(g=>setTimeout(g,N*Math.pow(2,h))))}throw T}let I=new Map;function k(f){try{let y=new URL(f).host,T=I.get(y);if(T&&T.expiresAt>Date.now()/1e3+10)return T.jwt;T&&I.delete(y)}catch{}return null}function W(f,y){try{let T=new URL(f).host,h=y.split(".");if(h.length===3){let u=JSON.parse(atob(h[1].replace(/-/g,"+").replace(/_/g,"/"))),g=Math.floor(Date.now()/1e3),m=g+86400,C=Math.min(typeof u.exp=="number"?u.exp:g,m);I.set(T,{jwt:y,expiresAt:C}),l("Access pass cached for",T,"| expires:",new Date(C*1e3).toISOString())}}catch{l("Failed to cache access pass")}}let R=t||{};n&&!R.solana&&j(n)&&(R.solana=n),n&&!R.evm&&H(n)&&(R.evm=n);function O(f){let y=[];for(let T of f){let h=T.scheme??"exact";if(h!=="exact"&&h!=="exact-approval")continue;let u=e.find(m=>m.canHandle(T.network));if(!u)continue;let g;u.name==="Solana"?g=R.solana:u.name==="EVM"&&(g=R.evm),g&&u.isConnected(g)&&y.push({accept:T,adapter:u,wallet:g})}if(y.length===0)return null;if(o){let T=y.find(h=>h.accept.network===o);if(T)return T}return y[0]}function x(f,y){return ut(f,y)}function B(f,y){return s[f]||y.getDefaultRpcUrl(f)}async function U(f,y,T,h,u){let g="";if(d?.preferTier&&h.tiers){let i=h.tiers.find(S=>S.id===d.preferTier);if(i){if(d.maxSpend&&parseFloat(i.price)>parseFloat(d.maxSpend))throw new b("access_pass_exceeds_max_spend",`Access pass tier "${i.id}" costs $${i.price}, exceeds max spend $${d.maxSpend}`);g=`tier=${i.id}`}}else if(d?.preferDuration&&h.ratePerHour)g=`duration=${d.preferDuration}`;else if(h.tiers&&h.tiers.length>0){let i=h.tiers[0];if(d?.maxSpend&&parseFloat(i.price)>parseFloat(d.maxSpend))throw new b("access_pass_exceeds_max_spend",`Cheapest access pass costs $${i.price}, exceeds max spend $${d?.maxSpend}`);g=`tier=${i.id}`}let m=g?u.includes("?")?`${u}&${g}`:`${u}?${g}`:u;l("Purchasing access pass:",g||"default tier");let C=T.headers.get("PAYMENT-REQUIRED");if(!C)return null;let L;try{L=JSON.parse(atob(C))}catch{return null}let _=O(L.accepts);if(!_)return null;let{accept:v,adapter:X,wallet:pe}=_;if(X.name==="Solana"&&!v.extra?.feePayer)return null;let V=v.extra?.decimals??(ot(v.asset)?6:void 0);if(typeof V!="number")return null;let xe=v.amount??v.maxAmountRequired;if(!xe)return null;let J=B(v.network,X);try{let i=await X.getBalance(v,pe,J),S=Number(xe)/Math.pow(10,V);if(i<S){let Ze=x(v.network,X.name);throw new b("insufficient_balance",`Insufficient balance for access pass on ${Ze}. Have $${i.toFixed(4)}, need $${S.toFixed(4)}`)}}catch(i){if(i instanceof b)throw i}let G=await X.buildTransaction(v,pe,J),de;X.name==="EVM"?de=JSON.parse(G.serialized):de={transaction:G.serialized};let Q=typeof f=="string"?f:f instanceof URL?f.href:f.url,ue=L.resource;if(typeof L.resource=="string")try{let i=new URL(L.resource,Q);["http:","https:"].includes(i.protocol)&&(ue=i.toString())}catch{}else if(L.resource&&typeof L.resource=="object"&&"url"in L.resource){let i=L.resource;try{let S=new URL(i.url,Q);["http:","https:"].includes(S.protocol)&&(ue={...i,url:S.toString()})}catch{}}let $e={x402Version:v.x402Version??2,resource:ue,accepted:v,payload:de};G.extensions&&($e.extensions=G.extensions);let Y=btoa(JSON.stringify($e)),Z=await a(m,{...y,method:"POST",headers:{...y?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":Y}});if(!Z.ok)return l("Pass purchase failed:",Z.status),null;let q=Z.headers.get("ACCESS-PASS");return q&&(W(u,q),l("Access pass purchased and cached")),Z}async function $(f,y){let T=f;if(l("Making request:",T),d){let i=k(T);if(i){l("Using cached access pass");let S=await a(f,{...y,headers:{...y?.headers||{},Authorization:`Bearer ${i}`}});if(S.status!==401&&S.status!==402)return S;l("Cached pass rejected (status",S.status,"), purchasing new pass");try{I.delete(new URL(T).host)}catch{}}}let h=await P(f,y);if(h.status!==402)return h;l("Received 402 Payment Required");let u=h.headers.get("X-ACCESS-PASS-TIERS");if(d&&u){l("Server offers access passes, purchasing...");try{let i=JSON.parse(atob(u)),S=await U(f,y,h,i,T);if(S)return S}catch(i){l("Access pass purchase failed, falling back to per-request payment:",i)}}let g=h.headers.get("PAYMENT-REQUIRED");if(!g)throw new b("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let m;try{let i=atob(g);m=JSON.parse(i)}catch{throw new b("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}l("Payment requirements:",m);let C=h.headers.get("X-Quote-Hash");C&&l("Quote hash received:",C);let L=O(m.accepts);if(!L){let i=m.accepts.map(S=>S.network).join(", ");throw new b("no_matching_payment_option",`No connected wallet for any available network: ${i}`)}let{accept:_,adapter:v,wallet:X}=L;if(l(`Using ${v.name} for ${_.network}`),v.name==="Solana"&&!_.extra?.feePayer)throw new b("missing_fee_payer","Solana payment option missing feePayer in extra");let pe=_.extra?.decimals??(ot(_.asset)?6:void 0);if(typeof pe!="number")throw new b("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let V=_.amount??_.maxAmountRequired;if(!V)throw new b("missing_amount","Payment option missing amount");if(p&&BigInt(V)>BigInt(p))throw new b("amount_exceeds_max",`Payment amount ${V} exceeds maximum ${p}`);let xe=B(_.network,v);l("Checking balance...");try{let i=await v.getBalance(_,X,xe),S=Number(V)/Math.pow(10,pe);if(i<S){let Ze=x(_.network,v.name);throw new b("insufficient_balance",`Insufficient balance on ${Ze}. Have $${i.toFixed(4)}, need $${S.toFixed(4)}`)}l(`Balance OK: $${i.toFixed(4)} >= $${S.toFixed(4)}`)}catch(i){if(i instanceof b)throw i;l("Balance check failed (RPC error), proceeding with transaction attempt")}if(E&&!await E(_))throw new b("payment_rejected","Payment rejected by onPaymentRequired callback");l("Building transaction...");let J=await v.buildTransaction(_,X,xe);l("Transaction signed");let G;v.name==="EVM"?G=JSON.parse(J.serialized):G={transaction:J.serialized};let de=f,Q=m.resource;if(typeof m.resource=="string")try{let i=new URL(m.resource,de).toString();i!==m.resource&&l("Resolved relative resource URL:",m.resource,"\u2192",i),Q=i}catch{Q=m.resource}else if(m.resource&&typeof m.resource=="object"&&"url"in m.resource){let i=m.resource;try{let S=new URL(i.url,de).toString();S!==i.url&&(l("Resolved relative resource URL:",i.url,"\u2192",S),Q={...i,url:S})}catch{}}let ue={x402Version:_.x402Version??2,resource:Q,accepted:_,payload:G};J.extensions&&(ue.extensions=J.extensions);let $e=btoa(JSON.stringify(ue));if(w)try{w(_,J.settlementProbe)}catch{}l("Retrying request with payment...");let Y=await P(f,{...y,headers:{...y?.headers||{},"PAYMENT-SIGNATURE":$e,...C?{"X-Quote-Hash":C}:{}}});if(l("Retry response status:",Y.status),Y.status===402){let i="unknown";try{let S=await Y.clone().json();i=String(S.error||S.message||JSON.stringify(S)),l("Rejection reason:",i)}catch{}throw new b("payment_rejected",`Payment was rejected by the server: ${i}`)}let Z=Y.headers.get("PAYMENT-RESPONSE"),q;if(Z)try{q=JSON.parse(atob(Z))}catch{}return q??={},q.amountAtomic=V,q.assetDecimals=pe,ft.set(Y,q),q.extensions&&l("Settlement extensions:",Object.keys(q.extensions).join(", ")),Y}async function D(f,y){let[T,h]=await Ct(f,y);return $(T,h)}return{fetch:D}}function At(r){let e=gt(r);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function at(r){let e=At(r);if(e?.recommendations?.length)return e.recommendations}async function it(r){let t=At(r)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function Ot(r){let{wallets:e,wallet:t,preferredNetwork:n,rpcUrls:o={},verbose:s=!1}=r,[p,a]=le(!1),[c,d]=le("idle"),[E,w]=le(null),[A,N]=le(null),[l,P]=le(null),[I,k]=le([]),[W,R]=le(null),O=Qe((...u)=>{s&&console.log("[useX402Payment]",...u)},[s]),x=We(()=>{let u={...e};return t&&!u.solana&&j(t)&&(u.solana=t),t&&!u.evm&&H(t)&&(u.evm=t),u},[e,t]),B=We(()=>[Se({verbose:s,rpcUrls:o}),Te({verbose:s,rpcUrls:o})],[s,o]),U=We(()=>({solana:x.solana?j(x.solana)&&B[0].isConnected(x.solana):!1,evm:x.evm?H(x.evm)&&B[1].isConnected(x.evm):!1}),[x,B]),$=U.solana||U.evm,D=Qe(async()=>{let u=[];if(U.solana&&x.solana)try{let g=B.find(m=>m.name==="Solana");if(g){let m={scheme:"exact",network:F,amount:"0",asset:Le,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},C=await g.getBalance(m,x.solana);u.push({network:F,chainName:ze(F),balance:C,asset:"USDC"})}}catch(g){O("Failed to fetch Solana balance:",g)}if(U.evm&&x.evm)try{let g=B.find(m=>m.name==="EVM");if(g){let m={scheme:"exact",network:K,amount:"0",asset:Fe,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},C=await g.getBalance(m,x.evm);u.push({network:K,chainName:ze(K),balance:C,asset:"USDC"})}}catch(g){O("Failed to fetch Base balance:",g)}k(u)},[U,x,B,O]);vt(()=>{D();let u=setInterval(D,3e4);return()=>clearInterval(u)},[D]);let f=Qe(()=>{a(!1),d("idle"),w(null),N(null),P(null),R(null)},[]),y=We(()=>ht({adapters:B,wallets:x,preferredNetwork:n,rpcUrls:o,verbose:s}),[B,x,n,o,s]),T=Qe(async(u,g)=>{if(a(!0),d("pending"),w(null),N(null),P(null),!$){let m=new b("wallet_not_connected","No wallet connected");throw w(m),d("error"),a(!1),m}try{let m=await y.fetch(u,g),C=m.headers.get("PAYMENT-RESPONSE");if(C)try{let _=JSON.parse(atob(C));_.transaction&&N(_.transaction),_.network&&P(_.network)}catch{O("Could not parse PAYMENT-RESPONSE header")}let L=at(m);return R(L??null),L&&(O("Sponsored recommendations received:",L.length),it(m).catch(()=>{})),d("success"),m}catch(m){let C=m instanceof Error?m:new Error(String(m));throw w(C),d("error"),m}finally{a(!1),setTimeout(D,2e3)}},[y,$,O,D]),h=We(()=>A?mt(A,l||n||F):null,[A,l,n]);return{fetch:T,isLoading:p,status:c,error:E,transactionId:A,transactionNetwork:l,transactionUrl:h,balances:I,connectedChains:U,isAnyWalletConnected:$,reset:f,refreshBalances:D,accessPass:null,sponsoredRecommendations:W}}export{b as X402Error,it as fireImpressionBeacon,at as getSponsoredRecommendations,Ot as useX402Payment};
|
|
1
|
+
import{useState as le,useCallback as Qe,useEffect as vt,useMemo as We}from"react";var F="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Re="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Ke="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",ee=F,we=Re,_e=Ke,K="eip155:8453",me="eip155:84532",fe="eip155:42161",ge="eip155:137",he="eip155:10",Ae="eip155:43114",ye="eip155:56",te="eip155:480",ne="eip155:143",re="eip155:4663",se="eip155:1187947933",oe="eip155:324705682",Ee="eip155:1",ae=K,qe=me,be=fe,Ne=ge,Pe=he,Ie=Ae,Ce=ye,ve=te,Oe=ne,Be=re,De=se,Me=oe,Ue=Ee,Le="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",ct="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",Fe="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",et="0x55d398326f99059fF775485246999027B3197955",He="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",tt="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",je={[ye]:He,[K]:Fe,[me]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[fe]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[ge]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[he]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[Ae]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[te]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[ne]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[re]:tt,[se]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[oe]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[Ee]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},Xe={[et]:{symbol:"USDT",decimals:18},[He]:{symbol:"USDC",decimals:18}};var Ve={[te]:{name:"USDC",version:"2"},[ne]:{name:"USDC",version:"2"},[re]:{name:"Global Dollar",version:"1"},[se]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[oe]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}},z="0x000000000022D473030F116dDEE9F6B43aC78BA3",ke="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",nt={[ye]:56,[K]:8453,[me]:84532,[fe]:42161,[ge]:137,[he]:10,[Ae]:43114,[te]:480,[ne]:143,[re]:4663,[se]:1187947933,[oe]:324705682,[Ee]:1},ie={[F]:"https://api.dexter.cash/api/solana/rpc",[Re]:"https://api.devnet.solana.com",[Ke]:"https://api.testnet.solana.com"},M={[ye]:"https://api.dexter.cash/api/evm/bsc/rpc",[K]:"https://api.dexter.cash/api/base/rpc",[me]:"https://sepolia.base.org",[fe]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[ge]:"https://api.dexter.cash/api/evm/polygon/rpc",[he]:"https://api.dexter.cash/api/evm/optimism/rpc",[Ae]:"https://api.dexter.cash/api/evm/avalanche/rpc",[te]:"https://worldchain-mainnet.g.alchemy.com/public",[ne]:"https://rpc.monad.xyz",[re]:"https://rpc.mainnet.chain.robinhood.com",[se]:"https://skale-base.skalenodes.com/v1/base",[oe]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[Ee]:"https://eth.llamarpc.com"};var b=class r extends Error{code;details;constructor(e,t,n){super(t),this.name="X402Error",this.code=e,this.details=n,Object.setPrototypeOf(this,r.prototype)}};import{PublicKey as ce,Connection as rt,TransactionMessage as yt,VersionedTransaction as Et,ComputeBudgetProgram as lt}from"@solana/web3.js";import{getAssociatedTokenAddress as st,getAccount as St,createTransferCheckedInstruction as Tt,getMint as xt,TOKEN_PROGRAM_ID as pt,TOKEN_2022_PROGRAM_ID as Je}from"@solana/spl-token";var Rt=12e3,wt=1;function H(r){if(!r||typeof r!="object")return!1;let e=r;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var Ge=class{name="Solana";networks=[ee,we,_e];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:solana]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="solana"||e==="solana-devnet"||e==="solana-testnet"||e.startsWith("solana:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:ie[e]?ie[e]:e==="solana"?ie[ee]:e==="solana-devnet"?ie[we]:e==="solana-testnet"?ie[_e]:ie[ee]}getAddress(e){return H(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return H(e)?e.publicKey!==null:!1}async getBalance(e,t,n){if(!H(t)||!t.publicKey)return 0;let o=n||this.getDefaultRpcUrl(e.network),s=new rt(o,"confirmed"),p=new ce(t.publicKey.toBase58()),a=new ce(e.asset);try{let d=(await s.getAccountInfo(a,"confirmed"))?.owner.toBase58()===Je.toBase58()?Je:pt,E=await st(a,p,!1,d),w=await St(s,E,void 0,d),A=e.extra?.decimals??6;return Number(w.amount)/Math.pow(10,A)}catch(c){if(c&&typeof c=="object"&&"name"in c&&(c.name==="TokenAccountNotFoundError"||c.name==="TokenInvalidAccountOwnerError"))return 0;throw c}}async buildTransaction(e,t,n){if(!H(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let o=n||this.getDefaultRpcUrl(e.network),s=new rt(o,"confirmed"),p=new ce(t.publicKey.toBase58()),{payTo:a,asset:c,extra:d}=e,E=e.amount??e.maxAmountRequired;if(!E)throw new Error("Missing amount in payment requirements");if(!d?.feePayer)throw new Error("Missing feePayer in payment requirements");let w=new ce(d.feePayer),A=new ce(c),N=new ce(a);this.log("Building transaction:",{from:p.toBase58(),to:a,amount:E,asset:c,feePayer:d.feePayer});let l=[];l.push(lt.setComputeUnitLimit({units:Rt})),l.push(lt.setComputeUnitPrice({microLamports:wt}));let P=await s.getAccountInfo(A,"confirmed");if(!P)throw new Error(`Token mint ${c} not found`);let I=P.owner.toBase58()===Je.toBase58()?Je:pt,k=await xt(s,A,void 0,I);typeof d?.decimals=="number"&&k.decimals!==d.decimals&&this.log(`Decimals mismatch: requirements say ${d.decimals}, mint says ${k.decimals}`);let W=await st(A,p,!1,I),R=await st(A,N,!0,I);if(!await s.getAccountInfo(W,"confirmed"))throw new Error(`No token account found for ${c}. Please ensure you have USDC in your wallet.`);if(!await s.getAccountInfo(R,"confirmed"))throw new Error(`Seller token account not found. The seller (${a}) must have a USDC account.`);let B=BigInt(E);l.push(Tt(W,A,R,p,B,k.decimals,[],I));let{blockhash:U}=await s.getLatestBlockhash("confirmed"),$=new yt({payerKey:w,recentBlockhash:U,instructions:l}).compileToV0Message(),D=new Et($),f=await t.signTransaction(D);return this.log("Transaction signed successfully"),{serialized:Buffer.from(f.serialize()).toString("base64"),settlementProbe:{kind:"solana",sourceAta:W.toBase58(),destinationAta:R.toBase58(),asset:c,amount:E,blockhash:U}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let n=new rt(t,"confirmed"),o=new ce(e.destinationAta),s=await n.getSignaturesForAddress(o,{limit:25});if(s.length===0)return{settled:!1};let p=BigInt(e.amount);for(let a of s){if(a.err)continue;let c=await n.getTransaction(a.signature,{commitment:"confirmed",maxSupportedTransactionVersion:0});if(!c?.meta)continue;let d=c.transaction.message.getAccountKeys().keySegments().flat(),E=c.meta.preTokenBalances??[],w=c.meta.postTokenBalances??[];for(let A of w){if(A.mint!==e.asset)continue;let N=d[A.accountIndex];if(!N||!N.equals(o))continue;let l=E.find(k=>k.accountIndex===A.accountIndex),P=BigInt(l?.uiTokenAmount.amount??"0");if(BigInt(A.uiTokenAmount.amount??"0")-P===p)return{settled:!0,txSignature:a.signature}}}return{settled:!1}}};function Se(r){return new Ge(r)}var _t={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"validAfter",type:"uint256"}]},dt=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function j(r){if(!r||typeof r!="object")return!1;let e=r;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var Ye=class{name="EVM";networks=[Ce,ae,qe,Ue,be,Ne,Pe,Ie,ve,Oe,Be,De,Me];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:evm]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="base"||e==="bsc"||e==="ethereum"||e==="arbitrum"||e==="polygon"||e==="optimism"||e==="avalanche"||e==="world"||e==="monad"||e==="robinhood"||e==="skale-base"||e==="skale-base-sepolia"||e.startsWith("eip155:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:M[e]?M[e]:e==="base"?M[ae]:e==="bsc"?M[Ce]:e==="ethereum"?M[Ue]:e==="arbitrum"?M[be]:e==="polygon"?M[Ne]:e==="optimism"?M[Pe]:e==="avalanche"?M[Ie]:e==="world"?M[ve]:e==="monad"?M[Oe]:e==="robinhood"?M[Be]:e==="skale-base"?M[De]:e==="skale-base-sepolia"?M[Me]:M[ae]}getAddress(e){return j(e)?e.address:null}isConnected(e){return j(e)?!!e.address:!1}getChainId(e){if(nt[e])return nt[e];if(e.startsWith("eip155:")){let t=e.split(":")[1];return parseInt(t,10)}return e==="base"?8453:e==="bsc"?56:e==="ethereum"?1:e==="arbitrum"?42161:e==="polygon"?137:e==="optimism"?10:e==="avalanche"?43114:e==="world"?480:e==="monad"?143:e==="robinhood"?4663:e==="skale-base"?1187947933:e==="skale-base-sepolia"?324705682:8453}async getBalance(e,t,n){if(!j(t)||!t.address)return 0;let o=n||this.getDefaultRpcUrl(e.network);try{let s=this.encodeBalanceOf(t.address),p=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:e.asset,data:s},"latest"]})});if(!p.ok)throw new Error(`RPC request failed: ${p.status}`);let a=await p.json();if(a.error)throw new Error(`RPC error: ${JSON.stringify(a.error)}`);if(!a.result||a.result==="0x")return 0;let c=BigInt(a.result),d=e.extra?.decimals??6;return Number(c)/Math.pow(10,d)}catch(s){throw s}}encodeBalanceOf(e){let t="0x70a08231",n=e.slice(2).toLowerCase().padStart(64,"0");return t+n}async confirmSettlement(e,t){if(e.kind==="eip3009"){let n="0xe94a0102",o=e.from.slice(2).toLowerCase().padStart(64,"0"),s=e.nonce.slice(2).toLowerCase().padStart(64,"0"),p=n+o+s,a=await this.ethCall(t,e.asset,p);return{settled:BigInt(a)!==0n}}if(e.kind==="permit2"){let n="0x4fe02b44",o=BigInt(e.nonce),s=o>>8n,p=o&0xffn,a=e.from.slice(2).toLowerCase().padStart(64,"0"),c=s.toString(16).padStart(64,"0"),d=n+a+c,E=await this.ethCall(t,z,d);return{settled:(BigInt(E)>>p&1n)===1n}}throw new Error(`EvmAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`)}async ethCall(e,t,n){let o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:n},"latest"]})});if(!o.ok)throw new Error(`RPC request failed: ${o.status}`);let s=await o.json();if(s.error)throw new Error(`RPC error: ${JSON.stringify(s.error)}`);if(!s.result||s.result==="0x")throw new Error("RPC returned an empty result");return s.result}async buildTransaction(e,t,n){if(!j(t))throw new Error("Invalid EVM wallet");if(!t.address)throw new Error("Wallet not connected");if(e.scheme==="exact-approval")return this.buildApprovalTransaction(e,t,n);if(e.extra?.assetTransferMethod==="permit2")return this.buildPermit2Transaction(e,t,n);let{payTo:o,asset:s,extra:p}=e,a=e.amount??e.maxAmountRequired;if(!a)throw new Error("Missing amount in payment requirements");this.log("Building EVM transaction:",{from:t.address,to:o,amount:a,asset:s,network:e.network});let c=this.getChainId(e.network),d=Ve[`eip155:${c}`],E={name:p?.name??d?.name??"USD Coin",version:p?.version??d?.version??"2",chainId:BigInt(c),verifyingContract:s},w={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},A=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(A);let N="0x"+[...A].map(R=>R.toString(16).padStart(2,"0")).join(""),l=Math.floor(Date.now()/1e3),P={from:t.address,to:o,value:a,validAfter:String(l-600),validBefore:String(l+(e.maxTimeoutSeconds||60)),nonce:N},I={from:t.address,to:o,value:BigInt(a),validAfter:BigInt(l-600),validBefore:BigInt(l+(e.maxTimeoutSeconds||60)),nonce:N};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let k=await t.signTypedData({domain:E,types:w,primaryType:"TransferWithAuthorization",message:I});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:P,signature:k}),signature:k,settlementProbe:{kind:"eip3009",from:t.address,nonce:N,asset:s,chainId:c}}}async buildApprovalTransaction(e,t,n){let{payTo:o,asset:s,extra:p}=e,a=e.amount??e.maxAmountRequired;if(!a)throw new Error("Missing amount in payment requirements");let c=p?.facilitatorContract;if(!c)throw new Error("exact-approval scheme requires extra.facilitatorContract from the facilitator. The /supported endpoint should provide this.");if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building approval-based transaction:",{from:t.address,to:o,amount:a,asset:s,network:e.network,facilitatorContract:c});let d=n||this.getDefaultRpcUrl(e.network),E=p?.fee??"0",w=BigInt(a)+BigInt(E),A=await this.readAllowance(d,s,t.address,c);if(A<w){if(!t.sendTransaction)throw new Error("BSC payments require a wallet that supports sendTransaction for the one-time token approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.");let D=this.calculateApprovalAmount(a,E,p?.approvalStrategy);this.log(`Approving ${D} for ${c} (current allowance: ${A})`);let f=await t.sendTransaction({to:s,data:this.encodeApprove(c,D),value:0n});this.log(`Approval tx sent: ${f}`),await this.waitForReceipt(d,f),this.log("Approval confirmed")}else this.log("Sufficient allowance, skipping approval");let N=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(N);let l=[...N].reduce((D,f)=>D*256n+BigInt(f),0n).toString(),P=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(P);let I="0x"+[...P].map(D=>D.toString(16).padStart(2,"0")).join(""),W=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),R=p?.eip712Domain,O=R?{name:R.name,version:R.version,chainId:BigInt(R.chainId),verifyingContract:R.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:c},x=p?.eip712Types??{Payment:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"token",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"paymentId",type:"bytes32"}]},B={from:t.address,to:o,token:s,amount:BigInt(a),fee:BigInt(E),nonce:BigInt(l),deadline:BigInt(W),paymentId:I},U=await t.signTypedData({domain:O,types:x,primaryType:"Payment",message:B});this.log("EIP-712 Payment signature obtained");let $={from:t.address,to:o,token:s,amount:a,fee:E,nonce:l,deadline:W,paymentId:I,signature:U};return{serialized:JSON.stringify($),signature:U}}async buildPermit2Transaction(e,t,n){let{payTo:o,asset:s}=e,p=e.amount??e.maxAmountRequired;if(!p)throw new Error("Missing amount in payment requirements");if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building Permit2 transaction:",{from:t.address,to:o,amount:p,asset:s,network:e.network});let a=n||this.getDefaultRpcUrl(e.network),c=await this.readAllowance(a,s,t.address,z),d;if(c<BigInt(p)){let O=this.encodeApprove(z,dt);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${c})`);let x=this.getChainId(e.network),B=await this.readGasPrice(a),U=await this.readNonce(a,t.address),$=await t.signTransaction({to:s,data:O,chainId:x,gas:50000n,gasPrice:B,nonce:U});d={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:s,spender:z,amount:dt.toString(),signedTransaction:$,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${c})`);let x=await t.sendTransaction({to:s,data:O,value:0n});this.log(`Permit2 approval tx sent: ${x}`),await this.waitForReceipt(a,x),this.log("Permit2 approval confirmed")}else throw new Error("Permit2 payments require a wallet that supports signTransaction or sendTransaction for the one-time Permit2 approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.")}else this.log("Sufficient Permit2 allowance, skipping approval");let E=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(E);let w=[...E].reduce((O,x)=>O*256n+BigInt(x),0n),A=Math.floor(Date.now()/1e3),N=A-600,l=A+(e.maxTimeoutSeconds||300),P=this.getChainId(e.network),I={name:"Permit2",chainId:BigInt(P),verifyingContract:z},k={permitted:{token:s,amount:BigInt(p)},spender:ke,nonce:w,deadline:BigInt(l),witness:{to:o,validAfter:BigInt(N)}},W=await t.signTypedData({domain:I,types:_t,primaryType:"PermitWitnessTransferFrom",message:k});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let R={signature:W,permit2Authorization:{from:t.address,permitted:{token:s,amount:p},spender:ke,nonce:w.toString(),deadline:String(l),witness:{to:o,validAfter:String(N)}}};return{serialized:JSON.stringify(R),signature:W,extensions:d,settlementProbe:{kind:"permit2",from:t.address,nonce:w.toString(),chainId:P}}}async readAllowance(e,t,n,o){let s="0xdd62ed3e",p=n.slice(2).toLowerCase().padStart(64,"0"),a=o.slice(2).toLowerCase().padStart(64,"0"),c=s+p+a;try{let E=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:c},"latest"]})})).json();return E.error||!E.result||E.result==="0x"?0n:BigInt(E.result)}catch{return 0n}}encodeApprove(e,t){let n="0x095ea7b3",o=e.slice(2).toLowerCase().padStart(64,"0"),s=t.toString(16).padStart(64,"0");return n+o+s}async waitForReceipt(e,t,n=3e4){let o=Date.now();for(;Date.now()-o<n;){try{let p=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionReceipt",params:[t]})})).json();if(p.result){if(p.result.status==="0x0")throw new Error(`Approval transaction reverted: ${t}`);return}}catch(s){if(s instanceof Error&&s.message.includes("reverted"))throw s}await new Promise(s=>setTimeout(s,2e3))}throw new Error(`Approval transaction receipt timeout after ${n}ms: ${t}`)}async readGasPrice(e){try{let n=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_gasPrice",params:[]})})).json();return n.result?BigInt(n.result):50000000n}catch{return 50000000n}}async readNonce(e,t){try{let o=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionCount",params:[t,"latest"]})})).json();return o.result?parseInt(o.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,n){let o=BigInt(e)+BigInt(t);if(!n||n.mode==="exact")return o;let s=BigInt(n.defaultMultiple??10),p=o*s;if(n.maxCapUsd){let a=this.inferDecimals(e),c=BigInt(Math.floor(n.maxCapUsd*Math.pow(10,a)));if(p>c)return c}if(n.exactAboveUsd){let a=this.inferDecimals(e),c=BigInt(Math.floor(n.exactAboveUsd*Math.pow(10,a)));if(BigInt(e)>c)return o}return p}inferDecimals(e){return e.length>12?18:6}};function Te(r){return new Ye(r)}function ot(r){if(r===Le||r===ct)return!0;let e=r.toLowerCase();for(let t of Object.values(je))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(Xe))if(t.toLowerCase()===e)return!0;return!1}function bt(r){return r.startsWith("solana:")||r==="solana"}var Nt=["base","base-sepolia","ethereum","arbitrum","polygon","optimism","avalanche","bsc","world","monad","robinhood","skale-base","skale-base-sepolia"];function Pt(r){return r.startsWith("eip155:")||Nt.includes(r)}function It(r){return bt(r)?"solana":Pt(r)?"evm":"unknown"}function ze(r){return{[F]:"Solana",[Re]:"Solana Devnet",[Ke]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[K]:"Base",[me]:"Base Sepolia",[Ee]:"Ethereum",[fe]:"Arbitrum",[ge]:"Polygon",[he]:"Optimism",[Ae]:"Avalanche",[ye]:"BSC",[te]:"World Chain",[ne]:"Monad",[re]:"Robinhood Chain",[se]:"SKALE Base",[oe]:"SKALE Base Sepolia",base:"Base","base-sepolia":"Base Sepolia",ethereum:"Ethereum",arbitrum:"Arbitrum",polygon:"Polygon",optimism:"Optimism",avalanche:"Avalanche",bsc:"BSC",world:"World Chain",monad:"Monad",robinhood:"Robinhood Chain","skale-base":"SKALE Base","skale-base-sepolia":"SKALE Base Sepolia"}[r]||r}function ut(r,e){let t=ze(r);return t===r?e:t}function mt(r,e){let t=It(e);if(t==="solana")return e.includes("devnet")||e===Re?`https://solscan.io/tx/${r}?cluster=devnet`:`https://www.orbmarkets.io/tx/${r}`;if(t==="evm"){let n="8453";switch(e.startsWith("eip155:")?n=e.split(":")[1]:e==="ethereum"?n="1":e==="arbitrum"?n="42161":e==="polygon"?n="137":e==="optimism"?n="10":e==="avalanche"?n="43114":e==="bsc"?n="56":e==="world"?n="480":e==="monad"?n="143":e==="robinhood"?n="4663":e==="skale-base"?n="1187947933":e==="skale-base-sepolia"&&(n="324705682"),n){case"8453":return`https://basescan.org/tx/${r}`;case"84532":return`https://sepolia.basescan.org/tx/${r}`;case"1":return`https://etherscan.io/tx/${r}`;case"42161":return`https://arbiscan.io/tx/${r}`;case"137":return`https://polygonscan.com/tx/${r}`;case"10":return`https://optimistic.etherscan.io/tx/${r}`;case"43114":return`https://snowtrace.io/tx/${r}`;case"56":return`https://bscscan.com/tx/${r}`;case"480":return`https://worldscan.org/tx/${r}`;case"143":return`https://monadvision.com/tx/${r}`;case"4663":return`https://robinhoodchain.blockscout.com/tx/${r}`;case"1187947933":return`https://elated-tan-skat.explorer.mainnet.skalenodes.com/tx/${r}`;case"324705682":return`https://base-sepolia-testnet.explorer.skalenodes.com/tx/${r}`;default:return`https://basescan.org/tx/${r}`}}return`https://solscan.io/tx/${r}`}async function Ct(r,e){if(typeof r=="string")return[r,e];if(r instanceof URL)return[r.href,e];let t=r,n=new Headers(t.headers);e?.headers&&new Headers(e.headers).forEach((p,a)=>n.set(a,p));let o={method:e?.method??t.method,headers:n,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},s=(o.method??"GET").toUpperCase();return e&&"body"in e?o.body=e.body:s!=="GET"&&s!=="HEAD"&&t.body&&(o.body=await t.arrayBuffer()),[t.url,o]}var ft=new WeakMap;function gt(r){return ft.get(r)}function ht(r){let{adapters:e=[Se({verbose:r.verbose}),Te({verbose:r.verbose})],wallets:t,wallet:n,preferredNetwork:o,rpcUrls:s={},maxAmountAtomic:p,fetch:a=globalThis.fetch,verbose:c=!1,accessPass:d,onPaymentRequired:E,onPaymentDispatched:w,maxRetries:A=0,retryDelayMs:N=500}=r,l=c?console.log.bind(console,"[x402]"):()=>{};async function P(f,y){let T;for(let h=0;h<=A;h++)try{let u=await a(f,y);if(u.status>=502&&u.status<=504&&h<A){l(`Retry ${h+1}/${A}: server returned ${u.status}`),await new Promise(g=>setTimeout(g,N*Math.pow(2,h)));continue}return u}catch(u){T=u,h<A&&(l(`Retry ${h+1}/${A}: ${u instanceof Error?u.message:"network error"}`),await new Promise(g=>setTimeout(g,N*Math.pow(2,h))))}throw T}let I=new Map;function k(f){try{let y=new URL(f).host,T=I.get(y);if(T&&T.expiresAt>Date.now()/1e3+10)return T.jwt;T&&I.delete(y)}catch{}return null}function W(f,y){try{let T=new URL(f).host,h=y.split(".");if(h.length===3){let u=JSON.parse(atob(h[1].replace(/-/g,"+").replace(/_/g,"/"))),g=Math.floor(Date.now()/1e3),m=g+86400,C=Math.min(typeof u.exp=="number"?u.exp:g,m);I.set(T,{jwt:y,expiresAt:C}),l("Access pass cached for",T,"| expires:",new Date(C*1e3).toISOString())}}catch{l("Failed to cache access pass")}}let R=t||{};n&&!R.solana&&H(n)&&(R.solana=n),n&&!R.evm&&j(n)&&(R.evm=n);function O(f){let y=[];for(let T of f){let h=T.scheme??"exact";if(h!=="exact"&&h!=="exact-approval")continue;let u=e.find(m=>m.canHandle(T.network));if(!u)continue;let g;u.name==="Solana"?g=R.solana:u.name==="EVM"&&(g=R.evm),g&&u.isConnected(g)&&y.push({accept:T,adapter:u,wallet:g})}if(y.length===0)return null;if(o){let T=y.find(h=>h.accept.network===o);if(T)return T}return y[0]}function x(f,y){return ut(f,y)}function B(f,y){return s[f]||y.getDefaultRpcUrl(f)}async function U(f,y,T,h,u){let g="";if(d?.preferTier&&h.tiers){let i=h.tiers.find(S=>S.id===d.preferTier);if(i){if(d.maxSpend&&parseFloat(i.price)>parseFloat(d.maxSpend))throw new b("access_pass_exceeds_max_spend",`Access pass tier "${i.id}" costs $${i.price}, exceeds max spend $${d.maxSpend}`);g=`tier=${i.id}`}}else if(d?.preferDuration&&h.ratePerHour)g=`duration=${d.preferDuration}`;else if(h.tiers&&h.tiers.length>0){let i=h.tiers[0];if(d?.maxSpend&&parseFloat(i.price)>parseFloat(d.maxSpend))throw new b("access_pass_exceeds_max_spend",`Cheapest access pass costs $${i.price}, exceeds max spend $${d?.maxSpend}`);g=`tier=${i.id}`}let m=g?u.includes("?")?`${u}&${g}`:`${u}?${g}`:u;l("Purchasing access pass:",g||"default tier");let C=T.headers.get("PAYMENT-REQUIRED");if(!C)return null;let L;try{L=JSON.parse(atob(C))}catch{return null}let _=O(L.accepts);if(!_)return null;let{accept:v,adapter:X,wallet:pe}=_;if(X.name==="Solana"&&!v.extra?.feePayer)return null;let V=v.extra?.decimals??(ot(v.asset)?6:void 0);if(typeof V!="number")return null;let xe=v.amount??v.maxAmountRequired;if(!xe)return null;let J=B(v.network,X);try{let i=await X.getBalance(v,pe,J),S=Number(xe)/Math.pow(10,V);if(i<S){let Ze=x(v.network,X.name);throw new b("insufficient_balance",`Insufficient balance for access pass on ${Ze}. Have $${i.toFixed(4)}, need $${S.toFixed(4)}`)}}catch(i){if(i instanceof b)throw i}let G=await X.buildTransaction(v,pe,J),de;X.name==="EVM"?de=JSON.parse(G.serialized):de={transaction:G.serialized};let Q=typeof f=="string"?f:f instanceof URL?f.href:f.url,ue=L.resource;if(typeof L.resource=="string")try{let i=new URL(L.resource,Q);["http:","https:"].includes(i.protocol)&&(ue=i.toString())}catch{}else if(L.resource&&typeof L.resource=="object"&&"url"in L.resource){let i=L.resource;try{let S=new URL(i.url,Q);["http:","https:"].includes(S.protocol)&&(ue={...i,url:S.toString()})}catch{}}let $e={x402Version:v.x402Version??2,resource:ue,accepted:v,payload:de};G.extensions&&($e.extensions=G.extensions);let Y=btoa(JSON.stringify($e)),Z=await a(m,{...y,method:"POST",headers:{...y?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":Y}});if(!Z.ok)return l("Pass purchase failed:",Z.status),null;let q=Z.headers.get("ACCESS-PASS");return q&&(W(u,q),l("Access pass purchased and cached")),Z}async function $(f,y){let T=f;if(l("Making request:",T),d){let i=k(T);if(i){l("Using cached access pass");let S=await a(f,{...y,headers:{...y?.headers||{},Authorization:`Bearer ${i}`}});if(S.status!==401&&S.status!==402)return S;l("Cached pass rejected (status",S.status,"), purchasing new pass");try{I.delete(new URL(T).host)}catch{}}}let h=await P(f,y);if(h.status!==402)return h;l("Received 402 Payment Required");let u=h.headers.get("X-ACCESS-PASS-TIERS");if(d&&u){l("Server offers access passes, purchasing...");try{let i=JSON.parse(atob(u)),S=await U(f,y,h,i,T);if(S)return S}catch(i){l("Access pass purchase failed, falling back to per-request payment:",i)}}let g=h.headers.get("PAYMENT-REQUIRED");if(!g)throw new b("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let m;try{let i=atob(g);m=JSON.parse(i)}catch{throw new b("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}l("Payment requirements:",m);let C=h.headers.get("X-Quote-Hash");C&&l("Quote hash received:",C);let L=O(m.accepts);if(!L){let i=m.accepts.map(S=>S.network).join(", ");throw new b("no_matching_payment_option",`No connected wallet for any available network: ${i}`)}let{accept:_,adapter:v,wallet:X}=L;if(l(`Using ${v.name} for ${_.network}`),v.name==="Solana"&&!_.extra?.feePayer)throw new b("missing_fee_payer","Solana payment option missing feePayer in extra");let pe=_.extra?.decimals??(ot(_.asset)?6:void 0);if(typeof pe!="number")throw new b("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let V=_.amount??_.maxAmountRequired;if(!V)throw new b("missing_amount","Payment option missing amount");if(p&&BigInt(V)>BigInt(p))throw new b("amount_exceeds_max",`Payment amount ${V} exceeds maximum ${p}`);let xe=B(_.network,v);l("Checking balance...");try{let i=await v.getBalance(_,X,xe),S=Number(V)/Math.pow(10,pe);if(i<S){let Ze=x(_.network,v.name);throw new b("insufficient_balance",`Insufficient balance on ${Ze}. Have $${i.toFixed(4)}, need $${S.toFixed(4)}`)}l(`Balance OK: $${i.toFixed(4)} >= $${S.toFixed(4)}`)}catch(i){if(i instanceof b)throw i;l("Balance check failed (RPC error), proceeding with transaction attempt")}if(E&&!await E(_))throw new b("payment_rejected","Payment rejected by onPaymentRequired callback");l("Building transaction...");let J=await v.buildTransaction(_,X,xe);l("Transaction signed");let G;v.name==="EVM"?G=JSON.parse(J.serialized):G={transaction:J.serialized};let de=f,Q=m.resource;if(typeof m.resource=="string")try{let i=new URL(m.resource,de).toString();i!==m.resource&&l("Resolved relative resource URL:",m.resource,"\u2192",i),Q=i}catch{Q=m.resource}else if(m.resource&&typeof m.resource=="object"&&"url"in m.resource){let i=m.resource;try{let S=new URL(i.url,de).toString();S!==i.url&&(l("Resolved relative resource URL:",i.url,"\u2192",S),Q={...i,url:S})}catch{}}let ue={x402Version:_.x402Version??2,resource:Q,accepted:_,payload:G};J.extensions&&(ue.extensions=J.extensions);let $e=btoa(JSON.stringify(ue));if(w)try{w(_,J.settlementProbe)}catch{}l("Retrying request with payment...");let Y=await P(f,{...y,headers:{...y?.headers||{},"PAYMENT-SIGNATURE":$e,...C?{"X-Quote-Hash":C}:{}}});if(l("Retry response status:",Y.status),Y.status===402){let i="unknown";try{let S=await Y.clone().json();i=String(S.error||S.message||JSON.stringify(S)),l("Rejection reason:",i)}catch{}throw new b("payment_rejected",`Payment was rejected by the server: ${i}`)}let Z=Y.headers.get("PAYMENT-RESPONSE"),q;if(Z)try{q=JSON.parse(atob(Z))}catch{}return q??={},q.amountAtomic=V,q.assetDecimals=pe,ft.set(Y,q),q.extensions&&l("Settlement extensions:",Object.keys(q.extensions).join(", ")),Y}async function D(f,y){let[T,h]=await Ct(f,y);return $(T,h)}return{fetch:D}}function At(r){let e=gt(r);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function at(r){let e=At(r);if(e?.recommendations?.length)return e.recommendations}async function it(r){let t=At(r)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function Ot(r){let{wallets:e,wallet:t,preferredNetwork:n,rpcUrls:o={},verbose:s=!1}=r,[p,a]=le(!1),[c,d]=le("idle"),[E,w]=le(null),[A,N]=le(null),[l,P]=le(null),[I,k]=le([]),[W,R]=le(null),O=Qe((...u)=>{s&&console.log("[useX402Payment]",...u)},[s]),x=We(()=>{let u={...e};return t&&!u.solana&&H(t)&&(u.solana=t),t&&!u.evm&&j(t)&&(u.evm=t),u},[e,t]),B=We(()=>[Se({verbose:s,rpcUrls:o}),Te({verbose:s,rpcUrls:o})],[s,o]),U=We(()=>({solana:x.solana?H(x.solana)&&B[0].isConnected(x.solana):!1,evm:x.evm?j(x.evm)&&B[1].isConnected(x.evm):!1}),[x,B]),$=U.solana||U.evm,D=Qe(async()=>{let u=[];if(U.solana&&x.solana)try{let g=B.find(m=>m.name==="Solana");if(g){let m={scheme:"exact",network:F,amount:"0",asset:Le,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},C=await g.getBalance(m,x.solana);u.push({network:F,chainName:ze(F),balance:C,asset:"USDC"})}}catch(g){O("Failed to fetch Solana balance:",g)}if(U.evm&&x.evm)try{let g=B.find(m=>m.name==="EVM");if(g){let m={scheme:"exact",network:K,amount:"0",asset:Fe,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},C=await g.getBalance(m,x.evm);u.push({network:K,chainName:ze(K),balance:C,asset:"USDC"})}}catch(g){O("Failed to fetch Base balance:",g)}k(u)},[U,x,B,O]);vt(()=>{D();let u=setInterval(D,3e4);return()=>clearInterval(u)},[D]);let f=Qe(()=>{a(!1),d("idle"),w(null),N(null),P(null),R(null)},[]),y=We(()=>ht({adapters:B,wallets:x,preferredNetwork:n,rpcUrls:o,verbose:s}),[B,x,n,o,s]),T=Qe(async(u,g)=>{if(a(!0),d("pending"),w(null),N(null),P(null),!$){let m=new b("wallet_not_connected","No wallet connected");throw w(m),d("error"),a(!1),m}try{let m=await y.fetch(u,g),C=m.headers.get("PAYMENT-RESPONSE");if(C)try{let _=JSON.parse(atob(C));_.transaction&&N(_.transaction),_.network&&P(_.network)}catch{O("Could not parse PAYMENT-RESPONSE header")}let L=at(m);return R(L??null),L&&(O("Sponsored recommendations received:",L.length),it(m).catch(()=>{})),d("success"),m}catch(m){let C=m instanceof Error?m:new Error(String(m));throw w(C),d("error"),m}finally{a(!1),setTimeout(D,2e3)}},[y,$,O,D]),h=We(()=>A?mt(A,l||n||F):null,[A,l,n]);return{fetch:T,isLoading:p,status:c,error:E,transactionId:A,transactionNetwork:l,transactionUrl:h,balances:I,connectedChains:U,isAnyWalletConnected:$,reset:f,refreshBalances:D,accessPass:null,sponsoredRecommendations:W}}export{b as X402Error,it as fireImpressionBeacon,at as getSponsoredRecommendations,Ot as useX402Payment};
|
package/dist/server/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var ae=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var Fe=(e,t)=>{for(var s in t)ae(e,s,{get:t[s],enumerable:!0})},je=(e,t,s,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of He(t))!We.call(e,n)&&n!==s&&ae(e,n,{get:()=>t[n],enumerable:!(r=$e(t,n))||r.enumerable});return e};var Ve=e=>je(ae({},"__esModule",{value:!0}),e);var pt={};Fe(pt,{BASE_MAINNET_NETWORK:()=>k,DEXTER_FACILITATOR_URL:()=>D,FacilitatorClient:()=>B,SOLANA_MAINNET_NETWORK:()=>N,SPONSORED_ACCESS_EXTENSION_KEY:()=>qe.SPONSORED_ACCESS_EXTENSION_KEY,USDC_BASE:()=>te,USDC_MINT:()=>M,bazaarExtension:()=>Ue,createX402Server:()=>se,declareDiscoveryExtension:()=>Le,resolveDefaultAsset:()=>ce,x402Middleware:()=>ke});module.exports=Ve(pt);var N="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",fe="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",ye="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";var k="eip155:8453",z="eip155:84532",J="eip155:42161",G="eip155:137",Y="eip155:10",Q="eip155:43114",Z="eip155:56",K="eip155:480",$="eip155:143",H="eip155:4663",W="eip155:1187947933",F="eip155:324705682",ee="eip155:1";var M="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";var te="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",Xe="0x55d398326f99059fF775485246999027B3197955",he="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",ze="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",ge={[Z]:he,[k]:te,[z]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[J]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[G]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[Y]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[Q]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[K]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[$]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[H]:ze,[W]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[F]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[ee]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},xe={[Xe]:{symbol:"USDT",decimals:18},[he]:{symbol:"USDC",decimals:18}};var dt={[K]:{name:"USDC",version:"2"},[$]:{name:"USDC",version:"2"},[H]:{name:"Global Dollar",version:"1"},[W]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[F]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}};var ut={[Z]:56,[k]:8453,[z]:84532,[J]:42161,[G]:137,[Y]:10,[Q]:43114,[K]:480,[$]:143,[H]:4663,[W]:1187947933,[F]:324705682,[ee]:1},mt={[N]:"https://api.dexter.cash/api/solana/rpc",[fe]:"https://api.devnet.solana.com",[ye]:"https://api.testnet.solana.com"},Je={[Z]:"https://api.dexter.cash/api/evm/bsc/rpc",[k]:"https://api.dexter.cash/api/base/rpc",[z]:"https://sepolia.base.org",[J]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[G]:"https://api.dexter.cash/api/evm/polygon/rpc",[Y]:"https://api.dexter.cash/api/evm/optimism/rpc",[Q]:"https://api.dexter.cash/api/evm/avalanche/rpc",[K]:"https://worldchain-mainnet.g.alchemy.com/public",[$]:"https://rpc.monad.xyz",[H]:"https://rpc.mainnet.chain.robinhood.com",[W]:"https://skale-base.skalenodes.com/v1/base",[F]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[ee]:"https://eth.llamarpc.com"},D="https://x402.dexter.cash",Se=N;function Ee(e,t){if(!Number.isFinite(e))throw new Error(`toAtomicUnits: amount must be finite, got ${e}`);if(e<0)throw new Error(`toAtomicUnits: amount must be non-negative, got ${e}`);if(!Number.isInteger(t)||t<0)throw new Error(`toAtomicUnits: decimals must be a non-negative integer, got ${t}`);let s=Ge(Math.abs(e)),[r,n=""]=s.split("."),a=n.slice(0,t).padEnd(t,"0");return BigInt(r+a).toString()}function Ge(e){let t=e.toString();if(!/[eE]/.test(t))return t;let[s,r]=t.split(/[eE]/),n=parseInt(r,10),a=s.startsWith("-"),p=a?s.slice(1):s,[m,f=""]=p.split("."),d=m+f,g=m.length+n,o;return g<=0?o="0."+"0".repeat(-g)+d:g>=d.length?o=d+"0".repeat(g-d.length):o=d.slice(0,g)+"."+d.slice(g),(a?"-":"")+o}function re(e){return e.startsWith("solana:")||e==="solana"}function Ye(e){if(typeof Buffer<"u")return Buffer.from(e,"utf-8").toString("base64");let t=new TextEncoder().encode(e),s="";for(let r=0;r<t.length;r++)s+=String.fromCharCode(t[r]);return btoa(s)}function Qe(e){if(typeof Buffer<"u")return Buffer.from(e,"base64").toString("utf-8");let t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return new TextDecoder().decode(s)}function ne(e){return Ye(JSON.stringify(e))}function j(e){return JSON.parse(Qe(e))}function Ze(e){if(e instanceof TypeError)return!0;if(e&&typeof e=="object"&&"status"in e){let t=e.status;return t>=500&&t<600}return!1}var V=class extends Error{status;body;constructor(t,s){super(`HTTP ${t}`),this.status=t,this.body=s}},B=class{facilitatorUrl;cachedSupported=null;cacheTime=0;CACHE_TTL_MS=6e4;timeoutMs;maxRetries;retryBaseMs;constructor(t=D,s){this.facilitatorUrl=t.replace(/\/$/,""),this.timeoutMs=s?.timeoutMs??1e4,this.maxRetries=s?.maxRetries??3,this.retryBaseMs=s?.retryBaseMs??500}async fetchWithTimeout(t,s){let r=new AbortController,n=setTimeout(()=>r.abort(),this.timeoutMs);try{return await fetch(t,{...s,signal:r.signal})}finally{clearTimeout(n)}}async fetchWithRetry(t,s){let r;for(let n=0;n<this.maxRetries;n++)try{let a=await this.fetchWithTimeout(t,s);if(!a.ok&&a.status>=500)throw new V(a.status,await a.text());return a}catch(a){if(r=a,n<this.maxRetries-1&&Ze(a)){let p=this.retryBaseMs*Math.pow(2,n);await new Promise(m=>setTimeout(m,p));continue}throw a}throw r}async getSupported(){let t=Date.now();if(this.cachedSupported&&t-this.cacheTime<this.CACHE_TTL_MS)return this.cachedSupported;let s=await this.fetchWithTimeout(`${this.facilitatorUrl}/supported`);if(!s.ok)throw new Error(`Facilitator /supported returned ${s.status}`);return this.cachedSupported=await s.json(),this.cacheTime=t,this.cachedSupported}async getFeePayer(t){let r=(await this.getSupported()).kinds.find(n=>n.x402Version===2&&(n.scheme==="exact"||n.scheme==="exact-approval")&&n.network===t);if(!r)throw new Error(`Facilitator does not support network "${t}" with a recognized scheme`);return r.extra?.feePayer}async getNetworkExtra(t){return(await this.getSupported()).kinds.find(n=>n.x402Version===2&&(n.scheme==="exact"||n.scheme==="exact-approval"||n.scheme==="batch-settlement")&&n.network===t)?.extra}async verifyPayment(t,s){try{let r=j(t),n=await this.fetchWithRetry(`${this.facilitatorUrl}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:r,paymentRequirements:s})});return n.ok?await n.json():{isValid:!1,invalidReason:`facilitator_error_${n.status}`}}catch(r){return{isValid:!1,invalidReason:r instanceof V?`facilitator_error_${r.status}`:r instanceof Error&&r.name==="AbortError"?"facilitator_timeout":r instanceof Error?r.message:"unexpected_verify_error"}}}async settlePayment(t,s){try{let r=j(t),n=await this.fetchWithRetry(`${this.facilitatorUrl}/settle`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:r,paymentRequirements:s})});return n.ok?{...await n.json(),network:s.network}:{success:!1,network:s.network,errorReason:`facilitator_error_${n.status}`}}catch(r){let n=r instanceof V?`facilitator_error_${r.status}`:r instanceof Error&&r.name==="AbortError"?"facilitator_timeout":r instanceof Error?r.message:"unexpected_settle_error";return{success:!1,network:s.network,errorReason:n}}}};function ce(e){if(re(e))return{address:M,decimals:6};let t=ge[e];if(t){let s=xe[t]?.decimals??6;return{address:t,decimals:s}}return{address:M,decimals:6}}function Re(e){try{let t=j(e);return t?.accepted?.amount??t?.accepted?.maxAmountRequired}catch{return}}function se(e){let{payTo:t,facilitatorUrl:s=D,network:r=N,defaultTimeoutSeconds:n=60}=e,a=e.asset??ce(r),p=e.scheme??"exact";if(p==="tab"&&!re(r))throw new Error(`scheme 'tab' is SVM-only; got network "${r}"`);let m=new B(s),f=null,d=new Map,g=3e4,o=Date.now();function y(i){let l=(i.maxTimeoutSeconds||n)*1e3;if(d.set(i.payTo,{accept:i,expiresAt:Date.now()+l}),Date.now()-o>g){let h=Date.now();for(let[S,v]of d)v.expiresAt<h&&d.delete(S);o=h}}function E(i){let l=d.get(i);if(l){if(l.expiresAt<Date.now()){d.delete(i);return}return l.accept}}async function x(i){return typeof t=="string"?t:t(i||{})}async function b(){if(f||(f=await m.getNetworkExtra(r)),re(r)&&!f?.feePayer)throw new Error(`Facilitator does not provide feePayer for network "${r}"`);return{...f?.feePayer?{feePayer:f.feePayer}:{},decimals:f?.decimals??a.decimals,name:f?.name,version:f?.version,...p==="batch-settlement"&&f?.receiverAuthorizer?{receiverAuthorizer:f.receiverAuthorizer}:{},...p==="tab"?{voucherHeader:"x-tab-voucher",registrationEncoding:"base64(188-byte sessionRegisterMessage)"}:{}}}async function O(i,l){let{amountAtomic:h,timeoutSeconds:S=n}=l,v=await b(),I={scheme:p,network:r,amount:h,maxAmountRequired:h,asset:a.address,payTo:i,maxTimeoutSeconds:S,extra:v};return y(I),I}async function C(i){let l=await x({amountAtomic:i.amountAtomic,resourceUrl:i.resourceUrl});return O(l,i)}async function _(i){let{resourceUrl:l,description:h,mimeType:S="application/json"}=i,v={url:l,description:h,mimeType:S},I=await C(i);return{x402Version:2,resource:v,accepts:[I],error:"Payment required"}}function R(i){return ne(i)}function c(i){return{status:402,headers:{"PAYMENT-REQUIRED":R(i)},body:{}}}async function u(i,l){if(!l){let h=await x({paymentHeader:i});l=E(h),l||(l=await O(h,{amountAtomic:Re(i)??"0",resourceUrl:""}))}return m.verifyPayment(i,l)}async function A(i,l){if(!l){let h=await x({paymentHeader:i});l=E(h),l||(l=await O(h,{amountAtomic:Re(i)??"0",resourceUrl:""}))}return m.settlePayment(i,l)}return{buildRequirements:_,encodeRequirements:R,create402Response:c,verifyPayment:u,settlePayment:A,getPaymentAccept:C,network:r,assetDecimals:a.decimals,facilitator:m}}var et=new WeakMap;function Ae(e){return et.get(e)}var Ne=require("os"),De=require("path"),Oe=require("@x402/evm/batch-settlement/server");var oe=require("@x402/core/server"),Te=require("@x402/core/http"),Pe=require("@x402/evm/batch-settlement/server");function be(e){let t=e.verbose?console.log.bind(console,"[batch-settlement:seller]"):()=>{},s=new oe.HTTPFacilitatorClient({url:e.facilitatorUrl}),r=new Pe.BatchSettlementEvmScheme(e.payTo,{storage:e.channelStore}),n=new oe.x402ResourceServer(s).register(e.network,r),a=new Te.x402HTTPResourceServer(n,{[e.route]:{accepts:{scheme:"batch-settlement",payTo:e.payTo,price:e.price,network:e.network},description:"batch-settlement protected route",mimeType:"application/json"}}),p=null;function m(){if(p)return p;let o=a.initialize();return o.catch(y=>{p===o&&(p=null),e.verbose?t("resource server initialize() failed:",y):console.error("[batch-settlement:seller] resource server initialize() failed:",y)}),p=o,o}let f=m();function d(o,y){if(o.headersSent)return;for(let[x,b]of Object.entries(y.headers))o.setHeader(x,b);o.status(y.status);let{body:E}=y;E==null?o.end():typeof E=="string"?o.send(E):o.json(E)}return{scheme:r,facilitator:s,handler:async(o,y,E)=>{try{await m();let x=o.get("host")??"",b=`${o.baseUrl??""}${o.path}`||"/",O={getHeader:A=>o.headers[A.toLowerCase()],getMethod:()=>o.method,getPath:()=>b,getUrl:()=>`${o.protocol}://${x}${o.originalUrl}`,getAcceptHeader:()=>o.headers.accept??"",getUserAgent:()=>o.headers["user-agent"]??"",getBody:()=>o.body??{},getQueryParams:()=>o.query,getQueryParam:A=>{let i=o.query[A];if(typeof i=="string"||Array.isArray(i))return i}},C=o.headers["payment-signature"]??o.headers["x-payment"],_={adapter:O,path:b,method:o.method,paymentHeader:C},R=await a.processHTTPRequest(_);if(t("processHTTPRequest ->",R.type),R.type==="no-payment-required"){E();return}if(R.type==="payment-error"){d(y,R.response);return}let c={request:_,responseBody:Buffer.alloc(0)},u=await a.processSettlement(R.paymentPayload,R.paymentRequirements,R.declaredExtensions,c);if(t("processSettlement ->",u.success?"success":`failure:${u.errorReason}`),!u.success){d(y,u.response);return}for(let[A,i]of Object.entries(u.headers))y.headersSent||y.setHeader(A,i);E()}catch(x){t("handler error:",x),y.headersSent||y.status(500).json({error:"Payment processing error"})}},ready:f}}var pe=require("viem"),_e=6;async function le(e){let{manager:t,store:s,channelId:r}=e,n=await s.get(r),a=BigInt(n?.chargedCumulativeAmount??"0"),p=BigInt(n?.balance??"0"),m=p>a?p-a:0n,{claims:f,settle:d}=await t.claimAndSettle(),g=await t.refund([r]),o=g.find(y=>y.channel===r)??g[0];return{claimTx:f[0]?.transaction??"",settleTx:d?.transaction??"",refundTx:o?.transaction??"",settledAmount:(0,pe.formatUnits)(a,_e),refundedAmount:(0,pe.formatUnits)(m,_e)}}async function ve(e){let t=await e.store.list(),s=[];for(let r of t)try{let n=await le({manager:e.manager,store:e.store,channelId:r.channelId});s.push({channelId:r.channelId,...n})}catch(n){s.push({channelId:r.channelId,error:n instanceof Error?n.message:String(n)})}return s}function we(e){let t=!1,s=async()=>{try{await e.claimAndSettle()}catch(n){e.onError?.(n)}},r=setInterval(()=>{t||s()},e.claimIntervalMs);return typeof r.unref=="function"&&r.unref(),{async stop(){t||(t=!0,clearInterval(r),await s())}}}var tt="https://x402.dexter.cash",rt="GET /",Ce=new Set(["eip155:8453","eip155:42161","eip155:137"]);function nt(e){return e===!1?null:e===void 0||e===!0?3e5:(e.claimIntervalSecs??300)*1e3}function de(e){if(!Ce.has(e.network))throw new Error(`batch-settlement is not supported on network "${e.network}" \u2014 supported: ${[...Ce].join(", ")}`);let t=e.facilitatorUrl??tt,s=e.channelStore??new Oe.FileChannelStorage({directory:(0,De.join)((0,Ne.homedir)(),".dexter-x402","seller-channels")}),r=be({payTo:e.payTo,network:e.network,price:e.price,route:e.route??rt,facilitatorUrl:t,channelStore:s,verbose:e.verbose}),n=r.scheme.createChannelManager(r.facilitator,e.network),a=async()=>{await n.claimAndSettle()},p=nt(e.autoSettle),m=null;p!==null&&(m=we({claimAndSettle:a,claimIntervalMs:p,onError:o=>console.error("[batch-settlement:seller] auto-loop claim pass failed",o)}));let f=s,d=(o,y,E)=>{r.handler(o,y,E)},g=d;return g.middleware=()=>d,g.closeChannel=o=>le({manager:n,store:f,channelId:o}),g.closeAll=()=>ve({manager:n,store:f}),g.stop=async()=>{m&&await m.stop()},g}async function Ie(e,t,s){let r={};for(let n of e)if(n.enrichPaymentRequiredResponse&&n.key in t)try{let a=await n.enrichPaymentRequiredResponse(t[n.key],s);a!==void 0&&(r[n.key]=a)}catch(a){console.warn(`[x402:extensions] extension "${n.key}" failed:`,a)}return Object.keys(r).length>0?r:void 0}function st(e,t){if(typeof e=="string"||typeof e=="function")return e;if(t in e)return e[t];let r=`${t.split(":")[0]}:*`;if(r in e)return e[r];if("*"in e)return e["*"];throw new Error(`No payTo configured for network "${t}"`)}function ke(e){if(e.scheme==="batch-settlement"){let c=Array.isArray(e.network)?e.network[0]:e.network;if(!c)throw new Error('x402Middleware: scheme "batch-settlement" requires a network');let u=typeof e.payTo=="string"?e.payTo:void 0;if(!u)throw new Error('x402Middleware: scheme "batch-settlement" requires a string payTo address');return de({payTo:u,network:c,price:e.amount,facilitatorUrl:e.facilitatorUrl,route:e.batchSettlement?.route,channelStore:e.batchSettlement?.channelStore,autoSettle:e.batchSettlement?.autoSettle,verbose:e.verbose})}let{payTo:t,amount:s,asset:r,description:n,resourceUrl:a,mimeType:p,timeoutSeconds:m,verbose:f=!1,getResourceUrl:d,getAmount:g,getDescription:o,extensions:y,declarations:E}=e,x=f?console.log.bind(console,"[x402:middleware]"):()=>{},b=typeof t=="function"?t._x402Defaults:void 0,O=e.facilitatorUrl??b?.facilitatorUrl,C=e.network?Array.isArray(e.network)?e.network:[e.network]:b?.network?[b.network]:[Se],_=new Map;for(let c of C){let u=st(t,c);if(typeof u=="function"){let A=Ae(u);if(A&&c!==A)throw new Error(`stripePayTo is configured for "${A}" but middleware includes network "${c}". Stripe only supports Base deposit addresses. Use a static payTo for other chains.`)}_.set(c,se({payTo:u,network:c,asset:r,facilitatorUrl:O,defaultTimeoutSeconds:m,scheme:e.scheme}))}let R=_.get(C[0]);return async(c,u,A)=>{try{let i=c.headers["payment-signature"];if(!i){x("No payment signature, returning 402");let U=d?.(c)??a??`${c.protocol}://${c.get("host")}${c.originalUrl}`,P=g?.(c)??s,L=o?.(c)??n,ue=parseFloat(P),w=[],T=null;for(let[,q]of _)try{let ie={amountAtomic:Ee(ue,q.assetDecimals),resourceUrl:U,description:L,mimeType:p,timeoutSeconds:m},me=await q.buildRequirements(ie);w.push(...me.accepts),T||(T=me)}catch(ie){x("Failed to build requirements for a network:",ie)}if(!T||w.length===0){u.status(500).json({error:"Failed to build payment requirements"});return}if(T={...T,accepts:w},y&&y.length>0){let q=await Ie(y,E??{},{response:T,request:{method:c.method,path:(c.baseUrl??"")+(c.route?.path??c.path),params:c.params}});q&&(T={...T,extensions:q})}let Ke=R.encodeRequirements(T);u.setHeader("PAYMENT-REQUIRED",Ke),u.status(402).json({error:"Payment required",accepts:T.accepts,resource:T.resource,...T.extensions?{extensions:T.extensions}:{}});return}x("Payment signature received, verifying...");let l=R;try{let P=JSON.parse(Buffer.from(i,"base64").toString())?.accepted?.network;P&&_.has(P)&&(l=_.get(P))}catch{}let h=await l.verifyPayment(i);if(!h.isValid){if(x("Payment verification failed:",h.invalidReason),e.onVerifyFailed)try{await e.onVerifyFailed({reason:h.invalidReason,resourceUrl:`${c.protocol}://${c.get("host")}${c.originalUrl}`})}catch{}u.status(402).json({error:"Payment verification failed",reason:h.invalidReason});return}x("Payment verified, settling...");let S=await l.settlePayment(i);if(!S.success){x("Payment settlement failed:",S.errorReason),u.status(402).json({error:"Payment settlement failed",reason:S.errorReason});return}x("Payment settled:",S.transaction);let v=S.network||C[0];if(e.onSettlement)try{await e.onSettlement({transaction:S.transaction,network:v,payer:h.payer??"",resourceUrl:`${c.protocol}://${c.get("host")}${c.originalUrl}`})}catch{}c.x402={transaction:S.transaction,payer:h.payer??"",network:v};let I={success:!0,transaction:S.transaction,network:v,payer:h.payer??""};if(S.extensions&&(I.extensions=S.extensions),u.setHeader("PAYMENT-RESPONSE",ne(I)),e.sponsoredAccess&&S.extensions?.["sponsored-access"]){let U=S.extensions["sponsored-access"],P=U?.info?.recommendations??U?.recommendations;if(P&&P.length>0){if(x("Injecting sponsored-access recommendations into response"),typeof e.sponsoredAccess=="object"&&e.sponsoredAccess.onMatch)try{e.sponsoredAccess.onMatch(P,{transaction:S.transaction,network:v,payer:h.payer??""})}catch{}let L=u.json.bind(u);u.json=function(w){return typeof e.sponsoredAccess=="object"&&e.sponsoredAccess.inject?L(e.sponsoredAccess.inject(w,P)):w&&typeof w=="object"&&!Array.isArray(w)?L({_x402_sponsored:P,...w}):L(w)}}}A()}catch(i){x("Middleware error:",i),u.status(500).json({error:"Payment processing error"})}}}var ot=/^\/[a-zA-Z0-9_/:.\-~%]+$/;function Me(e){if(!e||!ot.test(e))return!1;let t;try{t=decodeURIComponent(e)}catch{return!1}return!(t.includes("..")||t.includes("://"))}function X(e){return e.method==="POST"||e.method==="PUT"||e.method==="PATCH"}var it=["GET","HEAD","DELETE"],at=["POST","PUT","PATCH"];function Be(e,t){let s=t.pathParams!==void 0&&Object.keys(t.pathParams).length>0,r={type:"http",method:e.method};X(e)?(r.bodyType=e.bodyType,r.body=e.input??{}):e.input!==void 0&&(r.queryParams=e.input),s&&(r.pathParams=t.pathParams);let n=e.output?.example!==void 0?{type:"json",example:e.output.example}:void 0,a=X(e)?at:it,p={type:{type:"string",const:"http"},method:{type:"string",enum:a}};X(e)?(p.bodyType={type:"string",enum:["json","form-data","text"]},p.body={type:"object",...e.inputSchema??{}}):e.inputSchema&&(p.queryParams={type:"object",...e.inputSchema}),e.pathParamsSchema&&(p.pathParams={type:"object",...e.pathParamsSchema});let m={input:{type:"object",properties:p,required:X(e)?["type","method","bodyType","body"]:["type","method"],additionalProperties:!1}};n&&(m.output={type:"object",properties:{type:{type:"string"},example:{type:"object",...e.output?.schema??{}}},required:["type"]});let f={$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:m,required:["input"]},d={info:{input:r,...n?{output:n}:{}},schema:f};return Me(t.routeTemplate)&&(d.routeTemplate=t.routeTemplate),d}var ct=["GET","HEAD","DELETE","POST","PUT","PATCH"];function Ue(){return{key:"bazaar",enrichPaymentRequiredResponse:(e,t)=>{if(e==null)return;let s=e,r=(s.method??t.request.method).toUpperCase();if(!ct.includes(r))return;let n={...s,method:r};return Be(n,{pathParams:t.request.params,routeTemplate:t.request.path})}}}function Le(e){return{bazaar:e}}var qe=require("@dexterai/x402-ads-types");0&&(module.exports={BASE_MAINNET_NETWORK,DEXTER_FACILITATOR_URL,FacilitatorClient,SOLANA_MAINNET_NETWORK,SPONSORED_ACCESS_EXTENSION_KEY,USDC_BASE,USDC_MINT,bazaarExtension,createX402Server,declareDiscoveryExtension,resolveDefaultAsset,x402Middleware});
|
|
1
|
+
"use strict";var ae=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var Xe=Object.prototype.hasOwnProperty;var Ge=(e,t)=>{for(var s in t)ae(e,s,{get:t[s],enumerable:!0})},ze=(e,t,s,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of je(t))!Xe.call(e,n)&&n!==s&&ae(e,n,{get:()=>t[n],enumerable:!(r=Ve(t,n))||r.enumerable});return e};var Je=e=>ze(ae({},"__esModule",{value:!0}),e);var mt={};Ge(mt,{BASE_MAINNET_NETWORK:()=>k,DEXTER_FACILITATOR_URL:()=>D,FacilitatorClient:()=>M,SOLANA_MAINNET_NETWORK:()=>N,SPONSORED_ACCESS_EXTENSION_KEY:()=>We.SPONSORED_ACCESS_EXTENSION_KEY,USDC_BASE:()=>te,USDC_MINT:()=>B,bazaarExtension:()=>Ke,createX402Server:()=>se,declareDiscoveryExtension:()=>$e,resolveDefaultAsset:()=>ce,x402Middleware:()=>Le});module.exports=Je(mt);var N="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",fe="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",ye="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";var k="eip155:8453",G="eip155:84532",z="eip155:42161",J="eip155:137",Y="eip155:10",Q="eip155:43114",Z="eip155:56",q="eip155:480",K="eip155:143",$="eip155:4663",W="eip155:1187947933",F="eip155:324705682",ee="eip155:1";var B="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";var te="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",Ye="0x55d398326f99059fF775485246999027B3197955",he="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",Qe="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",ge={[Z]:he,[k]:te,[G]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[z]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[J]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[Y]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[Q]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[q]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[K]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[$]:Qe,[W]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[F]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[ee]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},Ee={[Ye]:{symbol:"USDT",decimals:18},[he]:{symbol:"USDC",decimals:18}};var yt={[q]:{name:"USDC",version:"2"},[K]:{name:"USDC",version:"2"},[$]:{name:"Global Dollar",version:"1"},[W]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[F]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}};var ht={[Z]:56,[k]:8453,[G]:84532,[z]:42161,[J]:137,[Y]:10,[Q]:43114,[q]:480,[K]:143,[$]:4663,[W]:1187947933,[F]:324705682,[ee]:1},gt={[N]:"https://api.dexter.cash/api/solana/rpc",[fe]:"https://api.devnet.solana.com",[ye]:"https://api.testnet.solana.com"},Ze={[Z]:"https://api.dexter.cash/api/evm/bsc/rpc",[k]:"https://api.dexter.cash/api/base/rpc",[G]:"https://sepolia.base.org",[z]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[J]:"https://api.dexter.cash/api/evm/polygon/rpc",[Y]:"https://api.dexter.cash/api/evm/optimism/rpc",[Q]:"https://api.dexter.cash/api/evm/avalanche/rpc",[q]:"https://worldchain-mainnet.g.alchemy.com/public",[K]:"https://rpc.monad.xyz",[$]:"https://rpc.mainnet.chain.robinhood.com",[W]:"https://skale-base.skalenodes.com/v1/base",[F]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[ee]:"https://eth.llamarpc.com"},D="https://x402.dexter.cash",xe=N;var Se="dexter-tab-hosted-pay-before-delivery/v1",Re="pay_before_delivery_seller_2xx",Ae="x-tab-voucher",Te="base64(188-byte sessionRegisterMessage)";function Pe(e,t){if(!Number.isFinite(e))throw new Error(`toAtomicUnits: amount must be finite, got ${e}`);if(e<0)throw new Error(`toAtomicUnits: amount must be non-negative, got ${e}`);if(!Number.isInteger(t)||t<0)throw new Error(`toAtomicUnits: decimals must be a non-negative integer, got ${t}`);let s=et(Math.abs(e)),[r,n=""]=s.split("."),a=n.slice(0,t).padEnd(t,"0");return BigInt(r+a).toString()}function et(e){let t=e.toString();if(!/[eE]/.test(t))return t;let[s,r]=t.split(/[eE]/),n=parseInt(r,10),a=s.startsWith("-"),p=a?s.slice(1):s,[m,f=""]=p.split("."),d=m+f,g=m.length+n,o;return g<=0?o="0."+"0".repeat(-g)+d:g>=d.length?o=d+"0".repeat(g-d.length):o=d.slice(0,g)+"."+d.slice(g),(a?"-":"")+o}function re(e){return e.startsWith("solana:")||e==="solana"}function tt(e){if(typeof Buffer<"u")return Buffer.from(e,"utf-8").toString("base64");let t=new TextEncoder().encode(e),s="";for(let r=0;r<t.length;r++)s+=String.fromCharCode(t[r]);return btoa(s)}function rt(e){if(typeof Buffer<"u")return Buffer.from(e,"base64").toString("utf-8");let t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return new TextDecoder().decode(s)}function ne(e){return tt(JSON.stringify(e))}function V(e){return JSON.parse(rt(e))}function nt(e){if(e instanceof TypeError)return!0;if(e&&typeof e=="object"&&"status"in e){let t=e.status;return t>=500&&t<600}return!1}var j=class extends Error{status;body;constructor(t,s){super(`HTTP ${t}`),this.status=t,this.body=s}},M=class{facilitatorUrl;cachedSupported=null;cacheTime=0;CACHE_TTL_MS=6e4;timeoutMs;maxRetries;retryBaseMs;constructor(t=D,s){this.facilitatorUrl=t.replace(/\/$/,""),this.timeoutMs=s?.timeoutMs??1e4,this.maxRetries=s?.maxRetries??3,this.retryBaseMs=s?.retryBaseMs??500}async fetchWithTimeout(t,s){let r=new AbortController,n=setTimeout(()=>r.abort(),this.timeoutMs);try{return await fetch(t,{...s,signal:r.signal})}finally{clearTimeout(n)}}async fetchWithRetry(t,s){let r;for(let n=0;n<this.maxRetries;n++)try{let a=await this.fetchWithTimeout(t,s);if(!a.ok&&a.status>=500)throw new j(a.status,await a.text());return a}catch(a){if(r=a,n<this.maxRetries-1&&nt(a)){let p=this.retryBaseMs*Math.pow(2,n);await new Promise(m=>setTimeout(m,p));continue}throw a}throw r}async getSupported(){let t=Date.now();if(this.cachedSupported&&t-this.cacheTime<this.CACHE_TTL_MS)return this.cachedSupported;let s=await this.fetchWithTimeout(`${this.facilitatorUrl}/supported`);if(!s.ok)throw new Error(`Facilitator /supported returned ${s.status}`);return this.cachedSupported=await s.json(),this.cacheTime=t,this.cachedSupported}async getFeePayer(t){let r=(await this.getSupported()).kinds.find(n=>n.x402Version===2&&(n.scheme==="exact"||n.scheme==="exact-approval")&&n.network===t);if(!r)throw new Error(`Facilitator does not support network "${t}" with a recognized scheme`);return r.extra?.feePayer}async getNetworkExtra(t){return(await this.getSupported()).kinds.find(n=>n.x402Version===2&&(n.scheme==="exact"||n.scheme==="exact-approval"||n.scheme==="batch-settlement")&&n.network===t)?.extra}async verifyPayment(t,s){try{let r=V(t),n=await this.fetchWithRetry(`${this.facilitatorUrl}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:r,paymentRequirements:s})});return n.ok?await n.json():{isValid:!1,invalidReason:`facilitator_error_${n.status}`}}catch(r){return{isValid:!1,invalidReason:r instanceof j?`facilitator_error_${r.status}`:r instanceof Error&&r.name==="AbortError"?"facilitator_timeout":r instanceof Error?r.message:"unexpected_verify_error"}}}async settlePayment(t,s){try{let r=V(t),n=await this.fetchWithRetry(`${this.facilitatorUrl}/settle`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:r,paymentRequirements:s})});return n.ok?{...await n.json(),network:s.network}:{success:!1,network:s.network,errorReason:`facilitator_error_${n.status}`}}catch(r){let n=r instanceof j?`facilitator_error_${r.status}`:r instanceof Error&&r.name==="AbortError"?"facilitator_timeout":r instanceof Error?r.message:"unexpected_settle_error";return{success:!1,network:s.network,errorReason:n}}}};function ce(e){if(re(e))return{address:B,decimals:6};let t=ge[e];if(t){let s=Ee[t]?.decimals??6;return{address:t,decimals:s}}return{address:B,decimals:6}}function _e(e){try{let t=V(e);return t?.accepted?.amount??t?.accepted?.maxAmountRequired}catch{return}}function se(e){let{payTo:t,facilitatorUrl:s=D,network:r=N,defaultTimeoutSeconds:n=60}=e,a=e.asset??ce(r),p=e.scheme??"exact";if(p==="tab"&&!re(r))throw new Error(`scheme 'tab' is SVM-only; got network "${r}"`);let m=new M(s),f=null,d=new Map,g=3e4,o=Date.now();function y(i){let l=(i.maxTimeoutSeconds||n)*1e3;if(d.set(i.payTo,{accept:i,expiresAt:Date.now()+l}),Date.now()-o>g){let h=Date.now();for(let[x,v]of d)v.expiresAt<h&&d.delete(x);o=h}}function S(i){let l=d.get(i);if(l){if(l.expiresAt<Date.now()){d.delete(i);return}return l.accept}}async function E(i){return typeof t=="string"?t:t(i||{})}async function _(){if(f||(f=await m.getNetworkExtra(r)),re(r)&&!f?.feePayer)throw new Error(`Facilitator does not provide feePayer for network "${r}"`);return{...f?.feePayer?{feePayer:f.feePayer}:{},decimals:f?.decimals??a.decimals,name:f?.name,version:f?.version,...p==="batch-settlement"&&f?.receiverAuthorizer?{receiverAuthorizer:f.receiverAuthorizer}:{},...p==="tab"?{voucherHeader:Ae,registrationEncoding:Te,termsVersion:Se,acceptanceRule:Re}:{}}}async function O(i,l){let{amountAtomic:h,timeoutSeconds:x=n}=l,v=await _(),I={scheme:p,network:r,amount:h,maxAmountRequired:h,asset:a.address,payTo:i,maxTimeoutSeconds:x,extra:v};return y(I),I}async function w(i){let l=await E({amountAtomic:i.amountAtomic,resourceUrl:i.resourceUrl});return O(l,i)}async function b(i){let{resourceUrl:l,description:h,mimeType:x="application/json"}=i,v={url:l,description:h,mimeType:x},I=await w(i);return{x402Version:2,resource:v,accepts:[I],error:"Payment required"}}function R(i){return ne(i)}function c(i){return{status:402,headers:{"PAYMENT-REQUIRED":R(i)},body:{}}}async function u(i,l){if(!l){let h=await E({paymentHeader:i});l=S(h),l||(l=await O(h,{amountAtomic:_e(i)??"0",resourceUrl:""}))}return m.verifyPayment(i,l)}async function A(i,l){if(!l){let h=await E({paymentHeader:i});l=S(h),l||(l=await O(h,{amountAtomic:_e(i)??"0",resourceUrl:""}))}return m.settlePayment(i,l)}return{buildRequirements:b,encodeRequirements:R,create402Response:c,verifyPayment:u,settlePayment:A,getPaymentAccept:w,network:r,assetDecimals:a.decimals,facilitator:m}}var st=new WeakMap;function be(e){return st.get(e)}var ke=require("os"),Be=require("path"),Me=require("@x402/evm/batch-settlement/server");var oe=require("@x402/core/server"),ve=require("@x402/core/http"),Ce=require("@x402/evm/batch-settlement/server");function we(e){let t=e.verbose?console.log.bind(console,"[batch-settlement:seller]"):()=>{},s=new oe.HTTPFacilitatorClient({url:e.facilitatorUrl}),r=new Ce.BatchSettlementEvmScheme(e.payTo,{storage:e.channelStore}),n=new oe.x402ResourceServer(s).register(e.network,r),a=new ve.x402HTTPResourceServer(n,{[e.route]:{accepts:{scheme:"batch-settlement",payTo:e.payTo,price:e.price,network:e.network},description:"batch-settlement protected route",mimeType:"application/json"}}),p=null;function m(){if(p)return p;let o=a.initialize();return o.catch(y=>{p===o&&(p=null),e.verbose?t("resource server initialize() failed:",y):console.error("[batch-settlement:seller] resource server initialize() failed:",y)}),p=o,o}let f=m();function d(o,y){if(o.headersSent)return;for(let[E,_]of Object.entries(y.headers))o.setHeader(E,_);o.status(y.status);let{body:S}=y;S==null?o.end():typeof S=="string"?o.send(S):o.json(S)}return{scheme:r,facilitator:s,handler:async(o,y,S)=>{try{await m();let E=o.get("host")??"",_=`${o.baseUrl??""}${o.path}`||"/",O={getHeader:A=>o.headers[A.toLowerCase()],getMethod:()=>o.method,getPath:()=>_,getUrl:()=>`${o.protocol}://${E}${o.originalUrl}`,getAcceptHeader:()=>o.headers.accept??"",getUserAgent:()=>o.headers["user-agent"]??"",getBody:()=>o.body??{},getQueryParams:()=>o.query,getQueryParam:A=>{let i=o.query[A];if(typeof i=="string"||Array.isArray(i))return i}},w=o.headers["payment-signature"]??o.headers["x-payment"],b={adapter:O,path:_,method:o.method,paymentHeader:w},R=await a.processHTTPRequest(b);if(t("processHTTPRequest ->",R.type),R.type==="no-payment-required"){S();return}if(R.type==="payment-error"){d(y,R.response);return}let c={request:b,responseBody:Buffer.alloc(0)},u=await a.processSettlement(R.paymentPayload,R.paymentRequirements,R.declaredExtensions,c);if(t("processSettlement ->",u.success?"success":`failure:${u.errorReason}`),!u.success){d(y,u.response);return}for(let[A,i]of Object.entries(u.headers))y.headersSent||y.setHeader(A,i);S()}catch(E){t("handler error:",E),y.headersSent||y.status(500).json({error:"Payment processing error"})}},ready:f}}var pe=require("viem"),Ne=6;async function le(e){let{manager:t,store:s,channelId:r}=e,n=await s.get(r),a=BigInt(n?.chargedCumulativeAmount??"0"),p=BigInt(n?.balance??"0"),m=p>a?p-a:0n,{claims:f,settle:d}=await t.claimAndSettle(),g=await t.refund([r]),o=g.find(y=>y.channel===r)??g[0];return{claimTx:f[0]?.transaction??"",settleTx:d?.transaction??"",refundTx:o?.transaction??"",settledAmount:(0,pe.formatUnits)(a,Ne),refundedAmount:(0,pe.formatUnits)(m,Ne)}}async function De(e){let t=await e.store.list(),s=[];for(let r of t)try{let n=await le({manager:e.manager,store:e.store,channelId:r.channelId});s.push({channelId:r.channelId,...n})}catch(n){s.push({channelId:r.channelId,error:n instanceof Error?n.message:String(n)})}return s}function Oe(e){let t=!1,s=async()=>{try{await e.claimAndSettle()}catch(n){e.onError?.(n)}},r=setInterval(()=>{t||s()},e.claimIntervalMs);return typeof r.unref=="function"&&r.unref(),{async stop(){t||(t=!0,clearInterval(r),await s())}}}var ot="https://x402.dexter.cash",it="GET /",Ie=new Set(["eip155:8453","eip155:42161","eip155:137"]);function at(e){return e===!1?null:e===void 0||e===!0?3e5:(e.claimIntervalSecs??300)*1e3}function de(e){if(!Ie.has(e.network))throw new Error(`batch-settlement is not supported on network "${e.network}" \u2014 supported: ${[...Ie].join(", ")}`);let t=e.facilitatorUrl??ot,s=e.channelStore??new Me.FileChannelStorage({directory:(0,Be.join)((0,ke.homedir)(),".dexter-x402","seller-channels")}),r=we({payTo:e.payTo,network:e.network,price:e.price,route:e.route??it,facilitatorUrl:t,channelStore:s,verbose:e.verbose}),n=r.scheme.createChannelManager(r.facilitator,e.network),a=async()=>{await n.claimAndSettle()},p=at(e.autoSettle),m=null;p!==null&&(m=Oe({claimAndSettle:a,claimIntervalMs:p,onError:o=>console.error("[batch-settlement:seller] auto-loop claim pass failed",o)}));let f=s,d=(o,y,S)=>{r.handler(o,y,S)},g=d;return g.middleware=()=>d,g.closeChannel=o=>le({manager:n,store:f,channelId:o}),g.closeAll=()=>De({manager:n,store:f}),g.stop=async()=>{m&&await m.stop()},g}async function Ue(e,t,s){let r={};for(let n of e)if(n.enrichPaymentRequiredResponse&&n.key in t)try{let a=await n.enrichPaymentRequiredResponse(t[n.key],s);a!==void 0&&(r[n.key]=a)}catch(a){console.warn(`[x402:extensions] extension "${n.key}" failed:`,a)}return Object.keys(r).length>0?r:void 0}function ct(e,t){if(typeof e=="string"||typeof e=="function")return e;if(t in e)return e[t];let r=`${t.split(":")[0]}:*`;if(r in e)return e[r];if("*"in e)return e["*"];throw new Error(`No payTo configured for network "${t}"`)}function Le(e){if(e.scheme==="batch-settlement"){let c=Array.isArray(e.network)?e.network[0]:e.network;if(!c)throw new Error('x402Middleware: scheme "batch-settlement" requires a network');let u=typeof e.payTo=="string"?e.payTo:void 0;if(!u)throw new Error('x402Middleware: scheme "batch-settlement" requires a string payTo address');return de({payTo:u,network:c,price:e.amount,facilitatorUrl:e.facilitatorUrl,route:e.batchSettlement?.route,channelStore:e.batchSettlement?.channelStore,autoSettle:e.batchSettlement?.autoSettle,verbose:e.verbose})}let{payTo:t,amount:s,asset:r,description:n,resourceUrl:a,mimeType:p,timeoutSeconds:m,verbose:f=!1,getResourceUrl:d,getAmount:g,getDescription:o,extensions:y,declarations:S}=e,E=f?console.log.bind(console,"[x402:middleware]"):()=>{},_=typeof t=="function"?t._x402Defaults:void 0,O=e.facilitatorUrl??_?.facilitatorUrl,w=e.network?Array.isArray(e.network)?e.network:[e.network]:_?.network?[_.network]:[xe],b=new Map;for(let c of w){let u=ct(t,c);if(typeof u=="function"){let A=be(u);if(A&&c!==A)throw new Error(`stripePayTo is configured for "${A}" but middleware includes network "${c}". Stripe only supports Base deposit addresses. Use a static payTo for other chains.`)}b.set(c,se({payTo:u,network:c,asset:r,facilitatorUrl:O,defaultTimeoutSeconds:m,scheme:e.scheme}))}let R=b.get(w[0]);return async(c,u,A)=>{try{let i=c.headers["payment-signature"];if(!i){E("No payment signature, returning 402");let U=d?.(c)??a??`${c.protocol}://${c.get("host")}${c.originalUrl}`,P=g?.(c)??s,L=o?.(c)??n,ue=parseFloat(P),C=[],T=null;for(let[,H]of b)try{let ie={amountAtomic:Pe(ue,H.assetDecimals),resourceUrl:U,description:L,mimeType:p,timeoutSeconds:m},me=await H.buildRequirements(ie);C.push(...me.accepts),T||(T=me)}catch(ie){E("Failed to build requirements for a network:",ie)}if(!T||C.length===0){u.status(500).json({error:"Failed to build payment requirements"});return}if(T={...T,accepts:C},y&&y.length>0){let H=await Ue(y,S??{},{response:T,request:{method:c.method,path:(c.baseUrl??"")+(c.route?.path??c.path),params:c.params}});H&&(T={...T,extensions:H})}let Fe=R.encodeRequirements(T);u.setHeader("PAYMENT-REQUIRED",Fe),u.status(402).json({error:"Payment required",accepts:T.accepts,resource:T.resource,...T.extensions?{extensions:T.extensions}:{}});return}E("Payment signature received, verifying...");let l=R;try{let P=JSON.parse(Buffer.from(i,"base64").toString())?.accepted?.network;P&&b.has(P)&&(l=b.get(P))}catch{}let h=await l.verifyPayment(i);if(!h.isValid){if(E("Payment verification failed:",h.invalidReason),e.onVerifyFailed)try{await e.onVerifyFailed({reason:h.invalidReason,resourceUrl:`${c.protocol}://${c.get("host")}${c.originalUrl}`})}catch{}u.status(402).json({error:"Payment verification failed",reason:h.invalidReason});return}E("Payment verified, settling...");let x=await l.settlePayment(i);if(!x.success){E("Payment settlement failed:",x.errorReason),u.status(402).json({error:"Payment settlement failed",reason:x.errorReason});return}E("Payment settled:",x.transaction);let v=x.network||w[0];if(e.onSettlement)try{await e.onSettlement({transaction:x.transaction,network:v,payer:h.payer??"",resourceUrl:`${c.protocol}://${c.get("host")}${c.originalUrl}`})}catch{}c.x402={transaction:x.transaction,payer:h.payer??"",network:v};let I={success:!0,transaction:x.transaction,network:v,payer:h.payer??""};if(x.extensions&&(I.extensions=x.extensions),u.setHeader("PAYMENT-RESPONSE",ne(I)),e.sponsoredAccess&&x.extensions?.["sponsored-access"]){let U=x.extensions["sponsored-access"],P=U?.info?.recommendations??U?.recommendations;if(P&&P.length>0){if(E("Injecting sponsored-access recommendations into response"),typeof e.sponsoredAccess=="object"&&e.sponsoredAccess.onMatch)try{e.sponsoredAccess.onMatch(P,{transaction:x.transaction,network:v,payer:h.payer??""})}catch{}let L=u.json.bind(u);u.json=function(C){return typeof e.sponsoredAccess=="object"&&e.sponsoredAccess.inject?L(e.sponsoredAccess.inject(C,P)):C&&typeof C=="object"&&!Array.isArray(C)?L({_x402_sponsored:P,...C}):L(C)}}}A()}catch(i){E("Middleware error:",i),u.status(500).json({error:"Payment processing error"})}}}var pt=/^\/[a-zA-Z0-9_/:.\-~%]+$/;function He(e){if(!e||!pt.test(e))return!1;let t;try{t=decodeURIComponent(e)}catch{return!1}return!(t.includes("..")||t.includes("://"))}function X(e){return e.method==="POST"||e.method==="PUT"||e.method==="PATCH"}var lt=["GET","HEAD","DELETE"],dt=["POST","PUT","PATCH"];function qe(e,t){let s=t.pathParams!==void 0&&Object.keys(t.pathParams).length>0,r={type:"http",method:e.method};X(e)?(r.bodyType=e.bodyType,r.body=e.input??{}):e.input!==void 0&&(r.queryParams=e.input),s&&(r.pathParams=t.pathParams);let n=e.output?.example!==void 0?{type:"json",example:e.output.example}:void 0,a=X(e)?dt:lt,p={type:{type:"string",const:"http"},method:{type:"string",enum:a}};X(e)?(p.bodyType={type:"string",enum:["json","form-data","text"]},p.body={type:"object",...e.inputSchema??{}}):e.inputSchema&&(p.queryParams={type:"object",...e.inputSchema}),e.pathParamsSchema&&(p.pathParams={type:"object",...e.pathParamsSchema});let m={input:{type:"object",properties:p,required:X(e)?["type","method","bodyType","body"]:["type","method"],additionalProperties:!1}};n&&(m.output={type:"object",properties:{type:{type:"string"},example:{type:"object",...e.output?.schema??{}}},required:["type"]});let f={$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:m,required:["input"]},d={info:{input:r,...n?{output:n}:{}},schema:f};return He(t.routeTemplate)&&(d.routeTemplate=t.routeTemplate),d}var ut=["GET","HEAD","DELETE","POST","PUT","PATCH"];function Ke(){return{key:"bazaar",enrichPaymentRequiredResponse:(e,t)=>{if(e==null)return;let s=e,r=(s.method??t.request.method).toUpperCase();if(!ut.includes(r))return;let n={...s,method:r};return qe(n,{pathParams:t.request.params,routeTemplate:t.request.path})}}}function $e(e){return{bazaar:e}}var We=require("@dexterai/x402-ads-types");0&&(module.exports={BASE_MAINNET_NETWORK,DEXTER_FACILITATOR_URL,FacilitatorClient,SOLANA_MAINNET_NETWORK,SPONSORED_ACCESS_EXTENSION_KEY,USDC_BASE,USDC_MINT,bazaarExtension,createX402Server,declareDiscoveryExtension,resolveDefaultAsset,x402Middleware});
|
package/dist/server/index.d.cts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { P as PaymentAccept, V as VerifyResponse,
|
|
2
|
-
export {
|
|
1
|
+
import { P as PaymentAccept, V as VerifyResponse, l as SettleResponse, m as PaymentRequired, n as PayToProvider } from '../types-BvQpNtFw.cjs';
|
|
2
|
+
export { o as AccessPassClaims, h as AccessPassClientConfig, j as AccessPassInfo, k as AccessPassTier, p as PayToContext, q as PayToProviderDefaults } from '../types-BvQpNtFw.cjs';
|
|
3
3
|
import * as _x402_evm_batch_settlement_server from '@x402/evm/batch-settlement/server';
|
|
4
4
|
import { Request, RequestHandler } from 'express';
|
|
5
5
|
import { SponsoredRecommendation } from '@dexterai/x402-ads-types';
|
|
6
6
|
export { SPONSORED_ACCESS_EXTENSION_KEY, SponsoredAccessClientConsent, SponsoredAccessPaymentRequiredInfo, SponsoredAccessSettlementInfo, SponsoredRecommendation } from '@dexterai/x402-ads-types';
|
|
7
|
-
import {
|
|
8
|
-
export {
|
|
9
|
-
import '../types-
|
|
7
|
+
import { a as BatchSettlementSeller } from '../types-JpkrtFbZ.cjs';
|
|
8
|
+
export { o as BASE_MAINNET_NETWORK, D as DEXTER_FACILITATOR_URL, p as SOLANA_MAINNET_NETWORK, q as USDC_BASE, n as USDC_MINT } from '../constants-BLvApMMl.cjs';
|
|
9
|
+
import '../types-BbvuPNXl.cjs';
|
|
10
10
|
import '@x402/evm/batch-settlement/client';
|
|
11
11
|
|
|
12
12
|
/**
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { P as PaymentAccept, V as VerifyResponse,
|
|
2
|
-
export {
|
|
1
|
+
import { P as PaymentAccept, V as VerifyResponse, l as SettleResponse, m as PaymentRequired, n as PayToProvider } from '../types-BvQpNtFw.js';
|
|
2
|
+
export { o as AccessPassClaims, h as AccessPassClientConfig, j as AccessPassInfo, k as AccessPassTier, p as PayToContext, q as PayToProviderDefaults } from '../types-BvQpNtFw.js';
|
|
3
3
|
import * as _x402_evm_batch_settlement_server from '@x402/evm/batch-settlement/server';
|
|
4
4
|
import { Request, RequestHandler } from 'express';
|
|
5
5
|
import { SponsoredRecommendation } from '@dexterai/x402-ads-types';
|
|
6
6
|
export { SPONSORED_ACCESS_EXTENSION_KEY, SponsoredAccessClientConsent, SponsoredAccessPaymentRequiredInfo, SponsoredAccessSettlementInfo, SponsoredRecommendation } from '@dexterai/x402-ads-types';
|
|
7
|
-
import {
|
|
8
|
-
export {
|
|
9
|
-
import '../types-
|
|
7
|
+
import { a as BatchSettlementSeller } from '../types-CkcNYx1Q.js';
|
|
8
|
+
export { o as BASE_MAINNET_NETWORK, D as DEXTER_FACILITATOR_URL, p as SOLANA_MAINNET_NETWORK, q as USDC_BASE, n as USDC_MINT } from '../constants-BLvApMMl.js';
|
|
9
|
+
import '../types-DwVhPqOZ.js';
|
|
10
10
|
import '@x402/evm/batch-settlement/client';
|
|
11
11
|
|
|
12
12
|
/**
|
package/dist/server/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var O="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",le="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",de="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";var k="eip155:8453",z="eip155:84532",J="eip155:42161",G="eip155:137",Y="eip155:10",Q="eip155:43114",Z="eip155:56",L="eip155:480",q="eip155:143",K="eip155:4663",$="eip155:1187947933",H="eip155:324705682",ee="eip155:1";var W="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";var se="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",Ne="0x55d398326f99059fF775485246999027B3197955",ue="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",De="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",me={[Z]:ue,[k]:se,[z]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[J]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[G]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[Y]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[Q]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[L]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[q]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[K]:De,[$]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[H]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[ee]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},fe={[Ne]:{symbol:"USDT",decimals:18},[ue]:{symbol:"USDC",decimals:18}};var rt={[L]:{name:"USDC",version:"2"},[q]:{name:"USDC",version:"2"},[K]:{name:"Global Dollar",version:"1"},[$]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[H]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}};var nt={[Z]:56,[k]:8453,[z]:84532,[J]:42161,[G]:137,[Y]:10,[Q]:43114,[L]:480,[q]:143,[K]:4663,[$]:1187947933,[H]:324705682,[ee]:1},st={[O]:"https://api.dexter.cash/api/solana/rpc",[le]:"https://api.devnet.solana.com",[de]:"https://api.testnet.solana.com"},Oe={[Z]:"https://api.dexter.cash/api/evm/bsc/rpc",[k]:"https://api.dexter.cash/api/base/rpc",[z]:"https://sepolia.base.org",[J]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[G]:"https://api.dexter.cash/api/evm/polygon/rpc",[Y]:"https://api.dexter.cash/api/evm/optimism/rpc",[Q]:"https://api.dexter.cash/api/evm/avalanche/rpc",[L]:"https://worldchain-mainnet.g.alchemy.com/public",[q]:"https://rpc.monad.xyz",[K]:"https://rpc.mainnet.chain.robinhood.com",[$]:"https://skale-base.skalenodes.com/v1/base",[H]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[ee]:"https://eth.llamarpc.com"},I="https://x402.dexter.cash",ye=O;function he(e,t){if(!Number.isFinite(e))throw new Error(`toAtomicUnits: amount must be finite, got ${e}`);if(e<0)throw new Error(`toAtomicUnits: amount must be non-negative, got ${e}`);if(!Number.isInteger(t)||t<0)throw new Error(`toAtomicUnits: decimals must be a non-negative integer, got ${t}`);let s=Ie(Math.abs(e)),[r,n=""]=s.split("."),a=n.slice(0,t).padEnd(t,"0");return BigInt(r+a).toString()}function Ie(e){let t=e.toString();if(!/[eE]/.test(t))return t;let[s,r]=t.split(/[eE]/),n=parseInt(r,10),a=s.startsWith("-"),p=a?s.slice(1):s,[m,f=""]=p.split("."),d=m+f,g=m.length+n,o;return g<=0?o="0."+"0".repeat(-g)+d:g>=d.length?o=d+"0".repeat(g-d.length):o=d.slice(0,g)+"."+d.slice(g),(a?"-":"")+o}function te(e){return e.startsWith("solana:")||e==="solana"}function ke(e){if(typeof Buffer<"u")return Buffer.from(e,"utf-8").toString("base64");let t=new TextEncoder().encode(e),s="";for(let r=0;r<t.length;r++)s+=String.fromCharCode(t[r]);return btoa(s)}function Me(e){if(typeof Buffer<"u")return Buffer.from(e,"base64").toString("utf-8");let t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return new TextDecoder().decode(s)}function re(e){return ke(JSON.stringify(e))}function F(e){return JSON.parse(Me(e))}function Be(e){if(e instanceof TypeError)return!0;if(e&&typeof e=="object"&&"status"in e){let t=e.status;return t>=500&&t<600}return!1}var j=class extends Error{status;body;constructor(t,s){super(`HTTP ${t}`),this.status=t,this.body=s}},V=class{facilitatorUrl;cachedSupported=null;cacheTime=0;CACHE_TTL_MS=6e4;timeoutMs;maxRetries;retryBaseMs;constructor(t=I,s){this.facilitatorUrl=t.replace(/\/$/,""),this.timeoutMs=s?.timeoutMs??1e4,this.maxRetries=s?.maxRetries??3,this.retryBaseMs=s?.retryBaseMs??500}async fetchWithTimeout(t,s){let r=new AbortController,n=setTimeout(()=>r.abort(),this.timeoutMs);try{return await fetch(t,{...s,signal:r.signal})}finally{clearTimeout(n)}}async fetchWithRetry(t,s){let r;for(let n=0;n<this.maxRetries;n++)try{let a=await this.fetchWithTimeout(t,s);if(!a.ok&&a.status>=500)throw new j(a.status,await a.text());return a}catch(a){if(r=a,n<this.maxRetries-1&&Be(a)){let p=this.retryBaseMs*Math.pow(2,n);await new Promise(m=>setTimeout(m,p));continue}throw a}throw r}async getSupported(){let t=Date.now();if(this.cachedSupported&&t-this.cacheTime<this.CACHE_TTL_MS)return this.cachedSupported;let s=await this.fetchWithTimeout(`${this.facilitatorUrl}/supported`);if(!s.ok)throw new Error(`Facilitator /supported returned ${s.status}`);return this.cachedSupported=await s.json(),this.cacheTime=t,this.cachedSupported}async getFeePayer(t){let r=(await this.getSupported()).kinds.find(n=>n.x402Version===2&&(n.scheme==="exact"||n.scheme==="exact-approval")&&n.network===t);if(!r)throw new Error(`Facilitator does not support network "${t}" with a recognized scheme`);return r.extra?.feePayer}async getNetworkExtra(t){return(await this.getSupported()).kinds.find(n=>n.x402Version===2&&(n.scheme==="exact"||n.scheme==="exact-approval"||n.scheme==="batch-settlement")&&n.network===t)?.extra}async verifyPayment(t,s){try{let r=F(t),n=await this.fetchWithRetry(`${this.facilitatorUrl}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:r,paymentRequirements:s})});return n.ok?await n.json():{isValid:!1,invalidReason:`facilitator_error_${n.status}`}}catch(r){return{isValid:!1,invalidReason:r instanceof j?`facilitator_error_${r.status}`:r instanceof Error&&r.name==="AbortError"?"facilitator_timeout":r instanceof Error?r.message:"unexpected_verify_error"}}}async settlePayment(t,s){try{let r=F(t),n=await this.fetchWithRetry(`${this.facilitatorUrl}/settle`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:r,paymentRequirements:s})});return n.ok?{...await n.json(),network:s.network}:{success:!1,network:s.network,errorReason:`facilitator_error_${n.status}`}}catch(r){let n=r instanceof j?`facilitator_error_${r.status}`:r instanceof Error&&r.name==="AbortError"?"facilitator_timeout":r instanceof Error?r.message:"unexpected_settle_error";return{success:!1,network:s.network,errorReason:n}}}};function xe(e){if(te(e))return{address:W,decimals:6};let t=me[e];if(t){let s=fe[t]?.decimals??6;return{address:t,decimals:s}}return{address:W,decimals:6}}function ge(e){try{let t=F(e);return t?.accepted?.amount??t?.accepted?.maxAmountRequired}catch{return}}function oe(e){let{payTo:t,facilitatorUrl:s=I,network:r=O,defaultTimeoutSeconds:n=60}=e,a=e.asset??xe(r),p=e.scheme??"exact";if(p==="tab"&&!te(r))throw new Error(`scheme 'tab' is SVM-only; got network "${r}"`);let m=new V(s),f=null,d=new Map,g=3e4,o=Date.now();function y(i){let l=(i.maxTimeoutSeconds||n)*1e3;if(d.set(i.payTo,{accept:i,expiresAt:Date.now()+l}),Date.now()-o>g){let h=Date.now();for(let[S,v]of d)v.expiresAt<h&&d.delete(S);o=h}}function E(i){let l=d.get(i);if(l){if(l.expiresAt<Date.now()){d.delete(i);return}return l.accept}}async function x(i){return typeof t=="string"?t:t(i||{})}async function b(){if(f||(f=await m.getNetworkExtra(r)),te(r)&&!f?.feePayer)throw new Error(`Facilitator does not provide feePayer for network "${r}"`);return{...f?.feePayer?{feePayer:f.feePayer}:{},decimals:f?.decimals??a.decimals,name:f?.name,version:f?.version,...p==="batch-settlement"&&f?.receiverAuthorizer?{receiverAuthorizer:f.receiverAuthorizer}:{},...p==="tab"?{voucherHeader:"x-tab-voucher",registrationEncoding:"base64(188-byte sessionRegisterMessage)"}:{}}}async function N(i,l){let{amountAtomic:h,timeoutSeconds:S=n}=l,v=await b(),D={scheme:p,network:r,amount:h,maxAmountRequired:h,asset:a.address,payTo:i,maxTimeoutSeconds:S,extra:v};return y(D),D}async function C(i){let l=await x({amountAtomic:i.amountAtomic,resourceUrl:i.resourceUrl});return N(l,i)}async function _(i){let{resourceUrl:l,description:h,mimeType:S="application/json"}=i,v={url:l,description:h,mimeType:S},D=await C(i);return{x402Version:2,resource:v,accepts:[D],error:"Payment required"}}function R(i){return re(i)}function c(i){return{status:402,headers:{"PAYMENT-REQUIRED":R(i)},body:{}}}async function u(i,l){if(!l){let h=await x({paymentHeader:i});l=E(h),l||(l=await N(h,{amountAtomic:ge(i)??"0",resourceUrl:""}))}return m.verifyPayment(i,l)}async function A(i,l){if(!l){let h=await x({paymentHeader:i});l=E(h),l||(l=await N(h,{amountAtomic:ge(i)??"0",resourceUrl:""}))}return m.settlePayment(i,l)}return{buildRequirements:_,encodeRequirements:R,create402Response:c,verifyPayment:u,settlePayment:A,getPaymentAccept:C,network:r,assetDecimals:a.decimals,facilitator:m}}var Ue=new WeakMap;function Se(e){return Ue.get(e)}import{homedir as He}from"os";import{join as We}from"path";import{FileChannelStorage as Fe}from"@x402/evm/batch-settlement/server";import{HTTPFacilitatorClient as Le,x402ResourceServer as qe}from"@x402/core/server";import{x402HTTPResourceServer as Ke}from"@x402/core/http";import{BatchSettlementEvmScheme as $e}from"@x402/evm/batch-settlement/server";function Ee(e){let t=e.verbose?console.log.bind(console,"[batch-settlement:seller]"):()=>{},s=new Le({url:e.facilitatorUrl}),r=new $e(e.payTo,{storage:e.channelStore}),n=new qe(s).register(e.network,r),a=new Ke(n,{[e.route]:{accepts:{scheme:"batch-settlement",payTo:e.payTo,price:e.price,network:e.network},description:"batch-settlement protected route",mimeType:"application/json"}}),p=null;function m(){if(p)return p;let o=a.initialize();return o.catch(y=>{p===o&&(p=null),e.verbose?t("resource server initialize() failed:",y):console.error("[batch-settlement:seller] resource server initialize() failed:",y)}),p=o,o}let f=m();function d(o,y){if(o.headersSent)return;for(let[x,b]of Object.entries(y.headers))o.setHeader(x,b);o.status(y.status);let{body:E}=y;E==null?o.end():typeof E=="string"?o.send(E):o.json(E)}return{scheme:r,facilitator:s,handler:async(o,y,E)=>{try{await m();let x=o.get("host")??"",b=`${o.baseUrl??""}${o.path}`||"/",N={getHeader:A=>o.headers[A.toLowerCase()],getMethod:()=>o.method,getPath:()=>b,getUrl:()=>`${o.protocol}://${x}${o.originalUrl}`,getAcceptHeader:()=>o.headers.accept??"",getUserAgent:()=>o.headers["user-agent"]??"",getBody:()=>o.body??{},getQueryParams:()=>o.query,getQueryParam:A=>{let i=o.query[A];if(typeof i=="string"||Array.isArray(i))return i}},C=o.headers["payment-signature"]??o.headers["x-payment"],_={adapter:N,path:b,method:o.method,paymentHeader:C},R=await a.processHTTPRequest(_);if(t("processHTTPRequest ->",R.type),R.type==="no-payment-required"){E();return}if(R.type==="payment-error"){d(y,R.response);return}let c={request:_,responseBody:Buffer.alloc(0)},u=await a.processSettlement(R.paymentPayload,R.paymentRequirements,R.declaredExtensions,c);if(t("processSettlement ->",u.success?"success":`failure:${u.errorReason}`),!u.success){d(y,u.response);return}for(let[A,i]of Object.entries(u.headers))y.headersSent||y.setHeader(A,i);E()}catch(x){t("handler error:",x),y.headersSent||y.status(500).json({error:"Payment processing error"})}},ready:f}}import{formatUnits as Re}from"viem";var Ae=6;async function ie(e){let{manager:t,store:s,channelId:r}=e,n=await s.get(r),a=BigInt(n?.chargedCumulativeAmount??"0"),p=BigInt(n?.balance??"0"),m=p>a?p-a:0n,{claims:f,settle:d}=await t.claimAndSettle(),g=await t.refund([r]),o=g.find(y=>y.channel===r)??g[0];return{claimTx:f[0]?.transaction??"",settleTx:d?.transaction??"",refundTx:o?.transaction??"",settledAmount:Re(a,Ae),refundedAmount:Re(m,Ae)}}async function Te(e){let t=await e.store.list(),s=[];for(let r of t)try{let n=await ie({manager:e.manager,store:e.store,channelId:r.channelId});s.push({channelId:r.channelId,...n})}catch(n){s.push({channelId:r.channelId,error:n instanceof Error?n.message:String(n)})}return s}function Pe(e){let t=!1,s=async()=>{try{await e.claimAndSettle()}catch(n){e.onError?.(n)}},r=setInterval(()=>{t||s()},e.claimIntervalMs);return typeof r.unref=="function"&&r.unref(),{async stop(){t||(t=!0,clearInterval(r),await s())}}}var je="https://x402.dexter.cash",Ve="GET /",be=new Set(["eip155:8453","eip155:42161","eip155:137"]);function Xe(e){return e===!1?null:e===void 0||e===!0?3e5:(e.claimIntervalSecs??300)*1e3}function ae(e){if(!be.has(e.network))throw new Error(`batch-settlement is not supported on network "${e.network}" \u2014 supported: ${[...be].join(", ")}`);let t=e.facilitatorUrl??je,s=e.channelStore??new Fe({directory:We(He(),".dexter-x402","seller-channels")}),r=Ee({payTo:e.payTo,network:e.network,price:e.price,route:e.route??Ve,facilitatorUrl:t,channelStore:s,verbose:e.verbose}),n=r.scheme.createChannelManager(r.facilitator,e.network),a=async()=>{await n.claimAndSettle()},p=Xe(e.autoSettle),m=null;p!==null&&(m=Pe({claimAndSettle:a,claimIntervalMs:p,onError:o=>console.error("[batch-settlement:seller] auto-loop claim pass failed",o)}));let f=s,d=(o,y,E)=>{r.handler(o,y,E)},g=d;return g.middleware=()=>d,g.closeChannel=o=>ie({manager:n,store:f,channelId:o}),g.closeAll=()=>Te({manager:n,store:f}),g.stop=async()=>{m&&await m.stop()},g}async function _e(e,t,s){let r={};for(let n of e)if(n.enrichPaymentRequiredResponse&&n.key in t)try{let a=await n.enrichPaymentRequiredResponse(t[n.key],s);a!==void 0&&(r[n.key]=a)}catch(a){console.warn(`[x402:extensions] extension "${n.key}" failed:`,a)}return Object.keys(r).length>0?r:void 0}function ze(e,t){if(typeof e=="string"||typeof e=="function")return e;if(t in e)return e[t];let r=`${t.split(":")[0]}:*`;if(r in e)return e[r];if("*"in e)return e["*"];throw new Error(`No payTo configured for network "${t}"`)}function Je(e){if(e.scheme==="batch-settlement"){let c=Array.isArray(e.network)?e.network[0]:e.network;if(!c)throw new Error('x402Middleware: scheme "batch-settlement" requires a network');let u=typeof e.payTo=="string"?e.payTo:void 0;if(!u)throw new Error('x402Middleware: scheme "batch-settlement" requires a string payTo address');return ae({payTo:u,network:c,price:e.amount,facilitatorUrl:e.facilitatorUrl,route:e.batchSettlement?.route,channelStore:e.batchSettlement?.channelStore,autoSettle:e.batchSettlement?.autoSettle,verbose:e.verbose})}let{payTo:t,amount:s,asset:r,description:n,resourceUrl:a,mimeType:p,timeoutSeconds:m,verbose:f=!1,getResourceUrl:d,getAmount:g,getDescription:o,extensions:y,declarations:E}=e,x=f?console.log.bind(console,"[x402:middleware]"):()=>{},b=typeof t=="function"?t._x402Defaults:void 0,N=e.facilitatorUrl??b?.facilitatorUrl,C=e.network?Array.isArray(e.network)?e.network:[e.network]:b?.network?[b.network]:[ye],_=new Map;for(let c of C){let u=ze(t,c);if(typeof u=="function"){let A=Se(u);if(A&&c!==A)throw new Error(`stripePayTo is configured for "${A}" but middleware includes network "${c}". Stripe only supports Base deposit addresses. Use a static payTo for other chains.`)}_.set(c,oe({payTo:u,network:c,asset:r,facilitatorUrl:N,defaultTimeoutSeconds:m,scheme:e.scheme}))}let R=_.get(C[0]);return async(c,u,A)=>{try{let i=c.headers["payment-signature"];if(!i){x("No payment signature, returning 402");let M=d?.(c)??a??`${c.protocol}://${c.get("host")}${c.originalUrl}`,P=g?.(c)??s,B=o?.(c)??n,ce=parseFloat(P),w=[],T=null;for(let[,U]of _)try{let ne={amountAtomic:he(ce,U.assetDecimals),resourceUrl:M,description:B,mimeType:p,timeoutSeconds:m},pe=await U.buildRequirements(ne);w.push(...pe.accepts),T||(T=pe)}catch(ne){x("Failed to build requirements for a network:",ne)}if(!T||w.length===0){u.status(500).json({error:"Failed to build payment requirements"});return}if(T={...T,accepts:w},y&&y.length>0){let U=await _e(y,E??{},{response:T,request:{method:c.method,path:(c.baseUrl??"")+(c.route?.path??c.path),params:c.params}});U&&(T={...T,extensions:U})}let Ce=R.encodeRequirements(T);u.setHeader("PAYMENT-REQUIRED",Ce),u.status(402).json({error:"Payment required",accepts:T.accepts,resource:T.resource,...T.extensions?{extensions:T.extensions}:{}});return}x("Payment signature received, verifying...");let l=R;try{let P=JSON.parse(Buffer.from(i,"base64").toString())?.accepted?.network;P&&_.has(P)&&(l=_.get(P))}catch{}let h=await l.verifyPayment(i);if(!h.isValid){if(x("Payment verification failed:",h.invalidReason),e.onVerifyFailed)try{await e.onVerifyFailed({reason:h.invalidReason,resourceUrl:`${c.protocol}://${c.get("host")}${c.originalUrl}`})}catch{}u.status(402).json({error:"Payment verification failed",reason:h.invalidReason});return}x("Payment verified, settling...");let S=await l.settlePayment(i);if(!S.success){x("Payment settlement failed:",S.errorReason),u.status(402).json({error:"Payment settlement failed",reason:S.errorReason});return}x("Payment settled:",S.transaction);let v=S.network||C[0];if(e.onSettlement)try{await e.onSettlement({transaction:S.transaction,network:v,payer:h.payer??"",resourceUrl:`${c.protocol}://${c.get("host")}${c.originalUrl}`})}catch{}c.x402={transaction:S.transaction,payer:h.payer??"",network:v};let D={success:!0,transaction:S.transaction,network:v,payer:h.payer??""};if(S.extensions&&(D.extensions=S.extensions),u.setHeader("PAYMENT-RESPONSE",re(D)),e.sponsoredAccess&&S.extensions?.["sponsored-access"]){let M=S.extensions["sponsored-access"],P=M?.info?.recommendations??M?.recommendations;if(P&&P.length>0){if(x("Injecting sponsored-access recommendations into response"),typeof e.sponsoredAccess=="object"&&e.sponsoredAccess.onMatch)try{e.sponsoredAccess.onMatch(P,{transaction:S.transaction,network:v,payer:h.payer??""})}catch{}let B=u.json.bind(u);u.json=function(w){return typeof e.sponsoredAccess=="object"&&e.sponsoredAccess.inject?B(e.sponsoredAccess.inject(w,P)):w&&typeof w=="object"&&!Array.isArray(w)?B({_x402_sponsored:P,...w}):B(w)}}}A()}catch(i){x("Middleware error:",i),u.status(500).json({error:"Payment processing error"})}}}var Ge=/^\/[a-zA-Z0-9_/:.\-~%]+$/;function ve(e){if(!e||!Ge.test(e))return!1;let t;try{t=decodeURIComponent(e)}catch{return!1}return!(t.includes("..")||t.includes("://"))}function X(e){return e.method==="POST"||e.method==="PUT"||e.method==="PATCH"}var Ye=["GET","HEAD","DELETE"],Qe=["POST","PUT","PATCH"];function we(e,t){let s=t.pathParams!==void 0&&Object.keys(t.pathParams).length>0,r={type:"http",method:e.method};X(e)?(r.bodyType=e.bodyType,r.body=e.input??{}):e.input!==void 0&&(r.queryParams=e.input),s&&(r.pathParams=t.pathParams);let n=e.output?.example!==void 0?{type:"json",example:e.output.example}:void 0,a=X(e)?Qe:Ye,p={type:{type:"string",const:"http"},method:{type:"string",enum:a}};X(e)?(p.bodyType={type:"string",enum:["json","form-data","text"]},p.body={type:"object",...e.inputSchema??{}}):e.inputSchema&&(p.queryParams={type:"object",...e.inputSchema}),e.pathParamsSchema&&(p.pathParams={type:"object",...e.pathParamsSchema});let m={input:{type:"object",properties:p,required:X(e)?["type","method","bodyType","body"]:["type","method"],additionalProperties:!1}};n&&(m.output={type:"object",properties:{type:{type:"string"},example:{type:"object",...e.output?.schema??{}}},required:["type"]});let f={$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:m,required:["input"]},d={info:{input:r,...n?{output:n}:{}},schema:f};return ve(t.routeTemplate)&&(d.routeTemplate=t.routeTemplate),d}var Ze=["GET","HEAD","DELETE","POST","PUT","PATCH"];function et(){return{key:"bazaar",enrichPaymentRequiredResponse:(e,t)=>{if(e==null)return;let s=e,r=(s.method??t.request.method).toUpperCase();if(!Ze.includes(r))return;let n={...s,method:r};return we(n,{pathParams:t.request.params,routeTemplate:t.request.path})}}}function tt(e){return{bazaar:e}}import{SPONSORED_ACCESS_EXTENSION_KEY as cr}from"@dexterai/x402-ads-types";export{k as BASE_MAINNET_NETWORK,I as DEXTER_FACILITATOR_URL,V as FacilitatorClient,O as SOLANA_MAINNET_NETWORK,cr as SPONSORED_ACCESS_EXTENSION_KEY,se as USDC_BASE,W as USDC_MINT,et as bazaarExtension,oe as createX402Server,tt as declareDiscoveryExtension,xe as resolveDefaultAsset,Je as x402Middleware};
|
|
1
|
+
var O="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",le="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",de="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";var k="eip155:8453",G="eip155:84532",z="eip155:42161",J="eip155:137",Y="eip155:10",Q="eip155:43114",Z="eip155:56",L="eip155:480",H="eip155:143",q="eip155:4663",K="eip155:1187947933",$="eip155:324705682",ee="eip155:1";var W="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";var se="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",ke="0x55d398326f99059fF775485246999027B3197955",ue="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",Be="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",me={[Z]:ue,[k]:se,[G]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[z]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[J]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[Y]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[Q]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[L]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[H]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[q]:Be,[K]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[$]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[ee]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},fe={[ke]:{symbol:"USDT",decimals:18},[ue]:{symbol:"USDC",decimals:18}};var it={[L]:{name:"USDC",version:"2"},[H]:{name:"USDC",version:"2"},[q]:{name:"Global Dollar",version:"1"},[K]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[$]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}};var at={[Z]:56,[k]:8453,[G]:84532,[z]:42161,[J]:137,[Y]:10,[Q]:43114,[L]:480,[H]:143,[q]:4663,[K]:1187947933,[$]:324705682,[ee]:1},ct={[O]:"https://api.dexter.cash/api/solana/rpc",[le]:"https://api.devnet.solana.com",[de]:"https://api.testnet.solana.com"},Me={[Z]:"https://api.dexter.cash/api/evm/bsc/rpc",[k]:"https://api.dexter.cash/api/base/rpc",[G]:"https://sepolia.base.org",[z]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[J]:"https://api.dexter.cash/api/evm/polygon/rpc",[Y]:"https://api.dexter.cash/api/evm/optimism/rpc",[Q]:"https://api.dexter.cash/api/evm/avalanche/rpc",[L]:"https://worldchain-mainnet.g.alchemy.com/public",[H]:"https://rpc.monad.xyz",[q]:"https://rpc.mainnet.chain.robinhood.com",[K]:"https://skale-base.skalenodes.com/v1/base",[$]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[ee]:"https://eth.llamarpc.com"},I="https://x402.dexter.cash",ye=O;var he="dexter-tab-hosted-pay-before-delivery/v1",ge="pay_before_delivery_seller_2xx",Ee="x-tab-voucher",xe="base64(188-byte sessionRegisterMessage)";function Se(e,t){if(!Number.isFinite(e))throw new Error(`toAtomicUnits: amount must be finite, got ${e}`);if(e<0)throw new Error(`toAtomicUnits: amount must be non-negative, got ${e}`);if(!Number.isInteger(t)||t<0)throw new Error(`toAtomicUnits: decimals must be a non-negative integer, got ${t}`);let s=Ue(Math.abs(e)),[r,n=""]=s.split("."),a=n.slice(0,t).padEnd(t,"0");return BigInt(r+a).toString()}function Ue(e){let t=e.toString();if(!/[eE]/.test(t))return t;let[s,r]=t.split(/[eE]/),n=parseInt(r,10),a=s.startsWith("-"),p=a?s.slice(1):s,[m,f=""]=p.split("."),d=m+f,g=m.length+n,o;return g<=0?o="0."+"0".repeat(-g)+d:g>=d.length?o=d+"0".repeat(g-d.length):o=d.slice(0,g)+"."+d.slice(g),(a?"-":"")+o}function te(e){return e.startsWith("solana:")||e==="solana"}function Le(e){if(typeof Buffer<"u")return Buffer.from(e,"utf-8").toString("base64");let t=new TextEncoder().encode(e),s="";for(let r=0;r<t.length;r++)s+=String.fromCharCode(t[r]);return btoa(s)}function He(e){if(typeof Buffer<"u")return Buffer.from(e,"base64").toString("utf-8");let t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return new TextDecoder().decode(s)}function re(e){return Le(JSON.stringify(e))}function F(e){return JSON.parse(He(e))}function qe(e){if(e instanceof TypeError)return!0;if(e&&typeof e=="object"&&"status"in e){let t=e.status;return t>=500&&t<600}return!1}var V=class extends Error{status;body;constructor(t,s){super(`HTTP ${t}`),this.status=t,this.body=s}},j=class{facilitatorUrl;cachedSupported=null;cacheTime=0;CACHE_TTL_MS=6e4;timeoutMs;maxRetries;retryBaseMs;constructor(t=I,s){this.facilitatorUrl=t.replace(/\/$/,""),this.timeoutMs=s?.timeoutMs??1e4,this.maxRetries=s?.maxRetries??3,this.retryBaseMs=s?.retryBaseMs??500}async fetchWithTimeout(t,s){let r=new AbortController,n=setTimeout(()=>r.abort(),this.timeoutMs);try{return await fetch(t,{...s,signal:r.signal})}finally{clearTimeout(n)}}async fetchWithRetry(t,s){let r;for(let n=0;n<this.maxRetries;n++)try{let a=await this.fetchWithTimeout(t,s);if(!a.ok&&a.status>=500)throw new V(a.status,await a.text());return a}catch(a){if(r=a,n<this.maxRetries-1&&qe(a)){let p=this.retryBaseMs*Math.pow(2,n);await new Promise(m=>setTimeout(m,p));continue}throw a}throw r}async getSupported(){let t=Date.now();if(this.cachedSupported&&t-this.cacheTime<this.CACHE_TTL_MS)return this.cachedSupported;let s=await this.fetchWithTimeout(`${this.facilitatorUrl}/supported`);if(!s.ok)throw new Error(`Facilitator /supported returned ${s.status}`);return this.cachedSupported=await s.json(),this.cacheTime=t,this.cachedSupported}async getFeePayer(t){let r=(await this.getSupported()).kinds.find(n=>n.x402Version===2&&(n.scheme==="exact"||n.scheme==="exact-approval")&&n.network===t);if(!r)throw new Error(`Facilitator does not support network "${t}" with a recognized scheme`);return r.extra?.feePayer}async getNetworkExtra(t){return(await this.getSupported()).kinds.find(n=>n.x402Version===2&&(n.scheme==="exact"||n.scheme==="exact-approval"||n.scheme==="batch-settlement")&&n.network===t)?.extra}async verifyPayment(t,s){try{let r=F(t),n=await this.fetchWithRetry(`${this.facilitatorUrl}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:r,paymentRequirements:s})});return n.ok?await n.json():{isValid:!1,invalidReason:`facilitator_error_${n.status}`}}catch(r){return{isValid:!1,invalidReason:r instanceof V?`facilitator_error_${r.status}`:r instanceof Error&&r.name==="AbortError"?"facilitator_timeout":r instanceof Error?r.message:"unexpected_verify_error"}}}async settlePayment(t,s){try{let r=F(t),n=await this.fetchWithRetry(`${this.facilitatorUrl}/settle`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x402Version:2,paymentPayload:r,paymentRequirements:s})});return n.ok?{...await n.json(),network:s.network}:{success:!1,network:s.network,errorReason:`facilitator_error_${n.status}`}}catch(r){let n=r instanceof V?`facilitator_error_${r.status}`:r instanceof Error&&r.name==="AbortError"?"facilitator_timeout":r instanceof Error?r.message:"unexpected_settle_error";return{success:!1,network:s.network,errorReason:n}}}};function Ae(e){if(te(e))return{address:W,decimals:6};let t=me[e];if(t){let s=fe[t]?.decimals??6;return{address:t,decimals:s}}return{address:W,decimals:6}}function Re(e){try{let t=F(e);return t?.accepted?.amount??t?.accepted?.maxAmountRequired}catch{return}}function oe(e){let{payTo:t,facilitatorUrl:s=I,network:r=O,defaultTimeoutSeconds:n=60}=e,a=e.asset??Ae(r),p=e.scheme??"exact";if(p==="tab"&&!te(r))throw new Error(`scheme 'tab' is SVM-only; got network "${r}"`);let m=new j(s),f=null,d=new Map,g=3e4,o=Date.now();function y(i){let l=(i.maxTimeoutSeconds||n)*1e3;if(d.set(i.payTo,{accept:i,expiresAt:Date.now()+l}),Date.now()-o>g){let h=Date.now();for(let[x,v]of d)v.expiresAt<h&&d.delete(x);o=h}}function S(i){let l=d.get(i);if(l){if(l.expiresAt<Date.now()){d.delete(i);return}return l.accept}}async function E(i){return typeof t=="string"?t:t(i||{})}async function _(){if(f||(f=await m.getNetworkExtra(r)),te(r)&&!f?.feePayer)throw new Error(`Facilitator does not provide feePayer for network "${r}"`);return{...f?.feePayer?{feePayer:f.feePayer}:{},decimals:f?.decimals??a.decimals,name:f?.name,version:f?.version,...p==="batch-settlement"&&f?.receiverAuthorizer?{receiverAuthorizer:f.receiverAuthorizer}:{},...p==="tab"?{voucherHeader:Ee,registrationEncoding:xe,termsVersion:he,acceptanceRule:ge}:{}}}async function N(i,l){let{amountAtomic:h,timeoutSeconds:x=n}=l,v=await _(),D={scheme:p,network:r,amount:h,maxAmountRequired:h,asset:a.address,payTo:i,maxTimeoutSeconds:x,extra:v};return y(D),D}async function w(i){let l=await E({amountAtomic:i.amountAtomic,resourceUrl:i.resourceUrl});return N(l,i)}async function b(i){let{resourceUrl:l,description:h,mimeType:x="application/json"}=i,v={url:l,description:h,mimeType:x},D=await w(i);return{x402Version:2,resource:v,accepts:[D],error:"Payment required"}}function R(i){return re(i)}function c(i){return{status:402,headers:{"PAYMENT-REQUIRED":R(i)},body:{}}}async function u(i,l){if(!l){let h=await E({paymentHeader:i});l=S(h),l||(l=await N(h,{amountAtomic:Re(i)??"0",resourceUrl:""}))}return m.verifyPayment(i,l)}async function A(i,l){if(!l){let h=await E({paymentHeader:i});l=S(h),l||(l=await N(h,{amountAtomic:Re(i)??"0",resourceUrl:""}))}return m.settlePayment(i,l)}return{buildRequirements:b,encodeRequirements:R,create402Response:c,verifyPayment:u,settlePayment:A,getPaymentAccept:w,network:r,assetDecimals:a.decimals,facilitator:m}}var Ke=new WeakMap;function Te(e){return Ke.get(e)}import{homedir as je}from"os";import{join as Xe}from"path";import{FileChannelStorage as Ge}from"@x402/evm/batch-settlement/server";import{HTTPFacilitatorClient as $e,x402ResourceServer as We}from"@x402/core/server";import{x402HTTPResourceServer as Fe}from"@x402/core/http";import{BatchSettlementEvmScheme as Ve}from"@x402/evm/batch-settlement/server";function Pe(e){let t=e.verbose?console.log.bind(console,"[batch-settlement:seller]"):()=>{},s=new $e({url:e.facilitatorUrl}),r=new Ve(e.payTo,{storage:e.channelStore}),n=new We(s).register(e.network,r),a=new Fe(n,{[e.route]:{accepts:{scheme:"batch-settlement",payTo:e.payTo,price:e.price,network:e.network},description:"batch-settlement protected route",mimeType:"application/json"}}),p=null;function m(){if(p)return p;let o=a.initialize();return o.catch(y=>{p===o&&(p=null),e.verbose?t("resource server initialize() failed:",y):console.error("[batch-settlement:seller] resource server initialize() failed:",y)}),p=o,o}let f=m();function d(o,y){if(o.headersSent)return;for(let[E,_]of Object.entries(y.headers))o.setHeader(E,_);o.status(y.status);let{body:S}=y;S==null?o.end():typeof S=="string"?o.send(S):o.json(S)}return{scheme:r,facilitator:s,handler:async(o,y,S)=>{try{await m();let E=o.get("host")??"",_=`${o.baseUrl??""}${o.path}`||"/",N={getHeader:A=>o.headers[A.toLowerCase()],getMethod:()=>o.method,getPath:()=>_,getUrl:()=>`${o.protocol}://${E}${o.originalUrl}`,getAcceptHeader:()=>o.headers.accept??"",getUserAgent:()=>o.headers["user-agent"]??"",getBody:()=>o.body??{},getQueryParams:()=>o.query,getQueryParam:A=>{let i=o.query[A];if(typeof i=="string"||Array.isArray(i))return i}},w=o.headers["payment-signature"]??o.headers["x-payment"],b={adapter:N,path:_,method:o.method,paymentHeader:w},R=await a.processHTTPRequest(b);if(t("processHTTPRequest ->",R.type),R.type==="no-payment-required"){S();return}if(R.type==="payment-error"){d(y,R.response);return}let c={request:b,responseBody:Buffer.alloc(0)},u=await a.processSettlement(R.paymentPayload,R.paymentRequirements,R.declaredExtensions,c);if(t("processSettlement ->",u.success?"success":`failure:${u.errorReason}`),!u.success){d(y,u.response);return}for(let[A,i]of Object.entries(u.headers))y.headersSent||y.setHeader(A,i);S()}catch(E){t("handler error:",E),y.headersSent||y.status(500).json({error:"Payment processing error"})}},ready:f}}import{formatUnits as _e}from"viem";var be=6;async function ie(e){let{manager:t,store:s,channelId:r}=e,n=await s.get(r),a=BigInt(n?.chargedCumulativeAmount??"0"),p=BigInt(n?.balance??"0"),m=p>a?p-a:0n,{claims:f,settle:d}=await t.claimAndSettle(),g=await t.refund([r]),o=g.find(y=>y.channel===r)??g[0];return{claimTx:f[0]?.transaction??"",settleTx:d?.transaction??"",refundTx:o?.transaction??"",settledAmount:_e(a,be),refundedAmount:_e(m,be)}}async function ve(e){let t=await e.store.list(),s=[];for(let r of t)try{let n=await ie({manager:e.manager,store:e.store,channelId:r.channelId});s.push({channelId:r.channelId,...n})}catch(n){s.push({channelId:r.channelId,error:n instanceof Error?n.message:String(n)})}return s}function Ce(e){let t=!1,s=async()=>{try{await e.claimAndSettle()}catch(n){e.onError?.(n)}},r=setInterval(()=>{t||s()},e.claimIntervalMs);return typeof r.unref=="function"&&r.unref(),{async stop(){t||(t=!0,clearInterval(r),await s())}}}var ze="https://x402.dexter.cash",Je="GET /",we=new Set(["eip155:8453","eip155:42161","eip155:137"]);function Ye(e){return e===!1?null:e===void 0||e===!0?3e5:(e.claimIntervalSecs??300)*1e3}function ae(e){if(!we.has(e.network))throw new Error(`batch-settlement is not supported on network "${e.network}" \u2014 supported: ${[...we].join(", ")}`);let t=e.facilitatorUrl??ze,s=e.channelStore??new Ge({directory:Xe(je(),".dexter-x402","seller-channels")}),r=Pe({payTo:e.payTo,network:e.network,price:e.price,route:e.route??Je,facilitatorUrl:t,channelStore:s,verbose:e.verbose}),n=r.scheme.createChannelManager(r.facilitator,e.network),a=async()=>{await n.claimAndSettle()},p=Ye(e.autoSettle),m=null;p!==null&&(m=Ce({claimAndSettle:a,claimIntervalMs:p,onError:o=>console.error("[batch-settlement:seller] auto-loop claim pass failed",o)}));let f=s,d=(o,y,S)=>{r.handler(o,y,S)},g=d;return g.middleware=()=>d,g.closeChannel=o=>ie({manager:n,store:f,channelId:o}),g.closeAll=()=>ve({manager:n,store:f}),g.stop=async()=>{m&&await m.stop()},g}async function Ne(e,t,s){let r={};for(let n of e)if(n.enrichPaymentRequiredResponse&&n.key in t)try{let a=await n.enrichPaymentRequiredResponse(t[n.key],s);a!==void 0&&(r[n.key]=a)}catch(a){console.warn(`[x402:extensions] extension "${n.key}" failed:`,a)}return Object.keys(r).length>0?r:void 0}function Qe(e,t){if(typeof e=="string"||typeof e=="function")return e;if(t in e)return e[t];let r=`${t.split(":")[0]}:*`;if(r in e)return e[r];if("*"in e)return e["*"];throw new Error(`No payTo configured for network "${t}"`)}function Ze(e){if(e.scheme==="batch-settlement"){let c=Array.isArray(e.network)?e.network[0]:e.network;if(!c)throw new Error('x402Middleware: scheme "batch-settlement" requires a network');let u=typeof e.payTo=="string"?e.payTo:void 0;if(!u)throw new Error('x402Middleware: scheme "batch-settlement" requires a string payTo address');return ae({payTo:u,network:c,price:e.amount,facilitatorUrl:e.facilitatorUrl,route:e.batchSettlement?.route,channelStore:e.batchSettlement?.channelStore,autoSettle:e.batchSettlement?.autoSettle,verbose:e.verbose})}let{payTo:t,amount:s,asset:r,description:n,resourceUrl:a,mimeType:p,timeoutSeconds:m,verbose:f=!1,getResourceUrl:d,getAmount:g,getDescription:o,extensions:y,declarations:S}=e,E=f?console.log.bind(console,"[x402:middleware]"):()=>{},_=typeof t=="function"?t._x402Defaults:void 0,N=e.facilitatorUrl??_?.facilitatorUrl,w=e.network?Array.isArray(e.network)?e.network:[e.network]:_?.network?[_.network]:[ye],b=new Map;for(let c of w){let u=Qe(t,c);if(typeof u=="function"){let A=Te(u);if(A&&c!==A)throw new Error(`stripePayTo is configured for "${A}" but middleware includes network "${c}". Stripe only supports Base deposit addresses. Use a static payTo for other chains.`)}b.set(c,oe({payTo:u,network:c,asset:r,facilitatorUrl:N,defaultTimeoutSeconds:m,scheme:e.scheme}))}let R=b.get(w[0]);return async(c,u,A)=>{try{let i=c.headers["payment-signature"];if(!i){E("No payment signature, returning 402");let B=d?.(c)??a??`${c.protocol}://${c.get("host")}${c.originalUrl}`,P=g?.(c)??s,M=o?.(c)??n,ce=parseFloat(P),C=[],T=null;for(let[,U]of b)try{let ne={amountAtomic:Se(ce,U.assetDecimals),resourceUrl:B,description:M,mimeType:p,timeoutSeconds:m},pe=await U.buildRequirements(ne);C.push(...pe.accepts),T||(T=pe)}catch(ne){E("Failed to build requirements for a network:",ne)}if(!T||C.length===0){u.status(500).json({error:"Failed to build payment requirements"});return}if(T={...T,accepts:C},y&&y.length>0){let U=await Ne(y,S??{},{response:T,request:{method:c.method,path:(c.baseUrl??"")+(c.route?.path??c.path),params:c.params}});U&&(T={...T,extensions:U})}let Ie=R.encodeRequirements(T);u.setHeader("PAYMENT-REQUIRED",Ie),u.status(402).json({error:"Payment required",accepts:T.accepts,resource:T.resource,...T.extensions?{extensions:T.extensions}:{}});return}E("Payment signature received, verifying...");let l=R;try{let P=JSON.parse(Buffer.from(i,"base64").toString())?.accepted?.network;P&&b.has(P)&&(l=b.get(P))}catch{}let h=await l.verifyPayment(i);if(!h.isValid){if(E("Payment verification failed:",h.invalidReason),e.onVerifyFailed)try{await e.onVerifyFailed({reason:h.invalidReason,resourceUrl:`${c.protocol}://${c.get("host")}${c.originalUrl}`})}catch{}u.status(402).json({error:"Payment verification failed",reason:h.invalidReason});return}E("Payment verified, settling...");let x=await l.settlePayment(i);if(!x.success){E("Payment settlement failed:",x.errorReason),u.status(402).json({error:"Payment settlement failed",reason:x.errorReason});return}E("Payment settled:",x.transaction);let v=x.network||w[0];if(e.onSettlement)try{await e.onSettlement({transaction:x.transaction,network:v,payer:h.payer??"",resourceUrl:`${c.protocol}://${c.get("host")}${c.originalUrl}`})}catch{}c.x402={transaction:x.transaction,payer:h.payer??"",network:v};let D={success:!0,transaction:x.transaction,network:v,payer:h.payer??""};if(x.extensions&&(D.extensions=x.extensions),u.setHeader("PAYMENT-RESPONSE",re(D)),e.sponsoredAccess&&x.extensions?.["sponsored-access"]){let B=x.extensions["sponsored-access"],P=B?.info?.recommendations??B?.recommendations;if(P&&P.length>0){if(E("Injecting sponsored-access recommendations into response"),typeof e.sponsoredAccess=="object"&&e.sponsoredAccess.onMatch)try{e.sponsoredAccess.onMatch(P,{transaction:x.transaction,network:v,payer:h.payer??""})}catch{}let M=u.json.bind(u);u.json=function(C){return typeof e.sponsoredAccess=="object"&&e.sponsoredAccess.inject?M(e.sponsoredAccess.inject(C,P)):C&&typeof C=="object"&&!Array.isArray(C)?M({_x402_sponsored:P,...C}):M(C)}}}A()}catch(i){E("Middleware error:",i),u.status(500).json({error:"Payment processing error"})}}}var et=/^\/[a-zA-Z0-9_/:.\-~%]+$/;function De(e){if(!e||!et.test(e))return!1;let t;try{t=decodeURIComponent(e)}catch{return!1}return!(t.includes("..")||t.includes("://"))}function X(e){return e.method==="POST"||e.method==="PUT"||e.method==="PATCH"}var tt=["GET","HEAD","DELETE"],rt=["POST","PUT","PATCH"];function Oe(e,t){let s=t.pathParams!==void 0&&Object.keys(t.pathParams).length>0,r={type:"http",method:e.method};X(e)?(r.bodyType=e.bodyType,r.body=e.input??{}):e.input!==void 0&&(r.queryParams=e.input),s&&(r.pathParams=t.pathParams);let n=e.output?.example!==void 0?{type:"json",example:e.output.example}:void 0,a=X(e)?rt:tt,p={type:{type:"string",const:"http"},method:{type:"string",enum:a}};X(e)?(p.bodyType={type:"string",enum:["json","form-data","text"]},p.body={type:"object",...e.inputSchema??{}}):e.inputSchema&&(p.queryParams={type:"object",...e.inputSchema}),e.pathParamsSchema&&(p.pathParams={type:"object",...e.pathParamsSchema});let m={input:{type:"object",properties:p,required:X(e)?["type","method","bodyType","body"]:["type","method"],additionalProperties:!1}};n&&(m.output={type:"object",properties:{type:{type:"string"},example:{type:"object",...e.output?.schema??{}}},required:["type"]});let f={$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:m,required:["input"]},d={info:{input:r,...n?{output:n}:{}},schema:f};return De(t.routeTemplate)&&(d.routeTemplate=t.routeTemplate),d}var nt=["GET","HEAD","DELETE","POST","PUT","PATCH"];function st(){return{key:"bazaar",enrichPaymentRequiredResponse:(e,t)=>{if(e==null)return;let s=e,r=(s.method??t.request.method).toUpperCase();if(!nt.includes(r))return;let n={...s,method:r};return Oe(n,{pathParams:t.request.params,routeTemplate:t.request.path})}}}function ot(e){return{bazaar:e}}import{SPONSORED_ACCESS_EXTENSION_KEY as fr}from"@dexterai/x402-ads-types";export{k as BASE_MAINNET_NETWORK,I as DEXTER_FACILITATOR_URL,j as FacilitatorClient,O as SOLANA_MAINNET_NETWORK,fr as SPONSORED_ACCESS_EXTENSION_KEY,se as USDC_BASE,W as USDC_MINT,st as bazaarExtension,oe as createX402Server,ot as declareDiscoveryExtension,Ae as resolveDefaultAsset,Ze as x402Middleware};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { PublicKey } from '@solana/web3.js';
|
|
2
|
-
import { SessionScope, SessionKey, VoucherPayload, SignedVoucher
|
|
2
|
+
import { SessionScope, SessionKey, AtomicAmount, VoucherPayload, SignedVoucher } from '@dexterai/vault/types';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Session-key lifecycle: generation, voucher signing, in-memory hygiene.
|
|
6
6
|
*
|
|
7
7
|
* A session key is an ed25519 keypair generated in process memory at tab
|
|
8
|
-
* open. The buyer's passkey signs a
|
|
8
|
+
* open. The buyer's passkey signs a 188-byte V2 registration message endorsing
|
|
9
9
|
* the session pubkey within a scope (counterparty, max amount, expiry).
|
|
10
10
|
* From that point until tab close, the session key signs every voucher; the
|
|
11
11
|
* passkey is never invoked again for the lifetime of the tab.
|
|
@@ -54,6 +54,38 @@ declare function makeSessionKey(keypair: {
|
|
|
54
54
|
* guard so a misbehaving caller can't sign vouchers the seller will reject.
|
|
55
55
|
*/
|
|
56
56
|
declare function signVoucher(session: SessionKey, payload: VoucherPayload, channelIdBytes: Uint8Array): SignedVoucher;
|
|
57
|
+
interface SignContextBoundFinalVoucherV2Input {
|
|
58
|
+
programId: string;
|
|
59
|
+
vaultPda: string;
|
|
60
|
+
sessionPda: string;
|
|
61
|
+
seller: string;
|
|
62
|
+
sessionNonce: number;
|
|
63
|
+
channelId: string;
|
|
64
|
+
cumulativeAmountAtomic: string;
|
|
65
|
+
sequenceOrdinal: number;
|
|
66
|
+
sessionPrivateKey: Uint8Array;
|
|
67
|
+
sessionPublicKey: Uint8Array;
|
|
68
|
+
sessionRegistration: Uint8Array;
|
|
69
|
+
/** Testable freshness seam. Defaults to the current Unix second. */
|
|
70
|
+
nowUnixSeconds?: number;
|
|
71
|
+
}
|
|
72
|
+
interface SignContextBoundFinalVoucherV2Result {
|
|
73
|
+
channelId: string;
|
|
74
|
+
cumulativeAmount: string;
|
|
75
|
+
sequenceNumber: number;
|
|
76
|
+
sessionPublicKey: string;
|
|
77
|
+
sessionSignature: string;
|
|
78
|
+
sessionRegistration: string;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Canonical hosted-purchase signer for Native Tab V2.
|
|
82
|
+
*
|
|
83
|
+
* Every output is a FINAL, context-bound obligation. The function owns bytes
|
|
84
|
+
* only: it validates the complete registration, derived session PDA, expiry,
|
|
85
|
+
* scope, and ed25519 keypair before signing. The caller must durably establish
|
|
86
|
+
* the exact reservation before releasing the resulting voucher.
|
|
87
|
+
*/
|
|
88
|
+
declare function signContextBoundFinalVoucherV2(input: SignContextBoundFinalVoucherV2Input): SignContextBoundFinalVoucherV2Result;
|
|
57
89
|
/**
|
|
58
90
|
* Convert a `SessionScope` (which uses string AtomicAmount for JSON
|
|
59
91
|
* portability) to the bigint cap actually needed for signing. Throws on
|
|
@@ -67,4 +99,4 @@ declare function deriveChannelId(args: {
|
|
|
67
99
|
nonce: bigint;
|
|
68
100
|
}): Uint8Array;
|
|
69
101
|
|
|
70
|
-
export {
|
|
102
|
+
export { type SignContextBoundFinalVoucherV2Input as S, type SignContextBoundFinalVoucherV2Result as a, signContextBoundFinalVoucherV2 as b, signVoucher as c, deriveChannelId as d, generateSessionKeypair as g, makeSessionKey as m, parseAtomic as p, scopeCapAtomic as s };
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { PublicKey } from '@solana/web3.js';
|
|
2
|
-
import { SessionScope, SessionKey, VoucherPayload, SignedVoucher
|
|
2
|
+
import { SessionScope, SessionKey, AtomicAmount, VoucherPayload, SignedVoucher } from '@dexterai/vault/types';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Session-key lifecycle: generation, voucher signing, in-memory hygiene.
|
|
6
6
|
*
|
|
7
7
|
* A session key is an ed25519 keypair generated in process memory at tab
|
|
8
|
-
* open. The buyer's passkey signs a
|
|
8
|
+
* open. The buyer's passkey signs a 188-byte V2 registration message endorsing
|
|
9
9
|
* the session pubkey within a scope (counterparty, max amount, expiry).
|
|
10
10
|
* From that point until tab close, the session key signs every voucher; the
|
|
11
11
|
* passkey is never invoked again for the lifetime of the tab.
|
|
@@ -54,6 +54,38 @@ declare function makeSessionKey(keypair: {
|
|
|
54
54
|
* guard so a misbehaving caller can't sign vouchers the seller will reject.
|
|
55
55
|
*/
|
|
56
56
|
declare function signVoucher(session: SessionKey, payload: VoucherPayload, channelIdBytes: Uint8Array): SignedVoucher;
|
|
57
|
+
interface SignContextBoundFinalVoucherV2Input {
|
|
58
|
+
programId: string;
|
|
59
|
+
vaultPda: string;
|
|
60
|
+
sessionPda: string;
|
|
61
|
+
seller: string;
|
|
62
|
+
sessionNonce: number;
|
|
63
|
+
channelId: string;
|
|
64
|
+
cumulativeAmountAtomic: string;
|
|
65
|
+
sequenceOrdinal: number;
|
|
66
|
+
sessionPrivateKey: Uint8Array;
|
|
67
|
+
sessionPublicKey: Uint8Array;
|
|
68
|
+
sessionRegistration: Uint8Array;
|
|
69
|
+
/** Testable freshness seam. Defaults to the current Unix second. */
|
|
70
|
+
nowUnixSeconds?: number;
|
|
71
|
+
}
|
|
72
|
+
interface SignContextBoundFinalVoucherV2Result {
|
|
73
|
+
channelId: string;
|
|
74
|
+
cumulativeAmount: string;
|
|
75
|
+
sequenceNumber: number;
|
|
76
|
+
sessionPublicKey: string;
|
|
77
|
+
sessionSignature: string;
|
|
78
|
+
sessionRegistration: string;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Canonical hosted-purchase signer for Native Tab V2.
|
|
82
|
+
*
|
|
83
|
+
* Every output is a FINAL, context-bound obligation. The function owns bytes
|
|
84
|
+
* only: it validates the complete registration, derived session PDA, expiry,
|
|
85
|
+
* scope, and ed25519 keypair before signing. The caller must durably establish
|
|
86
|
+
* the exact reservation before releasing the resulting voucher.
|
|
87
|
+
*/
|
|
88
|
+
declare function signContextBoundFinalVoucherV2(input: SignContextBoundFinalVoucherV2Input): SignContextBoundFinalVoucherV2Result;
|
|
57
89
|
/**
|
|
58
90
|
* Convert a `SessionScope` (which uses string AtomicAmount for JSON
|
|
59
91
|
* portability) to the bigint cap actually needed for signing. Throws on
|
|
@@ -67,4 +99,4 @@ declare function deriveChannelId(args: {
|
|
|
67
99
|
nonce: bigint;
|
|
68
100
|
}): Uint8Array;
|
|
69
101
|
|
|
70
|
-
export {
|
|
102
|
+
export { type SignContextBoundFinalVoucherV2Input as S, type SignContextBoundFinalVoucherV2Result as a, signContextBoundFinalVoucherV2 as b, signVoucher as c, deriveChannelId as d, generateSessionKeypair as g, makeSessionKey as m, parseAtomic as p, scopeCapAtomic as s };
|