@dexterai/x402 3.1.1 → 3.2.1

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
- "use strict";var He=Object.create;var he=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Qe=Object.prototype.hasOwnProperty;var Ze=(n,e)=>{for(var t in e)he(n,t,{get:e[t],enumerable:!0})},Me=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ze(e))!Qe.call(n,o)&&o!==t&&he(n,o,{get:()=>e[o],enumerable:!(s=Ye(e,o))||s.enumerable});return n};var ye=(n,e,t)=>(t=n!=null?He(Ge(n)):{},Me(e||!n||!n.__esModule?he(t,"default",{value:n,enumerable:!0}):t,n)),et=n=>Me(he({},"__esModule",{value:!0}),n);var it={};Ze(it,{X402Error:()=>D,fireImpressionBeacon:()=>Ie,getSponsoredRecommendations:()=>Ce,useAccessPass:()=>Ve,useX402Payment:()=>Ke});module.exports=et(it);var M=require("react");var ae="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",ce="eip155:8453";var Oe="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",We="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";var D=class n extends Error{code;details;constructor(e,t,s){super(t),this.name="X402Error",this.code=e,this.details=s,Object.setPrototypeOf(this,n.prototype)}};var X=require("@solana/web3.js"),J=require("@solana/spl-token"),fe="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",we="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Se="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",le={[fe]:"https://api.dexter.cash/api/solana/rpc",[we]:"https://api.devnet.solana.com",[Se]:"https://api.testnet.solana.com"},tt=12e3,nt=1;function G(n){if(!n||typeof n!="object")return!1;let e=n;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var Ae=class{name="Solana";networks=[fe,we,Se];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[fe]:e==="solana-devnet"?le[we]:e==="solana-testnet"?le[Se]:le[fe]}getAddress(e){return G(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return G(e)?e.publicKey!==null:!1}async getBalance(e,t,s){if(!G(t)||!t.publicKey)return 0;let o=s||this.getDefaultRpcUrl(e.network),r=new X.Connection(o,"confirmed"),f=new X.PublicKey(t.publicKey.toBase58()),a=new X.PublicKey(e.asset);try{let m=(await r.getAccountInfo(a,"confirmed"))?.owner.toBase58()===J.TOKEN_2022_PROGRAM_ID.toBase58()?J.TOKEN_2022_PROGRAM_ID:J.TOKEN_PROGRAM_ID,P=await(0,J.getAssociatedTokenAddress)(a,f,!1,m),E=await(0,J.getAccount)(r,P,void 0,m),T=e.extra?.decimals??6;return Number(E.amount)/Math.pow(10,T)}catch(p){if(p&&typeof p=="object"&&"name"in p&&(p.name==="TokenAccountNotFoundError"||p.name==="TokenInvalidAccountOwnerError"))return 0;throw p}}async buildTransaction(e,t,s){if(!G(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let o=s||this.getDefaultRpcUrl(e.network),r=new X.Connection(o,"confirmed"),f=new X.PublicKey(t.publicKey.toBase58()),{payTo:a,asset:p,extra:m}=e,P=e.amount??e.maxAmountRequired;if(!P)throw new Error("Missing amount in payment requirements");if(!m?.feePayer)throw new Error("Missing feePayer in payment requirements");let E=new X.PublicKey(m.feePayer),T=new X.PublicKey(p),i=new X.PublicKey(a);this.log("Building transaction:",{from:f.toBase58(),to:a,amount:P,asset:p,feePayer:m.feePayer});let k=[];k.push(X.ComputeBudgetProgram.setComputeUnitLimit({units:tt})),k.push(X.ComputeBudgetProgram.setComputeUnitPrice({microLamports:nt}));let O=await r.getAccountInfo(T,"confirmed");if(!O)throw new Error(`Token mint ${p} not found`);let $=O.owner.toBase58()===J.TOKEN_2022_PROGRAM_ID.toBase58()?J.TOKEN_2022_PROGRAM_ID:J.TOKEN_PROGRAM_ID,H=await(0,J.getMint)(r,T,void 0,$);typeof m?.decimals=="number"&&H.decimals!==m.decimals&&this.log(`Decimals mismatch: requirements say ${m.decimals}, mint says ${H.decimals}`);let R=await(0,J.getAssociatedTokenAddress)(T,f,!1,$),W=await(0,J.getAssociatedTokenAddress)(T,i,!1,$);if(!await r.getAccountInfo(R,"confirmed"))throw new Error(`No token account found for ${p}. Please ensure you have USDC in your wallet.`);if(!await r.getAccountInfo(W,"confirmed"))throw new Error(`Seller token account not found. The seller (${a}) must have a USDC account.`);let q=BigInt(P);k.push((0,J.createTransferCheckedInstruction)(R,T,W,f,q,H.decimals,[],$));let{blockhash:L}=await r.getLatestBlockhash("confirmed"),c=new X.TransactionMessage({payerKey:E,recentBlockhash:L,instructions:k}).compileToV0Message(),l=new X.VersionedTransaction(c),S=await t.signTransaction(l);return this.log("Transaction signed successfully"),{serialized:Buffer.from(S.serialize()).toString("base64")}}};function te(n){return new Ae(n)}var me="0x000000000022D473030F116dDEE9F6B43aC78BA3",_e="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",rt={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"}]},$e=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),ie="eip155:8453",ge="eip155:84532",pe="eip155:42161",be="eip155:137",Pe="eip155:10",Ee="eip155:43114",ue="eip155:56",Re="eip155:1187947933",Te="eip155:324705682",de="eip155:1",Le="0x55d398326f99059fF775485246999027B3197955",Ne="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",qe={[ue]:56,[ie]:8453,[ge]:84532,[pe]:42161,[be]:137,[Pe]:10,[Ee]:43114,[Re]:1187947933,[Te]:324705682,[de]:1},oe={[ue]:"https://bsc-dataseed1.binance.org",[ie]:"https://api.dexter.cash/api/base/rpc",[ge]:"https://sepolia.base.org",[pe]:"https://arb1.arbitrum.io/rpc",[be]:"https://polygon-rpc.com",[Pe]:"https://mainnet.optimism.io",[Ee]:"https://api.avax.network/ext/bc/C/rpc",[Re]:"https://skale-base.skalenodes.com/v1/base",[Te]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[de]:"https://eth.llamarpc.com"},Be={[ue]:Ne,[ie]:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",[ge]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[pe]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[be]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[Pe]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[Ee]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[Re]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[Te]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[de]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},Ue={[Le]:{symbol:"USDT",decimals:18},[Ne]:{symbol:"USDC",decimals:18}};function Q(n){if(!n||typeof n!="object")return!1;let e=n;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var xe=class{name="EVM";networks=[ue,ie,ge,de,pe];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.startsWith("eip155:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:oe[e]?oe[e]:e==="base"?oe[ie]:e==="bsc"?oe[ue]:e==="ethereum"?oe[de]:e==="arbitrum"?oe[pe]:oe[ie]}getAddress(e){return Q(e)?e.address:null}isConnected(e){return Q(e)?!!e.address:!1}getChainId(e){if(qe[e])return qe[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,s){if(!Q(t)||!t.address)return 0;let o=s||this.getDefaultRpcUrl(e.network);try{let r=this.encodeBalanceOf(t.address),f=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:r},"latest"]})});if(!f.ok)throw new Error(`RPC request failed: ${f.status}`);let a=await f.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),m=e.extra?.decimals??6;return Number(p)/Math.pow(10,m)}catch(r){throw r}}encodeBalanceOf(e){let t="0x70a08231",s=e.slice(2).toLowerCase().padStart(64,"0");return t+s}async buildTransaction(e,t,s){if(!Q(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,s);if(e.extra?.assetTransferMethod==="permit2")return this.buildPermit2Transaction(e,t,s);let{payTo:o,asset:r,extra:f}=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:r,network:e.network});let p=this.getChainId(e.network),m={name:f?.name??"USD Coin",version:f?.version??"2",chainId:BigInt(p),verifyingContract:r},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"}]},E=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(E);let T="0x"+[...E].map(R=>R.toString(16).padStart(2,"0")).join(""),i=Math.floor(Date.now()/1e3),k={from:t.address,to:o,value:a,validAfter:String(i-600),validBefore:String(i+(e.maxTimeoutSeconds||60)),nonce:T},O={from:t.address,to:o,value:BigInt(a),validAfter:BigInt(i-600),validBefore:BigInt(i+(e.maxTimeoutSeconds||60)),nonce:T};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let $=await t.signTypedData({domain:m,types:P,primaryType:"TransferWithAuthorization",message:O});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:k,signature:$}),signature:$}}async buildApprovalTransaction(e,t,s){let{payTo:o,asset:r,extra:f}=e,a=e.amount??e.maxAmountRequired;if(!a)throw new Error("Missing amount in payment requirements");let p=f?.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:o,amount:a,asset:r,network:e.network,facilitatorContract:p});let m=s||this.getDefaultRpcUrl(e.network),P=f?.fee??"0",E=BigInt(a)+BigInt(P),T=await this.readAllowance(m,r,t.address,p);if(T<E){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,f?.approvalStrategy);this.log(`Approving ${l} for ${p} (current allowance: ${T})`);let S=await t.sendTransaction({to:r,data:this.encodeApprove(p,l),value:0n});this.log(`Approval tx sent: ${S}`),await this.waitForReceipt(m,S),this.log("Approval confirmed")}else this.log("Sufficient allowance, skipping approval");let i=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(i);let k=[...i].reduce((l,S)=>l*256n+BigInt(S),0n).toString(),O=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(O);let $="0x"+[...O].map(l=>l.toString(16).padStart(2,"0")).join(""),R=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),W=f?.eip712Domain,U=W?{name:W.name,version:W.version,chainId:BigInt(W.chainId),verifyingContract:W.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:p},x=f?.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"}]},q={from:t.address,to:o,token:r,amount:BigInt(a),fee:BigInt(P),nonce:BigInt(k),deadline:BigInt(R),paymentId:$},L=await t.signTypedData({domain:U,types:x,primaryType:"Payment",message:q});this.log("EIP-712 Payment signature obtained");let c={from:t.address,to:o,token:r,amount:a,fee:P,nonce:k,deadline:R,paymentId:$,signature:L};return{serialized:JSON.stringify(c),signature:L}}async buildPermit2Transaction(e,t,s){let{payTo:o,asset:r}=e,f=e.amount??e.maxAmountRequired;if(!f)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:f,asset:r,network:e.network});let a=s||this.getDefaultRpcUrl(e.network),p=await this.readAllowance(a,r,t.address,me),m;if(p<BigInt(f)){let U=this.encodeApprove(me,$e);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${p})`);let x=this.getChainId(e.network),q=await this.readGasPrice(a),L=await this.readNonce(a,t.address),c=await t.signTransaction({to:r,data:U,chainId:x,gas:50000n,gasPrice:q,nonce:L});m={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:r,spender:me,amount:$e.toString(),signedTransaction:c,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${p})`);let x=await t.sendTransaction({to:r,data:U,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 P=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(P);let E=[...P].reduce((U,x)=>U*256n+BigInt(x),0n),T=Math.floor(Date.now()/1e3),i=T-600,k=T+(e.maxTimeoutSeconds||300),O=this.getChainId(e.network),$={name:"Permit2",chainId:BigInt(O),verifyingContract:me},H={permitted:{token:r,amount:BigInt(f)},spender:_e,nonce:E,deadline:BigInt(k),witness:{to:o,validAfter:BigInt(i)}},R=await t.signTypedData({domain:$,types:rt,primaryType:"PermitWitnessTransferFrom",message:H});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let W={signature:R,permit2Authorization:{from:t.address,permitted:{token:r,amount:f},spender:_e,nonce:E.toString(),deadline:String(k),witness:{to:o,validAfter:String(i)}}};return{serialized:JSON.stringify(W),signature:R,extensions:m}}async readAllowance(e,t,s,o){let r="0xdd62ed3e",f=s.slice(2).toLowerCase().padStart(64,"0"),a=o.slice(2).toLowerCase().padStart(64,"0"),p=r+f+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 s="0x095ea7b3",o=e.slice(2).toLowerCase().padStart(64,"0"),r=t.toString(16).padStart(64,"0");return s+o+r}async waitForReceipt(e,t,s=3e4){let o=Date.now();for(;Date.now()-o<s;){try{let f=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(f.result){if(f.result.status==="0x0")throw new Error(`Approval transaction reverted: ${t}`);return}}catch(r){if(r instanceof Error&&r.message.includes("reverted"))throw r}await new Promise(r=>setTimeout(r,2e3))}throw new Error(`Approval transaction receipt timeout after ${s}ms: ${t}`)}async readGasPrice(e){try{let s=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 s.result?BigInt(s.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,s){let o=BigInt(e)+BigInt(t);if(!s||s.mode==="exact")return o;let r=BigInt(s.defaultMultiple??10),f=o*r;if(s.maxCapUsd){let a=this.inferDecimals(e),p=BigInt(Math.floor(s.maxCapUsd*Math.pow(10,a)));if(f>p)return p}if(s.exactAboveUsd){let a=this.inferDecimals(e),p=BigInt(Math.floor(s.exactAboveUsd*Math.pow(10,a)));if(BigInt(e)>p)return o}return f}inferDecimals(e){return e.length>12?18:6}};function ne(n){return new xe(n)}function De(n){if(n==="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"||n==="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU")return!0;let e=n.toLowerCase();for(let t of Object.values(Be))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(Ue))if(t.toLowerCase()===e)return!0;return!1}var je=new WeakMap;function Fe(n){return je.get(n)}function ve(n){let{adapters:e=[te({verbose:n.verbose}),ne({verbose:n.verbose})],wallets:t,wallet:s,preferredNetwork:o,rpcUrls:r={},maxAmountAtomic:f,fetch:a=globalThis.fetch,verbose:p=!1,accessPass:m,onPaymentRequired:P,maxRetries:E=0,retryDelayMs:T=500}=n,i=p?console.log.bind(console,"[x402]"):()=>{};async function k(c,l){let S;for(let u=0;u<=E;u++)try{let A=await a(c,l);if(A.status>=502&&A.status<=504&&u<E){i(`Retry ${u+1}/${E}: server returned ${A.status}`),await new Promise(v=>setTimeout(v,T*Math.pow(2,u)));continue}return A}catch(A){S=A,u<E&&(i(`Retry ${u+1}/${E}: ${A instanceof Error?A.message:"network error"}`),await new Promise(v=>setTimeout(v,T*Math.pow(2,u))))}throw S}let O=new Map;function $(c){try{let l=new URL(c).host,S=O.get(l);if(S&&S.expiresAt>Date.now()/1e3+10)return S.jwt;S&&O.delete(l)}catch{}return null}function H(c,l){try{let S=new URL(c).host,u=l.split(".");if(u.length===3){let A=JSON.parse(atob(u[1].replace(/-/g,"+").replace(/_/g,"/"))),v=Math.floor(Date.now()/1e3),y=v+86400,N=Math.min(typeof A.exp=="number"?A.exp:v,y);O.set(S,{jwt:l,expiresAt:N}),i("Access pass cached for",S,"| expires:",new Date(N*1e3).toISOString())}}catch{i("Failed to cache access pass")}}let R=t||{};s&&!R.solana&&G(s)&&(R.solana=s),s&&!R.evm&&Q(s)&&(R.evm=s);function W(c){let l=[];for(let S of c){let u=e.find(v=>v.canHandle(S.network));if(!u)continue;let A;u.name==="Solana"?A=R.solana:u.name==="EVM"&&(A=R.evm),A&&u.isConnected(A)&&l.push({accept:S,adapter:u,wallet:A})}if(l.length===0)return null;if(o){let S=l.find(u=>u.accept.network===o);if(S)return S}return l[0]}function U(c,l){return{"eip155:56":"BSC","eip155:8453":"Base","eip155:84532":"Base Sepolia","eip155:42161":"Arbitrum","eip155:137":"Polygon","eip155:10":"Optimism","eip155:43114":"Avalanche","eip155:1":"Ethereum"}[c]||l}function x(c,l){return r[c]||l.getDefaultRpcUrl(c)}async function q(c,l,S,u,A){let v="";if(m?.preferTier&&u.tiers){let d=u.tiers.find(ee=>ee.id===m.preferTier);if(d){if(m.maxSpend&&parseFloat(d.price)>parseFloat(m.maxSpend))throw new D("access_pass_exceeds_max_spend",`Access pass tier "${d.id}" costs $${d.price}, exceeds max spend $${m.maxSpend}`);v=`tier=${d.id}`}}else if(m?.preferDuration&&u.ratePerHour)v=`duration=${m.preferDuration}`;else if(u.tiers&&u.tiers.length>0){let d=u.tiers[0];if(m?.maxSpend&&parseFloat(d.price)>parseFloat(m.maxSpend))throw new D("access_pass_exceeds_max_spend",`Cheapest access pass costs $${d.price}, exceeds max spend $${m?.maxSpend}`);v=`tier=${d.id}`}let y=v?A.includes("?")?`${A}&${v}`:`${A}?${v}`:A;i("Purchasing access pass:",v||"default tier");let N=S.headers.get("PAYMENT-REQUIRED");if(!N)return null;let w;try{w=JSON.parse(atob(N))}catch{return null}let b=W(w.accepts);if(!b)return null;let{accept:C,adapter:K,wallet:re}=b;if(K.name==="Solana"&&!C.extra?.feePayer)return null;let g=C.extra?.decimals??(De(C.asset)?6:void 0);if(typeof g!="number")return null;let _=C.amount??C.maxAmountRequired;if(!_)return null;let I=x(C.network,K);try{let d=await K.getBalance(C,re,I),ee=Number(_)/Math.pow(10,g);if(d<ee)throw new D("insufficient_balance",`Insufficient balance for access pass. Have $${d.toFixed(4)}, need $${ee.toFixed(4)}`)}catch(d){if(d instanceof D)throw d}let j=await K.buildTransaction(C,re,I),V;K.name==="EVM"?V=JSON.parse(j.serialized):V={transaction:j.serialized};let F=typeof c=="string"?c:c instanceof URL?c.href:c.url,Y=w.resource;if(typeof w.resource=="string")try{let d=new URL(w.resource,F);["http:","https:"].includes(d.protocol)&&(Y=d.toString())}catch{}else if(w.resource&&typeof w.resource=="object"&&"url"in w.resource){let d=w.resource;try{let ee=new URL(d.url,F);["http:","https:"].includes(ee.protocol)&&(Y={...d,url:ee.toString()})}catch{}}let Z={x402Version:C.x402Version??2,resource:Y,accepted:C,payload:V};j.extensions&&(Z.extensions=j.extensions);let z=btoa(JSON.stringify(Z)),se=await a(y,{...l,method:"POST",headers:{...l?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":z}});if(!se.ok)return i("Pass purchase failed:",se.status),null;let h=se.headers.get("ACCESS-PASS");return h&&(H(A,h),i("Access pass purchased and cached")),se}async function L(c,l){let S=typeof c=="string"?c:c instanceof URL?c.href:c.url;if(i("Making request:",S),m){let h=$(S);if(h){i("Using cached access pass");let d=await a(c,{...l,headers:{...l?.headers||{},Authorization:`Bearer ${h}`}});if(d.status!==401&&d.status!==402)return d;i("Cached pass rejected (status",d.status,"), purchasing new pass");try{O.delete(new URL(S).host)}catch{}}}let u=await k(c,l);if(u.status!==402)return u;i("Received 402 Payment Required");let A=u.headers.get("X-ACCESS-PASS-TIERS");if(m&&A){i("Server offers access passes, purchasing...");try{let h=JSON.parse(atob(A)),d=await q(c,l,u,h,S);if(d)return d}catch(h){i("Access pass purchase failed, falling back to per-request payment:",h)}}let v=u.headers.get("PAYMENT-REQUIRED");if(!v)throw new D("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let y;try{let h=atob(v);y=JSON.parse(h)}catch{throw new D("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}i("Payment requirements:",y);let N=u.headers.get("X-Quote-Hash");N&&i("Quote hash received:",N);let w=W(y.accepts);if(!w){let h=y.accepts.map(d=>d.network).join(", ");throw new D("no_matching_payment_option",`No connected wallet for any available network: ${h}`)}let{accept:b,adapter:C,wallet:K}=w;if(i(`Using ${C.name} for ${b.network}`),C.name==="Solana"&&!b.extra?.feePayer)throw new D("missing_fee_payer","Solana payment option missing feePayer in extra");let re=b.extra?.decimals??(De(b.asset)?6:void 0);if(typeof re!="number")throw new D("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let g=b.amount??b.maxAmountRequired;if(!g)throw new D("missing_amount","Payment option missing amount");if(f&&BigInt(g)>BigInt(f))throw new D("amount_exceeds_max",`Payment amount ${g} exceeds maximum ${f}`);let _=x(b.network,C);i("Checking balance...");try{let h=await C.getBalance(b,K,_),d=Number(g)/Math.pow(10,re);if(h<d){let ee=U(b.network,C.name);throw new D("insufficient_balance",`Insufficient balance on ${ee}. Have $${h.toFixed(4)}, need $${d.toFixed(4)}`)}i(`Balance OK: $${h.toFixed(4)} >= $${d.toFixed(4)}`)}catch(h){if(h instanceof D)throw h;i("Balance check failed (RPC error), proceeding with transaction attempt")}if(P&&!await P(b))throw new D("payment_rejected","Payment rejected by onPaymentRequired callback");i("Building transaction...");let I=await C.buildTransaction(b,K,_);i("Transaction signed");let j;C.name==="EVM"?j=JSON.parse(I.serialized):j={transaction:I.serialized};let V=typeof c=="string"?c:c instanceof URL?c.href:c.url,F=y.resource;if(typeof y.resource=="string")try{let h=new URL(y.resource,V).toString();h!==y.resource&&i("Resolved relative resource URL:",y.resource,"\u2192",h),F=h}catch{F=y.resource}else if(y.resource&&typeof y.resource=="object"&&"url"in y.resource){let h=y.resource;try{let d=new URL(h.url,V).toString();d!==h.url&&(i("Resolved relative resource URL:",h.url,"\u2192",d),F={...h,url:d})}catch{}}let Y={x402Version:b.x402Version??2,resource:F,accepted:b,payload:j};I.extensions&&(Y.extensions=I.extensions);let Z=btoa(JSON.stringify(Y));i("Retrying request with payment...");let z=await k(c,{...l,headers:{...l?.headers||{},"PAYMENT-SIGNATURE":Z,...N?{"X-Quote-Hash":N}:{}}});if(i("Retry response status:",z.status),z.status===402){let h="unknown";try{let d=await z.clone().json();h=String(d.error||d.message||JSON.stringify(d)),i("Rejection reason:",h)}catch{}throw new D("payment_rejected",`Payment was rejected by the server: ${h}`)}let se=z.headers.get("PAYMENT-RESPONSE");if(se)try{let h=JSON.parse(atob(se));je.set(z,h),z._x402=h,h.extensions&&i("Settlement extensions:",Object.keys(h.extensions).join(", "))}catch{}return z}return{fetch:L}}function st(n){return n.startsWith("solana:")||n==="solana"}function at(n){return n.startsWith("eip155:")||["base","ethereum","arbitrum"].includes(n)}function ot(n){return st(n)?"solana":at(n)?"evm":"unknown"}function ke(n){return{[ae]:"Solana","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1":"Solana Devnet","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"Solana Testnet",solana:"Solana",[ce]:"Base","eip155:84532":"Base Sepolia","eip155:1":"Ethereum","eip155:42161":"Arbitrum One",base:"Base",ethereum:"Ethereum",arbitrum:"Arbitrum"}[n]||n}function Je(n,e){let t=ot(e);if(t==="solana")return e.includes("devnet")||e==="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"?`https://solscan.io/tx/${n}?cluster=devnet`:`https://www.orbmarkets.io/tx/${n}`;if(t==="evm"){let s="8453";switch(e.startsWith("eip155:")?s=e.split(":")[1]:e==="ethereum"?s="1":e==="arbitrum"&&(s="42161"),s){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}`;default:return`https://basescan.org/tx/${n}`}}return`https://solscan.io/tx/${n}`}function Xe(n){let e=Fe(n);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function Ce(n){let e=Xe(n);if(e?.recommendations?.length)return e.recommendations}async function Ie(n){let t=Xe(n)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function Ke(n){let{wallets:e,wallet:t,preferredNetwork:s,rpcUrls:o={},verbose:r=!1}=n,[f,a]=(0,M.useState)(!1),[p,m]=(0,M.useState)("idle"),[P,E]=(0,M.useState)(null),[T,i]=(0,M.useState)(null),[k,O]=(0,M.useState)(null),[$,H]=(0,M.useState)([]),[R,W]=(0,M.useState)(null),U=(0,M.useCallback)((...y)=>{r&&console.log("[useX402Payment]",...y)},[r]),x=(0,M.useMemo)(()=>{let y={...e};return t&&!y.solana&&G(t)&&(y.solana=t),t&&!y.evm&&Q(t)&&(y.evm=t),y},[e,t]),q=(0,M.useMemo)(()=>[te({verbose:r,rpcUrls:o}),ne({verbose:r,rpcUrls:o})],[r,o]),L=(0,M.useMemo)(()=>({solana:x.solana?G(x.solana)&&q[0].isConnected(x.solana):!1,evm:x.evm?Q(x.evm)&&q[1].isConnected(x.evm):!1}),[x,q]),c=L.solana||L.evm,l=(0,M.useCallback)(async()=>{let y=[];if(L.solana&&x.solana)try{let N=q.find(w=>w.name==="Solana");if(N){let w={scheme:"exact",network:ae,amount:"0",asset:Oe,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},b=await N.getBalance(w,x.solana);y.push({network:ae,chainName:ke(ae),balance:b,asset:"USDC"})}}catch(N){U("Failed to fetch Solana balance:",N)}if(L.evm&&x.evm)try{let N=q.find(w=>w.name==="EVM");if(N){let w={scheme:"exact",network:ce,amount:"0",asset:We,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},b=await N.getBalance(w,x.evm);y.push({network:ce,chainName:ke(ce),balance:b,asset:"USDC"})}}catch(N){U("Failed to fetch Base balance:",N)}H(y)},[L,x,q,U]);(0,M.useEffect)(()=>{l();let y=setInterval(l,3e4);return()=>clearInterval(y)},[l]);let S=(0,M.useCallback)(()=>{a(!1),m("idle"),E(null),i(null),O(null),W(null)},[]),u=(0,M.useMemo)(()=>ve({adapters:q,wallets:x,preferredNetwork:s,rpcUrls:o,verbose:r}),[q,x,s,o,r]),A=(0,M.useCallback)(async(y,N)=>{if(a(!0),m("pending"),E(null),i(null),O(null),!c){let w=new D("wallet_not_connected","No wallet connected");throw E(w),m("error"),a(!1),w}try{let w=await u.fetch(y,N),b=w.headers.get("PAYMENT-RESPONSE");if(b)try{let K=JSON.parse(atob(b));K.transaction&&i(K.transaction),K.network&&O(K.network)}catch{U("Could not parse PAYMENT-RESPONSE header")}let C=Ce(w);return W(C??null),C&&(U("Sponsored recommendations received:",C.length),Ie(w).catch(()=>{})),m("success"),w}catch(w){let b=w instanceof Error?w:new Error(String(w));throw E(b),m("error"),w}finally{a(!1),setTimeout(l,2e3)}},[u,c,U,l]),v=(0,M.useMemo)(()=>T?Je(T,k||s||ae):null,[T,k,s]);return{fetch:A,isLoading:f,status:p,error:P,transactionId:T,transactionNetwork:k,transactionUrl:v,balances:$,connectedChains:L,isAnyWalletConnected:c,reset:S,refreshBalances:l,accessPass:null,sponsoredRecommendations:R}}var B=require("react");function Ve(n){let{wallets:e,wallet:t,preferredNetwork:s,rpcUrls:o={},resourceUrl:r,autoConnect:f=!0,verbose:a=!1}=n,p=`x402-access-pass:${r}`;function m(){if(typeof sessionStorage>"u")return null;try{let g=sessionStorage.getItem(p);if(!g)return null;let _=JSON.parse(g);return new Date(_.expiresAt).getTime()<=Date.now()?(sessionStorage.removeItem(p),null):_}catch{return null}}function P(g,_,I){if(!(typeof sessionStorage>"u"))try{sessionStorage.setItem(p,JSON.stringify({jwt:g,tier:_,expiresAt:I}))}catch{}}let E=m(),[T,i]=(0,B.useState)(null),[k,O]=(0,B.useState)(null),[$,H]=(0,B.useState)(!1),[R,W]=(0,B.useState)(E?.jwt||null),[U,x]=(0,B.useState)(E?{tier:E.tier,expiresAt:E.expiresAt}:null),[q,L]=(0,B.useState)(!1),[c,l]=(0,B.useState)(null),S=(0,B.useRef)(R);(0,B.useEffect)(()=>{S.current=R},[R]);let u=(0,B.useCallback)((...g)=>{a&&console.log("[useAccessPass]",...g)},[a]),A=(0,B.useMemo)(()=>{let g={...e};return t&&!g.solana&&G(t)&&(g.solana=t),t&&!g.evm&&Q(t)&&(g.evm=t),g},[e,t]),v=(0,B.useMemo)(()=>ve({adapters:[te({verbose:a,rpcUrls:o}),ne({verbose:a,rpcUrls:o})],wallets:A,preferredNetwork:s,rpcUrls:o,verbose:a,accessPass:{enabled:!0,autoRenew:!0}}),[A,s,o,a]),[y,N]=(0,B.useState)(0),w=(0,B.useMemo)(()=>{if(!R||!U)return null;let g=new Date(U.expiresAt).getTime(),_=Math.max(0,Math.floor((g-Date.now())/1e3));return _<=0?null:{jwt:R,tier:U.tier,expiresAt:U.expiresAt,remainingSeconds:_}},[R,U,y]),b=w!==null&&w.remainingSeconds>0;(0,B.useEffect)(()=>{if(!R||!U)return;let g=setInterval(()=>N(_=>_+1),1e3);return()=>clearInterval(g)},[b]);let C=(0,B.useCallback)(async()=>{H(!0);try{let g=await fetch(r);if(g.status===402){let _=g.headers.get("X-ACCESS-PASS-TIERS");if(_){let I=JSON.parse(atob(_));i(I.tiers||null),O(I.ratePerHour||null),u("Tier info loaded:",I)}}}catch(g){u("Failed to fetch tiers:",g)}finally{H(!1)}},[r,u]);(0,B.useEffect)(()=>{f&&C()},[f,C]);let K=(0,B.useCallback)(async(g,_)=>{L(!0),l(null);try{let I=r;g?I+=(I.includes("?")?"&":"?")+`tier=${g}`:_&&(I+=(I.includes("?")?"&":"?")+`duration=${_}`);let j=await v.fetch(I,{method:"POST"}),V=j.headers.get("ACCESS-PASS");if(u("ACCESS-PASS header:",V?"found":"NOT FOUND"),V){W(V);let F=g||"unknown",Y="";try{let Z=await j.json();F=Z.accessPass?.tier||F,Y=Z.accessPass?.expiresAt||""}catch{}if(!Y)try{let Z=V.split(".");if(Z.length===3){let z=JSON.parse(atob(Z[1].replace(/-/g,"+").replace(/_/g,"/")));F=z.tier||F,Y=new Date(z.exp*1e3).toISOString()}}catch{}x({tier:F,expiresAt:Y}),P(V,F,Y),u("Pass purchased and persisted:",F,Y)}}catch(I){let j=I instanceof Error?I:new Error(String(I));throw l(j),j}finally{L(!1)}},[r,v,u]),re=(0,B.useCallback)(async(g,_)=>{let I=!g||g===""?r:g.startsWith("http")?g:`${r.replace(/\/$/,"")}${g.startsWith("/")?"":"/"}${g}`,j=S.current;if(j){try{let V=j.split(".");if(V.length===3){let F=JSON.parse(atob(V[1].replace(/-/g,"+").replace(/_/g,"/")));if(F.exp&&F.exp>Date.now()/1e3)return fetch(I,{..._,headers:{..._?.headers||{},Authorization:`Bearer ${j}`}})}}catch{}W(null),x(null);try{sessionStorage.removeItem(p)}catch{}}return v.fetch(I,_)},[r,v,p]);return{tiers:T,customRatePerHour:k,isLoadingTiers:$,pass:w,isPassValid:b,fetchTiers:C,purchasePass:K,isPurchasing:q,purchaseError:c,fetch:re}}0&&(module.exports={X402Error,fireImpressionBeacon,getSponsoredRecommendations,useAccessPass,useX402Payment});
1
+ "use strict";var lt=Object.create;var Ue=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var dt=Object.getPrototypeOf,ft=Object.prototype.hasOwnProperty;var mt=(n,e)=>{for(var t in e)Ue(n,t,{get:e[t],enumerable:!0})},Qe=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ut(e))!ft.call(n,a)&&a!==t&&Ue(n,a,{get:()=>e[a],enumerable:!(r=pt(e,a))||r.enumerable});return n};var Me=(n,e,t)=>(t=n!=null?lt(dt(n)):{},Qe(e||!n||!n.__esModule?Ue(t,"default",{value:n,enumerable:!0}):t,n)),gt=n=>Qe(Ue({},"__esModule",{value:!0}),n);var xt={};mt(xt,{X402Error:()=>D,fireImpressionBeacon:()=>Je,getSponsoredRecommendations:()=>Ve,useAccessPass:()=>it,useX402Payment:()=>ot});module.exports=gt(xt);var M=require("react");var ne="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",we="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Le="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",le=ne,xe=we,Re=Le,te="eip155:8453",fe="eip155:84532",me="eip155:42161",ge="eip155:137",he="eip155:10",ye="eip155:43114",Ae="eip155:56",Se="eip155:1187947933",Ee="eip155:324705682",Te="eip155:1",pe=te,ke=fe,Pe=me,be=ge,_e=he,Ce=ye,Ne=Ae,Ie=Se,ve=Ee,Be=Te,Oe="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",Ze="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",We="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",Ye="0x55d398326f99059fF775485246999027B3197955",$e="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",qe={[Ae]:$e,[te]:We,[fe]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[me]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[ge]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[he]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[ye]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[Se]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[Ee]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[Te]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},Ke={[Ye]:{symbol:"USDT",decimals:18},[$e]:{symbol:"USDC",decimals:18}};var ue="0x000000000022D473030F116dDEE9F6B43aC78BA3",De="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",Ge={[Ae]:56,[te]:8453,[fe]:84532,[me]:42161,[ge]:137,[he]:10,[ye]:43114,[Se]:1187947933,[Ee]:324705682,[Te]:1},de={[ne]:"https://api.dexter.cash/api/solana/rpc",[we]:"https://api.devnet.solana.com",[Le]:"https://api.testnet.solana.com"},G={[Ae]:"https://bsc-dataseed1.binance.org",[te]:"https://api.dexter.cash/api/base/rpc",[fe]:"https://sepolia.base.org",[me]:"https://arb1.arbitrum.io/rpc",[ge]:"https://polygon-rpc.com",[he]:"https://mainnet.optimism.io",[ye]:"https://api.avax.network/ext/bc/C/rpc",[Se]:"https://skale-base.skalenodes.com/v1/base",[Ee]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[Te]:"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)}};var H=require("@solana/web3.js"),K=require("@solana/spl-token");var ht=12e3,yt=1;function Q(n){if(!n||typeof n!="object")return!1;let e=n;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var je=class{name="Solana";networks=[le,xe,Re];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]:de[e]?de[e]:e==="solana"?de[le]:e==="solana-devnet"?de[xe]:e==="solana-testnet"?de[Re]:de[le]}getAddress(e){return Q(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return Q(e)?e.publicKey!==null:!1}async getBalance(e,t,r){if(!Q(t)||!t.publicKey)return 0;let a=r||this.getDefaultRpcUrl(e.network),s=new H.Connection(a,"confirmed"),p=new H.PublicKey(t.publicKey.toBase58()),o=new H.PublicKey(e.asset);try{let d=(await s.getAccountInfo(o,"confirmed"))?.owner.toBase58()===K.TOKEN_2022_PROGRAM_ID.toBase58()?K.TOKEN_2022_PROGRAM_ID:K.TOKEN_PROGRAM_ID,x=await(0,K.getAssociatedTokenAddress)(o,p,!1,d),R=await(0,K.getAccount)(s,x,void 0,d),_=e.extra?.decimals??6;return Number(R.amount)/Math.pow(10,_)}catch(l){if(l&&typeof l=="object"&&"name"in l&&(l.name==="TokenAccountNotFoundError"||l.name==="TokenInvalidAccountOwnerError"))return 0;throw l}}async buildTransaction(e,t,r){if(!Q(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let a=r||this.getDefaultRpcUrl(e.network),s=new H.Connection(a,"confirmed"),p=new H.PublicKey(t.publicKey.toBase58()),{payTo:o,asset:l,extra:d}=e,x=e.amount??e.maxAmountRequired;if(!x)throw new Error("Missing amount in payment requirements");if(!d?.feePayer)throw new Error("Missing feePayer in payment requirements");let R=new H.PublicKey(d.feePayer),_=new H.PublicKey(l),i=new H.PublicKey(o);this.log("Building transaction:",{from:p.toBase58(),to:o,amount:x,asset:l,feePayer:d.feePayer});let U=[];U.push(H.ComputeBudgetProgram.setComputeUnitLimit({units:ht})),U.push(H.ComputeBudgetProgram.setComputeUnitPrice({microLamports:yt}));let L=await s.getAccountInfo(_,"confirmed");if(!L)throw new Error(`Token mint ${l} not found`);let W=L.owner.toBase58()===K.TOKEN_2022_PROGRAM_ID.toBase58()?K.TOKEN_2022_PROGRAM_ID:K.TOKEN_PROGRAM_ID,V=await(0,K.getMint)(s,_,void 0,W);typeof d?.decimals=="number"&&V.decimals!==d.decimals&&this.log(`Decimals mismatch: requirements say ${d.decimals}, mint says ${V.decimals}`);let P=await(0,K.getAssociatedTokenAddress)(_,p,!1,W),k=await(0,K.getAssociatedTokenAddress)(_,i,!1,W);if(!await s.getAccountInfo(P,"confirmed"))throw new Error(`No token account found for ${l}. Please ensure you have USDC in your wallet.`);if(!await s.getAccountInfo(k,"confirmed"))throw new Error(`Seller token account not found. The seller (${o}) must have a USDC account.`);let $=BigInt(x);U.push((0,K.createTransferCheckedInstruction)(P,_,k,p,$,V.decimals,[],W));let{blockhash:q}=await s.getLatestBlockhash("confirmed"),Y=new H.TransactionMessage({payerKey:R,recentBlockhash:q,instructions:U}).compileToV0Message(),c=new H.VersionedTransaction(Y),f=await t.signTransaction(c);return this.log("Transaction signed successfully"),{serialized:Buffer.from(f.serialize()).toString("base64")}}};function ae(n){return new je(n)}var At={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"}]},et=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function Z(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,pe,ke,Be,Pe,be,_e,Ce,Ie,ve];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]:G[e]?G[e]:e==="base"?G[pe]:e==="bsc"?G[Ne]:e==="ethereum"?G[Be]:e==="arbitrum"?G[Pe]:e==="polygon"?G[be]:e==="optimism"?G[_e]:e==="avalanche"?G[Ce]:e==="skale-base"?G[Ie]:e==="skale-base-sepolia"?G[ve]:G[pe]}getAddress(e){return Z(e)?e.address:null}isConnected(e){return Z(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(!Z(t)||!t.address)return 0;let a=r||this.getDefaultRpcUrl(e.network);try{let s=this.encodeBalanceOf(t.address),p=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(!p.ok)throw new Error(`RPC request failed: ${p.status}`);let o=await p.json();if(o.error)throw new Error(`RPC error: ${JSON.stringify(o.error)}`);if(!o.result||o.result==="0x")return 0;let l=BigInt(o.result),d=e.extra?.decimals??6;return Number(l)/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(!Z(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:s,extra:p}=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 l=this.getChainId(e.network),d={name:p?.name??"USD Coin",version:p?.version??"2",chainId:BigInt(l),verifyingContract:s},x={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(P=>P.toString(16).padStart(2,"0")).join(""),i=Math.floor(Date.now()/1e3),U={from:t.address,to:a,value:o,validAfter:String(i-600),validBefore:String(i+(e.maxTimeoutSeconds||60)),nonce:_},L={from:t.address,to:a,value:BigInt(o),validAfter:BigInt(i-600),validBefore:BigInt(i+(e.maxTimeoutSeconds||60)),nonce:_};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let W=await t.signTypedData({domain:d,types:x,primaryType:"TransferWithAuthorization",message:L});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:U,signature:W}),signature:W}}async buildApprovalTransaction(e,t,r){let{payTo:a,asset:s,extra:p}=e,o=e.amount??e.maxAmountRequired;if(!o)throw new Error("Missing amount in payment requirements");let l=p?.facilitatorContract;if(!l)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:l});let d=r||this.getDefaultRpcUrl(e.network),x=p?.fee??"0",R=BigInt(o)+BigInt(x),_=await this.readAllowance(d,s,t.address,l);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 c=this.calculateApprovalAmount(o,x,p?.approvalStrategy);this.log(`Approving ${c} for ${l} (current allowance: ${_})`);let f=await t.sendTransaction({to:s,data:this.encodeApprove(l,c),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 i=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(i);let U=[...i].reduce((c,f)=>c*256n+BigInt(f),0n).toString(),L=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(L);let W="0x"+[...L].map(c=>c.toString(16).padStart(2,"0")).join(""),P=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),k=p?.eip712Domain,N=k?{name:k.name,version:k.version,chainId:BigInt(k.chainId),verifyingContract:k.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:l},w=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"}]},$={from:t.address,to:a,token:s,amount:BigInt(o),fee:BigInt(x),nonce:BigInt(U),deadline:BigInt(P),paymentId:W},q=await t.signTypedData({domain:N,types:w,primaryType:"Payment",message:$});this.log("EIP-712 Payment signature obtained");let Y={from:t.address,to:a,token:s,amount:o,fee:x,nonce:U,deadline:P,paymentId:W,signature:q};return{serialized:JSON.stringify(Y),signature:q}}async buildPermit2Transaction(e,t,r){let{payTo:a,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:a,amount:p,asset:s,network:e.network});let o=r||this.getDefaultRpcUrl(e.network),l=await this.readAllowance(o,s,t.address,ue),d;if(l<BigInt(p)){let N=this.encodeApprove(ue,et);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${l})`);let w=this.getChainId(e.network),$=await this.readGasPrice(o),q=await this.readNonce(o,t.address),Y=await t.signTransaction({to:s,data:N,chainId:w,gas:50000n,gasPrice:$,nonce:q});d={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:s,spender:ue,amount:et.toString(),signedTransaction:Y,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${l})`);let w=await t.sendTransaction({to:s,data:N,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 x=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(x);let R=[...x].reduce((N,w)=>N*256n+BigInt(w),0n),_=Math.floor(Date.now()/1e3),i=_-600,U=_+(e.maxTimeoutSeconds||300),L=this.getChainId(e.network),W={name:"Permit2",chainId:BigInt(L),verifyingContract:ue},V={permitted:{token:s,amount:BigInt(p)},spender:De,nonce:R,deadline:BigInt(U),witness:{to:a,validAfter:BigInt(i)}},P=await t.signTypedData({domain:W,types:At,primaryType:"PermitWitnessTransferFrom",message:V});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let k={signature:P,permit2Authorization:{from:t.address,permitted:{token:s,amount:p},spender:De,nonce:R.toString(),deadline:String(U),witness:{to:a,validAfter:String(i)}}};return{serialized:JSON.stringify(k),signature:P,extensions:d}}async readAllowance(e,t,r,a){let s="0xdd62ed3e",p=r.slice(2).toLowerCase().padStart(64,"0"),o=a.slice(2).toLowerCase().padStart(64,"0"),l=s+p+o;try{let x=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:l},"latest"]})})).json();return x.error||!x.result||x.result==="0x"?0n:BigInt(x.result)}catch{return 0n}}encodeApprove(e,t){let r="0x095ea7b3",a=e.slice(2).toLowerCase().padStart(64,"0"),s=t.toString(16).padStart(64,"0");return r+a+s}async waitForReceipt(e,t,r=3e4){let a=Date.now();for(;Date.now()-a<r;){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 ${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 s=BigInt(r.defaultMultiple??10),p=a*s;if(r.maxCapUsd){let o=this.inferDecimals(e),l=BigInt(Math.floor(r.maxCapUsd*Math.pow(10,o)));if(p>l)return l}if(r.exactAboveUsd){let o=this.inferDecimals(e),l=BigInt(Math.floor(r.exactAboveUsd*Math.pow(10,o)));if(BigInt(e)>l)return a}return p}inferDecimals(e){return e.length>12?18:6}};function oe(n){return new Fe(n)}function ze(n){if(n===Oe||n===Ze)return!0;let e=n.toLowerCase();for(let t of Object.values(qe))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(Ke))if(t.toLowerCase()===e)return!0;return!1}function St(n){return n.startsWith("solana:")||n==="solana"}function Et(n){return n.startsWith("eip155:")||["base","ethereum","arbitrum"].includes(n)}function Tt(n){return St(n)?"solana":Et(n)?"evm":"unknown"}function Xe(n){return{[ne]:"Solana",[we]:"Solana Devnet",[Le]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[te]:"Base",[fe]:"Base Sepolia",[Te]:"Ethereum",[me]:"Arbitrum",[ge]:"Polygon",[he]:"Optimism",[ye]:"Avalanche",[Ae]:"BSC",[Se]:"SKALE Base",[Ee]:"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 tt(n,e){let t=Xe(n);return t===n?e:t}function nt(n,e){let t=Tt(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 wt(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((p,o)=>r.set(o,p));let a={method:e?.method??t.method,headers:r,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 rt=new WeakMap;function st(n){return rt.get(n)}function He(n){let{adapters:e=[ae({verbose:n.verbose}),oe({verbose:n.verbose})],wallets:t,wallet:r,preferredNetwork:a,rpcUrls:s={},maxAmountAtomic:p,fetch:o=globalThis.fetch,verbose:l=!1,accessPass:d,onPaymentRequired:x,maxRetries:R=0,retryDelayMs:_=500}=n,i=l?console.log.bind(console,"[x402]"):()=>{};async function U(c,f){let A;for(let m=0;m<=R;m++)try{let E=await o(c,f);if(E.status>=502&&E.status<=504&&m<R){i(`Retry ${m+1}/${R}: server returned ${E.status}`),await new Promise(g=>setTimeout(g,_*Math.pow(2,m)));continue}return E}catch(E){A=E,m<R&&(i(`Retry ${m+1}/${R}: ${E instanceof Error?E.message:"network error"}`),await new Promise(g=>setTimeout(g,_*Math.pow(2,m))))}throw A}let L=new Map;function W(c){try{let f=new URL(c).host,A=L.get(f);if(A&&A.expiresAt>Date.now()/1e3+10)return A.jwt;A&&L.delete(f)}catch{}return null}function V(c,f){try{let A=new URL(c).host,m=f.split(".");if(m.length===3){let E=JSON.parse(atob(m[1].replace(/-/g,"+").replace(/_/g,"/"))),g=Math.floor(Date.now()/1e3),T=g+86400,S=Math.min(typeof E.exp=="number"?E.exp:g,T);L.set(A,{jwt:f,expiresAt:S}),i("Access pass cached for",A,"| expires:",new Date(S*1e3).toISOString())}}catch{i("Failed to cache access pass")}}let P=t||{};r&&!P.solana&&Q(r)&&(P.solana=r),r&&!P.evm&&Z(r)&&(P.evm=r);function k(c){let f=[];for(let A of c){let m=e.find(g=>g.canHandle(A.network));if(!m)continue;let E;m.name==="Solana"?E=P.solana:m.name==="EVM"&&(E=P.evm),E&&m.isConnected(E)&&f.push({accept:A,adapter:m,wallet:E})}if(f.length===0)return null;if(a){let A=f.find(m=>m.accept.network===a);if(A)return A}return f[0]}function N(c,f){return tt(c,f)}function w(c,f){return s[c]||f.getDefaultRpcUrl(c)}async function $(c,f,A,m,E){let g="";if(d?.preferTier&&m.tiers){let u=m.tiers.find(re=>re.id===d.preferTier);if(u){if(d.maxSpend&&parseFloat(u.price)>parseFloat(d.maxSpend))throw new D("access_pass_exceeds_max_spend",`Access pass tier "${u.id}" costs $${u.price}, exceeds max spend $${d.maxSpend}`);g=`tier=${u.id}`}}else if(d?.preferDuration&&m.ratePerHour)g=`duration=${d.preferDuration}`;else if(m.tiers&&m.tiers.length>0){let u=m.tiers[0];if(d?.maxSpend&&parseFloat(u.price)>parseFloat(d.maxSpend))throw new D("access_pass_exceeds_max_spend",`Cheapest access pass costs $${u.price}, exceeds max spend $${d?.maxSpend}`);g=`tier=${u.id}`}let T=g?E.includes("?")?`${E}&${g}`:`${E}?${g}`:E;i("Purchasing access pass:",g||"default tier");let S=A.headers.get("PAYMENT-REQUIRED");if(!S)return null;let I;try{I=JSON.parse(atob(S))}catch{return null}let v=k(I.accepts);if(!v)return null;let{accept:C,adapter:ee,wallet:h}=v;if(ee.name==="Solana"&&!C.extra?.feePayer)return null;let b=C.extra?.decimals??(ze(C.asset)?6:void 0);if(typeof b!="number")return null;let B=C.amount??C.maxAmountRequired;if(!B)return null;let j=w(C.network,ee);try{let u=await ee.getBalance(C,h,j),re=Number(B)/Math.pow(10,b);if(u<re){let ct=N(C.network,ee.name);throw new D("insufficient_balance",`Insufficient balance for access pass on ${ct}. Have $${u.toFixed(4)}, need $${re.toFixed(4)}`)}}catch(u){if(u instanceof D)throw u}let F=await ee.buildTransaction(C,h,j),X;ee.name==="EVM"?X=JSON.parse(F.serialized):X={transaction:F.serialized};let J=typeof c=="string"?c:c instanceof URL?c.href:c.url,z=I.resource;if(typeof I.resource=="string")try{let u=new URL(I.resource,J);["http:","https:"].includes(u.protocol)&&(z=u.toString())}catch{}else if(I.resource&&typeof I.resource=="object"&&"url"in I.resource){let u=I.resource;try{let re=new URL(u.url,J);["http:","https:"].includes(re.protocol)&&(z={...u,url:re.toString()})}catch{}}let ie={x402Version:C.x402Version??2,resource:z,accepted:C,payload:X};F.extensions&&(ie.extensions=F.extensions);let se=btoa(JSON.stringify(ie)),ce=await o(T,{...f,method:"POST",headers:{...f?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":se}});if(!ce.ok)return i("Pass purchase failed:",ce.status),null;let y=ce.headers.get("ACCESS-PASS");return y&&(V(E,y),i("Access pass purchased and cached")),ce}async function q(c,f){let A=c;if(i("Making request:",A),d){let y=W(A);if(y){i("Using cached access pass");let u=await o(c,{...f,headers:{...f?.headers||{},Authorization:`Bearer ${y}`}});if(u.status!==401&&u.status!==402)return u;i("Cached pass rejected (status",u.status,"), purchasing new pass");try{L.delete(new URL(A).host)}catch{}}}let m=await U(c,f);if(m.status!==402)return m;i("Received 402 Payment Required");let E=m.headers.get("X-ACCESS-PASS-TIERS");if(d&&E){i("Server offers access passes, purchasing...");try{let y=JSON.parse(atob(E)),u=await $(c,f,m,y,A);if(u)return u}catch(y){i("Access pass purchase failed, falling back to per-request payment:",y)}}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 T;try{let y=atob(g);T=JSON.parse(y)}catch{throw new D("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}i("Payment requirements:",T);let S=m.headers.get("X-Quote-Hash");S&&i("Quote hash received:",S);let I=k(T.accepts);if(!I){let y=T.accepts.map(u=>u.network).join(", ");throw new D("no_matching_payment_option",`No connected wallet for any available network: ${y}`)}let{accept:v,adapter:C,wallet:ee}=I;if(i(`Using ${C.name} for ${v.network}`),C.name==="Solana"&&!v.extra?.feePayer)throw new D("missing_fee_payer","Solana payment option missing feePayer in extra");let h=v.extra?.decimals??(ze(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 b=v.amount??v.maxAmountRequired;if(!b)throw new D("missing_amount","Payment option missing amount");if(p&&BigInt(b)>BigInt(p))throw new D("amount_exceeds_max",`Payment amount ${b} exceeds maximum ${p}`);let B=w(v.network,C);i("Checking balance...");try{let y=await C.getBalance(v,ee,B),u=Number(b)/Math.pow(10,h);if(y<u){let re=N(v.network,C.name);throw new D("insufficient_balance",`Insufficient balance on ${re}. Have $${y.toFixed(4)}, need $${u.toFixed(4)}`)}i(`Balance OK: $${y.toFixed(4)} >= $${u.toFixed(4)}`)}catch(y){if(y instanceof D)throw y;i("Balance check failed (RPC error), proceeding with transaction attempt")}if(x&&!await x(v))throw new D("payment_rejected","Payment rejected by onPaymentRequired callback");i("Building transaction...");let j=await C.buildTransaction(v,ee,B);i("Transaction signed");let F;C.name==="EVM"?F=JSON.parse(j.serialized):F={transaction:j.serialized};let X=c,J=T.resource;if(typeof T.resource=="string")try{let y=new URL(T.resource,X).toString();y!==T.resource&&i("Resolved relative resource URL:",T.resource,"\u2192",y),J=y}catch{J=T.resource}else if(T.resource&&typeof T.resource=="object"&&"url"in T.resource){let y=T.resource;try{let u=new URL(y.url,X).toString();u!==y.url&&(i("Resolved relative resource URL:",y.url,"\u2192",u),J={...y,url:u})}catch{}}let z={x402Version:v.x402Version??2,resource:J,accepted:v,payload:F};j.extensions&&(z.extensions=j.extensions);let ie=btoa(JSON.stringify(z));i("Retrying request with payment...");let se=await U(c,{...f,headers:{...f?.headers||{},"PAYMENT-SIGNATURE":ie,...S?{"X-Quote-Hash":S}:{}}});if(i("Retry response status:",se.status),se.status===402){let y="unknown";try{let u=await se.clone().json();y=String(u.error||u.message||JSON.stringify(u)),i("Rejection reason:",y)}catch{}throw new D("payment_rejected",`Payment was rejected by the server: ${y}`)}let ce=se.headers.get("PAYMENT-RESPONSE");if(ce)try{let y=JSON.parse(atob(ce));rt.set(se,y),y.extensions&&i("Settlement extensions:",Object.keys(y.extensions).join(", "))}catch{}return se}async function Y(c,f){let[A,m]=await wt(c,f);return q(A,m)}return{fetch:Y}}function at(n){let e=st(n);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function Ve(n){let e=at(n);if(e?.recommendations?.length)return e.recommendations}async function Je(n){let t=at(n)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function ot(n){let{wallets:e,wallet:t,preferredNetwork:r,rpcUrls:a={},verbose:s=!1}=n,[p,o]=(0,M.useState)(!1),[l,d]=(0,M.useState)("idle"),[x,R]=(0,M.useState)(null),[_,i]=(0,M.useState)(null),[U,L]=(0,M.useState)(null),[W,V]=(0,M.useState)([]),[P,k]=(0,M.useState)(null),N=(0,M.useCallback)((...g)=>{s&&console.log("[useX402Payment]",...g)},[s]),w=(0,M.useMemo)(()=>{let g={...e};return t&&!g.solana&&Q(t)&&(g.solana=t),t&&!g.evm&&Z(t)&&(g.evm=t),g},[e,t]),$=(0,M.useMemo)(()=>[ae({verbose:s,rpcUrls:a}),oe({verbose:s,rpcUrls:a})],[s,a]),q=(0,M.useMemo)(()=>({solana:w.solana?Q(w.solana)&&$[0].isConnected(w.solana):!1,evm:w.evm?Z(w.evm)&&$[1].isConnected(w.evm):!1}),[w,$]),Y=q.solana||q.evm,c=(0,M.useCallback)(async()=>{let g=[];if(q.solana&&w.solana)try{let T=$.find(S=>S.name==="Solana");if(T){let S={scheme:"exact",network:ne,amount:"0",asset:Oe,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},I=await T.getBalance(S,w.solana);g.push({network:ne,chainName:Xe(ne),balance:I,asset:"USDC"})}}catch(T){N("Failed to fetch Solana balance:",T)}if(q.evm&&w.evm)try{let T=$.find(S=>S.name==="EVM");if(T){let S={scheme:"exact",network:te,amount:"0",asset:We,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},I=await T.getBalance(S,w.evm);g.push({network:te,chainName:Xe(te),balance:I,asset:"USDC"})}}catch(T){N("Failed to fetch Base balance:",T)}V(g)},[q,w,$,N]);(0,M.useEffect)(()=>{c();let g=setInterval(c,3e4);return()=>clearInterval(g)},[c]);let f=(0,M.useCallback)(()=>{o(!1),d("idle"),R(null),i(null),L(null),k(null)},[]),A=(0,M.useMemo)(()=>He({adapters:$,wallets:w,preferredNetwork:r,rpcUrls:a,verbose:s}),[$,w,r,a,s]),m=(0,M.useCallback)(async(g,T)=>{if(o(!0),d("pending"),R(null),i(null),L(null),!Y){let S=new D("wallet_not_connected","No wallet connected");throw R(S),d("error"),o(!1),S}try{let S=await A.fetch(g,T),I=S.headers.get("PAYMENT-RESPONSE");if(I)try{let C=JSON.parse(atob(I));C.transaction&&i(C.transaction),C.network&&L(C.network)}catch{N("Could not parse PAYMENT-RESPONSE header")}let v=Ve(S);return k(v??null),v&&(N("Sponsored recommendations received:",v.length),Je(S).catch(()=>{})),d("success"),S}catch(S){let I=S instanceof Error?S:new Error(String(S));throw R(I),d("error"),S}finally{o(!1),setTimeout(c,2e3)}},[A,Y,N,c]),E=(0,M.useMemo)(()=>_?nt(_,U||r||ne):null,[_,U,r]);return{fetch:m,isLoading:p,status:l,error:x,transactionId:_,transactionNetwork:U,transactionUrl:E,balances:W,connectedChains:q,isAnyWalletConnected:Y,reset:f,refreshBalances:c,accessPass:null,sponsoredRecommendations:P}}var O=require("react");function it(n){let{wallets:e,wallet:t,preferredNetwork:r,rpcUrls:a={},resourceUrl:s,autoConnect:p=!0,verbose:o=!1}=n,l=`x402-access-pass:${s}`;function d(){if(typeof sessionStorage>"u")return null;try{let h=sessionStorage.getItem(l);if(!h)return null;let b=JSON.parse(h);return new Date(b.expiresAt).getTime()<=Date.now()?(sessionStorage.removeItem(l),null):b}catch{return null}}function x(h,b,B){if(!(typeof sessionStorage>"u"))try{sessionStorage.setItem(l,JSON.stringify({jwt:h,tier:b,expiresAt:B}))}catch{}}let R=d(),[_,i]=(0,O.useState)(null),[U,L]=(0,O.useState)(null),[W,V]=(0,O.useState)(!1),[P,k]=(0,O.useState)(R?.jwt||null),[N,w]=(0,O.useState)(R?{tier:R.tier,expiresAt:R.expiresAt}:null),[$,q]=(0,O.useState)(!1),[Y,c]=(0,O.useState)(null),f=(0,O.useRef)(P);(0,O.useEffect)(()=>{f.current=P},[P]);let A=(0,O.useCallback)((...h)=>{o&&console.log("[useAccessPass]",...h)},[o]),m=(0,O.useMemo)(()=>{let h={...e};return t&&!h.solana&&Q(t)&&(h.solana=t),t&&!h.evm&&Z(t)&&(h.evm=t),h},[e,t]),E=(0,O.useMemo)(()=>He({adapters:[ae({verbose:o,rpcUrls:a}),oe({verbose:o,rpcUrls:a})],wallets:m,preferredNetwork:r,rpcUrls:a,verbose:o,accessPass:{enabled:!0,autoRenew:!0}}),[m,r,a,o]),[g,T]=(0,O.useState)(0),S=(0,O.useMemo)(()=>{if(!P||!N)return null;let h=new Date(N.expiresAt).getTime(),b=Math.max(0,Math.floor((h-Date.now())/1e3));return b<=0?null:{jwt:P,tier:N.tier,expiresAt:N.expiresAt,remainingSeconds:b}},[P,N,g]),I=S!==null&&S.remainingSeconds>0;(0,O.useEffect)(()=>{if(!P||!N)return;let h=setInterval(()=>T(b=>b+1),1e3);return()=>clearInterval(h)},[I]);let v=(0,O.useCallback)(async()=>{V(!0);try{let h=await fetch(s);if(h.status===402){let b=h.headers.get("X-ACCESS-PASS-TIERS");if(b){let B=JSON.parse(atob(b));i(B.tiers||null),L(B.ratePerHour||null),A("Tier info loaded:",B)}}}catch(h){A("Failed to fetch tiers:",h)}finally{V(!1)}},[s,A]);(0,O.useEffect)(()=>{p&&v()},[p,v]);let C=(0,O.useCallback)(async(h,b)=>{q(!0),c(null);try{let B=s;h?B+=(B.includes("?")?"&":"?")+`tier=${h}`:b&&(B+=(B.includes("?")?"&":"?")+`duration=${b}`);let j=await E.fetch(B,{method:"POST"}),F=j.headers.get("ACCESS-PASS");if(A("ACCESS-PASS header:",F?"found":"NOT FOUND"),F){k(F);let X=h||"unknown",J="";try{let z=await j.json();X=z.accessPass?.tier||X,J=z.accessPass?.expiresAt||""}catch{}if(!J)try{let z=F.split(".");if(z.length===3){let ie=JSON.parse(atob(z[1].replace(/-/g,"+").replace(/_/g,"/")));X=ie.tier||X,J=new Date(ie.exp*1e3).toISOString()}}catch{}w({tier:X,expiresAt:J}),x(F,X,J),A("Pass purchased and persisted:",X,J)}}catch(B){let j=B instanceof Error?B:new Error(String(B));throw c(j),j}finally{q(!1)}},[s,E,A]),ee=(0,O.useCallback)(async(h,b)=>{let B=!h||h===""?s:h.startsWith("http")?h:`${s.replace(/\/$/,"")}${h.startsWith("/")?"":"/"}${h}`,j=f.current;if(j){try{let F=j.split(".");if(F.length===3){let X=JSON.parse(atob(F[1].replace(/-/g,"+").replace(/_/g,"/")));if(X.exp&&X.exp>Date.now()/1e3)return fetch(B,{...b,headers:{...b?.headers||{},Authorization:`Bearer ${j}`}})}}catch{}k(null),w(null);try{sessionStorage.removeItem(l)}catch{}}return E.fetch(B,b)},[s,E,l]);return{tiers:_,customRatePerHour:U,isLoadingTiers:W,pass:S,isPassValid:I,fetchTiers:v,purchasePass:C,isPurchasing:$,purchaseError:Y,fetch:ee}}0&&(module.exports={X402Error,fireImpressionBeacon,getSponsoredRecommendations,useAccessPass,useX402Payment});
@@ -1,10 +1,10 @@
1
- import { a as X402Client } from '../sponsored-access-CE7WpV5b.cjs';
2
- export { f as fireImpressionBeacon, b as getSponsoredRecommendations } from '../sponsored-access-CE7WpV5b.cjs';
3
- import { W as WalletSet, d as BalanceInfo } from '../types-C_aQh02s.cjs';
1
+ import { a as X402Client } from '../sponsored-access-BuecDKXL.cjs';
2
+ export { f as fireImpressionBeacon, b as getSponsoredRecommendations } from '../sponsored-access-BuecDKXL.cjs';
3
+ import { W as WalletSet, B as BalanceInfo } from '../types-i7C2GiVY.cjs';
4
4
  import { SponsoredRecommendation } from '@dexterai/x402-ads-types';
5
5
  export { SponsoredRecommendation } from '@dexterai/x402-ads-types';
6
- import { a as AccessPassTier } from '../types-_iT11DL0.cjs';
7
- export { A as AccessPassClientConfig, b as AccessPassInfo, X as X402Error } from '../types-_iT11DL0.cjs';
6
+ import { a as AccessPassTier } from '../types-CKiTYeJ-.cjs';
7
+ export { A as AccessPassClientConfig, b as AccessPassInfo, X as X402Error } from '../types-CKiTYeJ-.cjs';
8
8
 
9
9
  /**
10
10
  * React Hook for x402 v2 Payments
@@ -1,10 +1,10 @@
1
- import { a as X402Client } from '../sponsored-access-BVoucsEW.js';
2
- export { f as fireImpressionBeacon, b as getSponsoredRecommendations } from '../sponsored-access-BVoucsEW.js';
3
- import { W as WalletSet, d as BalanceInfo } from '../types-DBS0XOsH.js';
1
+ import { a as X402Client } from '../sponsored-access-DP61rXDl.js';
2
+ export { f as fireImpressionBeacon, b as getSponsoredRecommendations } from '../sponsored-access-DP61rXDl.js';
3
+ import { W as WalletSet, B as BalanceInfo } from '../types-BPKUVJEl.js';
4
4
  import { SponsoredRecommendation } from '@dexterai/x402-ads-types';
5
5
  export { SponsoredRecommendation } from '@dexterai/x402-ads-types';
6
- import { a as AccessPassTier } from '../types-_iT11DL0.js';
7
- export { A as AccessPassClientConfig, b as AccessPassInfo, X as X402Error } from '../types-_iT11DL0.js';
6
+ import { a as AccessPassTier } from '../types-CKiTYeJ-.js';
7
+ export { A as AccessPassClientConfig, b as AccessPassInfo, X as X402Error } from '../types-CKiTYeJ-.js';
8
8
 
9
9
  /**
10
10
  * React Hook for x402 v2 Payments
@@ -1 +1 @@
1
- import{useState as ae,useCallback as ve,useEffect as lt,useMemo as ge}from"react";var ne="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",oe="eip155:8453";var qe="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",Le="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";var U=class r extends Error{code;details;constructor(e,t,s){super(t),this.name="X402Error",this.code=e,this.details=s,Object.setPrototypeOf(this,r.prototype)}};import{PublicKey as ie,Connection as je,TransactionMessage as Qe,VersionedTransaction as Ze,ComputeBudgetProgram as Fe}from"@solana/web3.js";import{getAssociatedTokenAddress as Ie,getAccount as et,createTransferCheckedInstruction as tt,getMint as nt,TOKEN_PROGRAM_ID as Je,TOKEN_2022_PROGRAM_ID as he}from"@solana/spl-token";var de="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",ye="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",we="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",ce={[de]:"https://api.dexter.cash/api/solana/rpc",[ye]:"https://api.devnet.solana.com",[we]:"https://api.testnet.solana.com"},rt=12e3,st=1;function V(r){if(!r||typeof r!="object")return!1;let e=r;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var Se=class{name="Solana";networks=[de,ye,we];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]:ce[e]?ce[e]:e==="solana"?ce[de]:e==="solana-devnet"?ce[ye]:e==="solana-testnet"?ce[we]:ce[de]}getAddress(e){return V(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return V(e)?e.publicKey!==null:!1}async getBalance(e,t,s){if(!V(t)||!t.publicKey)return 0;let l=s||this.getDefaultRpcUrl(e.network),n=new je(l,"confirmed"),f=new ie(t.publicKey.toBase58()),a=new ie(e.asset);try{let m=(await n.getAccountInfo(a,"confirmed"))?.owner.toBase58()===he.toBase58()?he:Je,P=await Ie(a,f,!1,m),E=await et(n,P,void 0,m),T=e.extra?.decimals??6;return Number(E.amount)/Math.pow(10,T)}catch(p){if(p&&typeof p=="object"&&"name"in p&&(p.name==="TokenAccountNotFoundError"||p.name==="TokenInvalidAccountOwnerError"))return 0;throw p}}async buildTransaction(e,t,s){if(!V(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let l=s||this.getDefaultRpcUrl(e.network),n=new je(l,"confirmed"),f=new ie(t.publicKey.toBase58()),{payTo:a,asset:p,extra:m}=e,P=e.amount??e.maxAmountRequired;if(!P)throw new Error("Missing amount in payment requirements");if(!m?.feePayer)throw new Error("Missing feePayer in payment requirements");let E=new ie(m.feePayer),T=new ie(p),o=new ie(a);this.log("Building transaction:",{from:f.toBase58(),to:a,amount:P,asset:p,feePayer:m.feePayer});let D=[];D.push(Fe.setComputeUnitLimit({units:rt})),D.push(Fe.setComputeUnitPrice({microLamports:st}));let k=await n.getAccountInfo(T,"confirmed");if(!k)throw new Error(`Token mint ${p} not found`);let O=k.owner.toBase58()===he.toBase58()?he:Je,J=await nt(n,T,void 0,O);typeof m?.decimals=="number"&&J.decimals!==m.decimals&&this.log(`Decimals mismatch: requirements say ${m.decimals}, mint says ${J.decimals}`);let R=await Ie(T,f,!1,O),M=await Ie(T,o,!1,O);if(!await n.getAccountInfo(R,"confirmed"))throw new Error(`No token account found for ${p}. Please ensure you have USDC in your wallet.`);if(!await n.getAccountInfo(M,"confirmed"))throw new Error(`Seller token account not found. The seller (${a}) must have a USDC account.`);let W=BigInt(P);D.push(tt(R,T,M,f,W,J.decimals,[],O));let{blockhash:$}=await n.getLatestBlockhash("confirmed"),i=new Qe({payerKey:E,recentBlockhash:$,instructions:D}).compileToV0Message(),c=new Ze(i),S=await t.signTransaction(c);return this.log("Transaction signed successfully"),{serialized:Buffer.from(S.serialize()).toString("base64")}}};function G(r){return new Se(r)}var fe="0x000000000022D473030F116dDEE9F6B43aC78BA3",_e="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",at={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"}]},Xe=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),se="eip155:8453",me="eip155:84532",le="eip155:42161",xe="eip155:137",be="eip155:10",Pe="eip155:43114",pe="eip155:56",Ee="eip155:1187947933",Re="eip155:324705682",ue="eip155:1",Ve="0x55d398326f99059fF775485246999027B3197955",Ne="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",Ke={[pe]:56,[se]:8453,[me]:84532,[le]:42161,[xe]:137,[be]:10,[Pe]:43114,[Ee]:1187947933,[Re]:324705682,[ue]:1},re={[pe]:"https://bsc-dataseed1.binance.org",[se]:"https://api.dexter.cash/api/base/rpc",[me]:"https://sepolia.base.org",[le]:"https://arb1.arbitrum.io/rpc",[xe]:"https://polygon-rpc.com",[be]:"https://mainnet.optimism.io",[Pe]:"https://api.avax.network/ext/bc/C/rpc",[Ee]:"https://skale-base.skalenodes.com/v1/base",[Re]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[ue]:"https://eth.llamarpc.com"},Be={[pe]:Ne,[se]:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",[me]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[le]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[xe]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[be]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[Pe]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[Ee]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[Re]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[ue]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},Ue={[Ve]:{symbol:"USDT",decimals:18},[Ne]:{symbol:"USDC",decimals:18}};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 Ae=class{name="EVM";networks=[pe,se,me,ue,le];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.startsWith("eip155:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:re[e]?re[e]:e==="base"?re[se]:e==="bsc"?re[pe]:e==="ethereum"?re[ue]:e==="arbitrum"?re[le]:re[se]}getAddress(e){return H(e)?e.address:null}isConnected(e){return H(e)?!!e.address:!1}getChainId(e){if(Ke[e])return Ke[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,s){if(!H(t)||!t.address)return 0;let l=s||this.getDefaultRpcUrl(e.network);try{let n=this.encodeBalanceOf(t.address),f=await fetch(l,{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(!f.ok)throw new Error(`RPC request failed: ${f.status}`);let a=await f.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),m=e.extra?.decimals??6;return Number(p)/Math.pow(10,m)}catch(n){throw n}}encodeBalanceOf(e){let t="0x70a08231",s=e.slice(2).toLowerCase().padStart(64,"0");return t+s}async buildTransaction(e,t,s){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,s);if(e.extra?.assetTransferMethod==="permit2")return this.buildPermit2Transaction(e,t,s);let{payTo:l,asset:n,extra:f}=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:l,amount:a,asset:n,network:e.network});let p=this.getChainId(e.network),m={name:f?.name??"USD Coin",version:f?.version??"2",chainId:BigInt(p),verifyingContract:n},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"}]},E=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(E);let T="0x"+[...E].map(R=>R.toString(16).padStart(2,"0")).join(""),o=Math.floor(Date.now()/1e3),D={from:t.address,to:l,value:a,validAfter:String(o-600),validBefore:String(o+(e.maxTimeoutSeconds||60)),nonce:T},k={from:t.address,to:l,value:BigInt(a),validAfter:BigInt(o-600),validBefore:BigInt(o+(e.maxTimeoutSeconds||60)),nonce:T};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let O=await t.signTypedData({domain:m,types:P,primaryType:"TransferWithAuthorization",message:k});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:D,signature:O}),signature:O}}async buildApprovalTransaction(e,t,s){let{payTo:l,asset:n,extra:f}=e,a=e.amount??e.maxAmountRequired;if(!a)throw new Error("Missing amount in payment requirements");let p=f?.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:l,amount:a,asset:n,network:e.network,facilitatorContract:p});let m=s||this.getDefaultRpcUrl(e.network),P=f?.fee??"0",E=BigInt(a)+BigInt(P),T=await this.readAllowance(m,n,t.address,p);if(T<E){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 c=this.calculateApprovalAmount(a,P,f?.approvalStrategy);this.log(`Approving ${c} for ${p} (current allowance: ${T})`);let S=await t.sendTransaction({to:n,data:this.encodeApprove(p,c),value:0n});this.log(`Approval tx sent: ${S}`),await this.waitForReceipt(m,S),this.log("Approval confirmed")}else this.log("Sufficient allowance, skipping approval");let o=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(o);let D=[...o].reduce((c,S)=>c*256n+BigInt(S),0n).toString(),k=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(k);let O="0x"+[...k].map(c=>c.toString(16).padStart(2,"0")).join(""),R=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),M=f?.eip712Domain,B=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},x=f?.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:l,token:n,amount:BigInt(a),fee:BigInt(P),nonce:BigInt(D),deadline:BigInt(R),paymentId:O},$=await t.signTypedData({domain:B,types:x,primaryType:"Payment",message:W});this.log("EIP-712 Payment signature obtained");let i={from:t.address,to:l,token:n,amount:a,fee:P,nonce:D,deadline:R,paymentId:O,signature:$};return{serialized:JSON.stringify(i),signature:$}}async buildPermit2Transaction(e,t,s){let{payTo:l,asset:n}=e,f=e.amount??e.maxAmountRequired;if(!f)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:l,amount:f,asset:n,network:e.network});let a=s||this.getDefaultRpcUrl(e.network),p=await this.readAllowance(a,n,t.address,fe),m;if(p<BigInt(f)){let B=this.encodeApprove(fe,Xe);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${p})`);let x=this.getChainId(e.network),W=await this.readGasPrice(a),$=await this.readNonce(a,t.address),i=await t.signTransaction({to:n,data:B,chainId:x,gas:50000n,gasPrice:W,nonce:$});m={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:n,spender:fe,amount:Xe.toString(),signedTransaction:i,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${p})`);let x=await t.sendTransaction({to:n,data:B,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 P=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(P);let E=[...P].reduce((B,x)=>B*256n+BigInt(x),0n),T=Math.floor(Date.now()/1e3),o=T-600,D=T+(e.maxTimeoutSeconds||300),k=this.getChainId(e.network),O={name:"Permit2",chainId:BigInt(k),verifyingContract:fe},J={permitted:{token:n,amount:BigInt(f)},spender:_e,nonce:E,deadline:BigInt(D),witness:{to:l,validAfter:BigInt(o)}},R=await t.signTypedData({domain:O,types:at,primaryType:"PermitWitnessTransferFrom",message:J});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let M={signature:R,permit2Authorization:{from:t.address,permitted:{token:n,amount:f},spender:_e,nonce:E.toString(),deadline:String(D),witness:{to:l,validAfter:String(o)}}};return{serialized:JSON.stringify(M),signature:R,extensions:m}}async readAllowance(e,t,s,l){let n="0xdd62ed3e",f=s.slice(2).toLowerCase().padStart(64,"0"),a=l.slice(2).toLowerCase().padStart(64,"0"),p=n+f+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 s="0x095ea7b3",l=e.slice(2).toLowerCase().padStart(64,"0"),n=t.toString(16).padStart(64,"0");return s+l+n}async waitForReceipt(e,t,s=3e4){let l=Date.now();for(;Date.now()-l<s;){try{let f=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(f.result){if(f.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 ${s}ms: ${t}`)}async readGasPrice(e){try{let s=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 s.result?BigInt(s.result):50000000n}catch{return 50000000n}}async readNonce(e,t){try{let l=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 l.result?parseInt(l.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,s){let l=BigInt(e)+BigInt(t);if(!s||s.mode==="exact")return l;let n=BigInt(s.defaultMultiple??10),f=l*n;if(s.maxCapUsd){let a=this.inferDecimals(e),p=BigInt(Math.floor(s.maxCapUsd*Math.pow(10,a)));if(f>p)return p}if(s.exactAboveUsd){let a=this.inferDecimals(e),p=BigInt(Math.floor(s.exactAboveUsd*Math.pow(10,a)));if(BigInt(e)>p)return l}return f}inferDecimals(e){return e.length>12?18:6}};function Q(r){return new Ae(r)}function De(r){if(r==="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"||r==="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU")return!0;let e=r.toLowerCase();for(let t of Object.values(Be))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(Ue))if(t.toLowerCase()===e)return!0;return!1}var He=new WeakMap;function Ye(r){return He.get(r)}function Te(r){let{adapters:e=[G({verbose:r.verbose}),Q({verbose:r.verbose})],wallets:t,wallet:s,preferredNetwork:l,rpcUrls:n={},maxAmountAtomic:f,fetch:a=globalThis.fetch,verbose:p=!1,accessPass:m,onPaymentRequired:P,maxRetries:E=0,retryDelayMs:T=500}=r,o=p?console.log.bind(console,"[x402]"):()=>{};async function D(i,c){let S;for(let u=0;u<=E;u++)try{let A=await a(i,c);if(A.status>=502&&A.status<=504&&u<E){o(`Retry ${u+1}/${E}: server returned ${A.status}`),await new Promise(v=>setTimeout(v,T*Math.pow(2,u)));continue}return A}catch(A){S=A,u<E&&(o(`Retry ${u+1}/${E}: ${A instanceof Error?A.message:"network error"}`),await new Promise(v=>setTimeout(v,T*Math.pow(2,u))))}throw S}let k=new Map;function O(i){try{let c=new URL(i).host,S=k.get(c);if(S&&S.expiresAt>Date.now()/1e3+10)return S.jwt;S&&k.delete(c)}catch{}return null}function J(i,c){try{let S=new URL(i).host,u=c.split(".");if(u.length===3){let A=JSON.parse(atob(u[1].replace(/-/g,"+").replace(/_/g,"/"))),v=Math.floor(Date.now()/1e3),y=v+86400,N=Math.min(typeof A.exp=="number"?A.exp:v,y);k.set(S,{jwt:c,expiresAt:N}),o("Access pass cached for",S,"| expires:",new Date(N*1e3).toISOString())}}catch{o("Failed to cache access pass")}}let R=t||{};s&&!R.solana&&V(s)&&(R.solana=s),s&&!R.evm&&H(s)&&(R.evm=s);function M(i){let c=[];for(let S of i){let u=e.find(v=>v.canHandle(S.network));if(!u)continue;let A;u.name==="Solana"?A=R.solana:u.name==="EVM"&&(A=R.evm),A&&u.isConnected(A)&&c.push({accept:S,adapter:u,wallet:A})}if(c.length===0)return null;if(l){let S=c.find(u=>u.accept.network===l);if(S)return S}return c[0]}function B(i,c){return{"eip155:56":"BSC","eip155:8453":"Base","eip155:84532":"Base Sepolia","eip155:42161":"Arbitrum","eip155:137":"Polygon","eip155:10":"Optimism","eip155:43114":"Avalanche","eip155:1":"Ethereum"}[i]||c}function x(i,c){return n[i]||c.getDefaultRpcUrl(i)}async function W(i,c,S,u,A){let v="";if(m?.preferTier&&u.tiers){let d=u.tiers.find(z=>z.id===m.preferTier);if(d){if(m.maxSpend&&parseFloat(d.price)>parseFloat(m.maxSpend))throw new U("access_pass_exceeds_max_spend",`Access pass tier "${d.id}" costs $${d.price}, exceeds max spend $${m.maxSpend}`);v=`tier=${d.id}`}}else if(m?.preferDuration&&u.ratePerHour)v=`duration=${m.preferDuration}`;else if(u.tiers&&u.tiers.length>0){let d=u.tiers[0];if(m?.maxSpend&&parseFloat(d.price)>parseFloat(m.maxSpend))throw new U("access_pass_exceeds_max_spend",`Cheapest access pass costs $${d.price}, exceeds max spend $${m?.maxSpend}`);v=`tier=${d.id}`}let y=v?A.includes("?")?`${A}&${v}`:`${A}?${v}`:A;o("Purchasing access pass:",v||"default tier");let N=S.headers.get("PAYMENT-REQUIRED");if(!N)return null;let w;try{w=JSON.parse(atob(N))}catch{return null}let b=M(w.accepts);if(!b)return null;let{accept:C,adapter:j,wallet:ee}=b;if(j.name==="Solana"&&!C.extra?.feePayer)return null;let g=C.extra?.decimals??(De(C.asset)?6:void 0);if(typeof g!="number")return null;let _=C.amount??C.maxAmountRequired;if(!_)return null;let I=x(C.network,j);try{let d=await j.getBalance(C,ee,I),z=Number(_)/Math.pow(10,g);if(d<z)throw new U("insufficient_balance",`Insufficient balance for access pass. Have $${d.toFixed(4)}, need $${z.toFixed(4)}`)}catch(d){if(d instanceof U)throw d}let q=await j.buildTransaction(C,ee,I),F;j.name==="EVM"?F=JSON.parse(q.serialized):F={transaction:q.serialized};let L=typeof i=="string"?i:i instanceof URL?i.href:i.url,X=w.resource;if(typeof w.resource=="string")try{let d=new URL(w.resource,L);["http:","https:"].includes(d.protocol)&&(X=d.toString())}catch{}else if(w.resource&&typeof w.resource=="object"&&"url"in w.resource){let d=w.resource;try{let z=new URL(d.url,L);["http:","https:"].includes(z.protocol)&&(X={...d,url:z.toString()})}catch{}}let Y={x402Version:C.x402Version??2,resource:X,accepted:C,payload:F};q.extensions&&(Y.extensions=q.extensions);let K=btoa(JSON.stringify(Y)),te=await a(y,{...c,method:"POST",headers:{...c?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":K}});if(!te.ok)return o("Pass purchase failed:",te.status),null;let h=te.headers.get("ACCESS-PASS");return h&&(J(A,h),o("Access pass purchased and cached")),te}async function $(i,c){let S=typeof i=="string"?i:i instanceof URL?i.href:i.url;if(o("Making request:",S),m){let h=O(S);if(h){o("Using cached access pass");let d=await a(i,{...c,headers:{...c?.headers||{},Authorization:`Bearer ${h}`}});if(d.status!==401&&d.status!==402)return d;o("Cached pass rejected (status",d.status,"), purchasing new pass");try{k.delete(new URL(S).host)}catch{}}}let u=await D(i,c);if(u.status!==402)return u;o("Received 402 Payment Required");let A=u.headers.get("X-ACCESS-PASS-TIERS");if(m&&A){o("Server offers access passes, purchasing...");try{let h=JSON.parse(atob(A)),d=await W(i,c,u,h,S);if(d)return d}catch(h){o("Access pass purchase failed, falling back to per-request payment:",h)}}let v=u.headers.get("PAYMENT-REQUIRED");if(!v)throw new U("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let y;try{let h=atob(v);y=JSON.parse(h)}catch{throw new U("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}o("Payment requirements:",y);let N=u.headers.get("X-Quote-Hash");N&&o("Quote hash received:",N);let w=M(y.accepts);if(!w){let h=y.accepts.map(d=>d.network).join(", ");throw new U("no_matching_payment_option",`No connected wallet for any available network: ${h}`)}let{accept:b,adapter:C,wallet:j}=w;if(o(`Using ${C.name} for ${b.network}`),C.name==="Solana"&&!b.extra?.feePayer)throw new U("missing_fee_payer","Solana payment option missing feePayer in extra");let ee=b.extra?.decimals??(De(b.asset)?6:void 0);if(typeof ee!="number")throw new U("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let g=b.amount??b.maxAmountRequired;if(!g)throw new U("missing_amount","Payment option missing amount");if(f&&BigInt(g)>BigInt(f))throw new U("amount_exceeds_max",`Payment amount ${g} exceeds maximum ${f}`);let _=x(b.network,C);o("Checking balance...");try{let h=await C.getBalance(b,j,_),d=Number(g)/Math.pow(10,ee);if(h<d){let z=B(b.network,C.name);throw new U("insufficient_balance",`Insufficient balance on ${z}. Have $${h.toFixed(4)}, need $${d.toFixed(4)}`)}o(`Balance OK: $${h.toFixed(4)} >= $${d.toFixed(4)}`)}catch(h){if(h instanceof U)throw h;o("Balance check failed (RPC error), proceeding with transaction attempt")}if(P&&!await P(b))throw new U("payment_rejected","Payment rejected by onPaymentRequired callback");o("Building transaction...");let I=await C.buildTransaction(b,j,_);o("Transaction signed");let q;C.name==="EVM"?q=JSON.parse(I.serialized):q={transaction:I.serialized};let F=typeof i=="string"?i:i instanceof URL?i.href:i.url,L=y.resource;if(typeof y.resource=="string")try{let h=new URL(y.resource,F).toString();h!==y.resource&&o("Resolved relative resource URL:",y.resource,"\u2192",h),L=h}catch{L=y.resource}else if(y.resource&&typeof y.resource=="object"&&"url"in y.resource){let h=y.resource;try{let d=new URL(h.url,F).toString();d!==h.url&&(o("Resolved relative resource URL:",h.url,"\u2192",d),L={...h,url:d})}catch{}}let X={x402Version:b.x402Version??2,resource:L,accepted:b,payload:q};I.extensions&&(X.extensions=I.extensions);let Y=btoa(JSON.stringify(X));o("Retrying request with payment...");let K=await D(i,{...c,headers:{...c?.headers||{},"PAYMENT-SIGNATURE":Y,...N?{"X-Quote-Hash":N}:{}}});if(o("Retry response status:",K.status),K.status===402){let h="unknown";try{let d=await K.clone().json();h=String(d.error||d.message||JSON.stringify(d)),o("Rejection reason:",h)}catch{}throw new U("payment_rejected",`Payment was rejected by the server: ${h}`)}let te=K.headers.get("PAYMENT-RESPONSE");if(te)try{let h=JSON.parse(atob(te));He.set(K,h),K._x402=h,h.extensions&&o("Settlement extensions:",Object.keys(h.extensions).join(", "))}catch{}return K}return{fetch:$}}function ot(r){return r.startsWith("solana:")||r==="solana"}function it(r){return r.startsWith("eip155:")||["base","ethereum","arbitrum"].includes(r)}function ct(r){return ot(r)?"solana":it(r)?"evm":"unknown"}function ke(r){return{[ne]:"Solana","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1":"Solana Devnet","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"Solana Testnet",solana:"Solana",[oe]:"Base","eip155:84532":"Base Sepolia","eip155:1":"Ethereum","eip155:42161":"Arbitrum One",base:"Base",ethereum:"Ethereum",arbitrum:"Arbitrum"}[r]||r}function ze(r,e){let t=ct(e);if(t==="solana")return e.includes("devnet")||e==="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"?`https://solscan.io/tx/${r}?cluster=devnet`:`https://www.orbmarkets.io/tx/${r}`;if(t==="evm"){let s="8453";switch(e.startsWith("eip155:")?s=e.split(":")[1]:e==="ethereum"?s="1":e==="arbitrum"&&(s="42161"),s){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}`;default:return`https://basescan.org/tx/${r}`}}return`https://solscan.io/tx/${r}`}function Ge(r){let e=Ye(r);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function Me(r){let e=Ge(r);if(e?.recommendations?.length)return e.recommendations}async function Oe(r){let t=Ge(r)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function pt(r){let{wallets:e,wallet:t,preferredNetwork:s,rpcUrls:l={},verbose:n=!1}=r,[f,a]=ae(!1),[p,m]=ae("idle"),[P,E]=ae(null),[T,o]=ae(null),[D,k]=ae(null),[O,J]=ae([]),[R,M]=ae(null),B=ve((...y)=>{n&&console.log("[useX402Payment]",...y)},[n]),x=ge(()=>{let y={...e};return t&&!y.solana&&V(t)&&(y.solana=t),t&&!y.evm&&H(t)&&(y.evm=t),y},[e,t]),W=ge(()=>[G({verbose:n,rpcUrls:l}),Q({verbose:n,rpcUrls:l})],[n,l]),$=ge(()=>({solana:x.solana?V(x.solana)&&W[0].isConnected(x.solana):!1,evm:x.evm?H(x.evm)&&W[1].isConnected(x.evm):!1}),[x,W]),i=$.solana||$.evm,c=ve(async()=>{let y=[];if($.solana&&x.solana)try{let N=W.find(w=>w.name==="Solana");if(N){let w={scheme:"exact",network:ne,amount:"0",asset:qe,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},b=await N.getBalance(w,x.solana);y.push({network:ne,chainName:ke(ne),balance:b,asset:"USDC"})}}catch(N){B("Failed to fetch Solana balance:",N)}if($.evm&&x.evm)try{let N=W.find(w=>w.name==="EVM");if(N){let w={scheme:"exact",network:oe,amount:"0",asset:Le,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},b=await N.getBalance(w,x.evm);y.push({network:oe,chainName:ke(oe),balance:b,asset:"USDC"})}}catch(N){B("Failed to fetch Base balance:",N)}J(y)},[$,x,W,B]);lt(()=>{c();let y=setInterval(c,3e4);return()=>clearInterval(y)},[c]);let S=ve(()=>{a(!1),m("idle"),E(null),o(null),k(null),M(null)},[]),u=ge(()=>Te({adapters:W,wallets:x,preferredNetwork:s,rpcUrls:l,verbose:n}),[W,x,s,l,n]),A=ve(async(y,N)=>{if(a(!0),m("pending"),E(null),o(null),k(null),!i){let w=new U("wallet_not_connected","No wallet connected");throw E(w),m("error"),a(!1),w}try{let w=await u.fetch(y,N),b=w.headers.get("PAYMENT-RESPONSE");if(b)try{let j=JSON.parse(atob(b));j.transaction&&o(j.transaction),j.network&&k(j.network)}catch{B("Could not parse PAYMENT-RESPONSE header")}let C=Me(w);return M(C??null),C&&(B("Sponsored recommendations received:",C.length),Oe(w).catch(()=>{})),m("success"),w}catch(w){let b=w instanceof Error?w:new Error(String(w));throw E(b),m("error"),w}finally{a(!1),setTimeout(c,2e3)}},[u,i,B,c]),v=ge(()=>T?ze(T,D||s||ne):null,[T,D,s]);return{fetch:A,isLoading:f,status:p,error:P,transactionId:T,transactionNetwork:D,transactionUrl:v,balances:O,connectedChains:$,isAnyWalletConnected:i,reset:S,refreshBalances:c,accessPass:null,sponsoredRecommendations:R}}import{useState as Z,useCallback as Ce,useEffect as We,useMemo as $e,useRef as ut}from"react";function dt(r){let{wallets:e,wallet:t,preferredNetwork:s,rpcUrls:l={},resourceUrl:n,autoConnect:f=!0,verbose:a=!1}=r,p=`x402-access-pass:${n}`;function m(){if(typeof sessionStorage>"u")return null;try{let g=sessionStorage.getItem(p);if(!g)return null;let _=JSON.parse(g);return new Date(_.expiresAt).getTime()<=Date.now()?(sessionStorage.removeItem(p),null):_}catch{return null}}function P(g,_,I){if(!(typeof sessionStorage>"u"))try{sessionStorage.setItem(p,JSON.stringify({jwt:g,tier:_,expiresAt:I}))}catch{}}let E=m(),[T,o]=Z(null),[D,k]=Z(null),[O,J]=Z(!1),[R,M]=Z(E?.jwt||null),[B,x]=Z(E?{tier:E.tier,expiresAt:E.expiresAt}:null),[W,$]=Z(!1),[i,c]=Z(null),S=ut(R);We(()=>{S.current=R},[R]);let u=Ce((...g)=>{a&&console.log("[useAccessPass]",...g)},[a]),A=$e(()=>{let g={...e};return t&&!g.solana&&V(t)&&(g.solana=t),t&&!g.evm&&H(t)&&(g.evm=t),g},[e,t]),v=$e(()=>Te({adapters:[G({verbose:a,rpcUrls:l}),Q({verbose:a,rpcUrls:l})],wallets:A,preferredNetwork:s,rpcUrls:l,verbose:a,accessPass:{enabled:!0,autoRenew:!0}}),[A,s,l,a]),[y,N]=Z(0),w=$e(()=>{if(!R||!B)return null;let g=new Date(B.expiresAt).getTime(),_=Math.max(0,Math.floor((g-Date.now())/1e3));return _<=0?null:{jwt:R,tier:B.tier,expiresAt:B.expiresAt,remainingSeconds:_}},[R,B,y]),b=w!==null&&w.remainingSeconds>0;We(()=>{if(!R||!B)return;let g=setInterval(()=>N(_=>_+1),1e3);return()=>clearInterval(g)},[b]);let C=Ce(async()=>{J(!0);try{let g=await fetch(n);if(g.status===402){let _=g.headers.get("X-ACCESS-PASS-TIERS");if(_){let I=JSON.parse(atob(_));o(I.tiers||null),k(I.ratePerHour||null),u("Tier info loaded:",I)}}}catch(g){u("Failed to fetch tiers:",g)}finally{J(!1)}},[n,u]);We(()=>{f&&C()},[f,C]);let j=Ce(async(g,_)=>{$(!0),c(null);try{let I=n;g?I+=(I.includes("?")?"&":"?")+`tier=${g}`:_&&(I+=(I.includes("?")?"&":"?")+`duration=${_}`);let q=await v.fetch(I,{method:"POST"}),F=q.headers.get("ACCESS-PASS");if(u("ACCESS-PASS header:",F?"found":"NOT FOUND"),F){M(F);let L=g||"unknown",X="";try{let Y=await q.json();L=Y.accessPass?.tier||L,X=Y.accessPass?.expiresAt||""}catch{}if(!X)try{let Y=F.split(".");if(Y.length===3){let K=JSON.parse(atob(Y[1].replace(/-/g,"+").replace(/_/g,"/")));L=K.tier||L,X=new Date(K.exp*1e3).toISOString()}}catch{}x({tier:L,expiresAt:X}),P(F,L,X),u("Pass purchased and persisted:",L,X)}}catch(I){let q=I instanceof Error?I:new Error(String(I));throw c(q),q}finally{$(!1)}},[n,v,u]),ee=Ce(async(g,_)=>{let I=!g||g===""?n:g.startsWith("http")?g:`${n.replace(/\/$/,"")}${g.startsWith("/")?"":"/"}${g}`,q=S.current;if(q){try{let F=q.split(".");if(F.length===3){let L=JSON.parse(atob(F[1].replace(/-/g,"+").replace(/_/g,"/")));if(L.exp&&L.exp>Date.now()/1e3)return fetch(I,{..._,headers:{..._?.headers||{},Authorization:`Bearer ${q}`}})}}catch{}M(null),x(null);try{sessionStorage.removeItem(p)}catch{}}return v.fetch(I,_)},[n,v,p]);return{tiers:T,customRatePerHour:D,isLoadingTiers:O,pass:w,isPassValid:b,fetchTiers:C,purchasePass:j,isPurchasing:W,purchaseError:i,fetch:ee}}export{U as X402Error,Oe as fireImpressionBeacon,Me as getSponsoredRecommendations,dt as useAccessPass,pt as useX402Payment};
1
+ import{useState as pe,useCallback as He,useEffect as Pt,useMemo as De}from"react";var Q="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Te="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Ue="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",oe=Q,we=Te,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,Re=de,Pe=fe,be=me,_e=ge,Ce=he,Ne=ye,Ie=Ae,ve=Se,Be="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",nt="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",Le="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",Je="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={[Je]:{symbol:"USDT",decimals:18},[ke]:{symbol:"USDC",decimals:18}};var ce="0x000000000022D473030F116dDEE9F6B43aC78BA3",Oe="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",Ye={[he]:56,[z]:8453,[ue]:84532,[de]:42161,[fe]:137,[me]:10,[ge]:43114,[ye]:1187947933,[Ae]:324705682,[Se]:1},le={[Q]:"https://api.dexter.cash/api/solana/rpc",[Te]:"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 O=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 rt,TransactionMessage as ft,VersionedTransaction as mt,ComputeBudgetProgram as st}from"@solana/web3.js";import{getAssociatedTokenAddress as Ge,getAccount as gt,createTransferCheckedInstruction as ht,getMint as yt,TOKEN_PROGRAM_ID as at,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,we,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[we]: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 o=r||this.getDefaultRpcUrl(e.network),s=new rt(o,"confirmed"),p=new Ee(t.publicKey.toBase58()),a=new Ee(e.asset);try{let d=(await s.getAccountInfo(a,"confirmed"))?.owner.toBase58()===qe.toBase58()?qe:at,x=await Ge(a,p,!1,d),R=await gt(s,x,void 0,d),_=e.extra?.decimals??6;return Number(R.amount)/Math.pow(10,_)}catch(l){if(l&&typeof l=="object"&&"name"in l&&(l.name==="TokenAccountNotFoundError"||l.name==="TokenInvalidAccountOwnerError"))return 0;throw l}}async buildTransaction(e,t,r){if(!J(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let o=r||this.getDefaultRpcUrl(e.network),s=new rt(o,"confirmed"),p=new Ee(t.publicKey.toBase58()),{payTo:a,asset:l,extra:d}=e,x=e.amount??e.maxAmountRequired;if(!x)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(l),i=new Ee(a);this.log("Building transaction:",{from:p.toBase58(),to:a,amount:x,asset:l,feePayer:d.feePayer});let D=[];D.push(st.setComputeUnitLimit({units:At})),D.push(st.setComputeUnitPrice({microLamports:St}));let U=await s.getAccountInfo(_,"confirmed");if(!U)throw new Error(`Token mint ${l} not found`);let L=U.owner.toBase58()===qe.toBase58()?qe:at,j=await yt(s,_,void 0,L);typeof d?.decimals=="number"&&j.decimals!==d.decimals&&this.log(`Decimals mismatch: requirements say ${d.decimals}, mint says ${j.decimals}`);let P=await Ge(_,p,!1,L),M=await Ge(_,i,!1,L);if(!await s.getAccountInfo(P,"confirmed"))throw new Error(`No token account found for ${l}. 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(x);D.push(ht(P,_,M,p,k,j.decimals,[],L));let{blockhash:W}=await s.getLatestBlockhash("confirmed"),X=new ft({payerKey:R,recentBlockhash:W,instructions:D}).compileToV0Message(),c=new mt(X),f=await t.signTransaction(c);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"}]},ot=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 je=class{name="EVM";networks=[Ce,ie,Me,ve,Re,Pe,be,_e,Ne,Ie];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[Ce]:e==="ethereum"?H[ve]:e==="arbitrum"?H[Re]:e==="polygon"?H[Pe]:e==="optimism"?H[be]:e==="avalanche"?H[_e]:e==="skale-base"?H[Ne]:e==="skale-base-sepolia"?H[Ie]:H[ie]}getAddress(e){return Y(e)?e.address:null}isConnected(e){return Y(e)?!!e.address:!1}getChainId(e){if(Ye[e])return Ye[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 o=r||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 l=BigInt(a.result),d=e.extra?.decimals??6;return Number(l)/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: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 l=this.getChainId(e.network),d={name:p?.name??"USD Coin",version:p?.version??"2",chainId:BigInt(l),verifyingContract:s},x={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(P=>P.toString(16).padStart(2,"0")).join(""),i=Math.floor(Date.now()/1e3),D={from:t.address,to:o,value:a,validAfter:String(i-600),validBefore:String(i+(e.maxTimeoutSeconds||60)),nonce:_},U={from:t.address,to:o,value:BigInt(a),validAfter:BigInt(i-600),validBefore:BigInt(i+(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:x,primaryType:"TransferWithAuthorization",message:U});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:D,signature:L}),signature:L}}async buildApprovalTransaction(e,t,r){let{payTo:o,asset:s,extra:p}=e,a=e.amount??e.maxAmountRequired;if(!a)throw new Error("Missing amount in payment requirements");let l=p?.facilitatorContract;if(!l)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:l});let d=r||this.getDefaultRpcUrl(e.network),x=p?.fee??"0",R=BigInt(a)+BigInt(x),_=await this.readAllowance(d,s,t.address,l);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 c=this.calculateApprovalAmount(a,x,p?.approvalStrategy);this.log(`Approving ${c} for ${l} (current allowance: ${_})`);let f=await t.sendTransaction({to:s,data:this.encodeApprove(l,c),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 i=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(i);let D=[...i].reduce((c,f)=>c*256n+BigInt(f),0n).toString(),U=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(U);let L="0x"+[...U].map(c=>c.toString(16).padStart(2,"0")).join(""),P=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),M=p?.eip712Domain,N=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:l},w=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"}]},k={from:t.address,to:o,token:s,amount:BigInt(a),fee:BigInt(x),nonce:BigInt(D),deadline:BigInt(P),paymentId:L},W=await t.signTypedData({domain:N,types:w,primaryType:"Payment",message:k});this.log("EIP-712 Payment signature obtained");let X={from:t.address,to:o,token:s,amount:a,fee:x,nonce:D,deadline:P,paymentId:L,signature:W};return{serialized:JSON.stringify(X),signature:W}}async buildPermit2Transaction(e,t,r){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=r||this.getDefaultRpcUrl(e.network),l=await this.readAllowance(a,s,t.address,ce),d;if(l<BigInt(p)){let N=this.encodeApprove(ce,ot);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${l})`);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:N,chainId:w,gas:50000n,gasPrice:k,nonce:W});d={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:s,spender:ce,amount:ot.toString(),signedTransaction:X,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${l})`);let w=await t.sendTransaction({to:s,data:N,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 x=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(x);let R=[...x].reduce((N,w)=>N*256n+BigInt(w),0n),_=Math.floor(Date.now()/1e3),i=_-600,D=_+(e.maxTimeoutSeconds||300),U=this.getChainId(e.network),L={name:"Permit2",chainId:BigInt(U),verifyingContract:ce},j={permitted:{token:s,amount:BigInt(p)},spender:Oe,nonce:R,deadline:BigInt(D),witness:{to:o,validAfter:BigInt(i)}},P=await t.signTypedData({domain:L,types:Et,primaryType:"PermitWitnessTransferFrom",message:j});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let M={signature:P,permit2Authorization:{from:t.address,permitted:{token:s,amount:p},spender:Oe,nonce:R.toString(),deadline:String(D),witness:{to:o,validAfter:String(i)}}};return{serialized:JSON.stringify(M),signature:P,extensions:d}}async readAllowance(e,t,r,o){let s="0xdd62ed3e",p=r.slice(2).toLowerCase().padStart(64,"0"),a=o.slice(2).toLowerCase().padStart(64,"0"),l=s+p+a;try{let x=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:l},"latest"]})})).json();return x.error||!x.result||x.result==="0x"?0n:BigInt(x.result)}catch{return 0n}}encodeApprove(e,t){let r="0x095ea7b3",o=e.slice(2).toLowerCase().padStart(64,"0"),s=t.toString(16).padStart(64,"0");return r+o+s}async waitForReceipt(e,t,r=3e4){let o=Date.now();for(;Date.now()-o<r;){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 ${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 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,r){let o=BigInt(e)+BigInt(t);if(!r||r.mode==="exact")return o;let s=BigInt(r.defaultMultiple??10),p=o*s;if(r.maxCapUsd){let a=this.inferDecimals(e),l=BigInt(Math.floor(r.maxCapUsd*Math.pow(10,a)));if(p>l)return l}if(r.exactAboveUsd){let a=this.inferDecimals(e),l=BigInt(Math.floor(r.exactAboveUsd*Math.pow(10,a)));if(BigInt(e)>l)return o}return p}inferDecimals(e){return e.length>12?18:6}};function ne(n){return new je(n)}function ze(n){if(n===Be||n===nt)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 Tt(n){return n.startsWith("solana:")||n==="solana"}function wt(n){return n.startsWith("eip155:")||["base","ethereum","arbitrum"].includes(n)}function xt(n){return Tt(n)?"solana":wt(n)?"evm":"unknown"}function Fe(n){return{[Q]:"Solana",[Te]:"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 it(n,e){let t=Fe(n);return t===n?e:t}function ct(n,e){let t=xt(e);if(t==="solana")return e.includes("devnet")||e===Te?`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 Rt(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((p,a)=>r.set(a,p));let o={method:e?.method??t.method,headers:r,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 lt=new WeakMap;function pt(n){return lt.get(n)}function Xe(n){let{adapters:e=[te({verbose:n.verbose}),ne({verbose:n.verbose})],wallets:t,wallet:r,preferredNetwork:o,rpcUrls:s={},maxAmountAtomic:p,fetch:a=globalThis.fetch,verbose:l=!1,accessPass:d,onPaymentRequired:x,maxRetries:R=0,retryDelayMs:_=500}=n,i=l?console.log.bind(console,"[x402]"):()=>{};async function D(c,f){let A;for(let m=0;m<=R;m++)try{let E=await a(c,f);if(E.status>=502&&E.status<=504&&m<R){i(`Retry ${m+1}/${R}: server returned ${E.status}`),await new Promise(g=>setTimeout(g,_*Math.pow(2,m)));continue}return E}catch(E){A=E,m<R&&(i(`Retry ${m+1}/${R}: ${E instanceof Error?E.message:"network error"}`),await new Promise(g=>setTimeout(g,_*Math.pow(2,m))))}throw A}let U=new Map;function L(c){try{let f=new URL(c).host,A=U.get(f);if(A&&A.expiresAt>Date.now()/1e3+10)return A.jwt;A&&U.delete(f)}catch{}return null}function j(c,f){try{let A=new URL(c).host,m=f.split(".");if(m.length===3){let E=JSON.parse(atob(m[1].replace(/-/g,"+").replace(/_/g,"/"))),g=Math.floor(Date.now()/1e3),T=g+86400,S=Math.min(typeof E.exp=="number"?E.exp:g,T);U.set(A,{jwt:f,expiresAt:S}),i("Access pass cached for",A,"| expires:",new Date(S*1e3).toISOString())}}catch{i("Failed to cache access pass")}}let P=t||{};r&&!P.solana&&J(r)&&(P.solana=r),r&&!P.evm&&Y(r)&&(P.evm=r);function M(c){let f=[];for(let A of c){let m=e.find(g=>g.canHandle(A.network));if(!m)continue;let E;m.name==="Solana"?E=P.solana:m.name==="EVM"&&(E=P.evm),E&&m.isConnected(E)&&f.push({accept:A,adapter:m,wallet:E})}if(f.length===0)return null;if(o){let A=f.find(m=>m.accept.network===o);if(A)return A}return f[0]}function N(c,f){return it(c,f)}function w(c,f){return s[c]||f.getDefaultRpcUrl(c)}async function k(c,f,A,m,E){let g="";if(d?.preferTier&&m.tiers){let u=m.tiers.find(Z=>Z.id===d.preferTier);if(u){if(d.maxSpend&&parseFloat(u.price)>parseFloat(d.maxSpend))throw new O("access_pass_exceeds_max_spend",`Access pass tier "${u.id}" costs $${u.price}, exceeds max spend $${d.maxSpend}`);g=`tier=${u.id}`}}else if(d?.preferDuration&&m.ratePerHour)g=`duration=${d.preferDuration}`;else if(m.tiers&&m.tiers.length>0){let u=m.tiers[0];if(d?.maxSpend&&parseFloat(u.price)>parseFloat(d.maxSpend))throw new O("access_pass_exceeds_max_spend",`Cheapest access pass costs $${u.price}, exceeds max spend $${d?.maxSpend}`);g=`tier=${u.id}`}let T=g?E.includes("?")?`${E}&${g}`:`${E}?${g}`:E;i("Purchasing access pass:",g||"default tier");let S=A.headers.get("PAYMENT-REQUIRED");if(!S)return null;let I;try{I=JSON.parse(atob(S))}catch{return null}let v=M(I.accepts);if(!v)return null;let{accept:C,adapter:G,wallet:h}=v;if(G.name==="Solana"&&!C.extra?.feePayer)return null;let b=C.extra?.decimals??(ze(C.asset)?6:void 0);if(typeof b!="number")return null;let B=C.amount??C.maxAmountRequired;if(!B)return null;let $=w(C.network,G);try{let u=await G.getBalance(C,h,$),Z=Number(B)/Math.pow(10,b);if(u<Z){let dt=N(C.network,G.name);throw new O("insufficient_balance",`Insufficient balance for access pass on ${dt}. Have $${u.toFixed(4)}, need $${Z.toFixed(4)}`)}}catch(u){if(u instanceof O)throw u}let q=await G.buildTransaction(C,h,$),K;G.name==="EVM"?K=JSON.parse(q.serialized):K={transaction:q.serialized};let F=typeof c=="string"?c:c instanceof URL?c.href:c.url,V=I.resource;if(typeof I.resource=="string")try{let u=new URL(I.resource,F);["http:","https:"].includes(u.protocol)&&(V=u.toString())}catch{}else if(I.resource&&typeof I.resource=="object"&&"url"in I.resource){let u=I.resource;try{let Z=new URL(u.url,F);["http:","https:"].includes(Z.protocol)&&(V={...u,url:Z.toString()})}catch{}}let se={x402Version:C.x402Version??2,resource:V,accepted:C,payload:K};q.extensions&&(se.extensions=q.extensions);let ee=btoa(JSON.stringify(se)),ae=await a(T,{...f,method:"POST",headers:{...f?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":ee}});if(!ae.ok)return i("Pass purchase failed:",ae.status),null;let y=ae.headers.get("ACCESS-PASS");return y&&(j(E,y),i("Access pass purchased and cached")),ae}async function W(c,f){let A=c;if(i("Making request:",A),d){let y=L(A);if(y){i("Using cached access pass");let u=await a(c,{...f,headers:{...f?.headers||{},Authorization:`Bearer ${y}`}});if(u.status!==401&&u.status!==402)return u;i("Cached pass rejected (status",u.status,"), purchasing new pass");try{U.delete(new URL(A).host)}catch{}}}let m=await D(c,f);if(m.status!==402)return m;i("Received 402 Payment Required");let E=m.headers.get("X-ACCESS-PASS-TIERS");if(d&&E){i("Server offers access passes, purchasing...");try{let y=JSON.parse(atob(E)),u=await k(c,f,m,y,A);if(u)return u}catch(y){i("Access pass purchase failed, falling back to per-request payment:",y)}}let g=m.headers.get("PAYMENT-REQUIRED");if(!g)throw new O("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let T;try{let y=atob(g);T=JSON.parse(y)}catch{throw new O("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}i("Payment requirements:",T);let S=m.headers.get("X-Quote-Hash");S&&i("Quote hash received:",S);let I=M(T.accepts);if(!I){let y=T.accepts.map(u=>u.network).join(", ");throw new O("no_matching_payment_option",`No connected wallet for any available network: ${y}`)}let{accept:v,adapter:C,wallet:G}=I;if(i(`Using ${C.name} for ${v.network}`),C.name==="Solana"&&!v.extra?.feePayer)throw new O("missing_fee_payer","Solana payment option missing feePayer in extra");let h=v.extra?.decimals??(ze(v.asset)?6:void 0);if(typeof h!="number")throw new O("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let b=v.amount??v.maxAmountRequired;if(!b)throw new O("missing_amount","Payment option missing amount");if(p&&BigInt(b)>BigInt(p))throw new O("amount_exceeds_max",`Payment amount ${b} exceeds maximum ${p}`);let B=w(v.network,C);i("Checking balance...");try{let y=await C.getBalance(v,G,B),u=Number(b)/Math.pow(10,h);if(y<u){let Z=N(v.network,C.name);throw new O("insufficient_balance",`Insufficient balance on ${Z}. Have $${y.toFixed(4)}, need $${u.toFixed(4)}`)}i(`Balance OK: $${y.toFixed(4)} >= $${u.toFixed(4)}`)}catch(y){if(y instanceof O)throw y;i("Balance check failed (RPC error), proceeding with transaction attempt")}if(x&&!await x(v))throw new O("payment_rejected","Payment rejected by onPaymentRequired callback");i("Building transaction...");let $=await C.buildTransaction(v,G,B);i("Transaction signed");let q;C.name==="EVM"?q=JSON.parse($.serialized):q={transaction:$.serialized};let K=c,F=T.resource;if(typeof T.resource=="string")try{let y=new URL(T.resource,K).toString();y!==T.resource&&i("Resolved relative resource URL:",T.resource,"\u2192",y),F=y}catch{F=T.resource}else if(T.resource&&typeof T.resource=="object"&&"url"in T.resource){let y=T.resource;try{let u=new URL(y.url,K).toString();u!==y.url&&(i("Resolved relative resource URL:",y.url,"\u2192",u),F={...y,url:u})}catch{}}let V={x402Version:v.x402Version??2,resource:F,accepted:v,payload:q};$.extensions&&(V.extensions=$.extensions);let se=btoa(JSON.stringify(V));i("Retrying request with payment...");let ee=await D(c,{...f,headers:{...f?.headers||{},"PAYMENT-SIGNATURE":se,...S?{"X-Quote-Hash":S}:{}}});if(i("Retry response status:",ee.status),ee.status===402){let y="unknown";try{let u=await ee.clone().json();y=String(u.error||u.message||JSON.stringify(u)),i("Rejection reason:",y)}catch{}throw new O("payment_rejected",`Payment was rejected by the server: ${y}`)}let ae=ee.headers.get("PAYMENT-RESPONSE");if(ae)try{let y=JSON.parse(atob(ae));lt.set(ee,y),y.extensions&&i("Settlement extensions:",Object.keys(y.extensions).join(", "))}catch{}return ee}async function X(c,f){let[A,m]=await Rt(c,f);return W(A,m)}return{fetch:X}}function ut(n){let e=pt(n);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function Qe(n){let e=ut(n);if(e?.recommendations?.length)return e.recommendations}async function Ze(n){let t=ut(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:o={},verbose:s=!1}=n,[p,a]=pe(!1),[l,d]=pe("idle"),[x,R]=pe(null),[_,i]=pe(null),[D,U]=pe(null),[L,j]=pe([]),[P,M]=pe(null),N=He((...g)=>{s&&console.log("[useX402Payment]",...g)},[s]),w=De(()=>{let g={...e};return t&&!g.solana&&J(t)&&(g.solana=t),t&&!g.evm&&Y(t)&&(g.evm=t),g},[e,t]),k=De(()=>[te({verbose:s,rpcUrls:o}),ne({verbose:s,rpcUrls:o})],[s,o]),W=De(()=>({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,c=He(async()=>{let g=[];if(W.solana&&w.solana)try{let T=k.find(S=>S.name==="Solana");if(T){let S={scheme:"exact",network:Q,amount:"0",asset:Be,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},I=await T.getBalance(S,w.solana);g.push({network:Q,chainName:Fe(Q),balance:I,asset:"USDC"})}}catch(T){N("Failed to fetch Solana balance:",T)}if(W.evm&&w.evm)try{let T=k.find(S=>S.name==="EVM");if(T){let S={scheme:"exact",network:z,amount:"0",asset:Le,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},I=await T.getBalance(S,w.evm);g.push({network:z,chainName:Fe(z),balance:I,asset:"USDC"})}}catch(T){N("Failed to fetch Base balance:",T)}j(g)},[W,w,k,N]);Pt(()=>{c();let g=setInterval(c,3e4);return()=>clearInterval(g)},[c]);let f=He(()=>{a(!1),d("idle"),R(null),i(null),U(null),M(null)},[]),A=De(()=>Xe({adapters:k,wallets:w,preferredNetwork:r,rpcUrls:o,verbose:s}),[k,w,r,o,s]),m=He(async(g,T)=>{if(a(!0),d("pending"),R(null),i(null),U(null),!X){let S=new O("wallet_not_connected","No wallet connected");throw R(S),d("error"),a(!1),S}try{let S=await A.fetch(g,T),I=S.headers.get("PAYMENT-RESPONSE");if(I)try{let C=JSON.parse(atob(I));C.transaction&&i(C.transaction),C.network&&U(C.network)}catch{N("Could not parse PAYMENT-RESPONSE header")}let v=Qe(S);return M(v??null),v&&(N("Sponsored recommendations received:",v.length),Ze(S).catch(()=>{})),d("success"),S}catch(S){let I=S instanceof Error?S:new Error(String(S));throw R(I),d("error"),S}finally{a(!1),setTimeout(c,2e3)}},[A,X,N,c]),E=De(()=>_?ct(_,D||r||Q):null,[_,D,r]);return{fetch:m,isLoading:p,status:l,error:x,transactionId:_,transactionNetwork:D,transactionUrl:E,balances:L,connectedChains:W,isAnyWalletConnected:X,reset:f,refreshBalances:c,accessPass:null,sponsoredRecommendations:P}}import{useState as re,useCallback as Ve,useEffect as et,useMemo as tt,useRef as _t}from"react";function Ct(n){let{wallets:e,wallet:t,preferredNetwork:r,rpcUrls:o={},resourceUrl:s,autoConnect:p=!0,verbose:a=!1}=n,l=`x402-access-pass:${s}`;function d(){if(typeof sessionStorage>"u")return null;try{let h=sessionStorage.getItem(l);if(!h)return null;let b=JSON.parse(h);return new Date(b.expiresAt).getTime()<=Date.now()?(sessionStorage.removeItem(l),null):b}catch{return null}}function x(h,b,B){if(!(typeof sessionStorage>"u"))try{sessionStorage.setItem(l,JSON.stringify({jwt:h,tier:b,expiresAt:B}))}catch{}}let R=d(),[_,i]=re(null),[D,U]=re(null),[L,j]=re(!1),[P,M]=re(R?.jwt||null),[N,w]=re(R?{tier:R.tier,expiresAt:R.expiresAt}:null),[k,W]=re(!1),[X,c]=re(null),f=_t(P);et(()=>{f.current=P},[P]);let A=Ve((...h)=>{a&&console.log("[useAccessPass]",...h)},[a]),m=tt(()=>{let h={...e};return t&&!h.solana&&J(t)&&(h.solana=t),t&&!h.evm&&Y(t)&&(h.evm=t),h},[e,t]),E=tt(()=>Xe({adapters:[te({verbose:a,rpcUrls:o}),ne({verbose:a,rpcUrls:o})],wallets:m,preferredNetwork:r,rpcUrls:o,verbose:a,accessPass:{enabled:!0,autoRenew:!0}}),[m,r,o,a]),[g,T]=re(0),S=tt(()=>{if(!P||!N)return null;let h=new Date(N.expiresAt).getTime(),b=Math.max(0,Math.floor((h-Date.now())/1e3));return b<=0?null:{jwt:P,tier:N.tier,expiresAt:N.expiresAt,remainingSeconds:b}},[P,N,g]),I=S!==null&&S.remainingSeconds>0;et(()=>{if(!P||!N)return;let h=setInterval(()=>T(b=>b+1),1e3);return()=>clearInterval(h)},[I]);let v=Ve(async()=>{j(!0);try{let h=await fetch(s);if(h.status===402){let b=h.headers.get("X-ACCESS-PASS-TIERS");if(b){let B=JSON.parse(atob(b));i(B.tiers||null),U(B.ratePerHour||null),A("Tier info loaded:",B)}}}catch(h){A("Failed to fetch tiers:",h)}finally{j(!1)}},[s,A]);et(()=>{p&&v()},[p,v]);let C=Ve(async(h,b)=>{W(!0),c(null);try{let B=s;h?B+=(B.includes("?")?"&":"?")+`tier=${h}`:b&&(B+=(B.includes("?")?"&":"?")+`duration=${b}`);let $=await E.fetch(B,{method:"POST"}),q=$.headers.get("ACCESS-PASS");if(A("ACCESS-PASS header:",q?"found":"NOT FOUND"),q){M(q);let K=h||"unknown",F="";try{let V=await $.json();K=V.accessPass?.tier||K,F=V.accessPass?.expiresAt||""}catch{}if(!F)try{let V=q.split(".");if(V.length===3){let se=JSON.parse(atob(V[1].replace(/-/g,"+").replace(/_/g,"/")));K=se.tier||K,F=new Date(se.exp*1e3).toISOString()}}catch{}w({tier:K,expiresAt:F}),x(q,K,F),A("Pass purchased and persisted:",K,F)}}catch(B){let $=B instanceof Error?B:new Error(String(B));throw c($),$}finally{W(!1)}},[s,E,A]),G=Ve(async(h,b)=>{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,{...b,headers:{...b?.headers||{},Authorization:`Bearer ${$}`}})}}catch{}M(null),w(null);try{sessionStorage.removeItem(l)}catch{}}return E.fetch(B,b)},[s,E,l]);return{tiers:_,customRatePerHour:D,isLoadingTiers:L,pass:S,isPassValid:I,fetchTiers:v,purchasePass:C,isPurchasing:k,purchaseError:X,fetch:G}}export{O as X402Error,Ze as fireImpressionBeacon,Qe as getSponsoredRecommendations,Ct as useAccessPass,bt as useX402Payment};