@dexterai/x402 5.3.3 → 5.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -1
- package/dist/adapters/index.cjs +1 -1
- package/dist/adapters/index.d.cts +1 -1
- package/dist/adapters/index.d.ts +1 -1
- package/dist/adapters/index.js +1 -1
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.js +1 -1
- package/dist/{constants-D41hDAG6.d.cts → constants-Icc4CXNG.d.cts} +32 -2
- package/dist/{constants-D41hDAG6.d.ts → constants-Icc4CXNG.d.ts} +32 -2
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.js +1 -1
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.d.cts +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js +1 -1
- package/dist/tab/index.cjs +4 -4
- package/dist/tab/index.js +4 -4
- package/dist/tab/seller/index.cjs +2 -2
- package/dist/tab/seller/index.js +2 -2
- package/dist/utils/index.cjs +1 -1
- package/dist/utils/index.d.cts +1 -1
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.js +1 -1
- package/package.json +5 -2
package/dist/react/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useState as se,useCallback as Xe,useEffect as Tt,useMemo as De}from"react";var F="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Ee="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Ue="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",ee=F,we=Ee,Te=Ue,q="eip155:8453",ce="eip155:84532",le="eip155:42161",pe="eip155:137",de="eip155:10",ue="eip155:43114",me="eip155:56",fe="eip155:1187947933",ge="eip155:324705682",he="eip155:1",te=q,Me=ce,xe=le,be=pe,Re=de,Pe=ue,_e=me,Ce=fe,Ne=ge,Ie=he,ve="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",et="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",ke="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",He="0x55d398326f99059fF775485246999027B3197955",Le="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",We={[me]:Le,[q]:ke,[ce]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[le]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[pe]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[de]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[ue]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[fe]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[ge]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[he]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},$e={[He]:{symbol:"USDT",decimals:18},[Le]:{symbol:"USDC",decimals:18}};var z="0x000000000022D473030F116dDEE9F6B43aC78BA3",Be="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",Je={[me]:56,[q]:8453,[ce]:84532,[le]:42161,[pe]:137,[de]:10,[ue]:43114,[fe]:1187947933,[ge]:324705682,[he]:1},ne={[F]:"https://api.dexter.cash/api/solana/rpc",[Ee]:"https://api.devnet.solana.com",[Ue]:"https://api.testnet.solana.com"},W={[me]:"https://api.dexter.cash/api/evm/bsc/rpc",[q]:"https://api.dexter.cash/api/base/rpc",[ce]:"https://sepolia.base.org",[le]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[pe]:"https://api.dexter.cash/api/evm/polygon/rpc",[de]:"https://api.dexter.cash/api/evm/optimism/rpc",[ue]:"https://api.dexter.cash/api/evm/avalanche/rpc",[fe]:"https://skale-base.skalenodes.com/v1/base",[ge]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[he]:"https://eth.llamarpc.com"};var P=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 re,Connection as Ye,TransactionMessage as pt,VersionedTransaction as dt,ComputeBudgetProgram as tt}from"@solana/web3.js";import{getAssociatedTokenAddress as Ge,getAccount as ut,createTransferCheckedInstruction as mt,getMint as ft,TOKEN_PROGRAM_ID as nt,TOKEN_2022_PROGRAM_ID as qe}from"@solana/spl-token";var gt=12e3,ht=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 Ke=class{name="Solana";networks=[ee,we,Te];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]:ne[e]?ne[e]:e==="solana"?ne[ee]:e==="solana-devnet"?ne[we]:e==="solana-testnet"?ne[Te]:ne[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 a=n||this.getDefaultRpcUrl(e.network),s=new Ye(a,"confirmed"),l=new re(t.publicKey.toBase58()),o=new re(e.asset);try{let d=(await s.getAccountInfo(o,"confirmed"))?.owner.toBase58()===qe.toBase58()?qe:nt,S=await Ge(o,l,!1,d),x=await ut(s,S,void 0,d),h=e.extra?.decimals??6;return Number(x.amount)/Math.pow(10,h)}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 a=n||this.getDefaultRpcUrl(e.network),s=new Ye(a,"confirmed"),l=new re(t.publicKey.toBase58()),{payTo:o,asset:c,extra:d}=e,S=e.amount??e.maxAmountRequired;if(!S)throw new Error("Missing amount in payment requirements");if(!d?.feePayer)throw new Error("Missing feePayer in payment requirements");let x=new re(d.feePayer),h=new re(c),b=new re(o);this.log("Building transaction:",{from:l.toBase58(),to:o,amount:S,asset:c,feePayer:d.feePayer});let p=[];p.push(tt.setComputeUnitLimit({units:gt})),p.push(tt.setComputeUnitPrice({microLamports:ht}));let N=await s.getAccountInfo(h,"confirmed");if(!N)throw new Error(`Token mint ${c} not found`);let C=N.owner.toBase58()===qe.toBase58()?qe:nt,L=await ft(s,h,void 0,C);typeof d?.decimals=="number"&&L.decimals!==d.decimals&&this.log(`Decimals mismatch: requirements say ${d.decimals}, mint says ${L.decimals}`);let k=await Ge(h,l,!1,C),_=await Ge(h,b,!0,C);if(!await s.getAccountInfo(k,"confirmed"))throw new Error(`No token account found for ${c}. Please ensure you have USDC in your wallet.`);if(!await s.getAccountInfo(_,"confirmed"))throw new Error(`Seller token account not found. The seller (${o}) must have a USDC account.`);let D=BigInt(S);p.push(mt(k,h,_,l,D,L.decimals,[],C));let{blockhash:U}=await s.getLatestBlockhash("confirmed"),$=new pt({payerKey:x,recentBlockhash:U,instructions:p}).compileToV0Message(),O=new dt($),f=await t.signTransaction(O);return this.log("Transaction signed successfully"),{serialized:Buffer.from(f.serialize()).toString("base64"),settlementProbe:{kind:"solana",sourceAta:k.toBase58(),destinationAta:_.toBase58(),asset:c,amount:S,blockhash:U}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let n=new Ye(t,"confirmed"),a=new re(e.destinationAta),s=await n.getSignaturesForAddress(a,{limit:25});if(s.length===0)return{settled:!1};let l=BigInt(e.amount);for(let o of s){if(o.err)continue;let c=await n.getTransaction(o.signature,{commitment:"confirmed",maxSupportedTransactionVersion:0});if(!c?.meta)continue;let d=c.transaction.message.getAccountKeys().keySegments().flat(),S=c.meta.preTokenBalances??[],x=c.meta.postTokenBalances??[];for(let h of x){if(h.mint!==e.asset)continue;let b=d[h.accountIndex];if(!b||!b.equals(a))continue;let p=S.find(L=>L.accountIndex===h.accountIndex),N=BigInt(p?.uiTokenAmount.amount??"0");if(BigInt(h.uiTokenAmount.amount??"0")-N===l)return{settled:!0,txSignature:o.signature}}}return{settled:!1}}};function ye(r){return new Ke(r)}var yt={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"}]},rt=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function X(r){if(!r||typeof r!="object")return!1;let e=r;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var Fe=class{name="EVM";networks=[_e,te,Me,Ie,xe,be,Re,Pe,Ce,Ne];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==="skale-base"||e==="skale-base-sepolia"||e.startsWith("eip155:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:W[e]?W[e]:e==="base"?W[te]:e==="bsc"?W[_e]:e==="ethereum"?W[Ie]:e==="arbitrum"?W[xe]:e==="polygon"?W[be]:e==="optimism"?W[Re]:e==="avalanche"?W[Pe]:e==="skale-base"?W[Ce]:e==="skale-base-sepolia"?W[Ne]:W[te]}getAddress(e){return X(e)?e.address:null}isConnected(e){return X(e)?!!e.address:!1}getChainId(e){if(Je[e])return Je[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:8453}async getBalance(e,t,n){if(!X(t)||!t.address)return 0;let a=n||this.getDefaultRpcUrl(e.network);try{let s=this.encodeBalanceOf(t.address),l=await fetch(a,{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(!l.ok)throw new Error(`RPC request failed: ${l.status}`);let o=await l.json();if(o.error)throw new Error(`RPC error: ${JSON.stringify(o.error)}`);if(!o.result||o.result==="0x")return 0;let c=BigInt(o.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",a=e.from.slice(2).toLowerCase().padStart(64,"0"),s=e.nonce.slice(2).toLowerCase().padStart(64,"0"),l=n+a+s,o=await this.ethCall(t,e.asset,l);return{settled:BigInt(o)!==0n}}if(e.kind==="permit2"){let n="0x4fe02b44",a=BigInt(e.nonce),s=a>>8n,l=a&0xffn,o=e.from.slice(2).toLowerCase().padStart(64,"0"),c=s.toString(16).padStart(64,"0"),d=n+o+c,S=await this.ethCall(t,z,d);return{settled:(BigInt(S)>>l&1n)===1n}}throw new Error(`EvmAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`)}async ethCall(e,t,n){let a=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(!a.ok)throw new Error(`RPC request failed: ${a.status}`);let s=await a.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(!X(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:a,asset:s,extra:l}=e,o=e.amount??e.maxAmountRequired;if(!o)throw new Error("Missing amount in payment requirements");this.log("Building EVM transaction:",{from:t.address,to:a,amount:o,asset:s,network:e.network});let c=this.getChainId(e.network),d={name:l?.name??"USD Coin",version:l?.version??"2",chainId:BigInt(c),verifyingContract:s},S={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"}]},x=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(x);let h="0x"+[...x].map(k=>k.toString(16).padStart(2,"0")).join(""),b=Math.floor(Date.now()/1e3),p={from:t.address,to:a,value:o,validAfter:String(b-600),validBefore:String(b+(e.maxTimeoutSeconds||60)),nonce:h},N={from:t.address,to:a,value:BigInt(o),validAfter:BigInt(b-600),validBefore:BigInt(b+(e.maxTimeoutSeconds||60)),nonce:h};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let C=await t.signTypedData({domain:d,types:S,primaryType:"TransferWithAuthorization",message:N});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:p,signature:C}),signature:C,settlementProbe:{kind:"eip3009",from:t.address,nonce:h,asset:s,chainId:c}}}async buildApprovalTransaction(e,t,n){let{payTo:a,asset:s,extra:l}=e,o=e.amount??e.maxAmountRequired;if(!o)throw new Error("Missing amount in payment requirements");let c=l?.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:a,amount:o,asset:s,network:e.network,facilitatorContract:c});let d=n||this.getDefaultRpcUrl(e.network),S=l?.fee??"0",x=BigInt(o)+BigInt(S),h=await this.readAllowance(d,s,t.address,c);if(h<x){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 O=this.calculateApprovalAmount(o,S,l?.approvalStrategy);this.log(`Approving ${O} for ${c} (current allowance: ${h})`);let f=await t.sendTransaction({to:s,data:this.encodeApprove(c,O),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 b=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(b);let p=[...b].reduce((O,f)=>O*256n+BigInt(f),0n).toString(),N=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(N);let C="0x"+[...N].map(O=>O.toString(16).padStart(2,"0")).join(""),k=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),_=l?.eip712Domain,B=_?{name:_.name,version:_.version,chainId:BigInt(_.chainId),verifyingContract:_.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:c},T=l?.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"}]},D={from:t.address,to:a,token:s,amount:BigInt(o),fee:BigInt(S),nonce:BigInt(p),deadline:BigInt(k),paymentId:C},U=await t.signTypedData({domain:B,types:T,primaryType:"Payment",message:D});this.log("EIP-712 Payment signature obtained");let $={from:t.address,to:a,token:s,amount:o,fee:S,nonce:p,deadline:k,paymentId:C,signature:U};return{serialized:JSON.stringify($),signature:U}}async buildPermit2Transaction(e,t,n){let{payTo:a,asset:s}=e,l=e.amount??e.maxAmountRequired;if(!l)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:a,amount:l,asset:s,network:e.network});let o=n||this.getDefaultRpcUrl(e.network),c=await this.readAllowance(o,s,t.address,z),d;if(c<BigInt(l)){let B=this.encodeApprove(z,rt);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${c})`);let T=this.getChainId(e.network),D=await this.readGasPrice(o),U=await this.readNonce(o,t.address),$=await t.signTransaction({to:s,data:B,chainId:T,gas:50000n,gasPrice:D,nonce:U});d={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:s,spender:z,amount:rt.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 T=await t.sendTransaction({to:s,data:B,value:0n});this.log(`Permit2 approval tx sent: ${T}`),await this.waitForReceipt(o,T),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 S=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(S);let x=[...S].reduce((B,T)=>B*256n+BigInt(T),0n),h=Math.floor(Date.now()/1e3),b=h-600,p=h+(e.maxTimeoutSeconds||300),N=this.getChainId(e.network),C={name:"Permit2",chainId:BigInt(N),verifyingContract:z},L={permitted:{token:s,amount:BigInt(l)},spender:Be,nonce:x,deadline:BigInt(p),witness:{to:a,validAfter:BigInt(b)}},k=await t.signTypedData({domain:C,types:yt,primaryType:"PermitWitnessTransferFrom",message:L});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let _={signature:k,permit2Authorization:{from:t.address,permitted:{token:s,amount:l},spender:Be,nonce:x.toString(),deadline:String(p),witness:{to:a,validAfter:String(b)}}};return{serialized:JSON.stringify(_),signature:k,extensions:d,settlementProbe:{kind:"permit2",from:t.address,nonce:x.toString(),chainId:N}}}async readAllowance(e,t,n,a){let s="0xdd62ed3e",l=n.slice(2).toLowerCase().padStart(64,"0"),o=a.slice(2).toLowerCase().padStart(64,"0"),c=s+l+o;try{let S=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 S.error||!S.result||S.result==="0x"?0n:BigInt(S.result)}catch{return 0n}}encodeApprove(e,t){let n="0x095ea7b3",a=e.slice(2).toLowerCase().padStart(64,"0"),s=t.toString(16).padStart(64,"0");return n+a+s}async waitForReceipt(e,t,n=3e4){let a=Date.now();for(;Date.now()-a<n;){try{let l=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(l.result){if(l.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 a=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 a.result?parseInt(a.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,n){let a=BigInt(e)+BigInt(t);if(!n||n.mode==="exact")return a;let s=BigInt(n.defaultMultiple??10),l=a*s;if(n.maxCapUsd){let o=this.inferDecimals(e),c=BigInt(Math.floor(n.maxCapUsd*Math.pow(10,o)));if(l>c)return c}if(n.exactAboveUsd){let o=this.inferDecimals(e),c=BigInt(Math.floor(n.exactAboveUsd*Math.pow(10,o)));if(BigInt(e)>c)return a}return l}inferDecimals(e){return e.length>12?18:6}};function Ae(r){return new Fe(r)}function ze(r){if(r===ve||r===et)return!0;let e=r.toLowerCase();for(let t of Object.values(We))if(t.toLowerCase()===e)return!0;for(let t of Object.keys($e))if(t.toLowerCase()===e)return!0;return!1}function At(r){return r.startsWith("solana:")||r==="solana"}function St(r){return r.startsWith("eip155:")||["base","ethereum","arbitrum"].includes(r)}function Et(r){return At(r)?"solana":St(r)?"evm":"unknown"}function je(r){return{[F]:"Solana",[Ee]:"Solana Devnet",[Ue]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[q]:"Base",[ce]:"Base Sepolia",[he]:"Ethereum",[le]:"Arbitrum",[pe]:"Polygon",[de]:"Optimism",[ue]:"Avalanche",[me]:"BSC",[fe]:"SKALE Base",[ge]:"SKALE Base Sepolia",base:"Base","base-sepolia":"Base Sepolia",ethereum:"Ethereum",arbitrum:"Arbitrum",polygon:"Polygon",optimism:"Optimism",avalanche:"Avalanche",bsc:"BSC","skale-base":"SKALE Base","skale-base-sepolia":"SKALE Base Sepolia"}[r]||r}function st(r,e){let t=je(r);return t===r?e:t}function at(r,e){let t=Et(e);if(t==="solana")return e.includes("devnet")||e===Ee?`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==="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"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 wt(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((l,o)=>n.set(o,l));let a={method:e?.method??t.method,headers:n,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},s=(a.method??"GET").toUpperCase();return e&&"body"in e?a.body=e.body:s!=="GET"&&s!=="HEAD"&&t.body&&(a.body=await t.arrayBuffer()),[t.url,a]}var ot=new WeakMap;function it(r){return ot.get(r)}function ct(r){let{adapters:e=[ye({verbose:r.verbose}),Ae({verbose:r.verbose})],wallets:t,wallet:n,preferredNetwork:a,rpcUrls:s={},maxAmountAtomic:l,fetch:o=globalThis.fetch,verbose:c=!1,accessPass:d,onPaymentRequired:S,onPaymentDispatched:x,maxRetries:h=0,retryDelayMs:b=500}=r,p=c?console.log.bind(console,"[x402]"):()=>{};async function N(f,A){let w;for(let y=0;y<=h;y++)try{let u=await o(f,A);if(u.status>=502&&u.status<=504&&y<h){p(`Retry ${y+1}/${h}: server returned ${u.status}`),await new Promise(g=>setTimeout(g,b*Math.pow(2,y)));continue}return u}catch(u){w=u,y<h&&(p(`Retry ${y+1}/${h}: ${u instanceof Error?u.message:"network error"}`),await new Promise(g=>setTimeout(g,b*Math.pow(2,y))))}throw w}let C=new Map;function L(f){try{let A=new URL(f).host,w=C.get(A);if(w&&w.expiresAt>Date.now()/1e3+10)return w.jwt;w&&C.delete(A)}catch{}return null}function k(f,A){try{let w=new URL(f).host,y=A.split(".");if(y.length===3){let u=JSON.parse(atob(y[1].replace(/-/g,"+").replace(/_/g,"/"))),g=Math.floor(Date.now()/1e3),m=g+86400,I=Math.min(typeof u.exp=="number"?u.exp:g,m);C.set(w,{jwt:A,expiresAt:I}),p("Access pass cached for",w,"| expires:",new Date(I*1e3).toISOString())}}catch{p("Failed to cache access pass")}}let _=t||{};n&&!_.solana&&j(n)&&(_.solana=n),n&&!_.evm&&X(n)&&(_.evm=n);function B(f){let A=[];for(let w of f){let y=w.scheme??"exact";if(y!=="exact"&&y!=="exact-approval")continue;let u=e.find(m=>m.canHandle(w.network));if(!u)continue;let g;u.name==="Solana"?g=_.solana:u.name==="EVM"&&(g=_.evm),g&&u.isConnected(g)&&A.push({accept:w,adapter:u,wallet:g})}if(A.length===0)return null;if(a){let w=A.find(y=>y.accept.network===a);if(w)return w}return A[0]}function T(f,A){return st(f,A)}function D(f,A){return s[f]||A.getDefaultRpcUrl(f)}async function U(f,A,w,y,u){let g="";if(d?.preferTier&&y.tiers){let i=y.tiers.find(E=>E.id===d.preferTier);if(i){if(d.maxSpend&&parseFloat(i.price)>parseFloat(d.maxSpend))throw new P("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&&y.ratePerHour)g=`duration=${d.preferDuration}`;else if(y.tiers&&y.tiers.length>0){let i=y.tiers[0];if(d?.maxSpend&&parseFloat(i.price)>parseFloat(d.maxSpend))throw new P("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;p("Purchasing access pass:",g||"default tier");let I=w.headers.get("PAYMENT-REQUIRED");if(!I)return null;let M;try{M=JSON.parse(atob(I))}catch{return null}let R=B(M.accepts);if(!R)return null;let{accept:v,adapter:V,wallet:ae}=R;if(V.name==="Solana"&&!v.extra?.feePayer)return null;let H=v.extra?.decimals??(ze(v.asset)?6:void 0);if(typeof H!="number")return null;let Se=v.amount??v.maxAmountRequired;if(!Se)return null;let J=D(v.network,V);try{let i=await V.getBalance(v,ae,J),E=Number(Se)/Math.pow(10,H);if(i<E){let Ve=T(v.network,V.name);throw new P("insufficient_balance",`Insufficient balance for access pass on ${Ve}. Have $${i.toFixed(4)}, need $${E.toFixed(4)}`)}}catch(i){if(i instanceof P)throw i}let Y=await V.buildTransaction(v,ae,J),oe;V.name==="EVM"?oe=JSON.parse(Y.serialized):oe={transaction:Y.serialized};let Q=typeof f=="string"?f:f instanceof URL?f.href:f.url,ie=M.resource;if(typeof M.resource=="string")try{let i=new URL(M.resource,Q);["http:","https:"].includes(i.protocol)&&(ie=i.toString())}catch{}else if(M.resource&&typeof M.resource=="object"&&"url"in M.resource){let i=M.resource;try{let E=new URL(i.url,Q);["http:","https:"].includes(E.protocol)&&(ie={...i,url:E.toString()})}catch{}}let Oe={x402Version:v.x402Version??2,resource:ie,accepted:v,payload:oe};Y.extensions&&(Oe.extensions=Y.extensions);let G=btoa(JSON.stringify(Oe)),Z=await o(m,{...A,method:"POST",headers:{...A?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":G}});if(!Z.ok)return p("Pass purchase failed:",Z.status),null;let K=Z.headers.get("ACCESS-PASS");return K&&(k(u,K),p("Access pass purchased and cached")),Z}async function $(f,A){let w=f;if(p("Making request:",w),d){let i=L(w);if(i){p("Using cached access pass");let E=await o(f,{...A,headers:{...A?.headers||{},Authorization:`Bearer ${i}`}});if(E.status!==401&&E.status!==402)return E;p("Cached pass rejected (status",E.status,"), purchasing new pass");try{C.delete(new URL(w).host)}catch{}}}let y=await N(f,A);if(y.status!==402)return y;p("Received 402 Payment Required");let u=y.headers.get("X-ACCESS-PASS-TIERS");if(d&&u){p("Server offers access passes, purchasing...");try{let i=JSON.parse(atob(u)),E=await U(f,A,y,i,w);if(E)return E}catch(i){p("Access pass purchase failed, falling back to per-request payment:",i)}}let g=y.headers.get("PAYMENT-REQUIRED");if(!g)throw new P("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 P("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}p("Payment requirements:",m);let I=y.headers.get("X-Quote-Hash");I&&p("Quote hash received:",I);let M=B(m.accepts);if(!M){let i=m.accepts.map(E=>E.network).join(", ");throw new P("no_matching_payment_option",`No connected wallet for any available network: ${i}`)}let{accept:R,adapter:v,wallet:V}=M;if(p(`Using ${v.name} for ${R.network}`),v.name==="Solana"&&!R.extra?.feePayer)throw new P("missing_fee_payer","Solana payment option missing feePayer in extra");let ae=R.extra?.decimals??(ze(R.asset)?6:void 0);if(typeof ae!="number")throw new P("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let H=R.amount??R.maxAmountRequired;if(!H)throw new P("missing_amount","Payment option missing amount");if(l&&BigInt(H)>BigInt(l))throw new P("amount_exceeds_max",`Payment amount ${H} exceeds maximum ${l}`);let Se=D(R.network,v);p("Checking balance...");try{let i=await v.getBalance(R,V,Se),E=Number(H)/Math.pow(10,ae);if(i<E){let Ve=T(R.network,v.name);throw new P("insufficient_balance",`Insufficient balance on ${Ve}. Have $${i.toFixed(4)}, need $${E.toFixed(4)}`)}p(`Balance OK: $${i.toFixed(4)} >= $${E.toFixed(4)}`)}catch(i){if(i instanceof P)throw i;p("Balance check failed (RPC error), proceeding with transaction attempt")}if(S&&!await S(R))throw new P("payment_rejected","Payment rejected by onPaymentRequired callback");p("Building transaction...");let J=await v.buildTransaction(R,V,Se);p("Transaction signed");let Y;v.name==="EVM"?Y=JSON.parse(J.serialized):Y={transaction:J.serialized};let oe=f,Q=m.resource;if(typeof m.resource=="string")try{let i=new URL(m.resource,oe).toString();i!==m.resource&&p("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 E=new URL(i.url,oe).toString();E!==i.url&&(p("Resolved relative resource URL:",i.url,"\u2192",E),Q={...i,url:E})}catch{}}let ie={x402Version:R.x402Version??2,resource:Q,accepted:R,payload:Y};J.extensions&&(ie.extensions=J.extensions);let Oe=btoa(JSON.stringify(ie));if(x)try{x(R,J.settlementProbe)}catch{}p("Retrying request with payment...");let G=await N(f,{...A,headers:{...A?.headers||{},"PAYMENT-SIGNATURE":Oe,...I?{"X-Quote-Hash":I}:{}}});if(p("Retry response status:",G.status),G.status===402){let i="unknown";try{let E=await G.clone().json();i=String(E.error||E.message||JSON.stringify(E)),p("Rejection reason:",i)}catch{}throw new P("payment_rejected",`Payment was rejected by the server: ${i}`)}let Z=G.headers.get("PAYMENT-RESPONSE"),K;if(Z)try{K=JSON.parse(atob(Z))}catch{}return K??={},K.amountAtomic=H,K.assetDecimals=ae,ot.set(G,K),K.extensions&&p("Settlement extensions:",Object.keys(K.extensions).join(", ")),G}async function O(f,A){let[w,y]=await wt(f,A);return $(w,y)}return{fetch:O}}function lt(r){let e=it(r);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function Qe(r){let e=lt(r);if(e?.recommendations?.length)return e.recommendations}async function Ze(r){let t=lt(r)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function xt(r){let{wallets:e,wallet:t,preferredNetwork:n,rpcUrls:a={},verbose:s=!1}=r,[l,o]=se(!1),[c,d]=se("idle"),[S,x]=se(null),[h,b]=se(null),[p,N]=se(null),[C,L]=se([]),[k,_]=se(null),B=Xe((...u)=>{s&&console.log("[useX402Payment]",...u)},[s]),T=De(()=>{let u={...e};return t&&!u.solana&&j(t)&&(u.solana=t),t&&!u.evm&&X(t)&&(u.evm=t),u},[e,t]),D=De(()=>[ye({verbose:s,rpcUrls:a}),Ae({verbose:s,rpcUrls:a})],[s,a]),U=De(()=>({solana:T.solana?j(T.solana)&&D[0].isConnected(T.solana):!1,evm:T.evm?X(T.evm)&&D[1].isConnected(T.evm):!1}),[T,D]),$=U.solana||U.evm,O=Xe(async()=>{let u=[];if(U.solana&&T.solana)try{let g=D.find(m=>m.name==="Solana");if(g){let m={scheme:"exact",network:F,amount:"0",asset:ve,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},I=await g.getBalance(m,T.solana);u.push({network:F,chainName:je(F),balance:I,asset:"USDC"})}}catch(g){B("Failed to fetch Solana balance:",g)}if(U.evm&&T.evm)try{let g=D.find(m=>m.name==="EVM");if(g){let m={scheme:"exact",network:q,amount:"0",asset:ke,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},I=await g.getBalance(m,T.evm);u.push({network:q,chainName:je(q),balance:I,asset:"USDC"})}}catch(g){B("Failed to fetch Base balance:",g)}L(u)},[U,T,D,B]);Tt(()=>{O();let u=setInterval(O,3e4);return()=>clearInterval(u)},[O]);let f=Xe(()=>{o(!1),d("idle"),x(null),b(null),N(null),_(null)},[]),A=De(()=>ct({adapters:D,wallets:T,preferredNetwork:n,rpcUrls:a,verbose:s}),[D,T,n,a,s]),w=Xe(async(u,g)=>{if(o(!0),d("pending"),x(null),b(null),N(null),!$){let m=new P("wallet_not_connected","No wallet connected");throw x(m),d("error"),o(!1),m}try{let m=await A.fetch(u,g),I=m.headers.get("PAYMENT-RESPONSE");if(I)try{let R=JSON.parse(atob(I));R.transaction&&b(R.transaction),R.network&&N(R.network)}catch{B("Could not parse PAYMENT-RESPONSE header")}let M=Qe(m);return _(M??null),M&&(B("Sponsored recommendations received:",M.length),Ze(m).catch(()=>{})),d("success"),m}catch(m){let I=m instanceof Error?m:new Error(String(m));throw x(I),d("error"),m}finally{o(!1),setTimeout(O,2e3)}},[A,$,B,O]),y=De(()=>h?at(h,p||n||F):null,[h,p,n]);return{fetch:w,isLoading:l,status:c,error:S,transactionId:h,transactionNetwork:p,transactionUrl:y,balances:C,connectedChains:U,isAnyWalletConnected:$,reset:f,refreshBalances:O,accessPass:null,sponsoredRecommendations:k}}export{P as X402Error,Ze as fireImpressionBeacon,Qe as getSponsoredRecommendations,xt 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",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};
|
package/dist/server/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var se=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var $e=Object.prototype.hasOwnProperty;var Ke=(e,t)=>{for(var s in t)se(e,s,{get:t[s],enumerable:!0})},He=(e,t,s,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of qe(t))!$e.call(e,n)&&n!==s&&se(e,n,{get:()=>t[n],enumerable:!(r=Le(t,n))||r.enumerable});return e};var Fe=e=>He(se({},"__esModule",{value:!0}),e);var st={};Ke(st,{BASE_MAINNET_NETWORK:()=>I,DEXTER_FACILITATOR_URL:()=>D,FacilitatorClient:()=>B,SOLANA_MAINNET_NETWORK:()=>N,SPONSORED_ACCESS_EXTENSION_KEY:()=>Be.SPONSORED_ACCESS_EXTENSION_KEY,USDC_BASE:()=>Q,USDC_MINT:()=>U,bazaarExtension:()=>Ie,createX402Server:()=>te,declareDiscoveryExtension:()=>Ue,resolveDefaultAsset:()=>oe,x402Middleware:()=>De});module.exports=Fe(st);var N="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",le="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",de="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";var I="eip155:8453",F="eip155:84532",W="eip155:42161",j="eip155:137",V="eip155:10",X="eip155:43114",z="eip155:56",J="eip155:1187947933",Y="eip155:324705682",G="eip155:1";var U="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";var Q="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",We="0x55d398326f99059fF775485246999027B3197955",me="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",fe={[z]:me,[I]:Q,[F]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[W]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[j]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[V]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[X]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[J]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[Y]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[G]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},ye={[We]:{symbol:"USDT",decimals:18},[me]:{symbol:"USDC",decimals:18}};var it={[z]:56,[I]:8453,[F]:84532,[W]:42161,[j]:137,[V]:10,[X]:43114,[J]:1187947933,[Y]:324705682,[G]:1},at={[N]:"https://api.dexter.cash/api/solana/rpc",[le]:"https://api.devnet.solana.com",[de]:"https://api.testnet.solana.com"},ct={[z]:"https://api.dexter.cash/api/evm/bsc/rpc",[I]:"https://api.dexter.cash/api/base/rpc",[F]:"https://sepolia.base.org",[W]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[j]:"https://api.dexter.cash/api/evm/polygon/rpc",[V]:"https://api.dexter.cash/api/evm/optimism/rpc",[X]:"https://api.dexter.cash/api/evm/avalanche/rpc",[J]:"https://skale-base.skalenodes.com/v1/base",[Y]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[G]:"https://eth.llamarpc.com"},D="https://x402.dexter.cash",he=N;function ge(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=je(Math.abs(e)),[r,n=""]=s.split("."),a=n.slice(0,t).padEnd(t,"0");return BigInt(r+a).toString()}function je(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("."),l=m+f,g=m.length+n,o;return g<=0?o="0."+"0".repeat(-g)+l:g>=l.length?o=l+"0".repeat(g-l.length):o=l.slice(0,g)+"."+l.slice(g),(a?"-":"")+o}function Z(e){return e.startsWith("solana:")||e==="solana"}function Ve(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 Xe(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 ee(e){return Ve(JSON.stringify(e))}function $(e){return JSON.parse(Xe(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 K=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 K(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=$(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 K?`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=$(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 K?`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 oe(e){if(Z(e))return{address:U,decimals:6};let t=fe[e];if(t){let s=ye[t]?.decimals??6;return{address:t,decimals:s}}return{address:U,decimals:6}}function xe(e){try{let t=$(e);return t?.accepted?.amount??t?.accepted?.maxAmountRequired}catch{return}}function te(e){let{payTo:t,facilitatorUrl:s=D,network:r=N,defaultTimeoutSeconds:n=60}=e,a=e.asset??oe(r),p=e.scheme??"exact";if(p==="tab"&&!Z(r))throw new Error(`scheme 'tab' is SVM-only; got network "${r}"`);let m=new B(s),f=null,l=new Map,g=3e4,o=Date.now();function y(i){let u=(i.maxTimeoutSeconds||n)*1e3;if(l.set(i.payTo,{accept:i,expiresAt:Date.now()+u}),Date.now()-o>g){let h=Date.now();for(let[S,_]of l)_.expiresAt<h&&l.delete(S);o=h}}function E(i){let u=l.get(i);if(u){if(u.expiresAt<Date.now()){l.delete(i);return}return u.accept}}async function x(i){return typeof t=="string"?t:t(i||{})}async function b(){if(f||(f=await m.getNetworkExtra(r)),Z(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 k(i,u){let{amountAtomic:h,timeoutSeconds:S=n}=u,_=await b(),O={scheme:p,network:r,amount:h,maxAmountRequired:h,asset:a.address,payTo:i,maxTimeoutSeconds:S,extra:_};return y(O),O}async function C(i){let u=await x({amountAtomic:i.amountAtomic,resourceUrl:i.resourceUrl});return k(u,i)}async function v(i){let{resourceUrl:u,description:h,mimeType:S="application/json"}=i,_={url:u,description:h,mimeType:S},O=await C(i);return{x402Version:2,resource:_,accepts:[O],error:"Payment required"}}function R(i){return ee(i)}function c(i){return{status:402,headers:{"PAYMENT-REQUIRED":R(i)},body:{}}}async function d(i,u){if(!u){let h=await x({paymentHeader:i});u=E(h),u||(u=await k(h,{amountAtomic:xe(i)??"0",resourceUrl:""}))}return m.verifyPayment(i,u)}async function A(i,u){if(!u){let h=await x({paymentHeader:i});u=E(h),u||(u=await k(h,{amountAtomic:xe(i)??"0",resourceUrl:""}))}return m.settlePayment(i,u)}return{buildRequirements:v,encodeRequirements:R,create402Response:c,verifyPayment:d,settlePayment:A,getPaymentAccept:C,network:r,assetDecimals:a.decimals,facilitator:m}}var Je=new WeakMap;function Se(e){return Je.get(e)}var _e=require("os"),we=require("path"),Ce=require("@x402/evm/batch-settlement/server");var re=require("@x402/core/server"),Ee=require("@x402/core/http"),Re=require("@x402/evm/batch-settlement/server");function Ae(e){let t=e.verbose?console.log.bind(console,"[batch-settlement:seller]"):()=>{},s=new re.HTTPFacilitatorClient({url:e.facilitatorUrl}),r=new Re.BatchSettlementEvmScheme(e.payTo,{storage:e.channelStore}),n=new re.x402ResourceServer(s).register(e.network,r),a=new Ee.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 l(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}`||"/",k={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"],v={adapter:k,path:b,method:o.method,paymentHeader:C},R=await a.processHTTPRequest(v);if(t("processHTTPRequest ->",R.type),R.type==="no-payment-required"){E();return}if(R.type==="payment-error"){l(y,R.response);return}let c={request:v,responseBody:Buffer.alloc(0)},d=await a.processSettlement(R.paymentPayload,R.paymentRequirements,R.declaredExtensions,c);if(t("processSettlement ->",d.success?"success":`failure:${d.errorReason}`),!d.success){l(y,d.response);return}for(let[A,i]of Object.entries(d.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 ie=require("viem"),Pe=6;async function ae(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:l}=await t.claimAndSettle(),g=await t.refund([r]),o=g.find(y=>y.channel===r)??g[0];return{claimTx:f[0]?.transaction??"",settleTx:l?.transaction??"",refundTx:o?.transaction??"",settledAmount:(0,ie.formatUnits)(a,Pe),refundedAmount:(0,ie.formatUnits)(m,Pe)}}async function Te(e){let t=await e.store.list(),s=[];for(let r of t)try{let n=await ae({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 be(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 Ye="https://x402.dexter.cash",Ge="GET /",ve=new Set(["eip155:8453","eip155:42161","eip155:137"]);function Qe(e){return e===!1?null:e===void 0||e===!0?3e5:(e.claimIntervalSecs??300)*1e3}function ce(e){if(!ve.has(e.network))throw new Error(`batch-settlement is not supported on network "${e.network}" \u2014 supported: ${[...ve].join(", ")}`);let t=e.facilitatorUrl??Ye,s=e.channelStore??new Ce.FileChannelStorage({directory:(0,we.join)((0,_e.homedir)(),".dexter-x402","seller-channels")}),r=Ae({payTo:e.payTo,network:e.network,price:e.price,route:e.route??Ge,facilitatorUrl:t,channelStore:s,verbose:e.verbose}),n=r.scheme.createChannelManager(r.facilitator,e.network),a=async()=>{await n.claimAndSettle()},p=Qe(e.autoSettle),m=null;p!==null&&(m=be({claimAndSettle:a,claimIntervalMs:p,onError:o=>console.error("[batch-settlement:seller] auto-loop claim pass failed",o)}));let f=s,l=(o,y,E)=>{r.handler(o,y,E)},g=l;return g.middleware=()=>l,g.closeChannel=o=>ae({manager:n,store:f,channelId:o}),g.closeAll=()=>Te({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 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 De(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 d=typeof e.payTo=="string"?e.payTo:void 0;if(!d)throw new Error('x402Middleware: scheme "batch-settlement" requires a string payTo address');return ce({payTo:d,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:l,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,k=e.facilitatorUrl??b?.facilitatorUrl,C=e.network?Array.isArray(e.network)?e.network:[e.network]:b?.network?[b.network]:[he],v=new Map;for(let c of C){let d=Ze(t,c);if(typeof d=="function"){let A=Se(d);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.`)}v.set(c,te({payTo:d,network:c,asset:r,facilitatorUrl:k,defaultTimeoutSeconds:m,scheme:e.scheme}))}let R=v.get(C[0]);return async(c,d,A)=>{try{let i=c.headers["payment-signature"];if(!i){x("No payment signature, returning 402");let M=l?.(c)??a??`${c.protocol}://${c.get("host")}${c.originalUrl}`,T=g?.(c)??s,L=o?.(c)??n,pe=parseFloat(T),w=[],P=null;for(let[,q]of v)try{let ne={amountAtomic:ge(pe,q.assetDecimals),resourceUrl:M,description:L,mimeType:p,timeoutSeconds:m},ue=await q.buildRequirements(ne);w.push(...ue.accepts),P||(P=ue)}catch(ne){x("Failed to build requirements for a network:",ne)}if(!P||w.length===0){d.status(500).json({error:"Failed to build payment requirements"});return}if(P={...P,accepts:w},y&&y.length>0){let q=await Ne(y,E??{},{response:P,request:{method:c.method,path:(c.baseUrl??"")+(c.route?.path??c.path),params:c.params}});q&&(P={...P,extensions:q})}let Me=R.encodeRequirements(P);d.setHeader("PAYMENT-REQUIRED",Me),d.status(402).json({error:"Payment required",accepts:P.accepts,resource:P.resource,...P.extensions?{extensions:P.extensions}:{}});return}x("Payment signature received, verifying...");let u=R;try{let T=JSON.parse(Buffer.from(i,"base64").toString())?.accepted?.network;T&&v.has(T)&&(u=v.get(T))}catch{}let h=await u.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{}d.status(402).json({error:"Payment verification failed",reason:h.invalidReason});return}x("Payment verified, settling...");let S=await u.settlePayment(i);if(!S.success){x("Payment settlement failed:",S.errorReason),d.status(402).json({error:"Payment settlement failed",reason:S.errorReason});return}x("Payment settled:",S.transaction);let _=S.network||C[0];if(e.onSettlement)try{await e.onSettlement({transaction:S.transaction,network:_,payer:h.payer??"",resourceUrl:`${c.protocol}://${c.get("host")}${c.originalUrl}`})}catch{}c.x402={transaction:S.transaction,payer:h.payer??"",network:_};let O={success:!0,transaction:S.transaction,network:_,payer:h.payer??""};if(S.extensions&&(O.extensions=S.extensions),d.setHeader("PAYMENT-RESPONSE",ee(O)),e.sponsoredAccess&&S.extensions?.["sponsored-access"]){let M=S.extensions["sponsored-access"],T=M?.info?.recommendations??M?.recommendations;if(T&&T.length>0){if(x("Injecting sponsored-access recommendations into response"),typeof e.sponsoredAccess=="object"&&e.sponsoredAccess.onMatch)try{e.sponsoredAccess.onMatch(T,{transaction:S.transaction,network:_,payer:h.payer??""})}catch{}let L=d.json.bind(d);d.json=function(w){return typeof e.sponsoredAccess=="object"&&e.sponsoredAccess.inject?L(e.sponsoredAccess.inject(w,T)):w&&typeof w=="object"&&!Array.isArray(w)?L({_x402_sponsored:T,...w}):L(w)}}}A()}catch(i){x("Middleware error:",i),d.status(500).json({error:"Payment processing error"})}}}var et=/^\/[a-zA-Z0-9_/:.\-~%]+$/;function ke(e){if(!e||!et.test(e))return!1;let t;try{t=decodeURIComponent(e)}catch{return!1}return!(t.includes("..")||t.includes("://"))}function H(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};H(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=H(e)?rt:tt,p={type:{type:"string",const:"http"},method:{type:"string",enum:a}};H(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:H(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"]},l={info:{input:r,...n?{output:n}:{}},schema:f};return ke(t.routeTemplate)&&(l.routeTemplate=t.routeTemplate),l}var nt=["GET","HEAD","DELETE","POST","PUT","PATCH"];function Ie(){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 Ue(e){return{bazaar:e}}var Be=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 $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});
|
package/dist/server/index.d.cts
CHANGED
|
@@ -5,7 +5,7 @@ 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
7
|
import { B as BatchSettlementSeller } from '../types-WMqs5xII.cjs';
|
|
8
|
-
export { b as BASE_MAINNET_NETWORK, D as DEXTER_FACILITATOR_URL, a as SOLANA_MAINNET_NETWORK, c as USDC_BASE, U as USDC_MINT } from '../constants-
|
|
8
|
+
export { b as BASE_MAINNET_NETWORK, D as DEXTER_FACILITATOR_URL, a as SOLANA_MAINNET_NETWORK, c as USDC_BASE, U as USDC_MINT } from '../constants-Icc4CXNG.cjs';
|
|
9
9
|
import '../types-BdS_uvNs.cjs';
|
|
10
10
|
import '@x402/evm/batch-settlement/client';
|
|
11
11
|
|
package/dist/server/index.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ 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
7
|
import { B as BatchSettlementSeller } from '../types-DY8xKheW.js';
|
|
8
|
-
export { b as BASE_MAINNET_NETWORK, D as DEXTER_FACILITATOR_URL, a as SOLANA_MAINNET_NETWORK, c as USDC_BASE, U as USDC_MINT } from '../constants-
|
|
8
|
+
export { b as BASE_MAINNET_NETWORK, D as DEXTER_FACILITATOR_URL, a as SOLANA_MAINNET_NETWORK, c as USDC_BASE, U as USDC_MINT } from '../constants-Icc4CXNG.js';
|
|
9
9
|
import '../types-_wdHzVG-.js';
|
|
10
10
|
import '@x402/evm/batch-settlement/client';
|
|
11
11
|
|
package/dist/server/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var k="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",ae="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",ce="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";var I="eip155:8453",F="eip155:84532",W="eip155:42161",j="eip155:137",V="eip155:10",X="eip155:43114",z="eip155:56",J="eip155:1187947933",Y="eip155:324705682",G="eip155:1";var L="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";var te="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",_e="0x55d398326f99059fF775485246999027B3197955",pe="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",ue={[z]:pe,[I]:te,[F]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[W]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[j]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[V]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[X]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[J]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[Y]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[G]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},le={[_e]:{symbol:"USDT",decimals:18},[pe]:{symbol:"USDC",decimals:18}};var Ge={[z]:56,[I]:8453,[F]:84532,[W]:42161,[j]:137,[V]:10,[X]:43114,[J]:1187947933,[Y]:324705682,[G]:1},Qe={[k]:"https://api.dexter.cash/api/solana/rpc",[ae]:"https://api.devnet.solana.com",[ce]:"https://api.testnet.solana.com"},Ze={[z]:"https://api.dexter.cash/api/evm/bsc/rpc",[I]:"https://api.dexter.cash/api/base/rpc",[F]:"https://sepolia.base.org",[W]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[j]:"https://api.dexter.cash/api/evm/polygon/rpc",[V]:"https://api.dexter.cash/api/evm/optimism/rpc",[X]:"https://api.dexter.cash/api/evm/avalanche/rpc",[J]:"https://skale-base.skalenodes.com/v1/base",[Y]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[G]:"https://eth.llamarpc.com"},O="https://x402.dexter.cash",de=k;function me(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=we(Math.abs(e)),[r,n=""]=s.split("."),a=n.slice(0,t).padEnd(t,"0");return BigInt(r+a).toString()}function we(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("."),l=m+f,g=m.length+n,o;return g<=0?o="0."+"0".repeat(-g)+l:g>=l.length?o=l+"0".repeat(g-l.length):o=l.slice(0,g)+"."+l.slice(g),(a?"-":"")+o}function Q(e){return e.startsWith("solana:")||e==="solana"}function Ce(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 Ne(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 Z(e){return Ce(JSON.stringify(e))}function q(e){return JSON.parse(Ne(e))}function De(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 $=class extends Error{status;body;constructor(t,s){super(`HTTP ${t}`),this.status=t,this.body=s}},K=class{facilitatorUrl;cachedSupported=null;cacheTime=0;CACHE_TTL_MS=6e4;timeoutMs;maxRetries;retryBaseMs;constructor(t=O,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 $(a.status,await a.text());return a}catch(a){if(r=a,n<this.maxRetries-1&&De(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=q(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 $?`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=q(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 $?`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 ye(e){if(Q(e))return{address:L,decimals:6};let t=ue[e];if(t){let s=le[t]?.decimals??6;return{address:t,decimals:s}}return{address:L,decimals:6}}function fe(e){try{let t=q(e);return t?.accepted?.amount??t?.accepted?.maxAmountRequired}catch{return}}function re(e){let{payTo:t,facilitatorUrl:s=O,network:r=k,defaultTimeoutSeconds:n=60}=e,a=e.asset??ye(r),p=e.scheme??"exact";if(p==="tab"&&!Q(r))throw new Error(`scheme 'tab' is SVM-only; got network "${r}"`);let m=new K(s),f=null,l=new Map,g=3e4,o=Date.now();function y(i){let u=(i.maxTimeoutSeconds||n)*1e3;if(l.set(i.payTo,{accept:i,expiresAt:Date.now()+u}),Date.now()-o>g){let h=Date.now();for(let[S,_]of l)_.expiresAt<h&&l.delete(S);o=h}}function E(i){let u=l.get(i);if(u){if(u.expiresAt<Date.now()){l.delete(i);return}return u.accept}}async function x(i){return typeof t=="string"?t:t(i||{})}async function b(){if(f||(f=await m.getNetworkExtra(r)),Q(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,u){let{amountAtomic:h,timeoutSeconds:S=n}=u,_=await b(),D={scheme:p,network:r,amount:h,maxAmountRequired:h,asset:a.address,payTo:i,maxTimeoutSeconds:S,extra:_};return y(D),D}async function C(i){let u=await x({amountAtomic:i.amountAtomic,resourceUrl:i.resourceUrl});return N(u,i)}async function v(i){let{resourceUrl:u,description:h,mimeType:S="application/json"}=i,_={url:u,description:h,mimeType:S},D=await C(i);return{x402Version:2,resource:_,accepts:[D],error:"Payment required"}}function R(i){return Z(i)}function c(i){return{status:402,headers:{"PAYMENT-REQUIRED":R(i)},body:{}}}async function d(i,u){if(!u){let h=await x({paymentHeader:i});u=E(h),u||(u=await N(h,{amountAtomic:fe(i)??"0",resourceUrl:""}))}return m.verifyPayment(i,u)}async function A(i,u){if(!u){let h=await x({paymentHeader:i});u=E(h),u||(u=await N(h,{amountAtomic:fe(i)??"0",resourceUrl:""}))}return m.settlePayment(i,u)}return{buildRequirements:v,encodeRequirements:R,create402Response:c,verifyPayment:d,settlePayment:A,getPaymentAccept:C,network:r,assetDecimals:a.decimals,facilitator:m}}var ke=new WeakMap;function he(e){return ke.get(e)}import{homedir as Me}from"os";import{join as Le}from"path";import{FileChannelStorage as qe}from"@x402/evm/batch-settlement/server";import{HTTPFacilitatorClient as Oe,x402ResourceServer as Ie}from"@x402/core/server";import{x402HTTPResourceServer as Ue}from"@x402/core/http";import{BatchSettlementEvmScheme as Be}from"@x402/evm/batch-settlement/server";function ge(e){let t=e.verbose?console.log.bind(console,"[batch-settlement:seller]"):()=>{},s=new Oe({url:e.facilitatorUrl}),r=new Be(e.payTo,{storage:e.channelStore}),n=new Ie(s).register(e.network,r),a=new Ue(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 l(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"],v={adapter:N,path:b,method:o.method,paymentHeader:C},R=await a.processHTTPRequest(v);if(t("processHTTPRequest ->",R.type),R.type==="no-payment-required"){E();return}if(R.type==="payment-error"){l(y,R.response);return}let c={request:v,responseBody:Buffer.alloc(0)},d=await a.processSettlement(R.paymentPayload,R.paymentRequirements,R.declaredExtensions,c);if(t("processSettlement ->",d.success?"success":`failure:${d.errorReason}`),!d.success){l(y,d.response);return}for(let[A,i]of Object.entries(d.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 xe}from"viem";var Se=6;async function ne(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:l}=await t.claimAndSettle(),g=await t.refund([r]),o=g.find(y=>y.channel===r)??g[0];return{claimTx:f[0]?.transaction??"",settleTx:l?.transaction??"",refundTx:o?.transaction??"",settledAmount:xe(a,Se),refundedAmount:xe(m,Se)}}async function Ee(e){let t=await e.store.list(),s=[];for(let r of t)try{let n=await ne({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 Re(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 $e="https://x402.dexter.cash",Ke="GET /",Ae=new Set(["eip155:8453","eip155:42161","eip155:137"]);function He(e){return e===!1?null:e===void 0||e===!0?3e5:(e.claimIntervalSecs??300)*1e3}function se(e){if(!Ae.has(e.network))throw new Error(`batch-settlement is not supported on network "${e.network}" \u2014 supported: ${[...Ae].join(", ")}`);let t=e.facilitatorUrl??$e,s=e.channelStore??new qe({directory:Le(Me(),".dexter-x402","seller-channels")}),r=ge({payTo:e.payTo,network:e.network,price:e.price,route:e.route??Ke,facilitatorUrl:t,channelStore:s,verbose:e.verbose}),n=r.scheme.createChannelManager(r.facilitator,e.network),a=async()=>{await n.claimAndSettle()},p=He(e.autoSettle),m=null;p!==null&&(m=Re({claimAndSettle:a,claimIntervalMs:p,onError:o=>console.error("[batch-settlement:seller] auto-loop claim pass failed",o)}));let f=s,l=(o,y,E)=>{r.handler(o,y,E)},g=l;return g.middleware=()=>l,g.closeChannel=o=>ne({manager:n,store:f,channelId:o}),g.closeAll=()=>Ee({manager:n,store:f}),g.stop=async()=>{m&&await m.stop()},g}async function Pe(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 Fe(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 We(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 d=typeof e.payTo=="string"?e.payTo:void 0;if(!d)throw new Error('x402Middleware: scheme "batch-settlement" requires a string payTo address');return se({payTo:d,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:l,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]:[de],v=new Map;for(let c of C){let d=Fe(t,c);if(typeof d=="function"){let A=he(d);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.`)}v.set(c,re({payTo:d,network:c,asset:r,facilitatorUrl:N,defaultTimeoutSeconds:m,scheme:e.scheme}))}let R=v.get(C[0]);return async(c,d,A)=>{try{let i=c.headers["payment-signature"];if(!i){x("No payment signature, returning 402");let U=l?.(c)??a??`${c.protocol}://${c.get("host")}${c.originalUrl}`,T=g?.(c)??s,B=o?.(c)??n,oe=parseFloat(T),w=[],P=null;for(let[,M]of v)try{let ee={amountAtomic:me(oe,M.assetDecimals),resourceUrl:U,description:B,mimeType:p,timeoutSeconds:m},ie=await M.buildRequirements(ee);w.push(...ie.accepts),P||(P=ie)}catch(ee){x("Failed to build requirements for a network:",ee)}if(!P||w.length===0){d.status(500).json({error:"Failed to build payment requirements"});return}if(P={...P,accepts:w},y&&y.length>0){let M=await Pe(y,E??{},{response:P,request:{method:c.method,path:(c.baseUrl??"")+(c.route?.path??c.path),params:c.params}});M&&(P={...P,extensions:M})}let ve=R.encodeRequirements(P);d.setHeader("PAYMENT-REQUIRED",ve),d.status(402).json({error:"Payment required",accepts:P.accepts,resource:P.resource,...P.extensions?{extensions:P.extensions}:{}});return}x("Payment signature received, verifying...");let u=R;try{let T=JSON.parse(Buffer.from(i,"base64").toString())?.accepted?.network;T&&v.has(T)&&(u=v.get(T))}catch{}let h=await u.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{}d.status(402).json({error:"Payment verification failed",reason:h.invalidReason});return}x("Payment verified, settling...");let S=await u.settlePayment(i);if(!S.success){x("Payment settlement failed:",S.errorReason),d.status(402).json({error:"Payment settlement failed",reason:S.errorReason});return}x("Payment settled:",S.transaction);let _=S.network||C[0];if(e.onSettlement)try{await e.onSettlement({transaction:S.transaction,network:_,payer:h.payer??"",resourceUrl:`${c.protocol}://${c.get("host")}${c.originalUrl}`})}catch{}c.x402={transaction:S.transaction,payer:h.payer??"",network:_};let D={success:!0,transaction:S.transaction,network:_,payer:h.payer??""};if(S.extensions&&(D.extensions=S.extensions),d.setHeader("PAYMENT-RESPONSE",Z(D)),e.sponsoredAccess&&S.extensions?.["sponsored-access"]){let U=S.extensions["sponsored-access"],T=U?.info?.recommendations??U?.recommendations;if(T&&T.length>0){if(x("Injecting sponsored-access recommendations into response"),typeof e.sponsoredAccess=="object"&&e.sponsoredAccess.onMatch)try{e.sponsoredAccess.onMatch(T,{transaction:S.transaction,network:_,payer:h.payer??""})}catch{}let B=d.json.bind(d);d.json=function(w){return typeof e.sponsoredAccess=="object"&&e.sponsoredAccess.inject?B(e.sponsoredAccess.inject(w,T)):w&&typeof w=="object"&&!Array.isArray(w)?B({_x402_sponsored:T,...w}):B(w)}}}A()}catch(i){x("Middleware error:",i),d.status(500).json({error:"Payment processing error"})}}}var je=/^\/[a-zA-Z0-9_/:.\-~%]+$/;function Te(e){if(!e||!je.test(e))return!1;let t;try{t=decodeURIComponent(e)}catch{return!1}return!(t.includes("..")||t.includes("://"))}function H(e){return e.method==="POST"||e.method==="PUT"||e.method==="PATCH"}var Ve=["GET","HEAD","DELETE"],Xe=["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};H(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=H(e)?Xe:Ve,p={type:{type:"string",const:"http"},method:{type:"string",enum:a}};H(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:H(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"]},l={info:{input:r,...n?{output:n}:{}},schema:f};return Te(t.routeTemplate)&&(l.routeTemplate=t.routeTemplate),l}var ze=["GET","HEAD","DELETE","POST","PUT","PATCH"];function Je(){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 be(n,{pathParams:t.request.params,routeTemplate:t.request.path})}}}function Ye(e){return{bazaar:e}}import{SPONSORED_ACCESS_EXTENSION_KEY as nr}from"@dexterai/x402-ads-types";export{I as BASE_MAINNET_NETWORK,O as DEXTER_FACILITATOR_URL,K as FacilitatorClient,k as SOLANA_MAINNET_NETWORK,nr as SPONSORED_ACCESS_EXTENSION_KEY,te as USDC_BASE,L as USDC_MINT,Je as bazaarExtension,re as createX402Server,Ye as declareDiscoveryExtension,ye as resolveDefaultAsset,We as x402Middleware};
|
|
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};
|