@dexterai/x402 3.8.1 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{useState as pe,useCallback as He,useEffect as Rt,useMemo as Oe}from"react";var Z="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",we="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Ue="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",oe=Z,Te=we,xe=Ue,z="eip155:8453",ue="eip155:84532",de="eip155:42161",fe="eip155:137",me="eip155:10",ge="eip155:43114",he="eip155:56",ye="eip155:1187947933",Ae="eip155:324705682",Se="eip155:1",ie=z,Me=ue,Pe=de,Re=fe,be=me,_e=ge,Ne=he,Ie=ye,Ce=Ae,ve=Se,Be="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",rt="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",Le="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",Ye="0x55d398326f99059fF775485246999027B3197955",ke="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",We={[he]:ke,[z]:Le,[ue]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[de]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[fe]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[me]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[ge]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[ye]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[Ae]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[Se]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},$e={[Ye]:{symbol:"USDT",decimals:18},[ke]:{symbol:"USDC",decimals:18}};var ce="0x000000000022D473030F116dDEE9F6B43aC78BA3",De="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",Ge={[he]:56,[z]:8453,[ue]:84532,[de]:42161,[fe]:137,[me]:10,[ge]:43114,[ye]:1187947933,[Ae]:324705682,[Se]:1},le={[Z]:"https://api.dexter.cash/api/solana/rpc",[we]:"https://api.devnet.solana.com",[Ue]:"https://api.testnet.solana.com"},H={[he]:"https://bsc-dataseed1.binance.org",[z]:"https://api.dexter.cash/api/base/rpc",[ue]:"https://sepolia.base.org",[de]:"https://arb1.arbitrum.io/rpc",[fe]:"https://polygon-rpc.com",[me]:"https://mainnet.optimism.io",[ge]:"https://api.avax.network/ext/bc/C/rpc",[ye]:"https://skale-base.skalenodes.com/v1/base",[Ae]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[Se]:"https://eth.llamarpc.com"};var D=class n extends Error{code;details;constructor(e,t,r){super(t),this.name="X402Error",this.code=e,this.details=r,Object.setPrototypeOf(this,n.prototype)}};import{PublicKey as Ee,Connection as st,TransactionMessage as ft,VersionedTransaction as mt,ComputeBudgetProgram as at}from"@solana/web3.js";import{getAssociatedTokenAddress as ze,getAccount as gt,createTransferCheckedInstruction as ht,getMint as yt,TOKEN_PROGRAM_ID as ot,TOKEN_2022_PROGRAM_ID as qe}from"@solana/spl-token";var At=12e3,St=1;function J(n){if(!n||typeof n!="object")return!1;let e=n;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var Ke=class{name="Solana";networks=[oe,Te,xe];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]:le[e]?le[e]:e==="solana"?le[oe]:e==="solana-devnet"?le[Te]:e==="solana-testnet"?le[xe]:le[oe]}getAddress(e){return J(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return J(e)?e.publicKey!==null:!1}async getBalance(e,t,r){if(!J(t)||!t.publicKey)return 0;let i=r||this.getDefaultRpcUrl(e.network),s=new st(i,"confirmed"),u=new Ee(t.publicKey.toBase58()),a=new Ee(e.asset);try{let d=(await s.getAccountInfo(a,"confirmed"))?.owner.toBase58()===qe.toBase58()?qe:ot,P=await ze(a,u,!1,d),R=await gt(s,P,void 0,d),_=e.extra?.decimals??6;return Number(R.amount)/Math.pow(10,_)}catch(p){if(p&&typeof p=="object"&&"name"in p&&(p.name==="TokenAccountNotFoundError"||p.name==="TokenInvalidAccountOwnerError"))return 0;throw p}}async buildTransaction(e,t,r){if(!J(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let i=r||this.getDefaultRpcUrl(e.network),s=new st(i,"confirmed"),u=new Ee(t.publicKey.toBase58()),{payTo:a,asset:p,extra:d}=e,P=e.amount??e.maxAmountRequired;if(!P)throw new Error("Missing amount in payment requirements");if(!d?.feePayer)throw new Error("Missing feePayer in payment requirements");let R=new Ee(d.feePayer),_=new Ee(p),c=new Ee(a);this.log("Building transaction:",{from:u.toBase58(),to:a,amount:P,asset:p,feePayer:d.feePayer});let O=[];O.push(at.setComputeUnitLimit({units:At})),O.push(at.setComputeUnitPrice({microLamports:St}));let U=await s.getAccountInfo(_,"confirmed");if(!U)throw new Error(`Token mint ${p} not found`);let L=U.owner.toBase58()===qe.toBase58()?qe:ot,F=await yt(s,_,void 0,L);typeof d?.decimals=="number"&&F.decimals!==d.decimals&&this.log(`Decimals mismatch: requirements say ${d.decimals}, mint says ${F.decimals}`);let b=await ze(_,u,!1,L),M=await ze(_,c,!0,L);if(!await s.getAccountInfo(b,"confirmed"))throw new Error(`No token account found for ${p}. Please ensure you have USDC in your wallet.`);if(!await s.getAccountInfo(M,"confirmed"))throw new Error(`Seller token account not found. The seller (${a}) must have a USDC account.`);let k=BigInt(P);O.push(ht(b,_,M,u,k,F.decimals,[],L));let{blockhash:W}=await s.getLatestBlockhash("confirmed"),X=new ft({payerKey:R,recentBlockhash:W,instructions:O}).compileToV0Message(),l=new mt(X),f=await t.signTransaction(l);return this.log("Transaction signed successfully"),{serialized:Buffer.from(f.serialize()).toString("base64")}}};function te(n){return new Ke(n)}var Et={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"}]},it=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function Y(n){if(!n||typeof n!="object")return!1;let e=n;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var Fe=class{name="EVM";networks=[Ne,ie,Me,ve,Pe,Re,be,_e,Ie,Ce];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]:H[e]?H[e]:e==="base"?H[ie]:e==="bsc"?H[Ne]:e==="ethereum"?H[ve]:e==="arbitrum"?H[Pe]:e==="polygon"?H[Re]:e==="optimism"?H[be]:e==="avalanche"?H[_e]:e==="skale-base"?H[Ie]:e==="skale-base-sepolia"?H[Ce]:H[ie]}getAddress(e){return Y(e)?e.address:null}isConnected(e){return Y(e)?!!e.address:!1}getChainId(e){if(Ge[e])return Ge[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,r){if(!Y(t)||!t.address)return 0;let i=r||this.getDefaultRpcUrl(e.network);try{let s=this.encodeBalanceOf(t.address),u=await fetch(i,{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(!u.ok)throw new Error(`RPC request failed: ${u.status}`);let a=await u.json();if(a.error)throw new Error(`RPC error: ${JSON.stringify(a.error)}`);if(!a.result||a.result==="0x")return 0;let p=BigInt(a.result),d=e.extra?.decimals??6;return Number(p)/Math.pow(10,d)}catch(s){throw s}}encodeBalanceOf(e){let t="0x70a08231",r=e.slice(2).toLowerCase().padStart(64,"0");return t+r}async buildTransaction(e,t,r){if(!Y(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,r);if(e.extra?.assetTransferMethod==="permit2")return this.buildPermit2Transaction(e,t,r);let{payTo:i,asset:s,extra:u}=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:i,amount:a,asset:s,network:e.network});let p=this.getChainId(e.network),d={name:u?.name??"USD Coin",version:u?.version??"2",chainId:BigInt(p),verifyingContract:s},P={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"}]},R=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(R);let _="0x"+[...R].map(b=>b.toString(16).padStart(2,"0")).join(""),c=Math.floor(Date.now()/1e3),O={from:t.address,to:i,value:a,validAfter:String(c-600),validBefore:String(c+(e.maxTimeoutSeconds||60)),nonce:_},U={from:t.address,to:i,value:BigInt(a),validAfter:BigInt(c-600),validBefore:BigInt(c+(e.maxTimeoutSeconds||60)),nonce:_};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let L=await t.signTypedData({domain:d,types:P,primaryType:"TransferWithAuthorization",message:U});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:O,signature:L}),signature:L}}async buildApprovalTransaction(e,t,r){let{payTo:i,asset:s,extra:u}=e,a=e.amount??e.maxAmountRequired;if(!a)throw new Error("Missing amount in payment requirements");let p=u?.facilitatorContract;if(!p)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:i,amount:a,asset:s,network:e.network,facilitatorContract:p});let d=r||this.getDefaultRpcUrl(e.network),P=u?.fee??"0",R=BigInt(a)+BigInt(P),_=await this.readAllowance(d,s,t.address,p);if(_<R){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 l=this.calculateApprovalAmount(a,P,u?.approvalStrategy);this.log(`Approving ${l} for ${p} (current allowance: ${_})`);let f=await t.sendTransaction({to:s,data:this.encodeApprove(p,l),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 c=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(c);let O=[...c].reduce((l,f)=>l*256n+BigInt(f),0n).toString(),U=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(U);let L="0x"+[...U].map(l=>l.toString(16).padStart(2,"0")).join(""),b=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),M=u?.eip712Domain,I=M?{name:M.name,version:M.version,chainId:BigInt(M.chainId),verifyingContract:M.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:p},w=u?.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"}]},k={from:t.address,to:i,token:s,amount:BigInt(a),fee:BigInt(P),nonce:BigInt(O),deadline:BigInt(b),paymentId:L},W=await t.signTypedData({domain:I,types:w,primaryType:"Payment",message:k});this.log("EIP-712 Payment signature obtained");let X={from:t.address,to:i,token:s,amount:a,fee:P,nonce:O,deadline:b,paymentId:L,signature:W};return{serialized:JSON.stringify(X),signature:W}}async buildPermit2Transaction(e,t,r){let{payTo:i,asset:s}=e,u=e.amount??e.maxAmountRequired;if(!u)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:i,amount:u,asset:s,network:e.network});let a=r||this.getDefaultRpcUrl(e.network),p=await this.readAllowance(a,s,t.address,ce),d;if(p<BigInt(u)){let I=this.encodeApprove(ce,it);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${p})`);let w=this.getChainId(e.network),k=await this.readGasPrice(a),W=await this.readNonce(a,t.address),X=await t.signTransaction({to:s,data:I,chainId:w,gas:50000n,gasPrice:k,nonce:W});d={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:s,spender:ce,amount:it.toString(),signedTransaction:X,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${p})`);let w=await t.sendTransaction({to:s,data:I,value:0n});this.log(`Permit2 approval tx sent: ${w}`),await this.waitForReceipt(a,w),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 P=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(P);let R=[...P].reduce((I,w)=>I*256n+BigInt(w),0n),_=Math.floor(Date.now()/1e3),c=_-600,O=_+(e.maxTimeoutSeconds||300),U=this.getChainId(e.network),L={name:"Permit2",chainId:BigInt(U),verifyingContract:ce},F={permitted:{token:s,amount:BigInt(u)},spender:De,nonce:R,deadline:BigInt(O),witness:{to:i,validAfter:BigInt(c)}},b=await t.signTypedData({domain:L,types:Et,primaryType:"PermitWitnessTransferFrom",message:F});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let M={signature:b,permit2Authorization:{from:t.address,permitted:{token:s,amount:u},spender:De,nonce:R.toString(),deadline:String(O),witness:{to:i,validAfter:String(c)}}};return{serialized:JSON.stringify(M),signature:b,extensions:d}}async readAllowance(e,t,r,i){let s="0xdd62ed3e",u=r.slice(2).toLowerCase().padStart(64,"0"),a=i.slice(2).toLowerCase().padStart(64,"0"),p=s+u+a;try{let P=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:p},"latest"]})})).json();return P.error||!P.result||P.result==="0x"?0n:BigInt(P.result)}catch{return 0n}}encodeApprove(e,t){let r="0x095ea7b3",i=e.slice(2).toLowerCase().padStart(64,"0"),s=t.toString(16).padStart(64,"0");return r+i+s}async waitForReceipt(e,t,r=3e4){let i=Date.now();for(;Date.now()-i<r;){try{let u=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(u.result){if(u.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 ${r}ms: ${t}`)}async readGasPrice(e){try{let r=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 r.result?BigInt(r.result):50000000n}catch{return 50000000n}}async readNonce(e,t){try{let i=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 i.result?parseInt(i.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,r){let i=BigInt(e)+BigInt(t);if(!r||r.mode==="exact")return i;let s=BigInt(r.defaultMultiple??10),u=i*s;if(r.maxCapUsd){let a=this.inferDecimals(e),p=BigInt(Math.floor(r.maxCapUsd*Math.pow(10,a)));if(u>p)return p}if(r.exactAboveUsd){let a=this.inferDecimals(e),p=BigInt(Math.floor(r.exactAboveUsd*Math.pow(10,a)));if(BigInt(e)>p)return i}return u}inferDecimals(e){return e.length>12?18:6}};function ne(n){return new Fe(n)}function Qe(n){if(n===Be||n===rt)return!0;let e=n.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 wt(n){return n.startsWith("solana:")||n==="solana"}function Tt(n){return n.startsWith("eip155:")||["base","ethereum","arbitrum"].includes(n)}function xt(n){return wt(n)?"solana":Tt(n)?"evm":"unknown"}function je(n){return{[Z]:"Solana",[we]:"Solana Devnet",[Ue]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[z]:"Base",[ue]:"Base Sepolia",[Se]:"Ethereum",[de]:"Arbitrum",[fe]:"Polygon",[me]:"Optimism",[ge]:"Avalanche",[he]:"BSC",[ye]:"SKALE Base",[Ae]:"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"}[n]||n}function ct(n,e){let t=je(n);return t===n?e:t}function lt(n,e){let t=xt(e);if(t==="solana")return e.includes("devnet")||e===we?`https://solscan.io/tx/${n}?cluster=devnet`:`https://www.orbmarkets.io/tx/${n}`;if(t==="evm"){let r="8453";switch(e.startsWith("eip155:")?r=e.split(":")[1]:e==="ethereum"?r="1":e==="arbitrum"?r="42161":e==="polygon"?r="137":e==="optimism"?r="10":e==="avalanche"?r="43114":e==="bsc"?r="56":e==="skale-base"?r="1187947933":e==="skale-base-sepolia"&&(r="324705682"),r){case"8453":return`https://basescan.org/tx/${n}`;case"84532":return`https://sepolia.basescan.org/tx/${n}`;case"1":return`https://etherscan.io/tx/${n}`;case"42161":return`https://arbiscan.io/tx/${n}`;case"137":return`https://polygonscan.com/tx/${n}`;case"10":return`https://optimistic.etherscan.io/tx/${n}`;case"43114":return`https://snowtrace.io/tx/${n}`;case"56":return`https://bscscan.com/tx/${n}`;case"1187947933":return`https://elated-tan-skat.explorer.mainnet.skalenodes.com/tx/${n}`;case"324705682":return`https://base-sepolia-testnet.explorer.skalenodes.com/tx/${n}`;default:return`https://basescan.org/tx/${n}`}}return`https://solscan.io/tx/${n}`}async function Pt(n,e){if(typeof n=="string")return[n,e];if(n instanceof URL)return[n.href,e];let t=n,r=new Headers(t.headers);e?.headers&&new Headers(e.headers).forEach((u,a)=>r.set(a,u));let i={method:e?.method??t.method,headers:r,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},s=(i.method??"GET").toUpperCase();return e&&"body"in e?i.body=e.body:s!=="GET"&&s!=="HEAD"&&t.body&&(i.body=await t.arrayBuffer()),[t.url,i]}var pt=new WeakMap;function ut(n){return pt.get(n)}function Xe(n){let{adapters:e=[te({verbose:n.verbose}),ne({verbose:n.verbose})],wallets:t,wallet:r,preferredNetwork:i,rpcUrls:s={},maxAmountAtomic:u,fetch:a=globalThis.fetch,verbose:p=!1,accessPass:d,onPaymentRequired:P,maxRetries:R=0,retryDelayMs:_=500}=n,c=p?console.log.bind(console,"[x402]"):()=>{};async function O(l,f){let y;for(let m=0;m<=R;m++)try{let S=await a(l,f);if(S.status>=502&&S.status<=504&&m<R){c(`Retry ${m+1}/${R}: server returned ${S.status}`),await new Promise(g=>setTimeout(g,_*Math.pow(2,m)));continue}return S}catch(S){y=S,m<R&&(c(`Retry ${m+1}/${R}: ${S instanceof Error?S.message:"network error"}`),await new Promise(g=>setTimeout(g,_*Math.pow(2,m))))}throw y}let U=new Map;function L(l){try{let f=new URL(l).host,y=U.get(f);if(y&&y.expiresAt>Date.now()/1e3+10)return y.jwt;y&&U.delete(f)}catch{}return null}function F(l,f){try{let y=new URL(l).host,m=f.split(".");if(m.length===3){let S=JSON.parse(atob(m[1].replace(/-/g,"+").replace(/_/g,"/"))),g=Math.floor(Date.now()/1e3),E=g+86400,A=Math.min(typeof S.exp=="number"?S.exp:g,E);U.set(y,{jwt:f,expiresAt:A}),c("Access pass cached for",y,"| expires:",new Date(A*1e3).toISOString())}}catch{c("Failed to cache access pass")}}let b=t||{};r&&!b.solana&&J(r)&&(b.solana=r),r&&!b.evm&&Y(r)&&(b.evm=r);function M(l){let f=[];for(let y of l){let m=e.find(g=>g.canHandle(y.network));if(!m)continue;let S;m.name==="Solana"?S=b.solana:m.name==="EVM"&&(S=b.evm),S&&m.isConnected(S)&&f.push({accept:y,adapter:m,wallet:S})}if(f.length===0)return null;if(i){let y=f.find(m=>m.accept.network===i);if(y)return y}return f[0]}function I(l,f){return ct(l,f)}function w(l,f){return s[l]||f.getDefaultRpcUrl(l)}async function k(l,f,y,m,S){let g="";if(d?.preferTier&&m.tiers){let o=m.tiers.find(T=>T.id===d.preferTier);if(o){if(d.maxSpend&&parseFloat(o.price)>parseFloat(d.maxSpend))throw new D("access_pass_exceeds_max_spend",`Access pass tier "${o.id}" costs $${o.price}, exceeds max spend $${d.maxSpend}`);g=`tier=${o.id}`}}else if(d?.preferDuration&&m.ratePerHour)g=`duration=${d.preferDuration}`;else if(m.tiers&&m.tiers.length>0){let o=m.tiers[0];if(d?.maxSpend&&parseFloat(o.price)>parseFloat(d.maxSpend))throw new D("access_pass_exceeds_max_spend",`Cheapest access pass costs $${o.price}, exceeds max spend $${d?.maxSpend}`);g=`tier=${o.id}`}let E=g?S.includes("?")?`${S}&${g}`:`${S}?${g}`:S;c("Purchasing access pass:",g||"default tier");let A=y.headers.get("PAYMENT-REQUIRED");if(!A)return null;let C;try{C=JSON.parse(atob(A))}catch{return null}let v=M(C.accepts);if(!v)return null;let{accept:N,adapter:G,wallet:h}=v;if(G.name==="Solana"&&!N.extra?.feePayer)return null;let x=N.extra?.decimals??(Qe(N.asset)?6:void 0);if(typeof x!="number")return null;let B=N.amount??N.maxAmountRequired;if(!B)return null;let $=w(N.network,G);try{let o=await G.getBalance(N,h,$),T=Number(B)/Math.pow(10,x);if(o<T){let Je=I(N.network,G.name);throw new D("insufficient_balance",`Insufficient balance for access pass on ${Je}. Have $${o.toFixed(4)}, need $${T.toFixed(4)}`)}}catch(o){if(o instanceof D)throw o}let q=await G.buildTransaction(N,h,$),K;G.name==="EVM"?K=JSON.parse(q.serialized):K={transaction:q.serialized};let j=typeof l=="string"?l:l instanceof URL?l.href:l.url,V=C.resource;if(typeof C.resource=="string")try{let o=new URL(C.resource,j);["http:","https:"].includes(o.protocol)&&(V=o.toString())}catch{}else if(C.resource&&typeof C.resource=="object"&&"url"in C.resource){let o=C.resource;try{let T=new URL(o.url,j);["http:","https:"].includes(T.protocol)&&(V={...o,url:T.toString()})}catch{}}let se={x402Version:N.x402Version??2,resource:V,accepted:N,payload:K};q.extensions&&(se.extensions=q.extensions);let ee=btoa(JSON.stringify(se)),ae=await a(E,{...f,method:"POST",headers:{...f?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":ee}});if(!ae.ok)return c("Pass purchase failed:",ae.status),null;let Q=ae.headers.get("ACCESS-PASS");return Q&&(F(S,Q),c("Access pass purchased and cached")),ae}async function W(l,f){let y=l;if(c("Making request:",y),d){let o=L(y);if(o){c("Using cached access pass");let T=await a(l,{...f,headers:{...f?.headers||{},Authorization:`Bearer ${o}`}});if(T.status!==401&&T.status!==402)return T;c("Cached pass rejected (status",T.status,"), purchasing new pass");try{U.delete(new URL(y).host)}catch{}}}let m=await O(l,f);if(m.status!==402)return m;c("Received 402 Payment Required");let S=m.headers.get("X-ACCESS-PASS-TIERS");if(d&&S){c("Server offers access passes, purchasing...");try{let o=JSON.parse(atob(S)),T=await k(l,f,m,o,y);if(T)return T}catch(o){c("Access pass purchase failed, falling back to per-request payment:",o)}}let g=m.headers.get("PAYMENT-REQUIRED");if(!g)throw new D("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let E;try{let o=atob(g);E=JSON.parse(o)}catch{throw new D("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}c("Payment requirements:",E);let A=m.headers.get("X-Quote-Hash");A&&c("Quote hash received:",A);let C=M(E.accepts);if(!C){let o=E.accepts.map(T=>T.network).join(", ");throw new D("no_matching_payment_option",`No connected wallet for any available network: ${o}`)}let{accept:v,adapter:N,wallet:G}=C;if(c(`Using ${N.name} for ${v.network}`),N.name==="Solana"&&!v.extra?.feePayer)throw new D("missing_fee_payer","Solana payment option missing feePayer in extra");let h=v.extra?.decimals??(Qe(v.asset)?6:void 0);if(typeof h!="number")throw new D("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let x=v.amount??v.maxAmountRequired;if(!x)throw new D("missing_amount","Payment option missing amount");if(u&&BigInt(x)>BigInt(u))throw new D("amount_exceeds_max",`Payment amount ${x} exceeds maximum ${u}`);let B=w(v.network,N);c("Checking balance...");try{let o=await N.getBalance(v,G,B),T=Number(x)/Math.pow(10,h);if(o<T){let Je=I(v.network,N.name);throw new D("insufficient_balance",`Insufficient balance on ${Je}. Have $${o.toFixed(4)}, need $${T.toFixed(4)}`)}c(`Balance OK: $${o.toFixed(4)} >= $${T.toFixed(4)}`)}catch(o){if(o instanceof D)throw o;c("Balance check failed (RPC error), proceeding with transaction attempt")}if(P&&!await P(v))throw new D("payment_rejected","Payment rejected by onPaymentRequired callback");c("Building transaction...");let $=await N.buildTransaction(v,G,B);c("Transaction signed");let q;N.name==="EVM"?q=JSON.parse($.serialized):q={transaction:$.serialized};let K=l,j=E.resource;if(typeof E.resource=="string")try{let o=new URL(E.resource,K).toString();o!==E.resource&&c("Resolved relative resource URL:",E.resource,"\u2192",o),j=o}catch{j=E.resource}else if(E.resource&&typeof E.resource=="object"&&"url"in E.resource){let o=E.resource;try{let T=new URL(o.url,K).toString();T!==o.url&&(c("Resolved relative resource URL:",o.url,"\u2192",T),j={...o,url:T})}catch{}}let V={x402Version:v.x402Version??2,resource:j,accepted:v,payload:q};$.extensions&&(V.extensions=$.extensions);let se=btoa(JSON.stringify(V));c("Retrying request with payment...");let ee=await O(l,{...f,headers:{...f?.headers||{},"PAYMENT-SIGNATURE":se,...A?{"X-Quote-Hash":A}:{}}});if(c("Retry response status:",ee.status),ee.status===402){let o="unknown";try{let T=await ee.clone().json();o=String(T.error||T.message||JSON.stringify(T)),c("Rejection reason:",o)}catch{}throw new D("payment_rejected",`Payment was rejected by the server: ${o}`)}let ae=ee.headers.get("PAYMENT-RESPONSE"),Q;if(ae)try{Q=JSON.parse(atob(ae))}catch{}return Q??={},Q.amountAtomic=x,Q.assetDecimals=h,pt.set(ee,Q),Q.extensions&&c("Settlement extensions:",Object.keys(Q.extensions).join(", ")),ee}async function X(l,f){let[y,m]=await Pt(l,f);return W(y,m)}return{fetch:X}}function dt(n){let e=ut(n);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function Ze(n){let e=dt(n);if(e?.recommendations?.length)return e.recommendations}async function et(n){let t=dt(n)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function bt(n){let{wallets:e,wallet:t,preferredNetwork:r,rpcUrls:i={},verbose:s=!1}=n,[u,a]=pe(!1),[p,d]=pe("idle"),[P,R]=pe(null),[_,c]=pe(null),[O,U]=pe(null),[L,F]=pe([]),[b,M]=pe(null),I=He((...g)=>{s&&console.log("[useX402Payment]",...g)},[s]),w=Oe(()=>{let g={...e};return t&&!g.solana&&J(t)&&(g.solana=t),t&&!g.evm&&Y(t)&&(g.evm=t),g},[e,t]),k=Oe(()=>[te({verbose:s,rpcUrls:i}),ne({verbose:s,rpcUrls:i})],[s,i]),W=Oe(()=>({solana:w.solana?J(w.solana)&&k[0].isConnected(w.solana):!1,evm:w.evm?Y(w.evm)&&k[1].isConnected(w.evm):!1}),[w,k]),X=W.solana||W.evm,l=He(async()=>{let g=[];if(W.solana&&w.solana)try{let E=k.find(A=>A.name==="Solana");if(E){let A={scheme:"exact",network:Z,amount:"0",asset:Be,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},C=await E.getBalance(A,w.solana);g.push({network:Z,chainName:je(Z),balance:C,asset:"USDC"})}}catch(E){I("Failed to fetch Solana balance:",E)}if(W.evm&&w.evm)try{let E=k.find(A=>A.name==="EVM");if(E){let A={scheme:"exact",network:z,amount:"0",asset:Le,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},C=await E.getBalance(A,w.evm);g.push({network:z,chainName:je(z),balance:C,asset:"USDC"})}}catch(E){I("Failed to fetch Base balance:",E)}F(g)},[W,w,k,I]);Rt(()=>{l();let g=setInterval(l,3e4);return()=>clearInterval(g)},[l]);let f=He(()=>{a(!1),d("idle"),R(null),c(null),U(null),M(null)},[]),y=Oe(()=>Xe({adapters:k,wallets:w,preferredNetwork:r,rpcUrls:i,verbose:s}),[k,w,r,i,s]),m=He(async(g,E)=>{if(a(!0),d("pending"),R(null),c(null),U(null),!X){let A=new D("wallet_not_connected","No wallet connected");throw R(A),d("error"),a(!1),A}try{let A=await y.fetch(g,E),C=A.headers.get("PAYMENT-RESPONSE");if(C)try{let N=JSON.parse(atob(C));N.transaction&&c(N.transaction),N.network&&U(N.network)}catch{I("Could not parse PAYMENT-RESPONSE header")}let v=Ze(A);return M(v??null),v&&(I("Sponsored recommendations received:",v.length),et(A).catch(()=>{})),d("success"),A}catch(A){let C=A instanceof Error?A:new Error(String(A));throw R(C),d("error"),A}finally{a(!1),setTimeout(l,2e3)}},[y,X,I,l]),S=Oe(()=>_?lt(_,O||r||Z):null,[_,O,r]);return{fetch:m,isLoading:u,status:p,error:P,transactionId:_,transactionNetwork:O,transactionUrl:S,balances:L,connectedChains:W,isAnyWalletConnected:X,reset:f,refreshBalances:l,accessPass:null,sponsoredRecommendations:b}}import{useState as re,useCallback as Ve,useEffect as tt,useMemo as nt,useRef as _t}from"react";function Nt(n){let{wallets:e,wallet:t,preferredNetwork:r,rpcUrls:i={},resourceUrl:s,autoConnect:u=!0,verbose:a=!1}=n,p=`x402-access-pass:${s}`;function d(){if(typeof sessionStorage>"u")return null;try{let h=sessionStorage.getItem(p);if(!h)return null;let x=JSON.parse(h);return new Date(x.expiresAt).getTime()<=Date.now()?(sessionStorage.removeItem(p),null):x}catch{return null}}function P(h,x,B){if(!(typeof sessionStorage>"u"))try{sessionStorage.setItem(p,JSON.stringify({jwt:h,tier:x,expiresAt:B}))}catch{}}let R=d(),[_,c]=re(null),[O,U]=re(null),[L,F]=re(!1),[b,M]=re(R?.jwt||null),[I,w]=re(R?{tier:R.tier,expiresAt:R.expiresAt}:null),[k,W]=re(!1),[X,l]=re(null),f=_t(b);tt(()=>{f.current=b},[b]);let y=Ve((...h)=>{a&&console.log("[useAccessPass]",...h)},[a]),m=nt(()=>{let h={...e};return t&&!h.solana&&J(t)&&(h.solana=t),t&&!h.evm&&Y(t)&&(h.evm=t),h},[e,t]),S=nt(()=>Xe({adapters:[te({verbose:a,rpcUrls:i}),ne({verbose:a,rpcUrls:i})],wallets:m,preferredNetwork:r,rpcUrls:i,verbose:a,accessPass:{enabled:!0,autoRenew:!0}}),[m,r,i,a]),[g,E]=re(0),A=nt(()=>{if(!b||!I)return null;let h=new Date(I.expiresAt).getTime(),x=Math.max(0,Math.floor((h-Date.now())/1e3));return x<=0?null:{jwt:b,tier:I.tier,expiresAt:I.expiresAt,remainingSeconds:x}},[b,I,g]),C=A!==null&&A.remainingSeconds>0;tt(()=>{if(!b||!I)return;let h=setInterval(()=>E(x=>x+1),1e3);return()=>clearInterval(h)},[C]);let v=Ve(async()=>{F(!0);try{let h=await fetch(s);if(h.status===402){let x=h.headers.get("X-ACCESS-PASS-TIERS");if(x){let B=JSON.parse(atob(x));c(B.tiers||null),U(B.ratePerHour||null),y("Tier info loaded:",B)}}}catch(h){y("Failed to fetch tiers:",h)}finally{F(!1)}},[s,y]);tt(()=>{u&&v()},[u,v]);let N=Ve(async(h,x)=>{W(!0),l(null);try{let B=s;h?B+=(B.includes("?")?"&":"?")+`tier=${h}`:x&&(B+=(B.includes("?")?"&":"?")+`duration=${x}`);let $=await S.fetch(B,{method:"POST"}),q=$.headers.get("ACCESS-PASS");if(y("ACCESS-PASS header:",q?"found":"NOT FOUND"),q){M(q);let K=h||"unknown",j="";try{let V=await $.json();K=V.accessPass?.tier||K,j=V.accessPass?.expiresAt||""}catch{}if(!j)try{let V=q.split(".");if(V.length===3){let se=JSON.parse(atob(V[1].replace(/-/g,"+").replace(/_/g,"/")));K=se.tier||K,j=new Date(se.exp*1e3).toISOString()}}catch{}w({tier:K,expiresAt:j}),P(q,K,j),y("Pass purchased and persisted:",K,j)}}catch(B){let $=B instanceof Error?B:new Error(String(B));throw l($),$}finally{W(!1)}},[s,S,y]),G=Ve(async(h,x)=>{let B=!h||h===""?s:h.startsWith("http")?h:`${s.replace(/\/$/,"")}${h.startsWith("/")?"":"/"}${h}`,$=f.current;if($){try{let q=$.split(".");if(q.length===3){let K=JSON.parse(atob(q[1].replace(/-/g,"+").replace(/_/g,"/")));if(K.exp&&K.exp>Date.now()/1e3)return fetch(B,{...x,headers:{...x?.headers||{},Authorization:`Bearer ${$}`}})}}catch{}M(null),w(null);try{sessionStorage.removeItem(p)}catch{}}return S.fetch(B,x)},[s,S,p]);return{tiers:_,customRatePerHour:O,isLoadingTiers:L,pass:A,isPassValid:C,fetchTiers:v,purchasePass:N,isPurchasing:k,purchaseError:X,fetch:G}}export{D as X402Error,et as fireImpressionBeacon,Ze as getSponsoredRecommendations,Nt as useAccessPass,bt as useX402Payment};
1
+ import{useState as ue,useCallback as He,useEffect as Rt,useMemo as De}from"react";var Z="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",we="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Me="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",ie=Z,xe=we,Te=Me,z="eip155:8453",de="eip155:84532",me="eip155:42161",fe="eip155:137",ge="eip155:10",he="eip155:43114",ye="eip155:56",Ae="eip155:1187947933",Se="eip155:324705682",Ee="eip155:1",ce=z,ke=de,Pe=me,be=fe,Re=ge,_e=he,Ce=ye,Ie=Ae,Ne=Se,ve=Ee,Be="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",at="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",Le="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",Ge="0x55d398326f99059fF775485246999027B3197955",We="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",$e={[ye]:We,[z]:Le,[de]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[me]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[fe]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[ge]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[he]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[Ae]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[Se]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[Ee]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},qe={[Ge]:{symbol:"USDT",decimals:18},[We]:{symbol:"USDC",decimals:18}};var ne="0x000000000022D473030F116dDEE9F6B43aC78BA3",Oe="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",ze={[ye]:56,[z]:8453,[de]:84532,[me]:42161,[fe]:137,[ge]:10,[he]:43114,[Ae]:1187947933,[Se]:324705682,[Ee]:1},le={[Z]:"https://api.dexter.cash/api/solana/rpc",[we]:"https://api.devnet.solana.com",[Me]:"https://api.testnet.solana.com"},J={[ye]:"https://bsc-dataseed1.binance.org",[z]:"https://api.dexter.cash/api/base/rpc",[de]:"https://sepolia.base.org",[me]:"https://arb1.arbitrum.io/rpc",[fe]:"https://polygon-rpc.com",[ge]:"https://mainnet.optimism.io",[he]:"https://api.avax.network/ext/bc/C/rpc",[Ae]:"https://skale-base.skalenodes.com/v1/base",[Se]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[Ee]:"https://eth.llamarpc.com"};var D=class s extends Error{code;details;constructor(e,t,r){super(t),this.name="X402Error",this.code=e,this.details=r,Object.setPrototypeOf(this,s.prototype)}};import{PublicKey as pe,Connection as Qe,TransactionMessage as ft,VersionedTransaction as gt,ComputeBudgetProgram as ot}from"@solana/web3.js";import{getAssociatedTokenAddress as Ze,getAccount as ht,createTransferCheckedInstruction as yt,getMint as At,TOKEN_PROGRAM_ID as it,TOKEN_2022_PROGRAM_ID as Ke}from"@solana/spl-token";var St=12e3,Et=1;function Y(s){if(!s||typeof s!="object")return!1;let e=s;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var je=class{name="Solana";networks=[ie,xe,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]:le[e]?le[e]:e==="solana"?le[ie]:e==="solana-devnet"?le[xe]:e==="solana-testnet"?le[Te]:le[ie]}getAddress(e){return Y(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return Y(e)?e.publicKey!==null:!1}async getBalance(e,t,r){if(!Y(t)||!t.publicKey)return 0;let a=r||this.getDefaultRpcUrl(e.network),n=new Qe(a,"confirmed"),l=new pe(t.publicKey.toBase58()),o=new pe(e.asset);try{let d=(await n.getAccountInfo(o,"confirmed"))?.owner.toBase58()===Ke.toBase58()?Ke:it,E=await Ze(o,l,!1,d),P=await ht(n,E,void 0,d),A=e.extra?.decimals??6;return Number(P.amount)/Math.pow(10,A)}catch(i){if(i&&typeof i=="object"&&"name"in i&&(i.name==="TokenAccountNotFoundError"||i.name==="TokenInvalidAccountOwnerError"))return 0;throw i}}async buildTransaction(e,t,r){if(!Y(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let a=r||this.getDefaultRpcUrl(e.network),n=new Qe(a,"confirmed"),l=new pe(t.publicKey.toBase58()),{payTo:o,asset:i,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 P=new pe(d.feePayer),A=new pe(i),_=new pe(o);this.log("Building transaction:",{from:l.toBase58(),to:o,amount:E,asset:i,feePayer:d.feePayer});let p=[];p.push(ot.setComputeUnitLimit({units:St})),p.push(ot.setComputeUnitPrice({microLamports:Et}));let U=await n.getAccountInfo(A,"confirmed");if(!U)throw new Error(`Token mint ${i} not found`);let B=U.owner.toBase58()===Ke.toBase58()?Ke:it,j=await At(n,A,void 0,B);typeof d?.decimals=="number"&&j.decimals!==d.decimals&&this.log(`Decimals mismatch: requirements say ${d.decimals}, mint says ${j.decimals}`);let v=await Ze(A,l,!1,B),C=await Ze(A,_,!0,B);if(!await n.getAccountInfo(v,"confirmed"))throw new Error(`No token account found for ${i}. Please ensure you have USDC in your wallet.`);if(!await n.getAccountInfo(C,"confirmed"))throw new Error(`Seller token account not found. The seller (${o}) must have a USDC account.`);let W=BigInt(E);p.push(yt(v,A,C,l,W,j.decimals,[],B));let{blockhash:$}=await n.getLatestBlockhash("confirmed"),X=new ft({payerKey:P,recentBlockhash:$,instructions:p}).compileToV0Message(),k=new gt(X),h=await t.signTransaction(k);return this.log("Transaction signed successfully"),{serialized:Buffer.from(h.serialize()).toString("base64"),settlementProbe:{kind:"solana",sourceAta:v.toBase58(),destinationAta:C.toBase58(),asset:i,amount:E,blockhash:$}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let r=new Qe(t,"confirmed"),a=new pe(e.destinationAta),n=await r.getSignaturesForAddress(a,{limit:25});if(n.length===0)return{settled:!1};let l=BigInt(e.amount);for(let o of n){if(o.err)continue;let i=await r.getTransaction(o.signature,{commitment:"confirmed",maxSupportedTransactionVersion:0});if(!i?.meta)continue;let d=i.transaction.message.getAccountKeys().keySegments().flat(),E=i.meta.preTokenBalances??[],P=i.meta.postTokenBalances??[];for(let A of P){if(A.mint!==e.asset)continue;let _=d[A.accountIndex];if(!_||!_.equals(a))continue;let p=E.find(j=>j.accountIndex===A.accountIndex),U=BigInt(p?.uiTokenAmount.amount??"0");if(BigInt(A.uiTokenAmount.amount??"0")-U===l)return{settled:!0,txSignature:o.signature}}}return{settled:!1}}};function re(s){return new je(s)}var wt={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"}]},ct=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function G(s){if(!s||typeof s!="object")return!1;let e=s;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var Fe=class{name="EVM";networks=[Ce,ce,ke,ve,Pe,be,Re,_e,Ie,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]:J[e]?J[e]:e==="base"?J[ce]:e==="bsc"?J[Ce]:e==="ethereum"?J[ve]:e==="arbitrum"?J[Pe]:e==="polygon"?J[be]:e==="optimism"?J[Re]:e==="avalanche"?J[_e]:e==="skale-base"?J[Ie]:e==="skale-base-sepolia"?J[Ne]:J[ce]}getAddress(e){return G(e)?e.address:null}isConnected(e){return G(e)?!!e.address:!1}getChainId(e){if(ze[e])return ze[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,r){if(!G(t)||!t.address)return 0;let a=r||this.getDefaultRpcUrl(e.network);try{let n=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:n},"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 i=BigInt(o.result),d=e.extra?.decimals??6;return Number(i)/Math.pow(10,d)}catch(n){throw n}}encodeBalanceOf(e){let t="0x70a08231",r=e.slice(2).toLowerCase().padStart(64,"0");return t+r}async confirmSettlement(e,t){if(e.kind==="eip3009"){let r="0xe94a0102",a=e.from.slice(2).toLowerCase().padStart(64,"0"),n=e.nonce.slice(2).toLowerCase().padStart(64,"0"),l=r+a+n,o=await this.ethCall(t,e.asset,l);return{settled:BigInt(o)!==0n}}if(e.kind==="permit2"){let r="0x4fe02b44",a=BigInt(e.nonce),n=a>>8n,l=a&0xffn,o=e.from.slice(2).toLowerCase().padStart(64,"0"),i=n.toString(16).padStart(64,"0"),d=r+o+i,E=await this.ethCall(t,ne,d);return{settled:(BigInt(E)>>l&1n)===1n}}throw new Error(`EvmAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`)}async ethCall(e,t,r){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:r},"latest"]})});if(!a.ok)throw new Error(`RPC request failed: ${a.status}`);let n=await a.json();if(n.error)throw new Error(`RPC error: ${JSON.stringify(n.error)}`);if(!n.result||n.result==="0x")throw new Error("RPC returned an empty result");return n.result}async buildTransaction(e,t,r){if(!G(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,r);if(e.extra?.assetTransferMethod==="permit2")return this.buildPermit2Transaction(e,t,r);let{payTo:a,asset:n,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:n,network:e.network});let i=this.getChainId(e.network),d={name:l?.name??"USD Coin",version:l?.version??"2",chainId:BigInt(i),verifyingContract:n},E={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"}]},P=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(P);let A="0x"+[...P].map(v=>v.toString(16).padStart(2,"0")).join(""),_=Math.floor(Date.now()/1e3),p={from:t.address,to:a,value:o,validAfter:String(_-600),validBefore:String(_+(e.maxTimeoutSeconds||60)),nonce:A},U={from:t.address,to:a,value:BigInt(o),validAfter:BigInt(_-600),validBefore:BigInt(_+(e.maxTimeoutSeconds||60)),nonce:A};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let B=await t.signTypedData({domain:d,types:E,primaryType:"TransferWithAuthorization",message:U});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:p,signature:B}),signature:B,settlementProbe:{kind:"eip3009",from:t.address,nonce:A,asset:n,chainId:i}}}async buildApprovalTransaction(e,t,r){let{payTo:a,asset:n,extra:l}=e,o=e.amount??e.maxAmountRequired;if(!o)throw new Error("Missing amount in payment requirements");let i=l?.facilitatorContract;if(!i)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:n,network:e.network,facilitatorContract:i});let d=r||this.getDefaultRpcUrl(e.network),E=l?.fee??"0",P=BigInt(o)+BigInt(E),A=await this.readAllowance(d,n,t.address,i);if(A<P){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 k=this.calculateApprovalAmount(o,E,l?.approvalStrategy);this.log(`Approving ${k} for ${i} (current allowance: ${A})`);let h=await t.sendTransaction({to:n,data:this.encodeApprove(i,k),value:0n});this.log(`Approval tx sent: ${h}`),await this.waitForReceipt(d,h),this.log("Approval confirmed")}else this.log("Sufficient allowance, skipping approval");let _=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(_);let p=[..._].reduce((k,h)=>k*256n+BigInt(h),0n).toString(),U=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(U);let B="0x"+[...U].map(k=>k.toString(16).padStart(2,"0")).join(""),v=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),C=l?.eip712Domain,I=C?{name:C.name,version:C.version,chainId:BigInt(C.chainId),verifyingContract:C.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:i},w=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"}]},W={from:t.address,to:a,token:n,amount:BigInt(o),fee:BigInt(E),nonce:BigInt(p),deadline:BigInt(v),paymentId:B},$=await t.signTypedData({domain:I,types:w,primaryType:"Payment",message:W});this.log("EIP-712 Payment signature obtained");let X={from:t.address,to:a,token:n,amount:o,fee:E,nonce:p,deadline:v,paymentId:B,signature:$};return{serialized:JSON.stringify(X),signature:$}}async buildPermit2Transaction(e,t,r){let{payTo:a,asset:n}=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:n,network:e.network});let o=r||this.getDefaultRpcUrl(e.network),i=await this.readAllowance(o,n,t.address,ne),d;if(i<BigInt(l)){let I=this.encodeApprove(ne,ct);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${i})`);let w=this.getChainId(e.network),W=await this.readGasPrice(o),$=await this.readNonce(o,t.address),X=await t.signTransaction({to:n,data:I,chainId:w,gas:50000n,gasPrice:W,nonce:$});d={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:n,spender:ne,amount:ct.toString(),signedTransaction:X,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${i})`);let w=await t.sendTransaction({to:n,data:I,value:0n});this.log(`Permit2 approval tx sent: ${w}`),await this.waitForReceipt(o,w),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 P=[...E].reduce((I,w)=>I*256n+BigInt(w),0n),A=Math.floor(Date.now()/1e3),_=A-600,p=A+(e.maxTimeoutSeconds||300),U=this.getChainId(e.network),B={name:"Permit2",chainId:BigInt(U),verifyingContract:ne},j={permitted:{token:n,amount:BigInt(l)},spender:Oe,nonce:P,deadline:BigInt(p),witness:{to:a,validAfter:BigInt(_)}},v=await t.signTypedData({domain:B,types:wt,primaryType:"PermitWitnessTransferFrom",message:j});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let C={signature:v,permit2Authorization:{from:t.address,permitted:{token:n,amount:l},spender:Oe,nonce:P.toString(),deadline:String(p),witness:{to:a,validAfter:String(_)}}};return{serialized:JSON.stringify(C),signature:v,extensions:d,settlementProbe:{kind:"permit2",from:t.address,nonce:P.toString(),chainId:U}}}async readAllowance(e,t,r,a){let n="0xdd62ed3e",l=r.slice(2).toLowerCase().padStart(64,"0"),o=a.slice(2).toLowerCase().padStart(64,"0"),i=n+l+o;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:i},"latest"]})})).json();return E.error||!E.result||E.result==="0x"?0n:BigInt(E.result)}catch{return 0n}}encodeApprove(e,t){let r="0x095ea7b3",a=e.slice(2).toLowerCase().padStart(64,"0"),n=t.toString(16).padStart(64,"0");return r+a+n}async waitForReceipt(e,t,r=3e4){let a=Date.now();for(;Date.now()-a<r;){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(n){if(n instanceof Error&&n.message.includes("reverted"))throw n}await new Promise(n=>setTimeout(n,2e3))}throw new Error(`Approval transaction receipt timeout after ${r}ms: ${t}`)}async readGasPrice(e){try{let r=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 r.result?BigInt(r.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,r){let a=BigInt(e)+BigInt(t);if(!r||r.mode==="exact")return a;let n=BigInt(r.defaultMultiple??10),l=a*n;if(r.maxCapUsd){let o=this.inferDecimals(e),i=BigInt(Math.floor(r.maxCapUsd*Math.pow(10,o)));if(l>i)return i}if(r.exactAboveUsd){let o=this.inferDecimals(e),i=BigInt(Math.floor(r.exactAboveUsd*Math.pow(10,o)));if(BigInt(e)>i)return a}return l}inferDecimals(e){return e.length>12?18:6}};function se(s){return new Fe(s)}function et(s){if(s===Be||s===at)return!0;let e=s.toLowerCase();for(let t of Object.values($e))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(qe))if(t.toLowerCase()===e)return!0;return!1}function xt(s){return s.startsWith("solana:")||s==="solana"}function Tt(s){return s.startsWith("eip155:")||["base","ethereum","arbitrum"].includes(s)}function Pt(s){return xt(s)?"solana":Tt(s)?"evm":"unknown"}function Xe(s){return{[Z]:"Solana",[we]:"Solana Devnet",[Me]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[z]:"Base",[de]:"Base Sepolia",[Ee]:"Ethereum",[me]:"Arbitrum",[fe]:"Polygon",[ge]:"Optimism",[he]:"Avalanche",[ye]:"BSC",[Ae]:"SKALE Base",[Se]:"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"}[s]||s}function lt(s,e){let t=Xe(s);return t===s?e:t}function pt(s,e){let t=Pt(e);if(t==="solana")return e.includes("devnet")||e===we?`https://solscan.io/tx/${s}?cluster=devnet`:`https://www.orbmarkets.io/tx/${s}`;if(t==="evm"){let r="8453";switch(e.startsWith("eip155:")?r=e.split(":")[1]:e==="ethereum"?r="1":e==="arbitrum"?r="42161":e==="polygon"?r="137":e==="optimism"?r="10":e==="avalanche"?r="43114":e==="bsc"?r="56":e==="skale-base"?r="1187947933":e==="skale-base-sepolia"&&(r="324705682"),r){case"8453":return`https://basescan.org/tx/${s}`;case"84532":return`https://sepolia.basescan.org/tx/${s}`;case"1":return`https://etherscan.io/tx/${s}`;case"42161":return`https://arbiscan.io/tx/${s}`;case"137":return`https://polygonscan.com/tx/${s}`;case"10":return`https://optimistic.etherscan.io/tx/${s}`;case"43114":return`https://snowtrace.io/tx/${s}`;case"56":return`https://bscscan.com/tx/${s}`;case"1187947933":return`https://elated-tan-skat.explorer.mainnet.skalenodes.com/tx/${s}`;case"324705682":return`https://base-sepolia-testnet.explorer.skalenodes.com/tx/${s}`;default:return`https://basescan.org/tx/${s}`}}return`https://solscan.io/tx/${s}`}async function bt(s,e){if(typeof s=="string")return[s,e];if(s instanceof URL)return[s.href,e];let t=s,r=new Headers(t.headers);e?.headers&&new Headers(e.headers).forEach((l,o)=>r.set(o,l));let a={method:e?.method??t.method,headers:r,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},n=(a.method??"GET").toUpperCase();return e&&"body"in e?a.body=e.body:n!=="GET"&&n!=="HEAD"&&t.body&&(a.body=await t.arrayBuffer()),[t.url,a]}var ut=new WeakMap;function dt(s){return ut.get(s)}function Ve(s){let{adapters:e=[re({verbose:s.verbose}),se({verbose:s.verbose})],wallets:t,wallet:r,preferredNetwork:a,rpcUrls:n={},maxAmountAtomic:l,fetch:o=globalThis.fetch,verbose:i=!1,accessPass:d,onPaymentRequired:E,onPaymentDispatched:P,maxRetries:A=0,retryDelayMs:_=500}=s,p=i?console.log.bind(console,"[x402]"):()=>{};async function U(h,y){let x;for(let f=0;f<=A;f++)try{let u=await o(h,y);if(u.status>=502&&u.status<=504&&f<A){p(`Retry ${f+1}/${A}: server returned ${u.status}`),await new Promise(S=>setTimeout(S,_*Math.pow(2,f)));continue}return u}catch(u){x=u,f<A&&(p(`Retry ${f+1}/${A}: ${u instanceof Error?u.message:"network error"}`),await new Promise(S=>setTimeout(S,_*Math.pow(2,f))))}throw x}let B=new Map;function j(h){try{let y=new URL(h).host,x=B.get(y);if(x&&x.expiresAt>Date.now()/1e3+10)return x.jwt;x&&B.delete(y)}catch{}return null}function v(h,y){try{let x=new URL(h).host,f=y.split(".");if(f.length===3){let u=JSON.parse(atob(f[1].replace(/-/g,"+").replace(/_/g,"/"))),S=Math.floor(Date.now()/1e3),m=S+86400,O=Math.min(typeof u.exp=="number"?u.exp:S,m);B.set(x,{jwt:y,expiresAt:O}),p("Access pass cached for",x,"| expires:",new Date(O*1e3).toISOString())}}catch{p("Failed to cache access pass")}}let C=t||{};r&&!C.solana&&Y(r)&&(C.solana=r),r&&!C.evm&&G(r)&&(C.evm=r);function I(h){let y=[];for(let x of h){let f=e.find(S=>S.canHandle(x.network));if(!f)continue;let u;f.name==="Solana"?u=C.solana:f.name==="EVM"&&(u=C.evm),u&&f.isConnected(u)&&y.push({accept:x,adapter:f,wallet:u})}if(y.length===0)return null;if(a){let x=y.find(f=>f.accept.network===a);if(x)return x}return y[0]}function w(h,y){return lt(h,y)}function W(h,y){return n[h]||y.getDefaultRpcUrl(h)}async function $(h,y,x,f,u){let S="";if(d?.preferTier&&f.tiers){let c=f.tiers.find(T=>T.id===d.preferTier);if(c){if(d.maxSpend&&parseFloat(c.price)>parseFloat(d.maxSpend))throw new D("access_pass_exceeds_max_spend",`Access pass tier "${c.id}" costs $${c.price}, exceeds max spend $${d.maxSpend}`);S=`tier=${c.id}`}}else if(d?.preferDuration&&f.ratePerHour)S=`duration=${d.preferDuration}`;else if(f.tiers&&f.tiers.length>0){let c=f.tiers[0];if(d?.maxSpend&&parseFloat(c.price)>parseFloat(d.maxSpend))throw new D("access_pass_exceeds_max_spend",`Cheapest access pass costs $${c.price}, exceeds max spend $${d?.maxSpend}`);S=`tier=${c.id}`}let m=S?u.includes("?")?`${u}&${S}`:`${u}?${S}`:u;p("Purchasing access pass:",S||"default tier");let O=x.headers.get("PAYMENT-REQUIRED");if(!O)return null;let L;try{L=JSON.parse(atob(O))}catch{return null}let N=I(L.accepts);if(!N)return null;let{accept:M,adapter:g,wallet:R}=N;if(g.name==="Solana"&&!M.extra?.feePayer)return null;let b=M.extra?.decimals??(et(M.asset)?6:void 0);if(typeof b!="number")return null;let F=M.amount??M.maxAmountRequired;if(!F)return null;let K=W(M.network,g);try{let c=await g.getBalance(M,R,K),T=Number(F)/Math.pow(10,b);if(c<T){let Ye=w(M.network,g.name);throw new D("insufficient_balance",`Insufficient balance for access pass on ${Ye}. Have $${c.toFixed(4)}, need $${T.toFixed(4)}`)}}catch(c){if(c instanceof D)throw c}let q=await g.buildTransaction(M,R,K),V;g.name==="EVM"?V=JSON.parse(q.serialized):V={transaction:q.serialized};let H=typeof h=="string"?h:h instanceof URL?h.href:h.url,ee=L.resource;if(typeof L.resource=="string")try{let c=new URL(L.resource,H);["http:","https:"].includes(c.protocol)&&(ee=c.toString())}catch{}else if(L.resource&&typeof L.resource=="object"&&"url"in L.resource){let c=L.resource;try{let T=new URL(c.url,H);["http:","https:"].includes(T.protocol)&&(ee={...c,url:T.toString()})}catch{}}let Ue={x402Version:M.x402Version??2,resource:ee,accepted:M,payload:V};q.extensions&&(Ue.extensions=q.extensions);let te=btoa(JSON.stringify(Ue)),oe=await o(m,{...y,method:"POST",headers:{...y?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":te}});if(!oe.ok)return p("Pass purchase failed:",oe.status),null;let Q=oe.headers.get("ACCESS-PASS");return Q&&(v(u,Q),p("Access pass purchased and cached")),oe}async function X(h,y){let x=h;if(p("Making request:",x),d){let c=j(x);if(c){p("Using cached access pass");let T=await o(h,{...y,headers:{...y?.headers||{},Authorization:`Bearer ${c}`}});if(T.status!==401&&T.status!==402)return T;p("Cached pass rejected (status",T.status,"), purchasing new pass");try{B.delete(new URL(x).host)}catch{}}}let f=await U(h,y);if(f.status!==402)return f;p("Received 402 Payment Required");let u=f.headers.get("X-ACCESS-PASS-TIERS");if(d&&u){p("Server offers access passes, purchasing...");try{let c=JSON.parse(atob(u)),T=await $(h,y,f,c,x);if(T)return T}catch(c){p("Access pass purchase failed, falling back to per-request payment:",c)}}let S=f.headers.get("PAYMENT-REQUIRED");if(!S)throw new D("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let m;try{let c=atob(S);m=JSON.parse(c)}catch{throw new D("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}p("Payment requirements:",m);let O=f.headers.get("X-Quote-Hash");O&&p("Quote hash received:",O);let L=I(m.accepts);if(!L){let c=m.accepts.map(T=>T.network).join(", ");throw new D("no_matching_payment_option",`No connected wallet for any available network: ${c}`)}let{accept:N,adapter:M,wallet:g}=L;if(p(`Using ${M.name} for ${N.network}`),M.name==="Solana"&&!N.extra?.feePayer)throw new D("missing_fee_payer","Solana payment option missing feePayer in extra");let R=N.extra?.decimals??(et(N.asset)?6:void 0);if(typeof R!="number")throw new D("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let b=N.amount??N.maxAmountRequired;if(!b)throw new D("missing_amount","Payment option missing amount");if(l&&BigInt(b)>BigInt(l))throw new D("amount_exceeds_max",`Payment amount ${b} exceeds maximum ${l}`);let F=W(N.network,M);p("Checking balance...");try{let c=await M.getBalance(N,g,F),T=Number(b)/Math.pow(10,R);if(c<T){let Ye=w(N.network,M.name);throw new D("insufficient_balance",`Insufficient balance on ${Ye}. Have $${c.toFixed(4)}, need $${T.toFixed(4)}`)}p(`Balance OK: $${c.toFixed(4)} >= $${T.toFixed(4)}`)}catch(c){if(c instanceof D)throw c;p("Balance check failed (RPC error), proceeding with transaction attempt")}if(E&&!await E(N))throw new D("payment_rejected","Payment rejected by onPaymentRequired callback");p("Building transaction...");let K=await M.buildTransaction(N,g,F);p("Transaction signed");let q;M.name==="EVM"?q=JSON.parse(K.serialized):q={transaction:K.serialized};let V=h,H=m.resource;if(typeof m.resource=="string")try{let c=new URL(m.resource,V).toString();c!==m.resource&&p("Resolved relative resource URL:",m.resource,"\u2192",c),H=c}catch{H=m.resource}else if(m.resource&&typeof m.resource=="object"&&"url"in m.resource){let c=m.resource;try{let T=new URL(c.url,V).toString();T!==c.url&&(p("Resolved relative resource URL:",c.url,"\u2192",T),H={...c,url:T})}catch{}}let ee={x402Version:N.x402Version??2,resource:H,accepted:N,payload:q};K.extensions&&(ee.extensions=K.extensions);let Ue=btoa(JSON.stringify(ee));if(P)try{P(N,K.settlementProbe)}catch{}p("Retrying request with payment...");let te=await U(h,{...y,headers:{...y?.headers||{},"PAYMENT-SIGNATURE":Ue,...O?{"X-Quote-Hash":O}:{}}});if(p("Retry response status:",te.status),te.status===402){let c="unknown";try{let T=await te.clone().json();c=String(T.error||T.message||JSON.stringify(T)),p("Rejection reason:",c)}catch{}throw new D("payment_rejected",`Payment was rejected by the server: ${c}`)}let oe=te.headers.get("PAYMENT-RESPONSE"),Q;if(oe)try{Q=JSON.parse(atob(oe))}catch{}return Q??={},Q.amountAtomic=b,Q.assetDecimals=R,ut.set(te,Q),Q.extensions&&p("Settlement extensions:",Object.keys(Q.extensions).join(", ")),te}async function k(h,y){let[x,f]=await bt(h,y);return X(x,f)}return{fetch:k}}function mt(s){let e=dt(s);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function tt(s){let e=mt(s);if(e?.recommendations?.length)return e.recommendations}async function nt(s){let t=mt(s)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function _t(s){let{wallets:e,wallet:t,preferredNetwork:r,rpcUrls:a={},verbose:n=!1}=s,[l,o]=ue(!1),[i,d]=ue("idle"),[E,P]=ue(null),[A,_]=ue(null),[p,U]=ue(null),[B,j]=ue([]),[v,C]=ue(null),I=He((...u)=>{n&&console.log("[useX402Payment]",...u)},[n]),w=De(()=>{let u={...e};return t&&!u.solana&&Y(t)&&(u.solana=t),t&&!u.evm&&G(t)&&(u.evm=t),u},[e,t]),W=De(()=>[re({verbose:n,rpcUrls:a}),se({verbose:n,rpcUrls:a})],[n,a]),$=De(()=>({solana:w.solana?Y(w.solana)&&W[0].isConnected(w.solana):!1,evm:w.evm?G(w.evm)&&W[1].isConnected(w.evm):!1}),[w,W]),X=$.solana||$.evm,k=He(async()=>{let u=[];if($.solana&&w.solana)try{let S=W.find(m=>m.name==="Solana");if(S){let m={scheme:"exact",network:Z,amount:"0",asset:Be,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},O=await S.getBalance(m,w.solana);u.push({network:Z,chainName:Xe(Z),balance:O,asset:"USDC"})}}catch(S){I("Failed to fetch Solana balance:",S)}if($.evm&&w.evm)try{let S=W.find(m=>m.name==="EVM");if(S){let m={scheme:"exact",network:z,amount:"0",asset:Le,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},O=await S.getBalance(m,w.evm);u.push({network:z,chainName:Xe(z),balance:O,asset:"USDC"})}}catch(S){I("Failed to fetch Base balance:",S)}j(u)},[$,w,W,I]);Rt(()=>{k();let u=setInterval(k,3e4);return()=>clearInterval(u)},[k]);let h=He(()=>{o(!1),d("idle"),P(null),_(null),U(null),C(null)},[]),y=De(()=>Ve({adapters:W,wallets:w,preferredNetwork:r,rpcUrls:a,verbose:n}),[W,w,r,a,n]),x=He(async(u,S)=>{if(o(!0),d("pending"),P(null),_(null),U(null),!X){let m=new D("wallet_not_connected","No wallet connected");throw P(m),d("error"),o(!1),m}try{let m=await y.fetch(u,S),O=m.headers.get("PAYMENT-RESPONSE");if(O)try{let N=JSON.parse(atob(O));N.transaction&&_(N.transaction),N.network&&U(N.network)}catch{I("Could not parse PAYMENT-RESPONSE header")}let L=tt(m);return C(L??null),L&&(I("Sponsored recommendations received:",L.length),nt(m).catch(()=>{})),d("success"),m}catch(m){let O=m instanceof Error?m:new Error(String(m));throw P(O),d("error"),m}finally{o(!1),setTimeout(k,2e3)}},[y,X,I,k]),f=De(()=>A?pt(A,p||r||Z):null,[A,p,r]);return{fetch:x,isLoading:l,status:i,error:E,transactionId:A,transactionNetwork:p,transactionUrl:f,balances:B,connectedChains:$,isAnyWalletConnected:X,reset:h,refreshBalances:k,accessPass:null,sponsoredRecommendations:v}}import{useState as ae,useCallback as Je,useEffect as rt,useMemo as st,useRef as Ct}from"react";function It(s){let{wallets:e,wallet:t,preferredNetwork:r,rpcUrls:a={},resourceUrl:n,autoConnect:l=!0,verbose:o=!1}=s,i=`x402-access-pass:${n}`;function d(){if(typeof sessionStorage>"u")return null;try{let g=sessionStorage.getItem(i);if(!g)return null;let R=JSON.parse(g);return new Date(R.expiresAt).getTime()<=Date.now()?(sessionStorage.removeItem(i),null):R}catch{return null}}function E(g,R,b){if(!(typeof sessionStorage>"u"))try{sessionStorage.setItem(i,JSON.stringify({jwt:g,tier:R,expiresAt:b}))}catch{}}let P=d(),[A,_]=ae(null),[p,U]=ae(null),[B,j]=ae(!1),[v,C]=ae(P?.jwt||null),[I,w]=ae(P?{tier:P.tier,expiresAt:P.expiresAt}:null),[W,$]=ae(!1),[X,k]=ae(null),h=Ct(v);rt(()=>{h.current=v},[v]);let y=Je((...g)=>{o&&console.log("[useAccessPass]",...g)},[o]),x=st(()=>{let g={...e};return t&&!g.solana&&Y(t)&&(g.solana=t),t&&!g.evm&&G(t)&&(g.evm=t),g},[e,t]),f=st(()=>Ve({adapters:[re({verbose:o,rpcUrls:a}),se({verbose:o,rpcUrls:a})],wallets:x,preferredNetwork:r,rpcUrls:a,verbose:o,accessPass:{enabled:!0,autoRenew:!0}}),[x,r,a,o]),[u,S]=ae(0),m=st(()=>{if(!v||!I)return null;let g=new Date(I.expiresAt).getTime(),R=Math.max(0,Math.floor((g-Date.now())/1e3));return R<=0?null:{jwt:v,tier:I.tier,expiresAt:I.expiresAt,remainingSeconds:R}},[v,I,u]),O=m!==null&&m.remainingSeconds>0;rt(()=>{if(!v||!I)return;let g=setInterval(()=>S(R=>R+1),1e3);return()=>clearInterval(g)},[O]);let L=Je(async()=>{j(!0);try{let g=await fetch(n);if(g.status===402){let R=g.headers.get("X-ACCESS-PASS-TIERS");if(R){let b=JSON.parse(atob(R));_(b.tiers||null),U(b.ratePerHour||null),y("Tier info loaded:",b)}}}catch(g){y("Failed to fetch tiers:",g)}finally{j(!1)}},[n,y]);rt(()=>{l&&L()},[l,L]);let N=Je(async(g,R)=>{$(!0),k(null);try{let b=n;g?b+=(b.includes("?")?"&":"?")+`tier=${g}`:R&&(b+=(b.includes("?")?"&":"?")+`duration=${R}`);let F=await f.fetch(b,{method:"POST"}),K=F.headers.get("ACCESS-PASS");if(y("ACCESS-PASS header:",K?"found":"NOT FOUND"),K){C(K);let q=g||"unknown",V="";try{let H=await F.json();q=H.accessPass?.tier||q,V=H.accessPass?.expiresAt||""}catch{}if(!V)try{let H=K.split(".");if(H.length===3){let ee=JSON.parse(atob(H[1].replace(/-/g,"+").replace(/_/g,"/")));q=ee.tier||q,V=new Date(ee.exp*1e3).toISOString()}}catch{}w({tier:q,expiresAt:V}),E(K,q,V),y("Pass purchased and persisted:",q,V)}}catch(b){let F=b instanceof Error?b:new Error(String(b));throw k(F),F}finally{$(!1)}},[n,f,y]),M=Je(async(g,R)=>{let b=!g||g===""?n:g.startsWith("http")?g:`${n.replace(/\/$/,"")}${g.startsWith("/")?"":"/"}${g}`,F=h.current;if(F){try{let K=F.split(".");if(K.length===3){let q=JSON.parse(atob(K[1].replace(/-/g,"+").replace(/_/g,"/")));if(q.exp&&q.exp>Date.now()/1e3)return fetch(b,{...R,headers:{...R?.headers||{},Authorization:`Bearer ${F}`}})}}catch{}C(null),w(null);try{sessionStorage.removeItem(i)}catch{}}return f.fetch(b,R)},[n,f,i]);return{tiers:A,customRatePerHour:p,isLoadingTiers:B,pass:m,isPassValid:O,fetchTiers:L,purchasePass:N,isPurchasing:W,purchaseError:X,fetch:M}}export{D as X402Error,nt as fireImpressionBeacon,tt as getSponsoredRecommendations,It as useAccessPass,_t as useX402Payment};
@@ -1,12 +1,12 @@
1
- import { P as PaymentAccept, V as VerifyResponse, e as SettleResponse, f as PayToProvider, g as PaymentRequired } from '../types-htvWHuW3.cjs';
2
- export { j as AccessPassClaims, A as AccessPassClientConfig, d as AccessPassInfo, b as AccessPassTier, h as PayToContext, i as PayToProviderDefaults } from '../types-htvWHuW3.cjs';
1
+ import { P as PaymentAccept, V as VerifyResponse, f as SettleResponse, g as PayToProvider, h as PaymentRequired } from '../types-RxdlGPaG.cjs';
2
+ export { k as AccessPassClaims, A as AccessPassClientConfig, e as AccessPassInfo, d as AccessPassTier, i as PayToContext, j as PayToProviderDefaults } from '../types-RxdlGPaG.cjs';
3
3
  import * as _x402_evm_batch_settlement_server from '@x402/evm/batch-settlement/server';
4
4
  import { Request, RequestHandler } from 'express';
5
5
  import { SponsoredRecommendation } from '@dexterai/x402-ads-types';
6
6
  export { SPONSORED_ACCESS_EXTENSION_KEY, SponsoredAccessClientConsent, SponsoredAccessPaymentRequiredInfo, SponsoredAccessSettlementInfo, SponsoredRecommendation } from '@dexterai/x402-ads-types';
7
- import { B as BatchSettlementSeller } from '../types-pOwQlGEV.cjs';
7
+ import { B as BatchSettlementSeller } from '../types-CiPcPs0w.cjs';
8
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-qU-4U3L-.cjs';
9
- import '../types-XG8QvfyL.cjs';
9
+ import '../types-C8lyIOmX.cjs';
10
10
  import '@x402/evm/batch-settlement/client';
11
11
 
12
12
  /**
@@ -615,6 +615,10 @@ declare function declareDiscoveryExtension(config: DeclareDiscoveryConfig): Reco
615
615
  /**
616
616
  * x402 Browser Support Middleware
617
617
  *
618
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. No replacement —
619
+ * the browser-paywall HTML page was a v1-era convenience that never picked
620
+ * up real consumers. Build a custom paywall page in your app if you need one.
621
+ *
618
622
  * Express middleware that automatically renders a branded HTML paywall page
619
623
  * when a browser (Accept: text/html) receives a 402 Payment Required response.
620
624
  * API clients continue to receive the standard JSON response unchanged.
@@ -665,12 +669,20 @@ declare function escapeHtml(s: string): string;
665
669
  * instead of raw JSON.
666
670
  *
667
671
  * API clients are completely unaffected -- they receive normal JSON.
672
+ *
673
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. No replacement —
674
+ * build a custom browser paywall page in your application if you need one.
668
675
  */
669
676
  declare function x402BrowserSupport(config?: X402BrowserSupportConfig): RequestHandler;
670
677
 
671
678
  /**
672
679
  * x402 Access Pass Middleware
673
680
  *
681
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. No replacement —
682
+ * Access Pass was a v1-era stopgap before x402 v2 dynamic pricing landed.
683
+ * The same product story is served better by per-request payments with
684
+ * `payAndFetch` on the client and `x402Middleware` on the server.
685
+ *
674
686
  * Pay once, get a time-limited JWT for unlimited API requests.
675
687
  * Supports both predefined tiers and custom durations.
676
688
  *
@@ -763,12 +775,19 @@ interface X402AccessPassRequest extends Request {
763
775
  *
764
776
  * Protects routes with time-limited access passes purchased via x402 payments.
765
777
  * Supports predefined tiers, custom durations, or both.
778
+ *
779
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. No replacement —
780
+ * use per-request `x402Middleware` with `payAndFetch` clients.
766
781
  */
767
782
  declare function x402AccessPass(config: X402AccessPassConfig): RequestHandler;
768
783
 
769
784
  /**
770
785
  * Dynamic Pricing for x402
771
786
  *
787
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. Use x402 v2 dynamic
788
+ * pricing on the server (compute the amount per request and pass it to
789
+ * `x402Middleware`), which superseded this character-based v1 helper.
790
+ *
772
791
  * Calculate prices based on input length (characters, tokens, etc.)
773
792
  * Perfect for LLM/AI endpoints where cost scales with input size.
774
793
  *
@@ -862,6 +881,10 @@ interface DynamicPricing {
862
881
  }
863
882
  /**
864
883
  * Create a dynamic pricing calculator
884
+ *
885
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. Use x402 v2 dynamic
886
+ * pricing instead — compute the price per request in your handler and pass it
887
+ * to `x402Middleware`.
865
888
  */
866
889
  declare function createDynamicPricing(config: DynamicPricingConfig): DynamicPricing;
867
890
  /**
@@ -873,6 +896,11 @@ declare function formatPricing(config: DynamicPricingConfig): string;
873
896
  /**
874
897
  * Token-Based Pricing for x402
875
898
  *
899
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0 (along with the
900
+ * underlying `model-registry.ts`). The hardcoded OpenAI pricing catalog goes
901
+ * stale within weeks; use x402 v2 dynamic pricing and price the request in
902
+ * your handler with live rates from your model provider.
903
+ *
876
904
  * Accurate LLM pricing using tiktoken for token counting.
877
905
  * Uses real OpenAI model rates for precise cost calculation.
878
906
  *
@@ -919,6 +947,10 @@ interface ModelPricing$1 {
919
947
  * The registry is the single source of truth for all model information.
920
948
  *
921
949
  * Updated: January 2026
950
+ *
951
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. The catalog is a
952
+ * January 2026 snapshot and goes stale fast — price requests from your model
953
+ * provider's live API instead.
922
954
  */
923
955
  declare const MODEL_PRICING: Record<string, ModelPricing$1>;
924
956
  /**
@@ -1024,6 +1056,9 @@ interface TokenPricing {
1024
1056
  declare function countTokens(text: string, model?: string): Promise<number>;
1025
1057
  /**
1026
1058
  * Create a token-based pricing calculator
1059
+ *
1060
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. Price requests with
1061
+ * your model provider's live API and pass the amount to `x402Middleware`.
1027
1062
  */
1028
1063
  declare function createTokenPricing(config?: TokenPricingConfig): TokenPricing;
1029
1064
  /**
@@ -1049,6 +1084,12 @@ declare function formatTokenPricing(model?: string): string;
1049
1084
  /**
1050
1085
  * OpenAI Model Registry
1051
1086
  *
1087
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0 (bundled with the
1088
+ * `token-pricing.ts` removal — `MODEL_PRICING_MAP` here is the underlying
1089
+ * data source for token-pricing's `MODEL_PRICING` re-export). The hardcoded
1090
+ * January 2026 snapshot goes stale fast; use your model provider's live API
1091
+ * instead.
1092
+ *
1052
1093
  * The single source of truth for all OpenAI models.
1053
1094
  * Contains pricing, capabilities, API requirements, and constraints.
1054
1095
  *
@@ -1151,6 +1192,9 @@ interface ModelDefinition {
1151
1192
  /**
1152
1193
  * Complete registry of all OpenAI models
1153
1194
  * Ordered by tier, then by capability rank (ascending)
1195
+ *
1196
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. Hardcoded January
1197
+ * 2026 snapshot — use your model provider's live API instead.
1154
1198
  */
1155
1199
  declare const MODEL_REGISTRY: ModelDefinition[];
1156
1200
  /**
@@ -1201,6 +1245,9 @@ declare function estimateCost(modelId: string, inputTokens: number, outputTokens
1201
1245
  declare function formatModelPricing(modelId: string): string;
1202
1246
  /**
1203
1247
  * Simple pricing map for token-pricing.ts compatibility
1248
+ *
1249
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0 alongside
1250
+ * `token-pricing.ts`. Hardcoded snapshot — use live provider rates instead.
1204
1251
  */
1205
1252
  declare const MODEL_PRICING_MAP: Record<string, {
1206
1253
  input: number;
@@ -1213,6 +1260,14 @@ declare const MODEL_PRICING_MAP: Record<string, {
1213
1260
  /**
1214
1261
  * Stripe Machine Payments — PayTo Provider
1215
1262
  *
1263
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. No replacement —
1264
+ * the Stripe machine-payments path was a v1-era hypothesis aimed at merchants
1265
+ * who wanted to accept x402 with Stripe-as-acquirer. The current x402 audience
1266
+ * is agents paying USDC directly; integrate Stripe at your own application
1267
+ * layer if you still need it. The `getStripeProviderNetwork` helper and the
1268
+ * Stripe-network check in `x402Middleware` are removed alongside this file in
1269
+ * 4.0.
1270
+ *
1216
1271
  * Generates per-request Stripe deposit addresses via PaymentIntents.
1217
1272
  * Payments land in your Stripe Dashboard with full reporting, taxes, and refunds.
1218
1273
  *
@@ -1274,6 +1329,9 @@ interface StripePayToConfig {
1274
1329
  *
1275
1330
  * @param secretKeyOrConfig - Stripe secret key string, or full config object
1276
1331
  * @returns A PayToProvider function with auto-configuration defaults
1332
+ *
1333
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. No replacement —
1334
+ * integrate Stripe at your application layer if still needed.
1277
1335
  */
1278
1336
  declare function stripePayTo(secretKeyOrConfig: string | StripePayToConfig): PayToProvider;
1279
1337
 
@@ -1,12 +1,12 @@
1
- import { P as PaymentAccept, V as VerifyResponse, e as SettleResponse, f as PayToProvider, g as PaymentRequired } from '../types-htvWHuW3.js';
2
- export { j as AccessPassClaims, A as AccessPassClientConfig, d as AccessPassInfo, b as AccessPassTier, h as PayToContext, i as PayToProviderDefaults } from '../types-htvWHuW3.js';
1
+ import { P as PaymentAccept, V as VerifyResponse, f as SettleResponse, g as PayToProvider, h as PaymentRequired } from '../types-RxdlGPaG.js';
2
+ export { k as AccessPassClaims, A as AccessPassClientConfig, e as AccessPassInfo, d as AccessPassTier, i as PayToContext, j as PayToProviderDefaults } from '../types-RxdlGPaG.js';
3
3
  import * as _x402_evm_batch_settlement_server from '@x402/evm/batch-settlement/server';
4
4
  import { Request, RequestHandler } from 'express';
5
5
  import { SponsoredRecommendation } from '@dexterai/x402-ads-types';
6
6
  export { SPONSORED_ACCESS_EXTENSION_KEY, SponsoredAccessClientConsent, SponsoredAccessPaymentRequiredInfo, SponsoredAccessSettlementInfo, SponsoredRecommendation } from '@dexterai/x402-ads-types';
7
- import { B as BatchSettlementSeller } from '../types-DDBPREEu.js';
7
+ import { B as BatchSettlementSeller } from '../types-D9VMq7In.js';
8
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-qU-4U3L-.js';
9
- import '../types-DllrEG_Z.js';
9
+ import '../types-CTl7yVq6.js';
10
10
  import '@x402/evm/batch-settlement/client';
11
11
 
12
12
  /**
@@ -615,6 +615,10 @@ declare function declareDiscoveryExtension(config: DeclareDiscoveryConfig): Reco
615
615
  /**
616
616
  * x402 Browser Support Middleware
617
617
  *
618
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. No replacement —
619
+ * the browser-paywall HTML page was a v1-era convenience that never picked
620
+ * up real consumers. Build a custom paywall page in your app if you need one.
621
+ *
618
622
  * Express middleware that automatically renders a branded HTML paywall page
619
623
  * when a browser (Accept: text/html) receives a 402 Payment Required response.
620
624
  * API clients continue to receive the standard JSON response unchanged.
@@ -665,12 +669,20 @@ declare function escapeHtml(s: string): string;
665
669
  * instead of raw JSON.
666
670
  *
667
671
  * API clients are completely unaffected -- they receive normal JSON.
672
+ *
673
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. No replacement —
674
+ * build a custom browser paywall page in your application if you need one.
668
675
  */
669
676
  declare function x402BrowserSupport(config?: X402BrowserSupportConfig): RequestHandler;
670
677
 
671
678
  /**
672
679
  * x402 Access Pass Middleware
673
680
  *
681
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. No replacement —
682
+ * Access Pass was a v1-era stopgap before x402 v2 dynamic pricing landed.
683
+ * The same product story is served better by per-request payments with
684
+ * `payAndFetch` on the client and `x402Middleware` on the server.
685
+ *
674
686
  * Pay once, get a time-limited JWT for unlimited API requests.
675
687
  * Supports both predefined tiers and custom durations.
676
688
  *
@@ -763,12 +775,19 @@ interface X402AccessPassRequest extends Request {
763
775
  *
764
776
  * Protects routes with time-limited access passes purchased via x402 payments.
765
777
  * Supports predefined tiers, custom durations, or both.
778
+ *
779
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. No replacement —
780
+ * use per-request `x402Middleware` with `payAndFetch` clients.
766
781
  */
767
782
  declare function x402AccessPass(config: X402AccessPassConfig): RequestHandler;
768
783
 
769
784
  /**
770
785
  * Dynamic Pricing for x402
771
786
  *
787
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. Use x402 v2 dynamic
788
+ * pricing on the server (compute the amount per request and pass it to
789
+ * `x402Middleware`), which superseded this character-based v1 helper.
790
+ *
772
791
  * Calculate prices based on input length (characters, tokens, etc.)
773
792
  * Perfect for LLM/AI endpoints where cost scales with input size.
774
793
  *
@@ -862,6 +881,10 @@ interface DynamicPricing {
862
881
  }
863
882
  /**
864
883
  * Create a dynamic pricing calculator
884
+ *
885
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. Use x402 v2 dynamic
886
+ * pricing instead — compute the price per request in your handler and pass it
887
+ * to `x402Middleware`.
865
888
  */
866
889
  declare function createDynamicPricing(config: DynamicPricingConfig): DynamicPricing;
867
890
  /**
@@ -873,6 +896,11 @@ declare function formatPricing(config: DynamicPricingConfig): string;
873
896
  /**
874
897
  * Token-Based Pricing for x402
875
898
  *
899
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0 (along with the
900
+ * underlying `model-registry.ts`). The hardcoded OpenAI pricing catalog goes
901
+ * stale within weeks; use x402 v2 dynamic pricing and price the request in
902
+ * your handler with live rates from your model provider.
903
+ *
876
904
  * Accurate LLM pricing using tiktoken for token counting.
877
905
  * Uses real OpenAI model rates for precise cost calculation.
878
906
  *
@@ -919,6 +947,10 @@ interface ModelPricing$1 {
919
947
  * The registry is the single source of truth for all model information.
920
948
  *
921
949
  * Updated: January 2026
950
+ *
951
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. The catalog is a
952
+ * January 2026 snapshot and goes stale fast — price requests from your model
953
+ * provider's live API instead.
922
954
  */
923
955
  declare const MODEL_PRICING: Record<string, ModelPricing$1>;
924
956
  /**
@@ -1024,6 +1056,9 @@ interface TokenPricing {
1024
1056
  declare function countTokens(text: string, model?: string): Promise<number>;
1025
1057
  /**
1026
1058
  * Create a token-based pricing calculator
1059
+ *
1060
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. Price requests with
1061
+ * your model provider's live API and pass the amount to `x402Middleware`.
1027
1062
  */
1028
1063
  declare function createTokenPricing(config?: TokenPricingConfig): TokenPricing;
1029
1064
  /**
@@ -1049,6 +1084,12 @@ declare function formatTokenPricing(model?: string): string;
1049
1084
  /**
1050
1085
  * OpenAI Model Registry
1051
1086
  *
1087
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0 (bundled with the
1088
+ * `token-pricing.ts` removal — `MODEL_PRICING_MAP` here is the underlying
1089
+ * data source for token-pricing's `MODEL_PRICING` re-export). The hardcoded
1090
+ * January 2026 snapshot goes stale fast; use your model provider's live API
1091
+ * instead.
1092
+ *
1052
1093
  * The single source of truth for all OpenAI models.
1053
1094
  * Contains pricing, capabilities, API requirements, and constraints.
1054
1095
  *
@@ -1151,6 +1192,9 @@ interface ModelDefinition {
1151
1192
  /**
1152
1193
  * Complete registry of all OpenAI models
1153
1194
  * Ordered by tier, then by capability rank (ascending)
1195
+ *
1196
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. Hardcoded January
1197
+ * 2026 snapshot — use your model provider's live API instead.
1154
1198
  */
1155
1199
  declare const MODEL_REGISTRY: ModelDefinition[];
1156
1200
  /**
@@ -1201,6 +1245,9 @@ declare function estimateCost(modelId: string, inputTokens: number, outputTokens
1201
1245
  declare function formatModelPricing(modelId: string): string;
1202
1246
  /**
1203
1247
  * Simple pricing map for token-pricing.ts compatibility
1248
+ *
1249
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0 alongside
1250
+ * `token-pricing.ts`. Hardcoded snapshot — use live provider rates instead.
1204
1251
  */
1205
1252
  declare const MODEL_PRICING_MAP: Record<string, {
1206
1253
  input: number;
@@ -1213,6 +1260,14 @@ declare const MODEL_PRICING_MAP: Record<string, {
1213
1260
  /**
1214
1261
  * Stripe Machine Payments — PayTo Provider
1215
1262
  *
1263
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. No replacement —
1264
+ * the Stripe machine-payments path was a v1-era hypothesis aimed at merchants
1265
+ * who wanted to accept x402 with Stripe-as-acquirer. The current x402 audience
1266
+ * is agents paying USDC directly; integrate Stripe at your own application
1267
+ * layer if you still need it. The `getStripeProviderNetwork` helper and the
1268
+ * Stripe-network check in `x402Middleware` are removed alongside this file in
1269
+ * 4.0.
1270
+ *
1216
1271
  * Generates per-request Stripe deposit addresses via PaymentIntents.
1217
1272
  * Payments land in your Stripe Dashboard with full reporting, taxes, and refunds.
1218
1273
  *
@@ -1274,6 +1329,9 @@ interface StripePayToConfig {
1274
1329
  *
1275
1330
  * @param secretKeyOrConfig - Stripe secret key string, or full config object
1276
1331
  * @returns A PayToProvider function with auto-configuration defaults
1332
+ *
1333
+ * @deprecated Slated for removal in `@dexterai/x402` 4.0. No replacement —
1334
+ * integrate Stripe at your application layer if still needed.
1277
1335
  */
1278
1336
  declare function stripePayTo(secretKeyOrConfig: string | StripePayToConfig): PayToProvider;
1279
1337
 
@@ -1,5 +1,5 @@
1
1
  import { ClientChannelStorage } from '@x402/evm/batch-settlement/client';
2
- import { E as EvmWallet } from './types-htvWHuW3.cjs';
2
+ import { E as EvmWallet } from './types-RxdlGPaG.cjs';
3
3
 
4
4
  /**
5
5
  * Buyer withdrawal escape hatch for batch-settlement escrow channels.
@@ -1,5 +1,5 @@
1
1
  import { ClientChannelStorage } from '@x402/evm/batch-settlement/client';
2
- import { E as EvmWallet } from './types-htvWHuW3.js';
2
+ import { E as EvmWallet } from './types-RxdlGPaG.js';
3
3
 
4
4
  /**
5
5
  * Buyer withdrawal escape hatch for batch-settlement escrow channels.
@@ -1,6 +1,6 @@
1
1
  import { RequestHandler } from 'express';
2
2
  import { ChannelStorage } from '@x402/evm/batch-settlement/server';
3
- import { b as CloseReceipt } from './types-XG8QvfyL.cjs';
3
+ import { b as CloseReceipt } from './types-C8lyIOmX.cjs';
4
4
 
5
5
  /**
6
6
  * Result of closing one channel from the seller side. Either a settlement
@@ -1,6 +1,6 @@
1
1
  import { RequestHandler } from 'express';
2
2
  import { ChannelStorage } from '@x402/evm/batch-settlement/server';
3
- import { b as CloseReceipt } from './types-DllrEG_Z.js';
3
+ import { b as CloseReceipt } from './types-CTl7yVq6.js';
4
4
 
5
5
  /**
6
6
  * Result of closing one channel from the seller side. Either a settlement