@dexterai/x402 6.0.3 → 6.0.4

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.
Files changed (35) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/REFERENCE.md +25 -0
  3. package/dist/adapters/index.cjs +1 -1
  4. package/dist/adapters/index.d.cts +2 -2
  5. package/dist/adapters/index.d.ts +2 -2
  6. package/dist/adapters/index.js +1 -1
  7. package/dist/batch-settlement/index.d.cts +3 -3
  8. package/dist/batch-settlement/index.d.ts +3 -3
  9. package/dist/batch-settlement/seller/index.d.cts +4 -4
  10. package/dist/batch-settlement/seller/index.d.ts +4 -4
  11. package/dist/client/index.cjs +1 -1
  12. package/dist/client/index.d.cts +4 -4
  13. package/dist/client/index.d.ts +4 -4
  14. package/dist/client/index.js +1 -1
  15. package/dist/react/index.cjs +1 -1
  16. package/dist/react/index.d.cts +2 -2
  17. package/dist/react/index.d.ts +2 -2
  18. package/dist/react/index.js +1 -1
  19. package/dist/server/index.d.cts +3 -3
  20. package/dist/server/index.d.ts +3 -3
  21. package/dist/tab/index.cjs +5 -5
  22. package/dist/tab/index.d.cts +3 -3
  23. package/dist/tab/index.d.ts +3 -3
  24. package/dist/tab/index.js +5 -5
  25. package/dist/{types-BOEYu6ya.d.cts → types-B-fkCTII.d.cts} +1 -1
  26. package/dist/{types-DhCxPFgg.d.ts → types-B4y1Lava.d.ts} +1 -1
  27. package/dist/{types-Ds9IUnXG.d.ts → types-Bm6-yPwi.d.ts} +3 -0
  28. package/dist/{types-B4JCwkHH.d.cts → types-CEOJ9sFp.d.cts} +3 -0
  29. package/dist/{types-CTYEYNZO.d.cts → types-CYO2QLUN.d.cts} +1 -1
  30. package/dist/{types-G6MIMJjK.d.cts → types-CnNjeeZP.d.cts} +2 -2
  31. package/dist/{types-zImyINj3.d.ts → types-CuTmhygi.d.ts} +2 -2
  32. package/dist/{types-BdUPQzXu.d.ts → types-REjsl5JJ.d.ts} +1 -1
  33. package/dist/{x402-client-Cil4Tmqy.d.ts → x402-client-zC0XNdb_.d.cts} +9 -0
  34. package/dist/{x402-client-Cil4Tmqy.d.cts → x402-client-zC0XNdb_.d.ts} +9 -0
  35. package/package.json +1 -1
@@ -1 +1 @@
1
- var Ee="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",je="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Xe="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",z=Ee,_e=je,Pe=Xe,te="eip155:8453",ge="eip155:84532",he="eip155:42161",ye="eip155:137",Ae="eip155:10",be="eip155:43114",Se="eip155:56",ne="eip155:480",re="eip155:143",oe="eip155:4663",se="eip155:1187947933",ae="eip155:324705682",we="eip155:1",J=te,ze=ge,Te=he,Ie=ye,Ne=Ae,Ce=be,ke=Se,Oe=ne,Ve=re,Be=oe,De=se,Ue=ae,Me=we,Je="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",bt="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",St="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",ut="0x55d398326f99059fF775485246999027B3197955",Ge="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",lt="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",Ye={[Se]:Ge,[te]:St,[ge]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[he]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[ye]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[Ae]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[be]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[ne]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[re]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[oe]:lt,[se]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[ae]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[we]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},Ze={[ut]:{symbol:"USDT",decimals:18},[Ge]:{symbol:"USDC",decimals:18}};var Qe={[ne]:{name:"USDC",version:"2"},[re]:{name:"USDC",version:"2"},[oe]:{name:"Global Dollar",version:"1"},[se]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[ae]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}},G="0x000000000022D473030F116dDEE9F6B43aC78BA3",$e="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",Ke={[Se]:56,[te]:8453,[ge]:84532,[he]:42161,[ye]:137,[Ae]:10,[be]:43114,[ne]:480,[re]:143,[oe]:4663,[se]:1187947933,[ae]:324705682,[we]:1},ie={[Ee]:"https://api.dexter.cash/api/solana/rpc",[je]:"https://api.devnet.solana.com",[Xe]:"https://api.testnet.solana.com"},O={[Se]:"https://api.dexter.cash/api/evm/bsc/rpc",[te]:"https://api.dexter.cash/api/base/rpc",[ge]:"https://sepolia.base.org",[he]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[ye]:"https://api.dexter.cash/api/evm/polygon/rpc",[Ae]:"https://api.dexter.cash/api/evm/optimism/rpc",[be]:"https://api.dexter.cash/api/evm/avalanche/rpc",[ne]:"https://worldchain-mainnet.g.alchemy.com/public",[re]:"https://rpc.monad.xyz",[oe]:"https://rpc.mainnet.chain.robinhood.com",[se]:"https://skale-base.skalenodes.com/v1/base",[ae]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[we]:"https://eth.llamarpc.com"},wt="https://x402.dexter.cash";var P=class r extends Error{code;details;constructor(e,t,n){super(t),this.name="X402Error",this.code=e,this.details=n,Object.setPrototypeOf(this,r.prototype)}};function K(r,e){let t=r.scheme??"exact";if(t!=="exact"&&!(e==="evm"&&t==="exact-approval"))return`Unsupported payment scheme: ${t}`;let n=r.extra?.paymentFlow;if(n!==void 0&&n!=="authorization")return`Unsupported payment flow: ${String(n)}`;let o=r.extra?.assetTransferMethod;if(o!==void 0&&(typeof o!="string"||!(t==="exact-approval"?[]:e==="evm"?["eip3009","permit2"]:["default"]).includes(o)))return`Unsupported payment asset transfer method: ${String(o)}`}function Le(r){let e=r?.["payment-identifier"];if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.info;return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.required===!0}var vt=[{caip2:"eip155:8453",bare:"base",family:"evm"},{caip2:"eip155:1",bare:"ethereum",family:"evm"},{caip2:"eip155:137",bare:"polygon",family:"evm"},{caip2:"eip155:42161",bare:"arbitrum",family:"evm"},{caip2:"eip155:10",bare:"optimism",family:"evm"},{caip2:"eip155:43114",bare:"avalanche",family:"evm"},{caip2:"eip155:56",bare:"bsc",family:"evm"},{caip2:"eip155:480",bare:"world",family:"evm"},{caip2:"eip155:143",bare:"monad",family:"evm"},{caip2:"eip155:4663",bare:"robinhood",family:"evm"},{caip2:"eip155:1187947933",bare:"skale-base",family:"evm"},{caip2:"eip155:324705682",bare:"skale-base-sepolia",family:"evm"},{caip2:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",bare:"solana",family:"svm"}],Lt=new Map(vt.map(r=>[r.caip2.toLowerCase(),r])),Ft=new Map(vt.map(r=>[r.bare.toLowerCase(),r]));function Y(r){if(!r)return null;let e=r.toLowerCase(),t=Lt.get(e)||Ft.get(e);return t?{caip2:t.caip2,bare:t.bare,family:t.family}:null}function mt(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-(e.length%4||4))%4);return JSON.parse(Buffer.from(t,"base64").toString("utf8"))}function Wt(r){let e=[];for(let t of r){if(!t||typeof t!="object")continue;let n=t,o=Y(String(n.network??""));o&&e.push({scheme:String(n.scheme??"exact"),network:o,amount:String(n.amount??n.maxAmountRequired??"0"),asset:String(n.asset??""),payTo:String(n.payTo??""),maxTimeoutSeconds:typeof n.maxTimeoutSeconds=="number"?n.maxTimeoutSeconds:void 0,extra:n.extra&&typeof n.extra=="object"?n.extra:void 0})}return e}async function xt(r){let e=r.headers.get("payment-required");if(!e)return null;let t;try{t=mt(e)}catch{return null}let n=Array.isArray(t.accepts)?t.accepts:[];return n.length===0?null:{x402Version:2,options:Wt(n),extensions:t.extensions&&typeof t.extensions=="object"&&!Array.isArray(t.extensions)?t.extensions:void 0,resourceUrl:t.resource&&typeof t.resource=="object"?String(t.resource.url??""):void 0}}import{PublicKey as ce,Connection as dt,TransactionMessage as qt,VersionedTransaction as Ht,ComputeBudgetProgram as Rt}from"@solana/web3.js";import{getAssociatedTokenAddress as pt,getAccount as jt,createTransferCheckedInstruction as Xt,getMint as zt,TOKEN_PROGRAM_ID as Et,TOKEN_2022_PROGRAM_ID as et}from"@solana/spl-token";var Jt=12e3,Gt=1;function ue(r){if(!r||typeof r!="object")return!1;let e=r;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var tt=class{name="Solana";networks=[z,_e,Pe];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:solana]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="solana"||e==="solana-devnet"||e==="solana-testnet"||e.startsWith("solana:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:ie[e]?ie[e]:e==="solana"?ie[z]:e==="solana-devnet"?ie[_e]:e==="solana-testnet"?ie[Pe]:ie[z]}getAddress(e){return ue(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return ue(e)?e.publicKey!==null:!1}async getBalance(e,t,n){if(!ue(t)||!t.publicKey)return 0;let o=n||this.getDefaultRpcUrl(e.network),s=new dt(o,"confirmed"),i=new ce(t.publicKey.toBase58()),a=new ce(e.asset);try{let u=(await s.getAccountInfo(a,"confirmed"))?.owner.toBase58()===et.toBase58()?et:Et,d=await pt(a,i,!1,u),f=await jt(s,d,void 0,u),A=e.extra?.decimals??6;return Number(f.amount)/Math.pow(10,A)}catch(c){if(c&&typeof c=="object"&&"name"in c&&(c.name==="TokenAccountNotFoundError"||c.name==="TokenInvalidAccountOwnerError"))return 0;throw c}}async buildTransaction(e,t,n){let o=K(e,"svm");if(o)throw new Error(o);if(!ue(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let s=n||this.getDefaultRpcUrl(e.network),i=new dt(s,"confirmed"),a=new ce(t.publicKey.toBase58()),{payTo:c,asset:u,extra:d}=e,f=e.amount??e.maxAmountRequired;if(!f)throw new Error("Missing amount in payment requirements");if(!d?.feePayer)throw new Error("Missing feePayer in payment requirements");let A=new ce(d.feePayer),w=new ce(u),l=new ce(c);this.log("Building transaction:",{from:a.toBase58(),to:c,amount:f,asset:u,feePayer:d.feePayer});let h=[];h.push(Rt.setComputeUnitLimit({units:Jt})),h.push(Rt.setComputeUnitPrice({microLamports:Gt}));let g=await i.getAccountInfo(w,"confirmed");if(!g)throw new Error(`Token mint ${u} not found`);let x=g.owner.toBase58()===et.toBase58()?et:Et,m=await zt(i,w,void 0,x);typeof d?.decimals=="number"&&m.decimals!==d.decimals&&this.log(`Decimals mismatch: requirements say ${d.decimals}, mint says ${m.decimals}`);let p=await pt(w,a,!1,x),v=await pt(w,l,!0,x);if(!await i.getAccountInfo(p,"confirmed"))throw new Error(`No token account found for ${u}. Please ensure you have USDC in your wallet.`);if(!await i.getAccountInfo(v,"confirmed"))throw new Error(`Seller token account not found. The seller (${c}) must have a USDC account.`);let W=BigInt(f);h.push(Xt(p,w,v,a,W,m.decimals,[],x));let{blockhash:q}=await i.getLatestBlockhash("confirmed"),D=new qt({payerKey:A,recentBlockhash:q,instructions:h}).compileToV0Message(),S=new Ht(D),R=await t.signTransaction(S);return this.log("Transaction signed successfully"),{serialized:Buffer.from(R.serialize()).toString("base64"),settlementProbe:{kind:"solana",sourceAta:p.toBase58(),destinationAta:v.toBase58(),asset:u,amount:f,blockhash:q}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let n=new dt(t,"confirmed"),o=new ce(e.destinationAta),s=await n.getSignaturesForAddress(o,{limit:25});if(s.length===0)return{settled:!1};let i=BigInt(e.amount);for(let a of s){if(a.err)continue;let c=await n.getTransaction(a.signature,{commitment:"confirmed",maxSupportedTransactionVersion:0});if(!c?.meta)continue;let u=c.transaction.message.getAccountKeys().keySegments().flat(),d=c.meta.preTokenBalances??[],f=c.meta.postTokenBalances??[];for(let A of f){if(A.mint!==e.asset)continue;let w=u[A.accountIndex];if(!w||!w.equals(o))continue;let l=d.find(x=>x.accountIndex===A.accountIndex),h=BigInt(l?.uiTokenAmount.amount??"0");if(BigInt(A.uiTokenAmount.amount??"0")-h===i)return{settled:!0,txSignature:a.signature}}}return{settled:!1}}};function L(r){return new tt(r)}var Yt={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"validAfter",type:"uint256"}]},_t=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function le(r){if(!r||typeof r!="object")return!1;let e=r;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var nt=class{name="EVM";networks=[ke,J,ze,Me,Te,Ie,Ne,Ce,Oe,Ve,Be,De,Ue];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:evm]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="base"||e==="bsc"||e==="ethereum"||e==="arbitrum"||e==="polygon"||e==="optimism"||e==="avalanche"||e==="world"||e==="monad"||e==="robinhood"||e==="skale-base"||e==="skale-base-sepolia"||e.startsWith("eip155:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:O[e]?O[e]:e==="base"?O[J]:e==="bsc"?O[ke]:e==="ethereum"?O[Me]:e==="arbitrum"?O[Te]:e==="polygon"?O[Ie]:e==="optimism"?O[Ne]:e==="avalanche"?O[Ce]:e==="world"?O[Oe]:e==="monad"?O[Ve]:e==="robinhood"?O[Be]:e==="skale-base"?O[De]:e==="skale-base-sepolia"?O[Ue]:O[J]}getAddress(e){return le(e)?e.address:null}isConnected(e){return le(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:e==="polygon"?137:e==="optimism"?10:e==="avalanche"?43114:e==="world"?480:e==="monad"?143:e==="robinhood"?4663:e==="skale-base"?1187947933:e==="skale-base-sepolia"?324705682:8453}async getBalance(e,t,n){if(!le(t)||!t.address)return 0;let o=n||this.getDefaultRpcUrl(e.network);try{let s=this.encodeBalanceOf(t.address),i=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(!i.ok)throw new Error(`RPC request failed: ${i.status}`);let a=await i.json();if(a.error)throw new Error(`RPC error: ${JSON.stringify(a.error)}`);if(!a.result||a.result==="0x")return 0;let c=BigInt(a.result),u=e.extra?.decimals??6;return Number(c)/Math.pow(10,u)}catch(s){throw s}}encodeBalanceOf(e){let t="0x70a08231",n=e.slice(2).toLowerCase().padStart(64,"0");return t+n}async confirmSettlement(e,t){if(e.kind==="eip3009"){let n="0xe94a0102",o=e.from.slice(2).toLowerCase().padStart(64,"0"),s=e.nonce.slice(2).toLowerCase().padStart(64,"0"),i=n+o+s,a=await this.ethCall(t,e.asset,i);return{settled:BigInt(a)!==0n}}if(e.kind==="permit2"){let n="0x4fe02b44",o=BigInt(e.nonce),s=o>>8n,i=o&0xffn,a=e.from.slice(2).toLowerCase().padStart(64,"0"),c=s.toString(16).padStart(64,"0"),u=n+a+c,d=await this.ethCall(t,G,u);return{settled:(BigInt(d)>>i&1n)===1n}}throw new Error(`EvmAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`)}async ethCall(e,t,n){let o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:n},"latest"]})});if(!o.ok)throw new Error(`RPC request failed: ${o.status}`);let s=await o.json();if(s.error)throw new Error(`RPC error: ${JSON.stringify(s.error)}`);if(!s.result||s.result==="0x")throw new Error("RPC returned an empty result");return s.result}async buildTransaction(e,t,n){let o=K(e,"evm");if(o)throw new Error(o);if(!le(t))throw new Error("Invalid EVM wallet");if(!t.address)throw new Error("Wallet not connected");if(e.scheme==="exact-approval")return this.buildApprovalTransaction(e,t,n);if(e.extra?.assetTransferMethod==="permit2")return this.buildPermit2Transaction(e,t,n);let{payTo:s,asset:i,extra:a}=e,c=e.amount??e.maxAmountRequired;if(!c)throw new Error("Missing amount in payment requirements");this.log("Building EVM transaction:",{from:t.address,to:s,amount:c,asset:i,network:e.network});let u=this.getChainId(e.network),d=Qe[`eip155:${u}`],f={name:a?.name??d?.name??"USD Coin",version:a?.version??d?.version??"2",chainId:BigInt(u),verifyingContract:i},A={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"}]},w=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(w);let l="0x"+[...w].map(v=>v.toString(16).padStart(2,"0")).join(""),h=Math.floor(Date.now()/1e3),g={from:t.address,to:s,value:c,validAfter:String(h-600),validBefore:String(h+(e.maxTimeoutSeconds||60)),nonce:l},x={from:t.address,to:s,value:BigInt(c),validAfter:BigInt(h-600),validBefore:BigInt(h+(e.maxTimeoutSeconds||60)),nonce:l};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let m=await t.signTypedData({domain:f,types:A,primaryType:"TransferWithAuthorization",message:x});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:g,signature:m}),signature:m,settlementProbe:{kind:"eip3009",from:t.address,nonce:l,asset:i,chainId:u}}}async buildApprovalTransaction(e,t,n){let{payTo:o,asset:s,extra:i}=e,a=e.amount??e.maxAmountRequired;if(!a)throw new Error("Missing amount in payment requirements");let c=i?.facilitatorContract;if(!c)throw new Error("exact-approval scheme requires extra.facilitatorContract from the facilitator. The /supported endpoint should provide this.");if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building approval-based transaction:",{from:t.address,to:o,amount:a,asset:s,network:e.network,facilitatorContract:c});let u=n||this.getDefaultRpcUrl(e.network),d=i?.fee??"0",f=BigInt(a)+BigInt(d),A=await this.readAllowance(u,s,t.address,c);if(A<f){if(!t.sendTransaction)throw new Error("BSC payments require a wallet that supports sendTransaction for the one-time token approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.");let D=this.calculateApprovalAmount(a,d,i?.approvalStrategy);this.log(`Approving ${D} for ${c} (current allowance: ${A})`);let S=await t.sendTransaction({to:s,data:this.encodeApprove(c,D),value:0n});this.log(`Approval tx sent: ${S}`),await this.waitForReceipt(u,S),this.log("Approval confirmed")}else this.log("Sufficient allowance, skipping approval");let w=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(w);let l=[...w].reduce((D,S)=>D*256n+BigInt(S),0n).toString(),h=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(h);let g="0x"+[...h].map(D=>D.toString(16).padStart(2,"0")).join(""),m=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),p=i?.eip712Domain,v=p?{name:p.name,version:p.version,chainId:BigInt(p.chainId),verifyingContract:p.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:c},V=i?.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"}]},Z={from:t.address,to:o,token:s,amount:BigInt(a),fee:BigInt(d),nonce:BigInt(l),deadline:BigInt(m),paymentId:g},W=await t.signTypedData({domain:v,types:V,primaryType:"Payment",message:Z});this.log("EIP-712 Payment signature obtained");let q={from:t.address,to:o,token:s,amount:a,fee:d,nonce:l,deadline:m,paymentId:g,signature:W};return{serialized:JSON.stringify(q),signature:W}}async buildPermit2Transaction(e,t,n){let{payTo:o,asset:s}=e,i=e.amount??e.maxAmountRequired;if(!i)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:i,asset:s,network:e.network});let a=n||this.getDefaultRpcUrl(e.network),c=await this.readAllowance(a,s,t.address,G),u;if(c<BigInt(i)){let v=this.encodeApprove(G,_t);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${c})`);let V=this.getChainId(e.network),Z=await this.readGasPrice(a),W=await this.readNonce(a,t.address),q=await t.signTransaction({to:s,data:v,chainId:V,gas:50000n,gasPrice:Z,nonce:W});u={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:s,spender:G,amount:_t.toString(),signedTransaction:q,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${c})`);let V=await t.sendTransaction({to:s,data:v,value:0n});this.log(`Permit2 approval tx sent: ${V}`),await this.waitForReceipt(a,V),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 d=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(d);let f=[...d].reduce((v,V)=>v*256n+BigInt(V),0n),A=Math.floor(Date.now()/1e3),w=A-600,l=A+(e.maxTimeoutSeconds||300),h=this.getChainId(e.network),g={name:"Permit2",chainId:BigInt(h),verifyingContract:G},x={permitted:{token:s,amount:BigInt(i)},spender:$e,nonce:f,deadline:BigInt(l),witness:{to:o,validAfter:BigInt(w)}},m=await t.signTypedData({domain:g,types:Yt,primaryType:"PermitWitnessTransferFrom",message:x});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let p={signature:m,permit2Authorization:{from:t.address,permitted:{token:s,amount:i},spender:$e,nonce:f.toString(),deadline:String(l),witness:{to:o,validAfter:String(w)}}};return{serialized:JSON.stringify(p),signature:m,extensions:u,settlementProbe:{kind:"permit2",from:t.address,nonce:f.toString(),chainId:h}}}async readAllowance(e,t,n,o){let s="0xdd62ed3e",i=n.slice(2).toLowerCase().padStart(64,"0"),a=o.slice(2).toLowerCase().padStart(64,"0"),c=s+i+a;try{let d=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:c},"latest"]})})).json();return d.error||!d.result||d.result==="0x"?0n:BigInt(d.result)}catch{return 0n}}encodeApprove(e,t){let n="0x095ea7b3",o=e.slice(2).toLowerCase().padStart(64,"0"),s=t.toString(16).padStart(64,"0");return n+o+s}async waitForReceipt(e,t,n=3e4){let o=Date.now();for(;Date.now()-o<n;){try{let i=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(i.result){if(i.result.status==="0x0")throw new Error(`Approval transaction reverted: ${t}`);return}}catch(s){if(s instanceof Error&&s.message.includes("reverted"))throw s}await new Promise(s=>setTimeout(s,2e3))}throw new Error(`Approval transaction receipt timeout after ${n}ms: ${t}`)}async readGasPrice(e){try{let n=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_gasPrice",params:[]})})).json();return n.result?BigInt(n.result):50000000n}catch{return 50000000n}}async readNonce(e,t){try{let o=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionCount",params:[t,"latest"]})})).json();return o.result?parseInt(o.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,n){let o=BigInt(e)+BigInt(t);if(!n||n.mode==="exact")return o;let s=BigInt(n.defaultMultiple??10),i=o*s;if(n.maxCapUsd){let a=this.inferDecimals(e),c=BigInt(Math.floor(n.maxCapUsd*Math.pow(10,a)));if(i>c)return c}if(n.exactAboveUsd){let a=this.inferDecimals(e),c=BigInt(Math.floor(n.exactAboveUsd*Math.pow(10,a)));if(BigInt(e)>c)return o}return i}inferDecimals(e){return e.length>12?18:6}};function me(r){return new nt(r)}function ft(r){if(r===Je||r===bt)return!0;let e=r.toLowerCase();for(let t of Object.values(Ye))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(Ze))if(t.toLowerCase()===e)return!0;return!1}function Zt(r){return{[Ee]:"Solana",[je]:"Solana Devnet",[Xe]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[te]:"Base",[ge]:"Base Sepolia",[we]:"Ethereum",[he]:"Arbitrum",[ye]:"Polygon",[Ae]:"Optimism",[be]:"Avalanche",[Se]:"BSC",[ne]:"World Chain",[re]:"Monad",[oe]:"Robinhood Chain",[se]:"SKALE Base",[ae]:"SKALE Base Sepolia",base:"Base","base-sepolia":"Base Sepolia",ethereum:"Ethereum",arbitrum:"Arbitrum",polygon:"Polygon",optimism:"Optimism",avalanche:"Avalanche",bsc:"BSC",world:"World Chain",monad:"Monad",robinhood:"Robinhood Chain","skale-base":"SKALE Base","skale-base-sepolia":"SKALE Base Sepolia"}[r]||r}function Pt(r,e){let t=Zt(r);return t===r?e:t}async function Qt(r,e){if(typeof r=="string")return[r,e];if(r instanceof URL)return[r.href,e];let t=r,n=new Headers(t.headers);e?.headers&&new Headers(e.headers).forEach((i,a)=>n.set(a,i));let o={method:e?.method??t.method,headers:n,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},s=(o.method??"GET").toUpperCase();return e&&"body"in e?o.body=e.body:s!=="GET"&&s!=="HEAD"&&t.body&&(o.body=await t.arrayBuffer()),[t.url,o]}var Tt=new WeakMap;function Fe(r){return Tt.get(r)}function It(r,e){let t=r.headers.get("PAYMENT-RESPONSE"),n;if(t)try{let a=mt(t);a&&typeof a=="object"&&!Array.isArray(a)&&(n={...a})}catch{}n??={},n.settlementStatus="unconfirmed";let o=n.network===e.network,s=[n.errorReason,n.errorCode,n.errorMessage].every(a=>a===void 0||typeof a=="string"),i=[n.errorReason,n.errorCode].filter(a=>typeof a=="string"&&a.length>0);return i.some(a=>/pending|unknown|unconfirmed|timeout|temporar/i.test(a))?n.settlementStatus="pending":n.success===!0&&o&&s&&i.length===0&&typeof n.transaction=="string"&&n.transaction.trim().length>0?n.settlementStatus="settled":n.success===!1&&(o||n.network===void 0)&&i.length>0&&(n.settlementStatus="failed"),n.attemptedAmountAtomic=e.amountAtomic,n.settlementStatus==="settled"?n.amountAtomic=e.amountAtomic:delete n.amountAtomic,n.assetDecimals=e.assetDecimals,Tt.set(r,n),n}function rt(r){let{adapters:e=[L({verbose:r.verbose}),me({verbose:r.verbose})],wallets:t,wallet:n,preferredNetwork:o,rpcUrls:s={},maxAmountAtomic:i,fetch:a=globalThis.fetch,verbose:c=!1,accessPass:u,onPaymentRequired:d,onPaymentDispatched:f,maxRetries:A=0,retryDelayMs:w=500}=r,l=c?console.log.bind(console,"[x402]"):()=>{};async function h(S,R){let _;for(let b=0;b<=A;b++)try{let I=await a(S,R);if(I.status>=502&&I.status<=504&&b<A){l(`Retry ${b+1}/${A}: server returned ${I.status}`),await new Promise(T=>setTimeout(T,w*Math.pow(2,b)));continue}return I}catch(I){_=I,b<A&&(l(`Retry ${b+1}/${A}: ${I instanceof Error?I.message:"network error"}`),await new Promise(T=>setTimeout(T,w*Math.pow(2,b))))}throw _}let g=new Map;function x(S){try{let R=new URL(S).host,_=g.get(R);if(_&&_.expiresAt>Date.now()/1e3+10)return _.jwt;_&&g.delete(R)}catch{}return null}function m(S,R){try{let _=new URL(S).host,b=R.split(".");if(b.length===3){let I=JSON.parse(atob(b[1].replace(/-/g,"+").replace(/_/g,"/"))),T=Math.floor(Date.now()/1e3),N=T+86400,U=Math.min(typeof I.exp=="number"?I.exp:T,N);g.set(_,{jwt:R,expiresAt:U}),l("Access pass cached for",_,"| expires:",new Date(U*1e3).toISOString())}}catch{l("Failed to cache access pass")}}let p=t||{};n&&!p.solana&&ue(n)&&(p.solana=n),n&&!p.evm&&le(n)&&(p.evm=n);function v(S){let R=[];for(let _ of S){let b=e.find(N=>N.canHandle(_.network));if(!b)continue;let I=b.name==="Solana"?"svm":"evm";if(K(_,I))continue;let T;b.name==="Solana"?T=p.solana:b.name==="EVM"&&(T=p.evm),T&&b.isConnected(T)&&R.push({accept:_,adapter:b,wallet:T})}if(R.length===0)return null;if(o){let _=R.find(b=>b.accept.network===o);if(_)return _}return R[0]}function V(S,R){return Pt(S,R)}function Z(S,R){return s[S]||R.getDefaultRpcUrl(S)}async function W(S,R,_,b,I){let T="";if(u?.preferTier&&b.tiers){let y=b.tiers.find($=>$.id===u.preferTier);if(y){if(u.maxSpend&&parseFloat(y.price)>parseFloat(u.maxSpend))throw new P("access_pass_exceeds_max_spend",`Access pass tier "${y.id}" costs $${y.price}, exceeds max spend $${u.maxSpend}`);T=`tier=${y.id}`}}else if(u?.preferDuration&&b.ratePerHour)T=`duration=${u.preferDuration}`;else if(b.tiers&&b.tiers.length>0){let y=b.tiers[0];if(u?.maxSpend&&parseFloat(y.price)>parseFloat(u.maxSpend))throw new P("access_pass_exceeds_max_spend",`Cheapest access pass costs $${y.price}, exceeds max spend $${u?.maxSpend}`);T=`tier=${y.id}`}let N=T?I.includes("?")?`${I}&${T}`:`${I}?${T}`:I;l("Purchasing access pass:",T||"default tier");let U=_.headers.get("PAYMENT-REQUIRED");if(!U)return null;let B;try{B=JSON.parse(atob(U))}catch{return null}let k=v(B.accepts);if(!k)return null;if(Le(B.extensions))throw new P("unsupported_required_payment_identifier","Required payment identifiers are not supported by this client");let{accept:C,adapter:M,wallet:de}=k;if(M.name==="Solana"&&!C.extra?.feePayer)return null;let H=C.extra?.decimals??(ft(C.asset)?6:void 0);if(typeof H!="number")return null;let xe=C.amount??C.maxAmountRequired;if(!xe)return null;let j=Z(C.network,M);try{let y=await M.getBalance(C,de,j),$=Number(xe)/Math.pow(10,H);if(y<$){let Kt=V(C.network,M.name);throw new P("insufficient_balance",`Insufficient balance for access pass on ${Kt}. Have $${y.toFixed(4)}, need $${$.toFixed(4)}`)}}catch(y){if(y instanceof P)throw y}let X=await M.buildTransaction(C,de,j),pe;M.name==="EVM"?pe=JSON.parse(X.serialized):pe={transaction:X.serialized};let Q=typeof S=="string"?S:S instanceof URL?S.href:S.url,fe=B.resource;if(typeof B.resource=="string")try{let y=new URL(B.resource,Q);["http:","https:"].includes(y.protocol)&&(fe=y.toString())}catch{}else if(B.resource&&typeof B.resource=="object"&&"url"in B.resource){let y=B.resource;try{let $=new URL(y.url,Q);["http:","https:"].includes($.protocol)&&(fe={...y,url:$.toString()})}catch{}}let He={x402Version:C.x402Version??2,resource:fe,accepted:C,payload:pe};X.extensions&&(He.extensions=X.extensions);let Re=btoa(JSON.stringify(He)),ee=await a(N,{...R,method:"POST",headers:{...R?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":Re}});if(!ee.ok)return l("Pass purchase failed:",ee.status),null;let E=ee.headers.get("ACCESS-PASS");return E&&(m(I,E),l("Access pass purchased and cached")),ee}async function q(S,R){let _=S;if(l("Making request:",_),u){let E=x(_);if(E){l("Using cached access pass");let y=await a(S,{...R,headers:{...R?.headers||{},Authorization:`Bearer ${E}`}});if(y.status!==401&&y.status!==402)return y;l("Cached pass rejected (status",y.status,"), purchasing new pass");try{g.delete(new URL(_).host)}catch{}}}let b=await h(S,R);if(b.status!==402)return b;l("Received 402 Payment Required");let I=b.headers.get("X-ACCESS-PASS-TIERS");if(u&&I){l("Server offers access passes, purchasing...");try{let E=JSON.parse(atob(I)),y=await W(S,R,b,E,_);if(y)return y}catch(E){l("Access pass purchase failed, falling back to per-request payment:",E)}}let T=b.headers.get("PAYMENT-REQUIRED");if(!T)throw new P("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let N;try{let E=atob(T);N=JSON.parse(E)}catch{throw new P("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}if(l("Payment requirements:",N),Le(N.extensions))throw new P("unsupported_required_payment_identifier","Required payment identifiers are not supported by this client");let U=b.headers.get("X-Quote-Hash");U&&l("Quote hash received:",U);let B=v(N.accepts);if(!B){let E=N.accepts.map(y=>y.network).join(", ");throw new P("no_matching_payment_option",`No supported payment option with a connected wallet for: ${E}`)}let{accept:k,adapter:C,wallet:M}=B;if(l(`Using ${C.name} for ${k.network}`),C.name==="Solana"&&!k.extra?.feePayer)throw new P("missing_fee_payer","Solana payment option missing feePayer in extra");let de=k.extra?.decimals??(ft(k.asset)?6:void 0);if(typeof de!="number")throw new P("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let H=k.amount??k.maxAmountRequired;if(!H)throw new P("missing_amount","Payment option missing amount");if(i&&BigInt(H)>BigInt(i))throw new P("amount_exceeds_max",`Payment amount ${H} exceeds maximum ${i}`);let xe=Z(k.network,C);l("Checking balance...");try{let E=await C.getBalance(k,M,xe),y=Number(H)/Math.pow(10,de);if(E<y){let $=V(k.network,C.name);throw new P("insufficient_balance",`Insufficient balance on ${$}. Have $${E.toFixed(4)}, need $${y.toFixed(4)}`)}l(`Balance OK: $${E.toFixed(4)} >= $${y.toFixed(4)}`)}catch(E){if(E instanceof P)throw E;l("Balance check failed (RPC error), proceeding with transaction attempt")}if(d&&!await d(k))throw new P("payment_rejected","Payment rejected by onPaymentRequired callback");l("Building transaction...");let j=await C.buildTransaction(k,M,xe);l("Transaction signed");let X;C.name==="EVM"?X=JSON.parse(j.serialized):X={transaction:j.serialized};let pe=S,Q=N.resource;if(typeof N.resource=="string")try{let E=new URL(N.resource,pe).toString();E!==N.resource&&l("Resolved relative resource URL:",N.resource,"\u2192",E),Q=E}catch{Q=N.resource}else if(N.resource&&typeof N.resource=="object"&&"url"in N.resource){let E=N.resource;try{let y=new URL(E.url,pe).toString();y!==E.url&&(l("Resolved relative resource URL:",E.url,"\u2192",y),Q={...E,url:y})}catch{}}let fe={x402Version:k.x402Version??2,resource:Q,accepted:k,payload:X};j.extensions&&(fe.extensions=j.extensions);let He=btoa(JSON.stringify(fe));if(f)try{f(k,j.settlementProbe)}catch{}l("Retrying request with payment...");let Re=await h(S,{...R,headers:{...R?.headers||{},"PAYMENT-SIGNATURE":He,...U?{"X-Quote-Hash":U}:{}}});l("Retry response status:",Re.status);let ee=It(Re,{network:k.network,amountAtomic:H,assetDecimals:de});return ee.extensions&&l("Settlement extensions:",Object.keys(ee.extensions).join(", ")),Re}async function D(S,R){let[_,b]=await Qt(S,R);return q(_,b)}return{fetch:D}}import{PublicKey as Zr}from"@solana/web3.js";import{bytesToHex as gt}from"@noble/hashes/utils";import pr from"tweetnacl";import{PublicKey as gr}from"@solana/web3.js";import{contextBoundVoucherV2Message as yr,finalVoucherV2Sequence as Ar,sessionRegisterMessage as br,sessionVoucherV2AuthorizationNonce as Sr}from"@dexterai/vault/messages";import{deriveSessionPda as vr}from"@dexterai/vault/session";import{sessionRegisterMessage as en,sessionReplaceV1Message as sr,sessionRevokeMessage as ar,sessionVoucherV2Nonce as ir,sessionVoucherV2AuthorizationNonce as cr,finalVoucherV2Sequence as ur,voucherV2SequenceOrdinal as lr,voucherPayloadMessage as tn,buildVoucherMessage as mr}from"@dexterai/vault/messages";import{sha256 as _r}from"@noble/hashes/sha256";var Rr=(1n<<64n)-1n;import{sha256 as Ir}from"@noble/hashes/sha256";import{bytesToHex as Cr}from"@noble/hashes/utils";var nn="dexter-native-tab-v2-reservation/v1",kr=`${nn}:`;import{deriveSessionPda as oo}from"@dexterai/vault/session";import{buildRegisterSessionKeyInstruction as Dr,buildRevokeSessionKeyInstruction as Ur,deriveSwigWalletAddress as Mr}from"@dexterai/vault/instructions";import{buildSecp256r1VerifyInstruction as Kr}from"@dexterai/vault/precompile";import{DEXTER_VAULT_PROGRAM_ID as rn,SECP256R1_PROGRAM_ID as Fr,INSTRUCTIONS_SYSVAR_ID as Wr}from"@dexterai/vault/constants";function Nt(r,e){let t=e??r.reservationReceipt;if((r.payload.sequenceNumber&2147483648)!==0&&!t)throw new Error("native_tab_v2_reservation_receipt_required");return Buffer.from(JSON.stringify({payload:r.payload,sessionPublicKey:gt(r.sessionPublicKey),sessionRegistration:gt(r.sessionRegistration),sessionSignature:gt(r.sessionSignature),...t?{reservationReceipt:t}:{}}),"utf8").toString("base64")}function F(r){if(r instanceof Error){if(r.message&&r.message.length>0)return r.message;if(r.name&&r.name.length>0)return r.name}let e=String(r);return e.length>0?e:"unknown error"}async function We(r){let e="";try{e=(await r.clone().text()).slice(0,600)}catch{}let t=e.toLowerCase(),n=t.includes("settle")||t.includes("facilitator"),o=e;try{let s=JSON.parse(e),i=[s.error,s.detail,s.message].filter(a=>typeof a=="string"&&a.length>0);i.length>0&&(o=i.join(" \u2014 "))}catch{}return o||(o=`HTTP ${r.status}`),{reason:n?"settlement_failed":"merchant_rejected",detail:`merchant HTTP ${r.status}: ${o}`}}var ot="Payment authorization was sent, but the merchant did not respond within the timeout. ",st=" Do not retry without checking \u2014 inspect the funding wallet for a transfer to the merchant before attempting payment again.";async function at(r,e,t){if(!r)return{confirmed:!1,detail:ot+"This payment scheme has no on-chain confirmation check, so the SDK cannot verify whether it settled."+st};try{if(r.kind==="solana"){let i=L(),a=t??i.getDefaultRpcUrl(e.caip2);if(!i.confirmSettlement)return kt();let c=await i.confirmSettlement(r,a);return c.settled?{confirmed:!0,txSignature:c.txSignature}:Ct()}let n=me(),o=n.getDefaultRpcUrl(e.caip2);if(!n.confirmSettlement)return kt();let s=await n.confirmSettlement(r,o);return s.settled?{confirmed:!0,txSignature:s.txSignature}:Ct()}catch(n){return{confirmed:!1,detail:ot+`On-chain confirmation could not be completed (${F(n)}).`+st}}}function Ct(){return{confirmed:!1,detail:ot+"On-chain confirmation found no matching settlement yet \u2014 the payment may still be pending, or may not have settled."+st}}function kt(){return{confirmed:!1,detail:ot+"The chain adapter does not support on-chain confirmation."+st}}async function on(r,e,t,n){let o;try{o=await n.signNextVoucher(t.amount)}catch(c){return n.voucherVersion!==1?{ok:!1,reason:"error",detail:`context-bound FINAL tab voucher was not safely released; retry or reconcile this tab before another payment rail is attempted (${c instanceof Error?c.message:String(c)})`}:null}let s=new Headers(e.headers??void 0);s.set("X-Tab-Voucher",Nt(o));let i={...e.redirect!==void 0?{redirect:e.redirect}:{},method:e.method??"GET",headers:s};e.signal&&(i.signal=e.signal),typeof e.body=="string"&&(i.body=e.body);let a;try{a=await fetch(r,i)}catch(c){return{ok:!1,reason:"error",detail:c?.message??String(c)}}return a.status===402?n.voucherVersion!==1?{ok:!1,reason:"error",detail:"seller refused an irrevocable FINAL tab voucher; its exact reservation must be reconciled before another payment rail is attempted"}:n.rollbackVoucher?.call(n,o)!==!0?{ok:!1,reason:"error",detail:"seller refused a V1 tab voucher but local rollback was unavailable or failed; another payment rail was not attempted to avoid double payment"}:null:a.ok?{ok:!0,paid:!0,response:a,amountPaid:t.amount,network:t.network}:{ok:!1,...await We(a)}}var Ot={version:2,async parseChallenge(r){return xt(r)},async pay(r,e,t,n,o){if(Le(t.extensions))return{ok:!1,reason:"no_payment_options",detail:"unsupported_required_payment_identifier"};if(o.tab){let m=t.options.find(p=>p.scheme==="tab"&&p.network.family==="svm"&&p.payTo===o.tab.counterparty);if(m){let p=await on(r,e,m,o.tab);if(p)return p}}let s=t.options.filter(m=>!K(m,m.network.family));if(s.length===0)return{ok:!1,reason:"no_payment_options",detail:`no supported payment capability offered: ${t.options.map(m=>K(m,m.network.family)).join("; ")}`};let i=s.find(m=>m.network.family==="evm"?!!n.evm:m.network.family==="svm"?!!n.solana:!1);if(!i)return{ok:!1,reason:"unsupported_network"};let a=o.timeoutMs??15e3,c=o.responseTimeoutMs??12e4,u=new AbortController,d=setTimeout(()=>u.abort(),a),f=!1,A,w,l=(m,p)=>{f=!0,w=m,A=p,clearTimeout(d),d=setTimeout(()=>u.abort(),c)},h=rt({wallets:n,preferredNetwork:i.network.caip2,maxAmountAtomic:o.maxAmountAtomic,fetch:globalThis.fetch,onPaymentDispatched:l}),g=e.signal?AbortSignal.any([e.signal,u.signal]):u.signal,x={...e.redirect!==void 0?{redirect:e.redirect}:{},method:e.method??"GET",headers:e.headers,signal:g};typeof e.body=="string"&&(x.body=e.body);try{let m=await h.fetch(r,x);if(clearTimeout(d),!f)return m.ok?{ok:!0,paid:!1,response:m}:{ok:!1,response:m,...await We(m)};let p=Fe(m),v=typeof p?.transaction=="string"?p.transaction:void 0;if(p?.settlementStatus!=="settled"){let V=p?.settlementStatus==="failed";return{ok:!1,reason:V?"settlement_failed":"payment_unconfirmed",detail:`${V?"Merchant reports settlement failure":"Settlement is unconfirmed"}${p?.errorReason||p?.errorCode?` (${p.errorReason??p.errorCode})`:""}. Recover or reconcile this same payment; do not create a new authorization.`,response:m,txSignature:v,paymentReceipt:p}}return m.ok?{ok:!0,paid:!0,response:m,amountPaid:w?.amount??w?.maxAmountRequired??i.amount,network:Y(w?.network??"")??i.network,txSignature:v,paymentReceipt:p}:{ok:!1,reason:"delivery_failed",detail:`Payment settled, but the merchant returned HTTP ${m.status}. Recover the result for this same payment; do not create a new authorization.`,response:m,txSignature:v,paymentReceipt:p}}catch(m){clearTimeout(d);let p=m;if(p?.name==="AbortError"){if(!f)return{ok:!1,reason:"timeout"};let v=await at(A,i.network,o.solanaRpcUrl);return v.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:i.amount,network:i.network,txSignature:v.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:v.detail}}return f?{ok:!1,reason:"payment_unconfirmed",detail:`${p?.message??String(m)}. Recover or reconcile this same payment; do not create a new authorization.`}:{ok:!1,reason:"error",detail:p?.message??String(m)}}}};import{getAddress as sn}from"viem";var an={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"}]};async function cn(){let r=globalThis.crypto??(await import("crypto")).webcrypto,e=new Uint8Array(32);return r.getRandomValues(e),"0x"+Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}async function un(r,e,t){if(typeof r.signTypedData!="function")throw new Error("EVM wallet does not support signTypedData");let n=Math.floor(Date.now()/1e3),o=String(n-600),s=String(n+(e.maxTimeoutSeconds??60)),i={from:r.address,to:e.payTo,value:e.amount,validAfter:o,validBefore:s,nonce:await cn()},a=Ke[e.network.caip2];if(a===void 0)throw new Error(`unknown chain id for network ${e.network.caip2}`);let c=e.extra,u=await r.signTypedData({domain:{name:c.name,version:c.version,chainId:a,verifyingContract:sn(e.asset)},types:an,primaryType:"TransferWithAuthorization",message:i});return{payment:{x402Version:1,scheme:e.scheme,network:t,payload:{signature:u,authorization:i}},settlementProbe:{kind:"eip3009",from:i.from,nonce:i.nonce,asset:e.asset,chainId:a}}}async function it(r,e,t){try{let n;for(let o of r.options){let s=o.network.family==="evm"&&!!e.evm||o.network.family==="svm"&&!!e.solana;if(o.scheme!=="exact"){s&&(n=o.scheme);continue}if(o.network.family==="evm"&&e.evm){let i=await e.evm;return await ln(o,i,t)}if(o.network.family==="svm"&&e.solana){let i=await e.solana;return await mn(o,i,t)}}return n!==void 0?{ok:!1,reason:"merchant_rejected",detail:`v1 supports only the 'exact' scheme, got '${n}'`}:{ok:!1,reason:"unsupported_network"}}catch(n){return{ok:!1,reason:"error",detail:F(n)}}}async function ln(r,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(r.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};let n=r.extra??{},o=n.name,s=n.version;if(typeof o!="string"||o.length===0||typeof s!="string"||s.length===0)return{ok:!1,reason:"merchant_rejected",detail:"v1 challenge missing exact-scheme EIP-712 domain (extra.name / extra.version)"};let i=r.network.bare,{payment:a,settlementProbe:c}=await un(e,r,i);return{ok:!0,headerValue:Buffer.from(JSON.stringify(a),"utf8").toString("base64"),option:r,settlementProbe:c}}async function mn(r,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(r.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};if(r.scheme!=="exact")return{ok:!1,reason:"merchant_rejected",detail:`v1 SVM supports only the 'exact' scheme, got '${r.scheme}'`};let n=r.extra??{};if(typeof n.feePayer!="string"||n.feePayer.length===0)return{ok:!1,reason:"merchant_rejected",detail:"v1 SVM challenge missing extra.feePayer (required as the transaction fee payer)"};let o=r.network.bare,s={x402Version:1,scheme:r.scheme,network:o,asset:r.asset,payTo:r.payTo,amount:r.amount,maxAmountRequired:r.amount,maxTimeoutSeconds:r.maxTimeoutSeconds??60,extra:n},a=await L().buildTransaction(s,e,t.solanaRpcUrl),c={x402Version:1,scheme:r.scheme,network:o,payload:{transaction:a.serialized}};return{ok:!0,headerValue:Buffer.from(JSON.stringify(c),"utf8").toString("base64"),option:r,settlementProbe:a.settlementProbe}}function dn(r){let e=[];for(let t of r){if(!t||typeof t!="object")continue;let n=t,o=Y(String(n.network??""));o&&e.push({scheme:String(n.scheme??"exact"),network:o,amount:String(n.maxAmountRequired??n.amount??"0"),asset:String(n.asset??""),payTo:String(n.payTo??""),maxTimeoutSeconds:typeof n.maxTimeoutSeconds=="number"?n.maxTimeoutSeconds:void 0,extra:n.extra&&typeof n.extra=="object"?n.extra:void 0})}return e}var Vt={version:1,async parseChallenge(r){if(r.headers.get("payment-required"))return null;let e;try{e=await r.clone().json()}catch{return null}let t=Array.isArray(e.accepts)?e.accepts:[];if(t.length===0)return null;let n=dn(t);return n.length===0?null:{x402Version:1,options:n}},async pay(r,e,t,n,o){let s,i=new AbortController,a=!1,c,u;try{let d=o.timeoutMs??15e3;s=setTimeout(()=>i.abort(),d);let f=await it(t,n,o);if(!f.ok)return{ok:!1,reason:f.reason,detail:f.detail};let A=f.headerValue,w=f.option;u=w,c=f.settlementProbe;let l=new Headers(e.headers??void 0);l.set("X-PAYMENT",A);let h=e.signal!=null?AbortSignal.any([e.signal,i.signal]):i.signal,g={...e.redirect!==void 0?{redirect:e.redirect}:{},method:e.method,headers:l,signal:h};typeof e.body=="string"&&(g.body=e.body),a=!0,clearTimeout(s);let x=o.responseTimeoutMs??12e4;s=setTimeout(()=>i.abort(),x);let m=await fetch(r,g);return m.ok?{ok:!0,paid:!0,response:m,amountPaid:w.amount,network:w.network,txSignature:pn(m)}:{ok:!1,...await We(m)}}catch(d){if(d instanceof Error&&d.name==="AbortError"){if(!a)return{ok:!1,reason:"timeout"};let f=await at(c,u.network,o.solanaRpcUrl);return f.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:u.amount,network:u.network,txSignature:f.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:f.detail}}return{ok:!1,reason:"error",detail:F(d)}}finally{s!==void 0&&clearTimeout(s)}}};function pn(r){let e=r.headers.get("x-payment-response")??r.headers.get("X-PAYMENT-RESPONSE");if(e)try{let t=JSON.parse(Buffer.from(e,"base64").toString("utf8")),n=t.transaction??t.txHash??t.transactionHash;return typeof n=="string"?n:void 0}catch{return}}import*as Bt from"tweetnacl";import{Keypair as qe,VersionedTransaction as fn,Transaction as gn}from"@solana/web3.js";var ve=Symbol.for("x402:keypair");async function ht(r){let e;if(typeof r=="string"){let t;try{let n=await import("bs58"),o=n.decode??n.default?.decode;if(!o)throw new Error("decode not found");t=o}catch{throw new Error('The "bs58" package is required for base58 private keys. Install it with: npm install bs58')}try{let n=t(r);e=qe.fromSecretKey(n)}catch{try{let o=JSON.parse(r);if(Array.isArray(o))e=qe.fromSecretKey(Uint8Array.from(o));else throw new Error("Invalid private key format")}catch{throw new Error("Invalid private key. Expected base58 string or JSON array of bytes.")}}}else if(Array.isArray(r))e=qe.fromSecretKey(Uint8Array.from(r));else if(r instanceof Uint8Array)e=qe.fromSecretKey(r);else throw new Error("Invalid private key type. Expected string, number[], or Uint8Array.");return{publicKey:{toBase58:()=>e.publicKey.toBase58()},signTransaction:async t=>{if(t instanceof fn)return t.sign([e]),t;if(t instanceof gn)return t.sign(e),t;throw new Error("Unknown transaction type")},[ve]:e}}function hn(r){if(!r||typeof r!="object")return!1;let e=r;return ve in e&&e[ve]instanceof qe&&"publicKey"in e&&"signTransaction"in e}function ct(r){let e=r.evm;if(e&&typeof e.signMessage=="function"&&typeof e.address=="string")return{address:e.address,signMessage:e.signMessage};let t=r.solana;if(t){let n=t[ve];if(n&&n.secretKey&&n.publicKey)return{publicKey:n.publicKey,signMessage:async o=>Bt.sign.detached(o,n.secretKey)}}return null}import{decodePaymentRequiredHeader as yn}from"@x402/core/http";var Dt=[Ot,Vt];async function Ut(r){for(let e of Dt)if(await e.parseChallenge(r.clone()))return e;return null}async function An(r){let e=async(o,s)=>({response:await fetch(o,s),paymentUrl:o,paymentInit:s}),t=ct(r);if(!t)return e;let n;try{n=await import("@x402/extensions/sign-in-with-x")}catch(o){return console.warn(`[x402] SIW-X unavailable \u2014 @x402/extensions failed to load; SIW-X merchants will not authenticate. ${F(o)}`),e}return async(o,s)=>{let i=new Request(o,s),a=i.clone(),c=await fetch(i),u={response:c,paymentUrl:o,paymentInit:s};if(c.status!==402)return u;let d=c.headers.get("PAYMENT-REQUIRED");if(!d)return u;let f=yn(d),A=f.extensions?.[n.SIGN_IN_WITH_X];if(!A?.supportedChains)return u;if(a.headers.has(n.SIGN_IN_WITH_X))throw new Error("SIWX authentication already attempted");let w=f.accepts?.[0]?.network,l=A.supportedChains.find(v=>v.chainId===w);if(!l)return u;let h=c.url||i.url;if(c.redirected&&!["GET","HEAD"].includes(i.method))throw new Error("SIWX cannot safely replay a redirected non-GET/HEAD request; use the final resource URL");let g={...A.info,chainId:l.chainId,type:l.type};if(n.assertSIWxChallengeBoundToOrigin(g,h),c.redirected||new URL(h).origin!==new URL(i.url).origin)for(let v of["authorization","cookie","cookie2","proxy-authorization","host"])a.headers.delete(v);let x=new Headers(a.headers),m={response:c,paymentUrl:h,paymentInit:{...s,headers:Object.fromEntries(x),redirect:"error"}};try{let v=await n.createSIWxPayload(g,t,h);a.headers.set(n.SIGN_IN_WITH_X,n.encodeSIWxHeader(v))}catch{return m}let p=new Request(new Request(h,a),{redirect:"error"});return{...m,response:await fetch(p)}}}async function Mt(r,e,t,n){if(e.body!==void 0&&e.body!==null&&typeof e.body!="string")return{ok:!1,reason:"error",detail:"payAndFetch requires a string body; non-string bodies (Buffer, FormData, URLSearchParams, ReadableStream) cannot be safely re-sent on the paid retry"};let o,s=r,i=e;try{let c=await(await An(t))(r,{...e});o=c.response,s=c.paymentUrl,i=c.paymentInit}catch(a){return{ok:!1,reason:"error",detail:F(a)}}if(o.status!==402)return{ok:!0,paid:!1,response:o};for(let a of Dt){let c=await a.parseChallenge(o.clone());if(c)return a.pay(s,i,c,t,n)}return{ok:!1,reason:"no_payment_options"}}async function yt(r){let e;try{e=(await import("viem/accounts")).privateKeyToAccount}catch{throw new Error("EVM wallet support requires viem as a peer dependency. Install with: npm install viem")}let t=r.startsWith("0x")?r:`0x${r}`,n=e(t);return{address:n.address,signTypedData:o=>n.signTypedData(o),signTransaction:o=>n.signTransaction({to:o.to,data:o.data,chainId:o.chainId,gas:o.gas,gasPrice:o.gasPrice,nonce:o.nonce,type:"legacy"}),signMessage:o=>n.signMessage({message:o.message})}}function bn(r){if(!r||typeof r!="object")return!1;let e=r;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")&&"signTypedData"in e&&typeof e.signTypedData=="function"}function At(r){let e=Fe(r);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function Sn(r){let e=At(r);if(e?.recommendations?.length)return e.recommendations}async function wn(r){let t=At(r)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function $t(r,e){let{walletPrivateKey:t,evmPrivateKey:n,preferredNetwork:o,rpcUrls:s,maxAmountAtomic:i,verbose:a,accessPass:c,onPaymentRequired:u}=e;if(!t&&!n)throw new Error("At least one wallet private key is required (walletPrivateKey or evmPrivateKey)");let d={},f=[];t&&f.push(ht(t).then(g=>{d.solana=g}).catch(g=>{console.warn(`[x402] Solana wallet init failed: ${g.message}`)})),n&&f.push(yt(n).then(g=>{d.evm=g}).catch(g=>{console.warn(`[x402] EVM wallet init failed: ${g.message}`)}));let A=f.length>0?Promise.all(f):null,l=rt({wallets:d,preferredNetwork:o,rpcUrls:s,maxAmountAtomic:i,fetch:r,verbose:a,accessPass:c,onPaymentRequired:u}),h=l.fetch.bind(l);return A?(async(g,x)=>(await A,h(g,x))):h}function vn(r){let{budget:e,allowedDomains:t,onPaymentRequired:n,...o}=r,s=parseFloat(e.total),i=e.perRequest?parseFloat(e.perRequest):1/0,a=e.perHour?parseFloat(e.perHour):1/0;if(isNaN(s)||s<=0)throw new Error("budget.total must be a positive number");let c=[],u=0;function d(){return c.reduce((l,h)=>l+h.amount,0)}function f(){let l=Date.now()-36e5;return c.filter(h=>h.timestamp>=l).reduce((h,g)=>h+g.amount,0)}let A=$t(fetch,{...o,onPaymentRequired:async l=>{let h=l.extra?.decimals??6,g=Number(l.amount)/Math.pow(10,h);if(g>i)throw new P("amount_exceeds_max",`$${g.toFixed(4)} exceeds per-request limit of $${i.toFixed(2)}`);let x=d();if(x+g>s)throw new P("amount_exceeds_max",`Budget exceeded. Spent $${x.toFixed(2)} of $${s.toFixed(2)}, payment: $${g.toFixed(4)}`);let m=f();if(m+g>a)throw new P("amount_exceeds_max",`Hourly limit ($${a.toFixed(2)}) exceeded. Spent $${m.toFixed(2)} this hour`);return u=g,n?n(l):!0}});return{fetch:(async(l,h)=>{let g=typeof l=="string"?l:l instanceof URL?l.href:l.url,x="unknown";try{x=new URL(g).hostname}catch{}if(t&&!t.some(p=>x===p||x.endsWith(`.${p}`)))throw new P("payment_rejected",`Domain "${x}" not in allowed domains`);u=0;let m=await A(l,h);if(u>0){let p="unknown",v=m.headers.get("PAYMENT-RESPONSE");if(v)try{p=JSON.parse(atob(v)).network||p}catch{}c.push({amount:u,domain:x,network:p,timestamp:Date.now()}),u=0}return m}),get spent(){return`$${d().toFixed(2)}`},get remaining(){return`$${(s-d()).toFixed(2)}`},get payments(){return c.length},get spentAmount(){return d()},get remainingAmount(){return s-d()},get ledger(){return c},get hourlySpend(){return f()},reset(){c=[]}}}import{capabilitySearch as xn}from"@dexterai/x402-core";export{J as BASE_MAINNET,wt as DEXTER_FACILITATOR_URL,ve as KEYPAIR_SYMBOL,z as SOLANA_MAINNET,Je as USDC_MINT,P as X402Error,it as buildV1PaymentHeader,xn as capabilitySearch,It as capturePaymentReceipt,vn as createBudgetAccount,me as createEvmAdapter,yt as createEvmKeypairWallet,ht as createKeypairWallet,L as createSolanaAdapter,Ut as detectStrategy,wn as fireImpressionBeacon,Fe as getPaymentReceipt,At as getSponsoredAccessInfo,Sn as getSponsoredRecommendations,bn as isEvmKeypairWallet,hn as isKeypairWallet,Mt as payAndFetch,Y as toNetworkRef,ct as toSiwxSigner};
1
+ var Pe="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Je="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Ye="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",J=Pe,Te=Je,Ie=Ye,ne="eip155:8453",he="eip155:84532",ye="eip155:42161",Ae="eip155:137",be="eip155:10",Se="eip155:43114",we="eip155:56",re="eip155:480",oe="eip155:143",se="eip155:4663",ae="eip155:1187947933",ie="eip155:324705682",ve="eip155:1",Y=ne,Ge=he,Ne=ye,Ce=Ae,ke=be,Oe=Se,Ve=we,Be=re,De=oe,Ue=se,Me=ae,$e=ie,Ke=ve,Ze="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",Et="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",_t="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",pt="0x55d398326f99059fF775485246999027B3197955",Qe="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",ft="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",xe={[we]:Qe,[ne]:_t,[he]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[ye]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[Ae]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[be]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[Se]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[re]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[oe]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[se]:ft,[ae]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[ie]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[ve]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},et={[pt]:{symbol:"USDT",decimals:18},[Qe]:{symbol:"USDC",decimals:18}};var tt={[re]:{name:"USDC",version:"2"},[oe]:{name:"USDC",version:"2"},[se]:{name:"Global Dollar",version:"1"},[ae]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[ie]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}},G="0x000000000022D473030F116dDEE9F6B43aC78BA3",Le="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",Fe={[we]:56,[ne]:8453,[he]:84532,[ye]:42161,[Ae]:137,[be]:10,[Se]:43114,[re]:480,[oe]:143,[se]:4663,[ae]:1187947933,[ie]:324705682,[ve]:1},ce={[Pe]:"https://api.dexter.cash/api/solana/rpc",[Je]:"https://api.devnet.solana.com",[Ye]:"https://api.testnet.solana.com"},O={[we]:"https://api.dexter.cash/api/evm/bsc/rpc",[ne]:"https://api.dexter.cash/api/base/rpc",[he]:"https://sepolia.base.org",[ye]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[Ae]:"https://api.dexter.cash/api/evm/polygon/rpc",[be]:"https://api.dexter.cash/api/evm/optimism/rpc",[Se]:"https://api.dexter.cash/api/evm/avalanche/rpc",[re]:"https://worldchain-mainnet.g.alchemy.com/public",[oe]:"https://rpc.monad.xyz",[se]:"https://rpc.mainnet.chain.robinhood.com",[ae]:"https://skale-base.skalenodes.com/v1/base",[ie]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[ve]:"https://eth.llamarpc.com"},Pt="https://x402.dexter.cash";var T=class r extends Error{code;details;constructor(e,t,n){super(t),this.name="X402Error",this.code=e,this.details=n,Object.setPrototypeOf(this,r.prototype)}};function L(r,e){let t=r.scheme??"exact";if(t!=="exact"&&!(e==="evm"&&t==="exact-approval"))return`Unsupported payment scheme: ${t}`;let n=r.extra?.paymentFlow;if(n!==void 0&&n!=="authorization")return`Unsupported payment flow: ${String(n)}`;let o=r.extra?.assetTransferMethod;if(o!==void 0&&(typeof o!="string"||!(t==="exact-approval"?[]:e==="evm"?["eip3009","permit2"]:["default"]).includes(o)))return`Unsupported payment asset transfer method: ${String(o)}`}function We(r){let e=r?.["payment-identifier"];if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.info;return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.required===!0}var Tt=[{caip2:"eip155:8453",bare:"base",family:"evm"},{caip2:"eip155:1",bare:"ethereum",family:"evm"},{caip2:"eip155:137",bare:"polygon",family:"evm"},{caip2:"eip155:42161",bare:"arbitrum",family:"evm"},{caip2:"eip155:10",bare:"optimism",family:"evm"},{caip2:"eip155:43114",bare:"avalanche",family:"evm"},{caip2:"eip155:56",bare:"bsc",family:"evm"},{caip2:"eip155:480",bare:"world",family:"evm"},{caip2:"eip155:143",bare:"monad",family:"evm"},{caip2:"eip155:4663",bare:"robinhood",family:"evm"},{caip2:"eip155:1187947933",bare:"skale-base",family:"evm"},{caip2:"eip155:324705682",bare:"skale-base-sepolia",family:"evm"},{caip2:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",bare:"solana",family:"svm"}],Yt=new Map(Tt.map(r=>[r.caip2.toLowerCase(),r])),Gt=new Map(Tt.map(r=>[r.bare.toLowerCase(),r]));function Z(r){if(!r)return null;let e=r.toLowerCase(),t=Yt.get(e)||Gt.get(e);return t?{caip2:t.caip2,bare:t.bare,family:t.family}:null}function gt(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-(e.length%4||4))%4);return JSON.parse(Buffer.from(t,"base64").toString("utf8"))}function Zt(r){let e=[];for(let t of r){if(!t||typeof t!="object")continue;let n=t,o=Z(String(n.network??""));o&&e.push({scheme:String(n.scheme??"exact"),network:o,amount:String(n.amount??n.maxAmountRequired??"0"),asset:String(n.asset??""),payTo:String(n.payTo??""),maxTimeoutSeconds:typeof n.maxTimeoutSeconds=="number"?n.maxTimeoutSeconds:void 0,extra:n.extra&&typeof n.extra=="object"?n.extra:void 0})}return e}async function It(r){let e=r.headers.get("payment-required");if(!e)return null;let t;try{t=gt(e)}catch{return null}let n=Array.isArray(t.accepts)?t.accepts:[];return n.length===0?null:{x402Version:2,options:Zt(n),extensions:t.extensions&&typeof t.extensions=="object"&&!Array.isArray(t.extensions)?t.extensions:void 0,resourceUrl:t.resource&&typeof t.resource=="object"?String(t.resource.url??""):void 0}}import{PublicKey as ue,Connection as ht,TransactionMessage as Qt,VersionedTransaction as en,ComputeBudgetProgram as Nt}from"@solana/web3.js";import{getAssociatedTokenAddress as yt,getAccount as tn,createTransferCheckedInstruction as nn,getMint as rn,TOKEN_PROGRAM_ID as Ct,TOKEN_2022_PROGRAM_ID as nt}from"@solana/spl-token";var on=12e3,sn=1;function le(r){if(!r||typeof r!="object")return!1;let e=r;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var rt=class{name="Solana";networks=[J,Te,Ie];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[J]:e==="solana-devnet"?ce[Te]:e==="solana-testnet"?ce[Ie]:ce[J]}getAddress(e){return le(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return le(e)?e.publicKey!==null:!1}async getBalance(e,t,n){if(!le(t)||!t.publicKey)return 0;let o=n||this.getDefaultRpcUrl(e.network),a=new ht(o,"confirmed"),c=new ue(t.publicKey.toBase58()),s=new ue(e.asset);try{let u=(await a.getAccountInfo(s,"confirmed"))?.owner.toBase58()===nt.toBase58()?nt:Ct,g=await yt(s,c,!1,u),h=await tn(a,g,void 0,u),y=e.extra?.decimals??6;return Number(h.amount)/Math.pow(10,y)}catch(i){if(i&&typeof i=="object"&&"name"in i&&(i.name==="TokenAccountNotFoundError"||i.name==="TokenInvalidAccountOwnerError"))return 0;throw i}}async buildTransaction(e,t,n){let o=L(e,"svm");if(o)throw new Error(o);if(!le(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let a=n||this.getDefaultRpcUrl(e.network),c=new ht(a,"confirmed"),s=new ue(t.publicKey.toBase58()),{payTo:i,asset:u,extra:g}=e,h=e.amount??e.maxAmountRequired;if(!h)throw new Error("Missing amount in payment requirements");if(!g?.feePayer)throw new Error("Missing feePayer in payment requirements");let y=new ue(g.feePayer),A=new ue(u),l=new ue(i);this.log("Building transaction:",{from:s.toBase58(),to:i,amount:h,asset:u,feePayer:g.feePayer});let d=[];d.push(Nt.setComputeUnitLimit({units:on})),d.push(Nt.setComputeUnitPrice({microLamports:sn}));let f=await c.getAccountInfo(A,"confirmed");if(!f)throw new Error(`Token mint ${u} not found`);let w=f.owner.toBase58()===nt.toBase58()?nt:Ct,m=await rn(c,A,void 0,w);typeof g?.decimals=="number"&&m.decimals!==g.decimals&&this.log(`Decimals mismatch: requirements say ${g.decimals}, mint says ${m.decimals}`);let p=await yt(A,s,!1,w),v=await yt(A,l,!0,w);if(!await c.getAccountInfo(p,"confirmed"))throw new Error(`No token account found for ${u}. Please ensure you have USDC in your wallet.`);if(!await c.getAccountInfo(v,"confirmed"))throw new Error(`Seller token account not found. The seller (${i}) must have a USDC account.`);let q=BigInt(h);d.push(nn(p,A,v,s,q,m.decimals,[],w));let{blockhash:H}=await c.getLatestBlockhash("confirmed"),U=new Qt({payerKey:y,recentBlockhash:H,instructions:d}).compileToV0Message(),R=new en(U),E=await t.signTransaction(R);return this.log("Transaction signed successfully"),{serialized:Buffer.from(E.serialize()).toString("base64"),settlementProbe:{kind:"solana",sourceAta:p.toBase58(),destinationAta:v.toBase58(),asset:u,amount:h,blockhash:H}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let n=new ht(t,"confirmed"),o=new ue(e.destinationAta),a=await n.getSignaturesForAddress(o,{limit:25});if(a.length===0)return{settled:!1};let c=BigInt(e.amount);for(let s of a){if(s.err)continue;let i=await n.getTransaction(s.signature,{commitment:"confirmed",maxSupportedTransactionVersion:0});if(!i?.meta)continue;let u=i.transaction.message.getAccountKeys().keySegments().flat(),g=i.meta.preTokenBalances??[],h=i.meta.postTokenBalances??[];for(let y of h){if(y.mint!==e.asset)continue;let A=u[y.accountIndex];if(!A||!A.equals(o))continue;let l=g.find(w=>w.accountIndex===y.accountIndex),d=BigInt(l?.uiTokenAmount.amount??"0");if(BigInt(y.uiTokenAmount.amount??"0")-d===c)return{settled:!0,txSignature:s.signature}}}return{settled:!1}}};function F(r){return new rt(r)}var an={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"}]},kt=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function de(r){if(!r||typeof r!="object")return!1;let e=r;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var ot=class{name="EVM";networks=[Ve,Y,Ge,Ke,Ne,Ce,ke,Oe,Be,De,Ue,Me,$e];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:evm]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="base"||e==="bsc"||e==="ethereum"||e==="arbitrum"||e==="polygon"||e==="optimism"||e==="avalanche"||e==="world"||e==="monad"||e==="robinhood"||e==="skale-base"||e==="skale-base-sepolia"||e.startsWith("eip155:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:O[e]?O[e]:e==="base"?O[Y]:e==="bsc"?O[Ve]:e==="ethereum"?O[Ke]:e==="arbitrum"?O[Ne]:e==="polygon"?O[Ce]:e==="optimism"?O[ke]:e==="avalanche"?O[Oe]:e==="world"?O[Be]:e==="monad"?O[De]:e==="robinhood"?O[Ue]:e==="skale-base"?O[Me]:e==="skale-base-sepolia"?O[$e]:O[Y]}getAddress(e){return de(e)?e.address:null}isConnected(e){return de(e)?!!e.address:!1}getChainId(e){if(Fe[e])return Fe[e];if(e.startsWith("eip155:")){let t=e.split(":")[1];return parseInt(t,10)}return e==="base"?8453:e==="bsc"?56:e==="ethereum"?1:e==="arbitrum"?42161:e==="polygon"?137:e==="optimism"?10:e==="avalanche"?43114:e==="world"?480:e==="monad"?143:e==="robinhood"?4663:e==="skale-base"?1187947933:e==="skale-base-sepolia"?324705682:8453}async getBalance(e,t,n){if(!de(t)||!t.address)return 0;let o=n||this.getDefaultRpcUrl(e.network);try{let a=this.encodeBalanceOf(t.address),c=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:a},"latest"]})});if(!c.ok)throw new Error(`RPC request failed: ${c.status}`);let s=await c.json();if(s.error)throw new Error(`RPC error: ${JSON.stringify(s.error)}`);if(!s.result||s.result==="0x")return 0;let i=BigInt(s.result),u=e.extra?.decimals??6;return Number(i)/Math.pow(10,u)}catch(a){throw a}}encodeBalanceOf(e){let t="0x70a08231",n=e.slice(2).toLowerCase().padStart(64,"0");return t+n}async confirmSettlement(e,t){if(e.kind==="eip3009"){let n="0xe94a0102",o=e.from.slice(2).toLowerCase().padStart(64,"0"),a=e.nonce.slice(2).toLowerCase().padStart(64,"0"),c=n+o+a,s=await this.ethCall(t,e.asset,c);return{settled:BigInt(s)!==0n}}if(e.kind==="permit2"){let n="0x4fe02b44",o=BigInt(e.nonce),a=o>>8n,c=o&0xffn,s=e.from.slice(2).toLowerCase().padStart(64,"0"),i=a.toString(16).padStart(64,"0"),u=n+s+i,g=await this.ethCall(t,G,u);return{settled:(BigInt(g)>>c&1n)===1n}}throw new Error(`EvmAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`)}async ethCall(e,t,n){let o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:n},"latest"]})});if(!o.ok)throw new Error(`RPC request failed: ${o.status}`);let a=await o.json();if(a.error)throw new Error(`RPC error: ${JSON.stringify(a.error)}`);if(!a.result||a.result==="0x")throw new Error("RPC returned an empty result");return a.result}async buildTransaction(e,t,n){let o=L(e,"evm");if(o)throw new Error(o);if(!de(t))throw new Error("Invalid EVM wallet");if(!t.address)throw new Error("Wallet not connected");if(e.scheme==="exact-approval")return this.buildApprovalTransaction(e,t,n);if(e.extra?.assetTransferMethod==="permit2")return this.buildPermit2Transaction(e,t,n);let{payTo:a,asset:c,extra:s}=e,i=e.amount??e.maxAmountRequired;if(!i)throw new Error("Missing amount in payment requirements");this.log("Building EVM transaction:",{from:t.address,to:a,amount:i,asset:c,network:e.network});let u=this.getChainId(e.network),g=tt[`eip155:${u}`],h={name:s?.name??g?.name??"USD Coin",version:s?.version??g?.version??"2",chainId:BigInt(u),verifyingContract:c},y={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},A=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(A);let l="0x"+[...A].map(v=>v.toString(16).padStart(2,"0")).join(""),d=Math.floor(Date.now()/1e3),f={from:t.address,to:a,value:i,validAfter:String(d-600),validBefore:String(d+(e.maxTimeoutSeconds||60)),nonce:l},w={from:t.address,to:a,value:BigInt(i),validAfter:BigInt(d-600),validBefore:BigInt(d+(e.maxTimeoutSeconds||60)),nonce:l};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let m=await t.signTypedData({domain:h,types:y,primaryType:"TransferWithAuthorization",message:w});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:f,signature:m}),signature:m,settlementProbe:{kind:"eip3009",from:f.from,to:f.to,amount:f.value,nonce:l,asset:c,chainId:u}}}async buildApprovalTransaction(e,t,n){let{payTo:o,asset:a,extra:c}=e,s=e.amount??e.maxAmountRequired;if(!s)throw new Error("Missing amount in payment requirements");let i=c?.facilitatorContract;if(!i)throw new Error("exact-approval scheme requires extra.facilitatorContract from the facilitator. The /supported endpoint should provide this.");if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building approval-based transaction:",{from:t.address,to:o,amount:s,asset:a,network:e.network,facilitatorContract:i});let u=n||this.getDefaultRpcUrl(e.network),g=c?.fee??"0",h=BigInt(s)+BigInt(g),y=await this.readAllowance(u,a,t.address,i);if(y<h){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 U=this.calculateApprovalAmount(s,g,c?.approvalStrategy);this.log(`Approving ${U} for ${i} (current allowance: ${y})`);let R=await t.sendTransaction({to:a,data:this.encodeApprove(i,U),value:0n});this.log(`Approval tx sent: ${R}`),await this.waitForReceipt(u,R),this.log("Approval confirmed")}else this.log("Sufficient allowance, skipping approval");let A=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(A);let l=[...A].reduce((U,R)=>U*256n+BigInt(R),0n).toString(),d=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(d);let f="0x"+[...d].map(U=>U.toString(16).padStart(2,"0")).join(""),m=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),p=c?.eip712Domain,v=p?{name:p.name,version:p.version,chainId:BigInt(p.chainId),verifyingContract:p.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:i},S=c?.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:a,amount:BigInt(s),fee:BigInt(g),nonce:BigInt(l),deadline:BigInt(m),paymentId:f},q=await t.signTypedData({domain:v,types:S,primaryType:"Payment",message:Q});this.log("EIP-712 Payment signature obtained");let H={from:t.address,to:o,token:a,amount:s,fee:g,nonce:l,deadline:m,paymentId:f,signature:q};return{serialized:JSON.stringify(H),signature:q}}async buildPermit2Transaction(e,t,n){let{payTo:o,asset:a}=e,c=e.amount??e.maxAmountRequired;if(!c)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:c,asset:a,network:e.network});let s=n||this.getDefaultRpcUrl(e.network),i=await this.readAllowance(s,a,t.address,G),u;if(i<BigInt(c)){let v=this.encodeApprove(G,kt);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${i})`);let S=this.getChainId(e.network),Q=await this.readGasPrice(s),q=await this.readNonce(s,t.address),H=await t.signTransaction({to:a,data:v,chainId:S,gas:50000n,gasPrice:Q,nonce:q});u={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:a,spender:G,amount:kt.toString(),signedTransaction:H,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${i})`);let S=await t.sendTransaction({to:a,data:v,value:0n});this.log(`Permit2 approval tx sent: ${S}`),await this.waitForReceipt(s,S),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 g=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(g);let h=[...g].reduce((v,S)=>v*256n+BigInt(S),0n),y=Math.floor(Date.now()/1e3),A=y-600,l=y+(e.maxTimeoutSeconds||300),d=this.getChainId(e.network),f={name:"Permit2",chainId:BigInt(d),verifyingContract:G},w={permitted:{token:a,amount:BigInt(c)},spender:Le,nonce:h,deadline:BigInt(l),witness:{to:o,validAfter:BigInt(A)}},m=await t.signTypedData({domain:f,types:an,primaryType:"PermitWitnessTransferFrom",message:w});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let p={signature:m,permit2Authorization:{from:t.address,permitted:{token:a,amount:c},spender:Le,nonce:h.toString(),deadline:String(l),witness:{to:o,validAfter:String(A)}}};return{serialized:JSON.stringify(p),signature:m,extensions:u,settlementProbe:{kind:"permit2",from:t.address,nonce:h.toString(),chainId:d}}}async readAllowance(e,t,n,o){let a="0xdd62ed3e",c=n.slice(2).toLowerCase().padStart(64,"0"),s=o.slice(2).toLowerCase().padStart(64,"0"),i=a+c+s;try{let g=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:i},"latest"]})})).json();return g.error||!g.result||g.result==="0x"?0n:BigInt(g.result)}catch{return 0n}}encodeApprove(e,t){let n="0x095ea7b3",o=e.slice(2).toLowerCase().padStart(64,"0"),a=t.toString(16).padStart(64,"0");return n+o+a}async waitForReceipt(e,t,n=3e4){let o=Date.now();for(;Date.now()-o<n;){try{let c=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(c.result){if(c.result.status==="0x0")throw new Error(`Approval transaction reverted: ${t}`);return}}catch(a){if(a instanceof Error&&a.message.includes("reverted"))throw a}await new Promise(a=>setTimeout(a,2e3))}throw new Error(`Approval transaction receipt timeout after ${n}ms: ${t}`)}async readGasPrice(e){try{let n=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_gasPrice",params:[]})})).json();return n.result?BigInt(n.result):50000000n}catch{return 50000000n}}async readNonce(e,t){try{let o=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionCount",params:[t,"latest"]})})).json();return o.result?parseInt(o.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,n){let o=BigInt(e)+BigInt(t);if(!n||n.mode==="exact")return o;let a=BigInt(n.defaultMultiple??10),c=o*a;if(n.maxCapUsd){let s=this.inferDecimals(e),i=BigInt(Math.floor(n.maxCapUsd*Math.pow(10,s)));if(c>i)return i}if(n.exactAboveUsd){let s=this.inferDecimals(e),i=BigInt(Math.floor(n.exactAboveUsd*Math.pow(10,s)));if(BigInt(e)>i)return o}return c}inferDecimals(e){return e.length>12?18:6}};function me(r){return new ot(r)}function At(r){if(r===Ze||r===Et)return!0;let e=r.toLowerCase();for(let t of Object.values(xe))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(et))if(t.toLowerCase()===e)return!0;return!1}function cn(r){return{[Pe]:"Solana",[Je]:"Solana Devnet",[Ye]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[ne]:"Base",[he]:"Base Sepolia",[ve]:"Ethereum",[ye]:"Arbitrum",[Ae]:"Polygon",[be]:"Optimism",[Se]:"Avalanche",[we]:"BSC",[re]:"World Chain",[oe]:"Monad",[se]:"Robinhood Chain",[ae]:"SKALE Base",[ie]:"SKALE Base Sepolia",base:"Base","base-sepolia":"Base Sepolia",ethereum:"Ethereum",arbitrum:"Arbitrum",polygon:"Polygon",optimism:"Optimism",avalanche:"Avalanche",bsc:"BSC",world:"World Chain",monad:"Monad",robinhood:"Robinhood Chain","skale-base":"SKALE Base","skale-base-sepolia":"SKALE Base Sepolia"}[r]||r}function Ot(r,e){let t=cn(r);return t===r?e:t}async function un(r,e){if(typeof r=="string")return[r,e];if(r instanceof URL)return[r.href,e];let t=r,n=new Headers(t.headers);e?.headers&&new Headers(e.headers).forEach((c,s)=>n.set(s,c));let o={method:e?.method??t.method,headers:n,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},a=(o.method??"GET").toUpperCase();return e&&"body"in e?o.body=e.body:a!=="GET"&&a!=="HEAD"&&t.body&&(o.body=await t.arrayBuffer()),[t.url,o]}var Vt=new WeakMap;function qe(r){return Vt.get(r)}function bt(r){if(!(r.length>16384))try{let e=r.trimStart().startsWith("{")?JSON.parse(r):gt(r);return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}catch{return}}function Bt(r,e){let t=r.headers.get("PAYMENT-RESPONSE")??r.headers.get("X-PAYMENT-RESPONSE"),n;if(t)try{let s=bt(t);s&&typeof s=="object"&&!Array.isArray(s)&&(n={...s})}catch{}n??={},delete n.chainConfirmation,n.settlementStatus="unconfirmed";let o=n.network===e.network,a=[n.errorReason,n.errorCode,n.errorMessage].every(s=>s===void 0||typeof s=="string"),c=[n.errorReason,n.errorCode].filter(s=>typeof s=="string"&&s.length>0);return c.some(s=>/pending|unknown|unconfirmed|timeout|temporar/i.test(s))?n.settlementStatus="pending":n.success===!0&&o&&a&&c.length===0&&typeof n.transaction=="string"&&n.transaction.trim().length>0?n.settlementStatus="settled":n.success===!1&&(o||n.network===void 0)&&c.length>0&&(n.settlementStatus="failed"),n.attemptedAmountAtomic=e.amountAtomic,n.settlementStatus==="settled"?n.amountAtomic=e.amountAtomic:delete n.amountAtomic,n.assetDecimals=e.assetDecimals,Vt.set(r,n),n}function st(r){let{adapters:e=[F({verbose:r.verbose}),me({verbose:r.verbose})],wallets:t,wallet:n,preferredNetwork:o,rpcUrls:a={},maxAmountAtomic:c,fetch:s=globalThis.fetch,verbose:i=!1,accessPass:u,onPaymentRequired:g,onPaymentDispatched:h,maxRetries:y=0,retryDelayMs:A=500}=r,l=i?console.log.bind(console,"[x402]"):()=>{};async function d(R,E){let P;for(let x=0;x<=y;x++)try{let N=await s(R,E);if(N.status>=502&&N.status<=504&&x<y){l(`Retry ${x+1}/${y}: server returned ${N.status}`),await new Promise(I=>setTimeout(I,A*Math.pow(2,x)));continue}return N}catch(N){P=N,x<y&&(l(`Retry ${x+1}/${y}: ${N instanceof Error?N.message:"network error"}`),await new Promise(I=>setTimeout(I,A*Math.pow(2,x))))}throw P}let f=new Map;function w(R){try{let E=new URL(R).host,P=f.get(E);if(P&&P.expiresAt>Date.now()/1e3+10)return P.jwt;P&&f.delete(E)}catch{}return null}function m(R,E){try{let P=new URL(R).host,x=E.split(".");if(x.length===3){let N=JSON.parse(atob(x[1].replace(/-/g,"+").replace(/_/g,"/"))),I=Math.floor(Date.now()/1e3),C=I+86400,M=Math.min(typeof N.exp=="number"?N.exp:I,C);f.set(P,{jwt:E,expiresAt:M}),l("Access pass cached for",P,"| expires:",new Date(M*1e3).toISOString())}}catch{l("Failed to cache access pass")}}let p=t||{};n&&!p.solana&&le(n)&&(p.solana=n),n&&!p.evm&&de(n)&&(p.evm=n);function v(R){let E=[];for(let P of R){let x=e.find(C=>C.canHandle(P.network));if(!x)continue;let N=x.name==="Solana"?"svm":"evm";if(L(P,N))continue;let I;x.name==="Solana"?I=p.solana:x.name==="EVM"&&(I=p.evm),I&&x.isConnected(I)&&E.push({accept:P,adapter:x,wallet:I})}if(E.length===0)return null;if(o){let P=E.find(x=>x.accept.network===o);if(P)return P}return E[0]}function S(R,E){return Ot(R,E)}function Q(R,E){return a[R]||E.getDefaultRpcUrl(R)}async function q(R,E,P,x,N){let I="";if(u?.preferTier&&x.tiers){let b=x.tiers.find(K=>K.id===u.preferTier);if(b){if(u.maxSpend&&parseFloat(b.price)>parseFloat(u.maxSpend))throw new T("access_pass_exceeds_max_spend",`Access pass tier "${b.id}" costs $${b.price}, exceeds max spend $${u.maxSpend}`);I=`tier=${b.id}`}}else if(u?.preferDuration&&x.ratePerHour)I=`duration=${u.preferDuration}`;else if(x.tiers&&x.tiers.length>0){let b=x.tiers[0];if(u?.maxSpend&&parseFloat(b.price)>parseFloat(u.maxSpend))throw new T("access_pass_exceeds_max_spend",`Cheapest access pass costs $${b.price}, exceeds max spend $${u?.maxSpend}`);I=`tier=${b.id}`}let C=I?N.includes("?")?`${N}&${I}`:`${N}?${I}`:N;l("Purchasing access pass:",I||"default tier");let M=P.headers.get("PAYMENT-REQUIRED");if(!M)return null;let D;try{D=JSON.parse(atob(M))}catch{return null}let B=v(D.accepts);if(!B)return null;if(We(D.extensions))throw new T("unsupported_required_payment_identifier","Required payment identifiers are not supported by this client");let{accept:k,adapter:$,wallet:pe}=B;if($.name==="Solana"&&!k.extra?.feePayer)return null;let j=k.extra?.decimals??(At(k.asset)?6:void 0);if(typeof j!="number")return null;let Ee=k.amount??k.maxAmountRequired;if(!Ee)return null;let z=Q(k.network,$);try{let b=await $.getBalance(k,pe,z),K=Number(Ee)/Math.pow(10,j);if(b<K){let Jt=S(k.network,$.name);throw new T("insufficient_balance",`Insufficient balance for access pass on ${Jt}. Have $${b.toFixed(4)}, need $${K.toFixed(4)}`)}}catch(b){if(b instanceof T)throw b}let X=await $.buildTransaction(k,pe,z),fe;$.name==="EVM"?fe=JSON.parse(X.serialized):fe={transaction:X.serialized};let ee=typeof R=="string"?R:R instanceof URL?R.href:R.url,ge=D.resource;if(typeof D.resource=="string")try{let b=new URL(D.resource,ee);["http:","https:"].includes(b.protocol)&&(ge=b.toString())}catch{}else if(D.resource&&typeof D.resource=="object"&&"url"in D.resource){let b=D.resource;try{let K=new URL(b.url,ee);["http:","https:"].includes(K.protocol)&&(ge={...b,url:K.toString()})}catch{}}let Xe={x402Version:k.x402Version??2,resource:ge,accepted:k,payload:fe};X.extensions&&(Xe.extensions=X.extensions);let _e=btoa(JSON.stringify(Xe)),te=await s(C,{...E,method:"POST",headers:{...E?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":_e}});if(!te.ok)return l("Pass purchase failed:",te.status),null;let _=te.headers.get("ACCESS-PASS");return _&&(m(N,_),l("Access pass purchased and cached")),te}async function H(R,E){let P=R;if(l("Making request:",P),u){let _=w(P);if(_){l("Using cached access pass");let b=await s(R,{...E,headers:{...E?.headers||{},Authorization:`Bearer ${_}`}});if(b.status!==401&&b.status!==402)return b;l("Cached pass rejected (status",b.status,"), purchasing new pass");try{f.delete(new URL(P).host)}catch{}}}let x=await d(R,E);if(x.status!==402)return x;l("Received 402 Payment Required");let N=x.headers.get("X-ACCESS-PASS-TIERS");if(u&&N){l("Server offers access passes, purchasing...");try{let _=JSON.parse(atob(N)),b=await q(R,E,x,_,P);if(b)return b}catch(_){l("Access pass purchase failed, falling back to per-request payment:",_)}}let I=x.headers.get("PAYMENT-REQUIRED");if(!I)throw new T("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let C;try{let _=atob(I);C=JSON.parse(_)}catch{throw new T("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}if(l("Payment requirements:",C),We(C.extensions))throw new T("unsupported_required_payment_identifier","Required payment identifiers are not supported by this client");let M=x.headers.get("X-Quote-Hash");M&&l("Quote hash received:",M);let D=v(C.accepts);if(!D){let _=C.accepts.map(b=>b.network).join(", ");throw new T("no_matching_payment_option",`No supported payment option with a connected wallet for: ${_}`)}let{accept:B,adapter:k,wallet:$}=D;if(l(`Using ${k.name} for ${B.network}`),k.name==="Solana"&&!B.extra?.feePayer)throw new T("missing_fee_payer","Solana payment option missing feePayer in extra");let pe=B.extra?.decimals??(At(B.asset)?6:void 0);if(typeof pe!="number")throw new T("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let j=B.amount??B.maxAmountRequired;if(!j)throw new T("missing_amount","Payment option missing amount");if(c&&BigInt(j)>BigInt(c))throw new T("amount_exceeds_max",`Payment amount ${j} exceeds maximum ${c}`);let Ee=Q(B.network,k);l("Checking balance...");try{let _=await k.getBalance(B,$,Ee),b=Number(j)/Math.pow(10,pe);if(_<b){let K=S(B.network,k.name);throw new T("insufficient_balance",`Insufficient balance on ${K}. Have $${_.toFixed(4)}, need $${b.toFixed(4)}`)}l(`Balance OK: $${_.toFixed(4)} >= $${b.toFixed(4)}`)}catch(_){if(_ instanceof T)throw _;l("Balance check failed (RPC error), proceeding with transaction attempt")}if(g&&!await g(B))throw new T("payment_rejected","Payment rejected by onPaymentRequired callback");l("Building transaction...");let z=await k.buildTransaction(B,$,Ee);l("Transaction signed");let X;k.name==="EVM"?X=JSON.parse(z.serialized):X={transaction:z.serialized};let fe=R,ee=C.resource;if(typeof C.resource=="string")try{let _=new URL(C.resource,fe).toString();_!==C.resource&&l("Resolved relative resource URL:",C.resource,"\u2192",_),ee=_}catch{ee=C.resource}else if(C.resource&&typeof C.resource=="object"&&"url"in C.resource){let _=C.resource;try{let b=new URL(_.url,fe).toString();b!==_.url&&(l("Resolved relative resource URL:",_.url,"\u2192",b),ee={..._,url:b})}catch{}}let ge={x402Version:B.x402Version??2,resource:ee,accepted:B,payload:X};z.extensions&&(ge.extensions=z.extensions);let Xe=btoa(JSON.stringify(ge));if(h)try{h(B,z.settlementProbe)}catch{}l("Retrying request with payment...");let _e=await d(R,{...E,headers:{...E?.headers||{},"PAYMENT-SIGNATURE":Xe,...M?{"X-Quote-Hash":M}:{}}});l("Retry response status:",_e.status);let te=Bt(_e,{network:B.network,amountAtomic:j,assetDecimals:pe});return te.extensions&&l("Settlement extensions:",Object.keys(te.extensions).join(", ")),_e}async function U(R,E){let[P,x]=await un(R,E);return H(P,x)}return{fetch:U}}import{PublicKey as go}from"@solana/web3.js";import{bytesToHex as St}from"@noble/hashes/utils";import Ir from"tweetnacl";import{PublicKey as Cr}from"@solana/web3.js";import{contextBoundVoucherV2Message as Or,finalVoucherV2Sequence as Vr,sessionRegisterMessage as Br,sessionVoucherV2AuthorizationNonce as Dr}from"@dexterai/vault/messages";import{deriveSessionPda as Mr}from"@dexterai/vault/session";import{sessionRegisterMessage as ln,sessionReplaceV1Message as wr,sessionRevokeMessage as vr,sessionVoucherV2Nonce as xr,sessionVoucherV2AuthorizationNonce as Rr,finalVoucherV2Sequence as Er,voucherV2SequenceOrdinal as _r,voucherPayloadMessage as dn,buildVoucherMessage as Pr}from"@dexterai/vault/messages";import{sha256 as Fr}from"@noble/hashes/sha256";var Kr=(1n<<64n)-1n;import{sha256 as Hr}from"@noble/hashes/sha256";import{bytesToHex as zr}from"@noble/hashes/utils";var mn="dexter-native-tab-v2-reservation/v1",Xr=`${mn}:`;import{deriveSessionPda as wo}from"@dexterai/vault/session";import{buildRegisterSessionKeyInstruction as Zr,buildRevokeSessionKeyInstruction as Qr,deriveSwigWalletAddress as eo}from"@dexterai/vault/instructions";import{buildSecp256r1VerifyInstruction as no}from"@dexterai/vault/precompile";import{DEXTER_VAULT_PROGRAM_ID as pn,SECP256R1_PROGRAM_ID as oo,INSTRUCTIONS_SYSVAR_ID as so}from"@dexterai/vault/constants";function Dt(r,e){let t=e??r.reservationReceipt;if((r.payload.sequenceNumber&2147483648)!==0&&!t)throw new Error("native_tab_v2_reservation_receipt_required");return Buffer.from(JSON.stringify({payload:r.payload,sessionPublicKey:St(r.sessionPublicKey),sessionRegistration:St(r.sessionRegistration),sessionSignature:St(r.sessionSignature),...t?{reservationReceipt:t}:{}}),"utf8").toString("base64")}function W(r){if(r instanceof Error){if(r.message&&r.message.length>0)return r.message;if(r.name&&r.name.length>0)return r.name}let e=String(r);return e.length>0?e:"unknown error"}async function He(r){let e="";try{e=(await r.clone().text()).slice(0,600)}catch{}let t=e.toLowerCase(),n=t.includes("settle")||t.includes("facilitator"),o=e;try{let a=JSON.parse(e),c=[a.error,a.detail,a.message].filter(s=>typeof s=="string"&&s.length>0);c.length>0&&(o=c.join(" \u2014 "))}catch{}return o||(o=`HTTP ${r.status}`),{reason:n?"settlement_failed":"merchant_rejected",detail:`merchant HTTP ${r.status}: ${o}`}}var at="Payment authorization was sent, but the merchant did not respond within the timeout. ",it=" Do not retry without checking \u2014 inspect the funding wallet for a transfer to the merchant before attempting payment again.";async function ct(r,e,t){if(!r)return{confirmed:!1,detail:at+"This payment scheme has no on-chain confirmation check, so the SDK cannot verify whether it settled."+it};try{if(r.kind==="solana"){let c=F(),s=t??c.getDefaultRpcUrl(e.caip2);if(!c.confirmSettlement)return Mt();let i=await c.confirmSettlement(r,s);return i.settled?{confirmed:!0,txSignature:i.txSignature}:Ut()}let n=me(),o=n.getDefaultRpcUrl(e.caip2);if(!n.confirmSettlement)return Mt();let a=await n.confirmSettlement(r,o);return a.settled?{confirmed:!0,txSignature:a.txSignature}:Ut()}catch(n){return{confirmed:!1,detail:at+`On-chain confirmation could not be completed (${W(n)}).`+it}}}function Ut(){return{confirmed:!1,detail:at+"On-chain confirmation found no matching settlement yet \u2014 the payment may still be pending, or may not have settled."+it}}function Mt(){return{confirmed:!1,detail:at+"The chain adapter does not support on-chain confirmation."+it}}import{keccak_256 as fn}from"@noble/hashes/sha3";import{bytesToHex as gn}from"@noble/hashes/utils";var lt=/^0x[0-9a-f]{64}$/i,$t=/^0x[0-9a-f]{40}$/i,hn=/^0x(?:0|[1-9a-f][0-9a-f]*)$/i,Kt=r=>`0x${gn(fn(new TextEncoder().encode(r)))}`,yn=Kt("AuthorizationUsed(address,bytes32)"),An=Kt("Transfer(address,address,uint256)"),wt=r=>`0x${r.slice(2).toLowerCase().padStart(64,"0")}`,V=(r,e)=>typeof r=="string"&&r.toLowerCase()===e.toLowerCase(),je=r=>!!r&&typeof r=="object"&&!Array.isArray(r),ut=r=>typeof r=="string"&&hn.test(r);function bn(r,e,t,n){let o;for(let a of["PAYMENT-RESPONSE","X-PAYMENT-RESPONSE"]){let c=r.headers.get(a);if(c===null)continue;let s=bt(c);if(!s||typeof s.transaction!="string"||!lt.test(s.transaction)||s.success!==void 0&&s.success!==!0||s.network!==void 0&&s.network!==e||s.settlementStatus!==void 0&&s.settlementStatus!=="settled"||[s.errorReason,s.errorCode,s.errorMessage].some(i=>i!==void 0&&i!=="")||s.payer!==void 0&&!V(s.payer,t)||[s.amountAtomic,s.attemptedAmountAtomic].some(i=>i!==void 0&&i!==n)||s.assetDecimals!==void 0&&s.assetDecimals!==6||s.success===!0&&s.network===e||o&&!V(s.transaction,o))return;o=s.transaction}return o}async function Sn(r,e){if(!r.ok||!r.body)throw new Error("RPC response unavailable");let t=r.body.getReader(),n=()=>{t.cancel().catch(()=>{})};e.addEventListener("abort",n,{once:!0});let o=[],a=0;try{for(;;){if(e.aborted)throw new Error("RPC confirmation aborted");let i=await t.read();if(i.done)break;if(a+=i.value.byteLength,a>1048576)throw new Error("RPC response too large");o.push(i.value)}let c=new Uint8Array(a),s=0;for(let i of o)c.set(i,s),s+=i.byteLength;return JSON.parse(new TextDecoder().decode(c))}finally{e.removeEventListener("abort",n),n()}}async function Lt(r,e,t,n){if(e.settlementStatus!=="unconfirmed"||t?.kind!=="eip3009"||n.scheme!=="exact"||n.extra?.assetTransferMethod!==void 0&&n.extra.assetTransferMethod!=="eip3009")return;let o=`eip155:${t.chainId}`,a=xe[o],c=O[o],s=n.amount??n.maxAmountRequired;if(!c||!a||n.network!==o||!V(t.asset,a)||!V(n.asset,t.asset)||!$t.test(t.from)||!t.to||!$t.test(t.to)||!V(n.payTo,t.to)||!s||!/^[0-9]+$/.test(s)||s!==t.amount||!lt.test(t.nonce))return;let i=bn(r,o,t.from,s);if(!i)return;let u=new AbortController,g,h=new Promise((l,d)=>{g=setTimeout(()=>{u.abort(),d(new Error("RPC confirmation timed out"))},5e3)}),y=0,A=async(l,d)=>{let f=++y,w=async()=>{let m=await fetch(c,{method:"POST",signal:u.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:f,method:l,params:d})}),p=await Sn(m,u.signal);if(!je(p)||p.jsonrpc!=="2.0"||p.id!==f||p.error)throw new Error("Invalid RPC response");return p.result};return Promise.race([w(),h])};try{let[l,d,f]=await Promise.all([A("eth_chainId",[]),A("eth_getTransactionReceipt",[i]),A("eth_getTransactionByHash",[i])]);if(!ut(l)||BigInt(l)!==BigInt(t.chainId)||!je(d)||!je(f)||d.status!=="0x1"||!V(d.transactionHash,i)||!V(f.hash,i)||typeof d.blockHash!="string"||!lt.test(d.blockHash)||!V(f.blockHash,d.blockHash)||!ut(d.blockNumber)||f.blockNumber!==d.blockNumber||!ut(d.transactionIndex)||f.transactionIndex!==d.transactionIndex||f.chainId!==void 0&&(!ut(f.chainId)||BigInt(f.chainId)!==BigInt(t.chainId)))return;let w=Number(BigInt(d.transactionIndex));if(!Number.isSafeInteger(w))return;let m=await A("eth_getBlockByNumber",[d.blockNumber,!1]);if(!je(m)||!V(m.hash,d.blockHash)||m.number!==d.blockNumber||!Array.isArray(m.transactions)||!V(m.transactions[w],i)||!Array.isArray(d.logs))return;let p=!1,v=!1;for(let S of d.logs){if(!je(S)||S.removed!==void 0&&S.removed!==!1||!V(S.blockHash,d.blockHash)||S.blockNumber!==d.blockNumber||!V(S.transactionHash,i)||S.transactionIndex!==d.transactionIndex||!Array.isArray(S.topics))return;if(V(S.address,t.asset)&&(V(S.topics[0],yn)&&S.topics.length===3&&V(S.topics[1],wt(t.from))&&V(S.topics[2],t.nonce)&&S.data==="0x"&&(p=!0),V(S.topics[0],An)&&V(S.topics[1],wt(t.from)))){if(v||S.topics.length!==3||!V(S.topics[2],wt(t.to))||typeof S.data!="string"||!lt.test(S.data)||BigInt(S.data)!==BigInt(s))return;v=!0}}if(!p||!v)return;e.settlementStatus="settled",e.amountAtomic=s,e.chainConfirmation={source:"eip3009_transaction",finality:"included",network:o,blockHash:d.blockHash,blockNumber:d.blockNumber,authorizationNonce:t.nonce}}catch{}finally{clearTimeout(g),u.abort()}}async function wn(r,e,t,n){let o;try{o=await n.signNextVoucher(t.amount)}catch(i){return n.voucherVersion!==1?{ok:!1,reason:"error",detail:`context-bound FINAL tab voucher was not safely released; retry or reconcile this tab before another payment rail is attempted (${i instanceof Error?i.message:String(i)})`}:null}let a=new Headers(e.headers??void 0);a.set("X-Tab-Voucher",Dt(o));let c={...e.redirect!==void 0?{redirect:e.redirect}:{},method:e.method??"GET",headers:a};e.signal&&(c.signal=e.signal),typeof e.body=="string"&&(c.body=e.body);let s;try{s=await fetch(r,c)}catch(i){return{ok:!1,reason:"error",detail:i?.message??String(i)}}return s.status===402?n.voucherVersion!==1?{ok:!1,reason:"error",detail:"seller refused an irrevocable FINAL tab voucher; its exact reservation must be reconciled before another payment rail is attempted"}:n.rollbackVoucher?.call(n,o)!==!0?{ok:!1,reason:"error",detail:"seller refused a V1 tab voucher but local rollback was unavailable or failed; another payment rail was not attempted to avoid double payment"}:null:s.ok?{ok:!0,paid:!0,response:s,amountPaid:t.amount,network:t.network}:{ok:!1,...await He(s)}}var Ft={version:2,async parseChallenge(r){return It(r)},async pay(r,e,t,n,o){if(We(t.extensions))return{ok:!1,reason:"no_payment_options",detail:"unsupported_required_payment_identifier"};if(o.tab){let m=t.options.find(p=>p.scheme==="tab"&&p.network.family==="svm"&&p.payTo===o.tab.counterparty);if(m){let p=await wn(r,e,m,o.tab);if(p)return p}}let a=t.options.filter(m=>!L(m,m.network.family));if(a.length===0)return{ok:!1,reason:"no_payment_options",detail:`no supported payment capability offered: ${t.options.map(m=>L(m,m.network.family)).join("; ")}`};let c=a.find(m=>m.network.family==="evm"?!!n.evm:m.network.family==="svm"?!!n.solana:!1);if(!c)return{ok:!1,reason:"unsupported_network"};let s=o.timeoutMs??15e3,i=o.responseTimeoutMs??12e4,u=new AbortController,g=setTimeout(()=>u.abort(),s),h=!1,y,A,l=(m,p)=>{h=!0,A=m,y=p,clearTimeout(g),g=setTimeout(()=>u.abort(),i)},d=st({wallets:n,preferredNetwork:c.network.caip2,maxAmountAtomic:o.maxAmountAtomic,fetch:globalThis.fetch,onPaymentDispatched:l}),f=e.signal?AbortSignal.any([e.signal,u.signal]):u.signal,w={...e.redirect!==void 0?{redirect:e.redirect}:{},method:e.method??"GET",headers:e.headers,signal:f};typeof e.body=="string"&&(w.body=e.body);try{let m=await d.fetch(r,w);if(clearTimeout(g),!h)return m.ok?{ok:!0,paid:!1,response:m}:{ok:!1,response:m,...await He(m)};let p=qe(m);p?.settlementStatus==="unconfirmed"&&A&&await Lt(m,p,y,A);let v=typeof p?.transaction=="string"?p.transaction:void 0;if(p?.settlementStatus!=="settled"){let S=p?.settlementStatus==="failed";return{ok:!1,reason:S?"settlement_failed":"payment_unconfirmed",detail:`${S?"Merchant reports settlement failure":"Settlement is unconfirmed"}${p?.errorReason||p?.errorCode?` (${p.errorReason??p.errorCode})`:""}. Recover or reconcile this same payment; do not create a new authorization.`,response:m,txSignature:v,paymentReceipt:p}}return m.ok?{ok:!0,paid:!0,response:m,amountPaid:A?.amount??A?.maxAmountRequired??c.amount,network:Z(A?.network??"")??c.network,txSignature:v,paymentReceipt:p}:{ok:!1,reason:"delivery_failed",detail:`Payment settled, but the merchant returned HTTP ${m.status}. Recover the result for this same payment; do not create a new authorization.`,response:m,txSignature:v,paymentReceipt:p}}catch(m){clearTimeout(g);let p=m;if(p?.name==="AbortError"){if(!h)return{ok:!1,reason:"timeout"};let v=await ct(y,c.network,o.solanaRpcUrl);return v.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:c.amount,network:c.network,txSignature:v.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:v.detail}}return h?{ok:!1,reason:"payment_unconfirmed",detail:`${p?.message??String(m)}. Recover or reconcile this same payment; do not create a new authorization.`}:{ok:!1,reason:"error",detail:p?.message??String(m)}}}};import{getAddress as vn}from"viem";var xn={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"}]};async function Rn(){let r=globalThis.crypto??(await import("crypto")).webcrypto,e=new Uint8Array(32);return r.getRandomValues(e),"0x"+Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}async function En(r,e,t){if(typeof r.signTypedData!="function")throw new Error("EVM wallet does not support signTypedData");let n=Math.floor(Date.now()/1e3),o=String(n-600),a=String(n+(e.maxTimeoutSeconds??60)),c={from:r.address,to:e.payTo,value:e.amount,validAfter:o,validBefore:a,nonce:await Rn()},s=Fe[e.network.caip2];if(s===void 0)throw new Error(`unknown chain id for network ${e.network.caip2}`);let i=e.extra,u=await r.signTypedData({domain:{name:i.name,version:i.version,chainId:s,verifyingContract:vn(e.asset)},types:xn,primaryType:"TransferWithAuthorization",message:c});return{payment:{x402Version:1,scheme:e.scheme,network:t,payload:{signature:u,authorization:c}},settlementProbe:{kind:"eip3009",from:c.from,nonce:c.nonce,asset:e.asset,chainId:s}}}async function dt(r,e,t){try{let n;for(let o of r.options){let a=o.network.family==="evm"&&!!e.evm||o.network.family==="svm"&&!!e.solana;if(o.scheme!=="exact"){a&&(n=o.scheme);continue}if(o.network.family==="evm"&&e.evm){let c=await e.evm;return await _n(o,c,t)}if(o.network.family==="svm"&&e.solana){let c=await e.solana;return await Pn(o,c,t)}}return n!==void 0?{ok:!1,reason:"merchant_rejected",detail:`v1 supports only the 'exact' scheme, got '${n}'`}:{ok:!1,reason:"unsupported_network"}}catch(n){return{ok:!1,reason:"error",detail:W(n)}}}async function _n(r,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(r.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};let n=r.extra??{},o=n.name,a=n.version;if(typeof o!="string"||o.length===0||typeof a!="string"||a.length===0)return{ok:!1,reason:"merchant_rejected",detail:"v1 challenge missing exact-scheme EIP-712 domain (extra.name / extra.version)"};let c=r.network.bare,{payment:s,settlementProbe:i}=await En(e,r,c);return{ok:!0,headerValue:Buffer.from(JSON.stringify(s),"utf8").toString("base64"),option:r,settlementProbe:i}}async function Pn(r,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(r.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};if(r.scheme!=="exact")return{ok:!1,reason:"merchant_rejected",detail:`v1 SVM supports only the 'exact' scheme, got '${r.scheme}'`};let n=r.extra??{};if(typeof n.feePayer!="string"||n.feePayer.length===0)return{ok:!1,reason:"merchant_rejected",detail:"v1 SVM challenge missing extra.feePayer (required as the transaction fee payer)"};let o=r.network.bare,a={x402Version:1,scheme:r.scheme,network:o,asset:r.asset,payTo:r.payTo,amount:r.amount,maxAmountRequired:r.amount,maxTimeoutSeconds:r.maxTimeoutSeconds??60,extra:n},s=await F().buildTransaction(a,e,t.solanaRpcUrl),i={x402Version:1,scheme:r.scheme,network:o,payload:{transaction:s.serialized}};return{ok:!0,headerValue:Buffer.from(JSON.stringify(i),"utf8").toString("base64"),option:r,settlementProbe:s.settlementProbe}}function Tn(r){let e=[];for(let t of r){if(!t||typeof t!="object")continue;let n=t,o=Z(String(n.network??""));o&&e.push({scheme:String(n.scheme??"exact"),network:o,amount:String(n.maxAmountRequired??n.amount??"0"),asset:String(n.asset??""),payTo:String(n.payTo??""),maxTimeoutSeconds:typeof n.maxTimeoutSeconds=="number"?n.maxTimeoutSeconds:void 0,extra:n.extra&&typeof n.extra=="object"?n.extra:void 0})}return e}var Wt={version:1,async parseChallenge(r){if(r.headers.get("payment-required"))return null;let e;try{e=await r.clone().json()}catch{return null}let t=Array.isArray(e.accepts)?e.accepts:[];if(t.length===0)return null;let n=Tn(t);return n.length===0?null:{x402Version:1,options:n}},async pay(r,e,t,n,o){let a,c=new AbortController,s=!1,i,u;try{let g=o.timeoutMs??15e3;a=setTimeout(()=>c.abort(),g);let h=await dt(t,n,o);if(!h.ok)return{ok:!1,reason:h.reason,detail:h.detail};let y=h.headerValue,A=h.option;u=A,i=h.settlementProbe;let l=new Headers(e.headers??void 0);l.set("X-PAYMENT",y);let d=e.signal!=null?AbortSignal.any([e.signal,c.signal]):c.signal,f={...e.redirect!==void 0?{redirect:e.redirect}:{},method:e.method,headers:l,signal:d};typeof e.body=="string"&&(f.body=e.body),s=!0,clearTimeout(a);let w=o.responseTimeoutMs??12e4;a=setTimeout(()=>c.abort(),w);let m=await fetch(r,f);return m.ok?{ok:!0,paid:!0,response:m,amountPaid:A.amount,network:A.network,txSignature:In(m)}:{ok:!1,...await He(m)}}catch(g){if(g instanceof Error&&g.name==="AbortError"){if(!s)return{ok:!1,reason:"timeout"};let h=await ct(i,u.network,o.solanaRpcUrl);return h.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:u.amount,network:u.network,txSignature:h.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:h.detail}}return{ok:!1,reason:"error",detail:W(g)}}finally{a!==void 0&&clearTimeout(a)}}};function In(r){let e=r.headers.get("x-payment-response")??r.headers.get("X-PAYMENT-RESPONSE");if(e)try{let t=JSON.parse(Buffer.from(e,"base64").toString("utf8")),n=t.transaction??t.txHash??t.transactionHash;return typeof n=="string"?n:void 0}catch{return}}import*as qt from"tweetnacl";import{Keypair as ze,VersionedTransaction as Nn,Transaction as Cn}from"@solana/web3.js";var Re=Symbol.for("x402:keypair");async function vt(r){let e;if(typeof r=="string"){let t;try{let n=await import("bs58"),o=n.decode??n.default?.decode;if(!o)throw new Error("decode not found");t=o}catch{throw new Error('The "bs58" package is required for base58 private keys. Install it with: npm install bs58')}try{let n=t(r);e=ze.fromSecretKey(n)}catch{try{let o=JSON.parse(r);if(Array.isArray(o))e=ze.fromSecretKey(Uint8Array.from(o));else throw new Error("Invalid private key format")}catch{throw new Error("Invalid private key. Expected base58 string or JSON array of bytes.")}}}else if(Array.isArray(r))e=ze.fromSecretKey(Uint8Array.from(r));else if(r instanceof Uint8Array)e=ze.fromSecretKey(r);else throw new Error("Invalid private key type. Expected string, number[], or Uint8Array.");return{publicKey:{toBase58:()=>e.publicKey.toBase58()},signTransaction:async t=>{if(t instanceof Nn)return t.sign([e]),t;if(t instanceof Cn)return t.sign(e),t;throw new Error("Unknown transaction type")},[Re]:e}}function kn(r){if(!r||typeof r!="object")return!1;let e=r;return Re in e&&e[Re]instanceof ze&&"publicKey"in e&&"signTransaction"in e}function mt(r){let e=r.evm;if(e&&typeof e.signMessage=="function"&&typeof e.address=="string")return{address:e.address,signMessage:e.signMessage};let t=r.solana;if(t){let n=t[Re];if(n&&n.secretKey&&n.publicKey)return{publicKey:n.publicKey,signMessage:async o=>qt.sign.detached(o,n.secretKey)}}return null}import{decodePaymentRequiredHeader as On}from"@x402/core/http";var Ht=[Ft,Wt];async function jt(r){for(let e of Ht)if(await e.parseChallenge(r.clone()))return e;return null}async function Vn(r){let e=async(o,a)=>({response:await fetch(o,a),paymentUrl:o,paymentInit:a}),t=mt(r);if(!t)return e;let n;try{n=await import("@x402/extensions/sign-in-with-x")}catch(o){return console.warn(`[x402] SIW-X unavailable \u2014 @x402/extensions failed to load; SIW-X merchants will not authenticate. ${W(o)}`),e}return async(o,a)=>{let c=new Request(o,a),s=c.clone(),i=await fetch(c),u={response:i,paymentUrl:o,paymentInit:a};if(i.status!==402)return u;let g=i.headers.get("PAYMENT-REQUIRED");if(!g)return u;let h=On(g),y=h.extensions?.[n.SIGN_IN_WITH_X];if(!y?.supportedChains)return u;if(s.headers.has(n.SIGN_IN_WITH_X))throw new Error("SIWX authentication already attempted");let A=h.accepts?.[0]?.network,l=y.supportedChains.find(v=>v.chainId===A);if(!l)return u;let d=i.url||c.url;if(i.redirected&&!["GET","HEAD"].includes(c.method))throw new Error("SIWX cannot safely replay a redirected non-GET/HEAD request; use the final resource URL");let f={...y.info,chainId:l.chainId,type:l.type};if(n.assertSIWxChallengeBoundToOrigin(f,d),i.redirected||new URL(d).origin!==new URL(c.url).origin)for(let v of["authorization","cookie","cookie2","proxy-authorization","host"])s.headers.delete(v);let w=new Headers(s.headers),m={response:i,paymentUrl:d,paymentInit:{...a,headers:Object.fromEntries(w),redirect:"error"}};try{let v=await n.createSIWxPayload(f,t,d);s.headers.set(n.SIGN_IN_WITH_X,n.encodeSIWxHeader(v))}catch{return m}let p=new Request(new Request(d,s),{redirect:"error"});return{...m,response:await fetch(p)}}}async function zt(r,e,t,n){if(e.body!==void 0&&e.body!==null&&typeof e.body!="string")return{ok:!1,reason:"error",detail:"payAndFetch requires a string body; non-string bodies (Buffer, FormData, URLSearchParams, ReadableStream) cannot be safely re-sent on the paid retry"};let o,a=r,c=e;try{let i=await(await Vn(t))(r,{...e});o=i.response,a=i.paymentUrl,c=i.paymentInit}catch(s){return{ok:!1,reason:"error",detail:W(s)}}if(o.status!==402)return{ok:!0,paid:!1,response:o};for(let s of Ht){let i=await s.parseChallenge(o.clone());if(i)return s.pay(a,c,i,t,n)}return{ok:!1,reason:"no_payment_options"}}async function xt(r){let e;try{e=(await import("viem/accounts")).privateKeyToAccount}catch{throw new Error("EVM wallet support requires viem as a peer dependency. Install with: npm install viem")}let t=r.startsWith("0x")?r:`0x${r}`,n=e(t);return{address:n.address,signTypedData:o=>n.signTypedData(o),signTransaction:o=>n.signTransaction({to:o.to,data:o.data,chainId:o.chainId,gas:o.gas,gasPrice:o.gasPrice,nonce:o.nonce,type:"legacy"}),signMessage:o=>n.signMessage({message:o.message})}}function Bn(r){if(!r||typeof r!="object")return!1;let e=r;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")&&"signTypedData"in e&&typeof e.signTypedData=="function"}function Rt(r){let e=qe(r);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function Dn(r){let e=Rt(r);if(e?.recommendations?.length)return e.recommendations}async function Un(r){let t=Rt(r)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function Xt(r,e){let{walletPrivateKey:t,evmPrivateKey:n,preferredNetwork:o,rpcUrls:a,maxAmountAtomic:c,verbose:s,accessPass:i,onPaymentRequired:u}=e;if(!t&&!n)throw new Error("At least one wallet private key is required (walletPrivateKey or evmPrivateKey)");let g={},h=[];t&&h.push(vt(t).then(f=>{g.solana=f}).catch(f=>{console.warn(`[x402] Solana wallet init failed: ${f.message}`)})),n&&h.push(xt(n).then(f=>{g.evm=f}).catch(f=>{console.warn(`[x402] EVM wallet init failed: ${f.message}`)}));let y=h.length>0?Promise.all(h):null,l=st({wallets:g,preferredNetwork:o,rpcUrls:a,maxAmountAtomic:c,fetch:r,verbose:s,accessPass:i,onPaymentRequired:u}),d=l.fetch.bind(l);return y?(async(f,w)=>(await y,d(f,w))):d}function Mn(r){let{budget:e,allowedDomains:t,onPaymentRequired:n,...o}=r,a=parseFloat(e.total),c=e.perRequest?parseFloat(e.perRequest):1/0,s=e.perHour?parseFloat(e.perHour):1/0;if(isNaN(a)||a<=0)throw new Error("budget.total must be a positive number");let i=[],u=0;function g(){return i.reduce((l,d)=>l+d.amount,0)}function h(){let l=Date.now()-36e5;return i.filter(d=>d.timestamp>=l).reduce((d,f)=>d+f.amount,0)}let y=Xt(fetch,{...o,onPaymentRequired:async l=>{let d=l.extra?.decimals??6,f=Number(l.amount)/Math.pow(10,d);if(f>c)throw new T("amount_exceeds_max",`$${f.toFixed(4)} exceeds per-request limit of $${c.toFixed(2)}`);let w=g();if(w+f>a)throw new T("amount_exceeds_max",`Budget exceeded. Spent $${w.toFixed(2)} of $${a.toFixed(2)}, payment: $${f.toFixed(4)}`);let m=h();if(m+f>s)throw new T("amount_exceeds_max",`Hourly limit ($${s.toFixed(2)}) exceeded. Spent $${m.toFixed(2)} this hour`);return u=f,n?n(l):!0}});return{fetch:(async(l,d)=>{let f=typeof l=="string"?l:l instanceof URL?l.href:l.url,w="unknown";try{w=new URL(f).hostname}catch{}if(t&&!t.some(p=>w===p||w.endsWith(`.${p}`)))throw new T("payment_rejected",`Domain "${w}" not in allowed domains`);u=0;let m=await y(l,d);if(u>0){let p="unknown",v=m.headers.get("PAYMENT-RESPONSE");if(v)try{p=JSON.parse(atob(v)).network||p}catch{}i.push({amount:u,domain:w,network:p,timestamp:Date.now()}),u=0}return m}),get spent(){return`$${g().toFixed(2)}`},get remaining(){return`$${(a-g()).toFixed(2)}`},get payments(){return i.length},get spentAmount(){return g()},get remainingAmount(){return a-g()},get ledger(){return i},get hourlySpend(){return h()},reset(){i=[]}}}import{capabilitySearch as $n}from"@dexterai/x402-core";export{Y as BASE_MAINNET,Pt as DEXTER_FACILITATOR_URL,Re as KEYPAIR_SYMBOL,J as SOLANA_MAINNET,Ze as USDC_MINT,T as X402Error,dt as buildV1PaymentHeader,$n as capabilitySearch,Bt as capturePaymentReceipt,Mn as createBudgetAccount,me as createEvmAdapter,xt as createEvmKeypairWallet,vt as createKeypairWallet,F as createSolanaAdapter,jt as detectStrategy,Un as fireImpressionBeacon,qe as getPaymentReceipt,Rt as getSponsoredAccessInfo,Dn as getSponsoredRecommendations,Bn as isEvmKeypairWallet,kn as isKeypairWallet,zt as payAndFetch,Z as toNetworkRef,mt as toSiwxSigner};
@@ -1 +1 @@
1
- "use strict";var St=Object.create;var Ke=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var Tt=Object.getOwnPropertyNames;var wt=Object.getPrototypeOf,bt=Object.prototype.hasOwnProperty;var Rt=(r,e)=>{for(var t in e)Ke(r,t,{get:e[t],enumerable:!0})},it=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Tt(e))!bt.call(r,s)&&s!==t&&Ke(r,s,{get:()=>e[s],enumerable:!(n=xt(e,s))||n.enumerable});return r};var Fe=(r,e,t)=>(t=r!=null?St(wt(r)):{},it(e||!r||!r.__esModule?Ke(t,"default",{value:r,enumerable:!0}):t,r)),_t=r=>it(Ke({},"__esModule",{value:!0}),r);var Ut={};Rt(Ut,{X402Error:()=>_,fireImpressionBeacon:()=>tt,getSponsoredRecommendations:()=>et,useX402Payment:()=>At});module.exports=_t(Ut);var I=require("react");var H="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Re="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",je="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",ne=H,_e=Re,Ne=je,j="eip155:8453",me="eip155:84532",fe="eip155:42161",ge="eip155:137",he="eip155:10",ye="eip155:43114",Ae="eip155:56",re="eip155:480",se="eip155:143",oe="eip155:4663",ae="eip155:1187947933",ie="eip155:324705682",Ee="eip155:1",ce=j,He=me,Pe=fe,Ce=ge,Ie=he,ve=ye,Oe=Ae,De=re,Be=se,Me=oe,Ue=ae,ke=ie,Le=Ee,We="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",ct="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",Ve="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",nt="0x55d398326f99059fF775485246999027B3197955",Xe="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",rt="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",Je={[Ae]:Xe,[j]:Ve,[me]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[fe]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[ge]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[he]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[ye]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[re]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[se]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[oe]:rt,[ae]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[ie]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[Ee]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},Ge={[nt]:{symbol:"USDT",decimals:18},[Xe]:{symbol:"USDC",decimals:18}};var Ye={[re]:{name:"USDC",version:"2"},[se]:{name:"USDC",version:"2"},[oe]:{name:"Global Dollar",version:"1"},[ae]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[ie]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}},Z="0x000000000022D473030F116dDEE9F6B43aC78BA3",$e="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",st={[Ae]:56,[j]:8453,[me]:84532,[fe]:42161,[ge]:137,[he]:10,[ye]:43114,[re]:480,[se]:143,[oe]:4663,[ae]:1187947933,[ie]:324705682,[Ee]:1},pe={[H]:"https://api.dexter.cash/api/solana/rpc",[Re]:"https://api.devnet.solana.com",[je]:"https://api.testnet.solana.com"},L={[Ae]:"https://api.dexter.cash/api/evm/bsc/rpc",[j]:"https://api.dexter.cash/api/base/rpc",[me]:"https://sepolia.base.org",[fe]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[ge]:"https://api.dexter.cash/api/evm/polygon/rpc",[he]:"https://api.dexter.cash/api/evm/optimism/rpc",[ye]:"https://api.dexter.cash/api/evm/avalanche/rpc",[re]:"https://worldchain-mainnet.g.alchemy.com/public",[se]:"https://rpc.monad.xyz",[oe]:"https://rpc.mainnet.chain.robinhood.com",[ae]:"https://skale-base.skalenodes.com/v1/base",[ie]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[Ee]:"https://eth.llamarpc.com"};var _=class r extends Error{code;details;constructor(e,t,n){super(t),this.name="X402Error",this.code=e,this.details=n,Object.setPrototypeOf(this,r.prototype)}};function Se(r,e){let t=r.scheme??"exact";if(t!=="exact"&&!(e==="evm"&&t==="exact-approval"))return`Unsupported payment scheme: ${t}`;let n=r.extra?.paymentFlow;if(n!==void 0&&n!=="authorization")return`Unsupported payment flow: ${String(n)}`;let s=r.extra?.assetTransferMethod;if(s!==void 0&&(typeof s!="string"||!(t==="exact-approval"?[]:e==="evm"?["eip3009","permit2"]:["default"]).includes(s)))return`Unsupported payment asset transfer method: ${String(s)}`}function ot(r){let e=r?.["payment-identifier"];if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.info;return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.required===!0}var pt=[{caip2:"eip155:8453",bare:"base",family:"evm"},{caip2:"eip155:1",bare:"ethereum",family:"evm"},{caip2:"eip155:137",bare:"polygon",family:"evm"},{caip2:"eip155:42161",bare:"arbitrum",family:"evm"},{caip2:"eip155:10",bare:"optimism",family:"evm"},{caip2:"eip155:43114",bare:"avalanche",family:"evm"},{caip2:"eip155:56",bare:"bsc",family:"evm"},{caip2:"eip155:480",bare:"world",family:"evm"},{caip2:"eip155:143",bare:"monad",family:"evm"},{caip2:"eip155:4663",bare:"robinhood",family:"evm"},{caip2:"eip155:1187947933",bare:"skale-base",family:"evm"},{caip2:"eip155:324705682",bare:"skale-base-sepolia",family:"evm"},{caip2:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",bare:"solana",family:"svm"}],Ft=new Map(pt.map(r=>[r.caip2.toLowerCase(),r])),jt=new Map(pt.map(r=>[r.bare.toLowerCase(),r]));function lt(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-(e.length%4||4))%4);return JSON.parse(Buffer.from(t,"base64").toString("utf8"))}var D=require("@solana/web3.js"),B=require("@solana/spl-token");var Nt=12e3,Pt=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 ze=class{name="Solana";networks=[ne,_e,Ne];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]:pe[e]?pe[e]:e==="solana"?pe[ne]:e==="solana-devnet"?pe[_e]:e==="solana-testnet"?pe[Ne]:pe[ne]}getAddress(e){return V(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return V(e)?e.publicKey!==null:!1}async getBalance(e,t,n){if(!V(t)||!t.publicKey)return 0;let s=n||this.getDefaultRpcUrl(e.network),o=new D.Connection(s,"confirmed"),i=new D.PublicKey(t.publicKey.toBase58()),a=new D.PublicKey(e.asset);try{let p=(await o.getAccountInfo(a,"confirmed"))?.owner.toBase58()===B.TOKEN_2022_PROGRAM_ID.toBase58()?B.TOKEN_2022_PROGRAM_ID:B.TOKEN_PROGRAM_ID,y=await(0,B.getAssociatedTokenAddress)(a,i,!1,p),w=await(0,B.getAccount)(o,y,void 0,p),S=e.extra?.decimals??6;return Number(w.amount)/Math.pow(10,S)}catch(c){if(c&&typeof c=="object"&&"name"in c&&(c.name==="TokenAccountNotFoundError"||c.name==="TokenInvalidAccountOwnerError"))return 0;throw c}}async buildTransaction(e,t,n){let s=Se(e,"svm");if(s)throw new Error(s);if(!V(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let o=n||this.getDefaultRpcUrl(e.network),i=new D.Connection(o,"confirmed"),a=new D.PublicKey(t.publicKey.toBase58()),{payTo:c,asset:p,extra:y}=e,w=e.amount??e.maxAmountRequired;if(!w)throw new Error("Missing amount in payment requirements");if(!y?.feePayer)throw new Error("Missing feePayer in payment requirements");let S=new D.PublicKey(y.feePayer),b=new D.PublicKey(p),l=new D.PublicKey(c);this.log("Building transaction:",{from:a.toBase58(),to:c,amount:w,asset:p,feePayer:y.feePayer});let R=[];R.push(D.ComputeBudgetProgram.setComputeUnitLimit({units:Nt})),R.push(D.ComputeBudgetProgram.setComputeUnitPrice({microLamports:Pt}));let M=await i.getAccountInfo(b,"confirmed");if(!M)throw new Error(`Token mint ${p} not found`);let q=M.owner.toBase58()===B.TOKEN_2022_PROGRAM_ID.toBase58()?B.TOKEN_2022_PROGRAM_ID:B.TOKEN_PROGRAM_ID,W=await(0,B.getMint)(i,b,void 0,q);typeof y?.decimals=="number"&&W.decimals!==y.decimals&&this.log(`Decimals mismatch: requirements say ${y.decimals}, mint says ${W.decimals}`);let P=await(0,B.getAssociatedTokenAddress)(b,a,!1,q),C=await(0,B.getAssociatedTokenAddress)(b,l,!0,q);if(!await i.getAccountInfo(P,"confirmed"))throw new Error(`No token account found for ${p}. Please ensure you have USDC in your wallet.`);if(!await i.getAccountInfo(C,"confirmed"))throw new Error(`Seller token account not found. The seller (${c}) must have a USDC account.`);let K=BigInt(w);R.push((0,B.createTransferCheckedInstruction)(P,b,C,a,K,W.decimals,[],q));let{blockhash:F}=await i.getLatestBlockhash("confirmed"),U=new D.TransactionMessage({payerKey:S,recentBlockhash:F,instructions:R}).compileToV0Message(),g=new D.VersionedTransaction(U),A=await t.signTransaction(g);return this.log("Transaction signed successfully"),{serialized:Buffer.from(A.serialize()).toString("base64"),settlementProbe:{kind:"solana",sourceAta:P.toBase58(),destinationAta:C.toBase58(),asset:p,amount:w,blockhash:F}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let n=new D.Connection(t,"confirmed"),s=new D.PublicKey(e.destinationAta),o=await n.getSignaturesForAddress(s,{limit:25});if(o.length===0)return{settled:!1};let i=BigInt(e.amount);for(let a of o){if(a.err)continue;let c=await n.getTransaction(a.signature,{commitment:"confirmed",maxSupportedTransactionVersion:0});if(!c?.meta)continue;let p=c.transaction.message.getAccountKeys().keySegments().flat(),y=c.meta.preTokenBalances??[],w=c.meta.postTokenBalances??[];for(let S of w){if(S.mint!==e.asset)continue;let b=p[S.accountIndex];if(!b||!b.equals(s))continue;let l=y.find(q=>q.accountIndex===S.accountIndex),R=BigInt(l?.uiTokenAmount.amount??"0");if(BigInt(S.uiTokenAmount.amount??"0")-R===i)return{settled:!0,txSignature:a.signature}}}return{settled:!1}}};function xe(r){return new ze(r)}var Ct={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"validAfter",type:"uint256"}]},dt=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function X(r){if(!r||typeof r!="object")return!1;let e=r;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var Qe=class{name="EVM";networks=[Oe,ce,He,Le,Pe,Ce,Ie,ve,De,Be,Me,Ue,ke];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:evm]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="base"||e==="bsc"||e==="ethereum"||e==="arbitrum"||e==="polygon"||e==="optimism"||e==="avalanche"||e==="world"||e==="monad"||e==="robinhood"||e==="skale-base"||e==="skale-base-sepolia"||e.startsWith("eip155:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:L[e]?L[e]:e==="base"?L[ce]:e==="bsc"?L[Oe]:e==="ethereum"?L[Le]:e==="arbitrum"?L[Pe]:e==="polygon"?L[Ce]:e==="optimism"?L[Ie]:e==="avalanche"?L[ve]:e==="world"?L[De]:e==="monad"?L[Be]:e==="robinhood"?L[Me]:e==="skale-base"?L[Ue]:e==="skale-base-sepolia"?L[ke]:L[ce]}getAddress(e){return X(e)?e.address:null}isConnected(e){return X(e)?!!e.address:!1}getChainId(e){if(st[e])return st[e];if(e.startsWith("eip155:")){let t=e.split(":")[1];return parseInt(t,10)}return e==="base"?8453:e==="bsc"?56:e==="ethereum"?1:e==="arbitrum"?42161:e==="polygon"?137:e==="optimism"?10:e==="avalanche"?43114:e==="world"?480:e==="monad"?143:e==="robinhood"?4663:e==="skale-base"?1187947933:e==="skale-base-sepolia"?324705682:8453}async getBalance(e,t,n){if(!X(t)||!t.address)return 0;let s=n||this.getDefaultRpcUrl(e.network);try{let o=this.encodeBalanceOf(t.address),i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:e.asset,data:o},"latest"]})});if(!i.ok)throw new Error(`RPC request failed: ${i.status}`);let a=await i.json();if(a.error)throw new Error(`RPC error: ${JSON.stringify(a.error)}`);if(!a.result||a.result==="0x")return 0;let c=BigInt(a.result),p=e.extra?.decimals??6;return Number(c)/Math.pow(10,p)}catch(o){throw o}}encodeBalanceOf(e){let t="0x70a08231",n=e.slice(2).toLowerCase().padStart(64,"0");return t+n}async confirmSettlement(e,t){if(e.kind==="eip3009"){let n="0xe94a0102",s=e.from.slice(2).toLowerCase().padStart(64,"0"),o=e.nonce.slice(2).toLowerCase().padStart(64,"0"),i=n+s+o,a=await this.ethCall(t,e.asset,i);return{settled:BigInt(a)!==0n}}if(e.kind==="permit2"){let n="0x4fe02b44",s=BigInt(e.nonce),o=s>>8n,i=s&0xffn,a=e.from.slice(2).toLowerCase().padStart(64,"0"),c=o.toString(16).padStart(64,"0"),p=n+a+c,y=await this.ethCall(t,Z,p);return{settled:(BigInt(y)>>i&1n)===1n}}throw new Error(`EvmAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`)}async ethCall(e,t,n){let s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:n},"latest"]})});if(!s.ok)throw new Error(`RPC request failed: ${s.status}`);let o=await s.json();if(o.error)throw new Error(`RPC error: ${JSON.stringify(o.error)}`);if(!o.result||o.result==="0x")throw new Error("RPC returned an empty result");return o.result}async buildTransaction(e,t,n){let s=Se(e,"evm");if(s)throw new Error(s);if(!X(t))throw new Error("Invalid EVM wallet");if(!t.address)throw new Error("Wallet not connected");if(e.scheme==="exact-approval")return this.buildApprovalTransaction(e,t,n);if(e.extra?.assetTransferMethod==="permit2")return this.buildPermit2Transaction(e,t,n);let{payTo:o,asset:i,extra:a}=e,c=e.amount??e.maxAmountRequired;if(!c)throw new Error("Missing amount in payment requirements");this.log("Building EVM transaction:",{from:t.address,to:o,amount:c,asset:i,network:e.network});let p=this.getChainId(e.network),y=Ye[`eip155:${p}`],w={name:a?.name??y?.name??"USD Coin",version:a?.version??y?.version??"2",chainId:BigInt(p),verifyingContract:i},S={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},b=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(b);let l="0x"+[...b].map(C=>C.toString(16).padStart(2,"0")).join(""),R=Math.floor(Date.now()/1e3),M={from:t.address,to:o,value:c,validAfter:String(R-600),validBefore:String(R+(e.maxTimeoutSeconds||60)),nonce:l},q={from:t.address,to:o,value:BigInt(c),validAfter:BigInt(R-600),validBefore:BigInt(R+(e.maxTimeoutSeconds||60)),nonce:l};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let W=await t.signTypedData({domain:w,types:S,primaryType:"TransferWithAuthorization",message:q});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:M,signature:W}),signature:W,settlementProbe:{kind:"eip3009",from:t.address,nonce:l,asset:i,chainId:p}}}async buildApprovalTransaction(e,t,n){let{payTo:s,asset:o,extra:i}=e,a=e.amount??e.maxAmountRequired;if(!a)throw new Error("Missing amount in payment requirements");let c=i?.facilitatorContract;if(!c)throw new Error("exact-approval scheme requires extra.facilitatorContract from the facilitator. The /supported endpoint should provide this.");if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building approval-based transaction:",{from:t.address,to:s,amount:a,asset:o,network:e.network,facilitatorContract:c});let p=n||this.getDefaultRpcUrl(e.network),y=i?.fee??"0",w=BigInt(a)+BigInt(y),S=await this.readAllowance(p,o,t.address,c);if(S<w){if(!t.sendTransaction)throw new Error("BSC payments require a wallet that supports sendTransaction for the one-time token approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.");let U=this.calculateApprovalAmount(a,y,i?.approvalStrategy);this.log(`Approving ${U} for ${c} (current allowance: ${S})`);let g=await t.sendTransaction({to:o,data:this.encodeApprove(c,U),value:0n});this.log(`Approval tx sent: ${g}`),await this.waitForReceipt(p,g),this.log("Approval confirmed")}else this.log("Sufficient allowance, skipping approval");let b=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(b);let l=[...b].reduce((U,g)=>U*256n+BigInt(g),0n).toString(),R=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(R);let M="0x"+[...R].map(U=>U.toString(16).padStart(2,"0")).join(""),W=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),P=i?.eip712Domain,C=P?{name:P.name,version:P.version,chainId:BigInt(P.chainId),verifyingContract:P.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:c},T=i?.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:s,token:o,amount:BigInt(a),fee:BigInt(y),nonce:BigInt(l),deadline:BigInt(W),paymentId:M},K=await t.signTypedData({domain:C,types:T,primaryType:"Payment",message:$});this.log("EIP-712 Payment signature obtained");let F={from:t.address,to:s,token:o,amount:a,fee:y,nonce:l,deadline:W,paymentId:M,signature:K};return{serialized:JSON.stringify(F),signature:K}}async buildPermit2Transaction(e,t,n){let{payTo:s,asset:o}=e,i=e.amount??e.maxAmountRequired;if(!i)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:s,amount:i,asset:o,network:e.network});let a=n||this.getDefaultRpcUrl(e.network),c=await this.readAllowance(a,o,t.address,Z),p;if(c<BigInt(i)){let C=this.encodeApprove(Z,dt);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${c})`);let T=this.getChainId(e.network),$=await this.readGasPrice(a),K=await this.readNonce(a,t.address),F=await t.signTransaction({to:o,data:C,chainId:T,gas:50000n,gasPrice:$,nonce:K});p={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:o,spender:Z,amount:dt.toString(),signedTransaction:F,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${c})`);let T=await t.sendTransaction({to:o,data:C,value:0n});this.log(`Permit2 approval tx sent: ${T}`),await this.waitForReceipt(a,T),this.log("Permit2 approval confirmed")}else throw new Error("Permit2 payments require a wallet that supports signTransaction or sendTransaction for the one-time Permit2 approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.")}else this.log("Sufficient Permit2 allowance, skipping approval");let y=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(y);let w=[...y].reduce((C,T)=>C*256n+BigInt(T),0n),S=Math.floor(Date.now()/1e3),b=S-600,l=S+(e.maxTimeoutSeconds||300),R=this.getChainId(e.network),M={name:"Permit2",chainId:BigInt(R),verifyingContract:Z},q={permitted:{token:o,amount:BigInt(i)},spender:$e,nonce:w,deadline:BigInt(l),witness:{to:s,validAfter:BigInt(b)}},W=await t.signTypedData({domain:M,types:Ct,primaryType:"PermitWitnessTransferFrom",message:q});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let P={signature:W,permit2Authorization:{from:t.address,permitted:{token:o,amount:i},spender:$e,nonce:w.toString(),deadline:String(l),witness:{to:s,validAfter:String(b)}}};return{serialized:JSON.stringify(P),signature:W,extensions:p,settlementProbe:{kind:"permit2",from:t.address,nonce:w.toString(),chainId:R}}}async readAllowance(e,t,n,s){let o="0xdd62ed3e",i=n.slice(2).toLowerCase().padStart(64,"0"),a=s.slice(2).toLowerCase().padStart(64,"0"),c=o+i+a;try{let y=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:c},"latest"]})})).json();return y.error||!y.result||y.result==="0x"?0n:BigInt(y.result)}catch{return 0n}}encodeApprove(e,t){let n="0x095ea7b3",s=e.slice(2).toLowerCase().padStart(64,"0"),o=t.toString(16).padStart(64,"0");return n+s+o}async waitForReceipt(e,t,n=3e4){let s=Date.now();for(;Date.now()-s<n;){try{let i=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(i.result){if(i.result.status==="0x0")throw new Error(`Approval transaction reverted: ${t}`);return}}catch(o){if(o instanceof Error&&o.message.includes("reverted"))throw o}await new Promise(o=>setTimeout(o,2e3))}throw new Error(`Approval transaction receipt timeout after ${n}ms: ${t}`)}async readGasPrice(e){try{let n=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_gasPrice",params:[]})})).json();return n.result?BigInt(n.result):50000000n}catch{return 50000000n}}async readNonce(e,t){try{let s=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 s.result?parseInt(s.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,n){let s=BigInt(e)+BigInt(t);if(!n||n.mode==="exact")return s;let o=BigInt(n.defaultMultiple??10),i=s*o;if(n.maxCapUsd){let a=this.inferDecimals(e),c=BigInt(Math.floor(n.maxCapUsd*Math.pow(10,a)));if(i>c)return c}if(n.exactAboveUsd){let a=this.inferDecimals(e),c=BigInt(Math.floor(n.exactAboveUsd*Math.pow(10,a)));if(BigInt(e)>c)return s}return i}inferDecimals(e){return e.length>12?18:6}};function Te(r){return new Qe(r)}function at(r){if(r===We||r===ct)return!0;let e=r.toLowerCase();for(let t of Object.values(Je))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(Ge))if(t.toLowerCase()===e)return!0;return!1}function It(r){return r.startsWith("solana:")||r==="solana"}var vt=["base","base-sepolia","ethereum","arbitrum","polygon","optimism","avalanche","bsc","world","monad","robinhood","skale-base","skale-base-sepolia"];function Ot(r){return r.startsWith("eip155:")||vt.includes(r)}function Dt(r){return It(r)?"solana":Ot(r)?"evm":"unknown"}function Ze(r){return{[H]:"Solana",[Re]:"Solana Devnet",[je]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[j]:"Base",[me]:"Base Sepolia",[Ee]:"Ethereum",[fe]:"Arbitrum",[ge]:"Polygon",[he]:"Optimism",[ye]:"Avalanche",[Ae]:"BSC",[re]:"World Chain",[se]:"Monad",[oe]:"Robinhood Chain",[ae]:"SKALE Base",[ie]:"SKALE Base Sepolia",base:"Base","base-sepolia":"Base Sepolia",ethereum:"Ethereum",arbitrum:"Arbitrum",polygon:"Polygon",optimism:"Optimism",avalanche:"Avalanche",bsc:"BSC",world:"World Chain",monad:"Monad",robinhood:"Robinhood Chain","skale-base":"SKALE Base","skale-base-sepolia":"SKALE Base Sepolia"}[r]||r}function ut(r,e){let t=Ze(r);return t===r?e:t}function mt(r,e){let t=Dt(e);if(t==="solana")return e.includes("devnet")||e===Re?`https://solscan.io/tx/${r}?cluster=devnet`:`https://www.orbmarkets.io/tx/${r}`;if(t==="evm"){let n="8453";switch(e.startsWith("eip155:")?n=e.split(":")[1]:e==="ethereum"?n="1":e==="arbitrum"?n="42161":e==="polygon"?n="137":e==="optimism"?n="10":e==="avalanche"?n="43114":e==="bsc"?n="56":e==="world"?n="480":e==="monad"?n="143":e==="robinhood"?n="4663":e==="skale-base"?n="1187947933":e==="skale-base-sepolia"&&(n="324705682"),n){case"8453":return`https://basescan.org/tx/${r}`;case"84532":return`https://sepolia.basescan.org/tx/${r}`;case"1":return`https://etherscan.io/tx/${r}`;case"42161":return`https://arbiscan.io/tx/${r}`;case"137":return`https://polygonscan.com/tx/${r}`;case"10":return`https://optimistic.etherscan.io/tx/${r}`;case"43114":return`https://snowtrace.io/tx/${r}`;case"56":return`https://bscscan.com/tx/${r}`;case"480":return`https://worldscan.org/tx/${r}`;case"143":return`https://monadvision.com/tx/${r}`;case"4663":return`https://robinhoodchain.blockscout.com/tx/${r}`;case"1187947933":return`https://elated-tan-skat.explorer.mainnet.skalenodes.com/tx/${r}`;case"324705682":return`https://base-sepolia-testnet.explorer.skalenodes.com/tx/${r}`;default:return`https://basescan.org/tx/${r}`}}return`https://solscan.io/tx/${r}`}async function Bt(r,e){if(typeof r=="string")return[r,e];if(r instanceof URL)return[r.href,e];let t=r,n=new Headers(t.headers);e?.headers&&new Headers(e.headers).forEach((i,a)=>n.set(a,i));let s={method:e?.method??t.method,headers:n,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},o=(s.method??"GET").toUpperCase();return e&&"body"in e?s.body=e.body:o!=="GET"&&o!=="HEAD"&&t.body&&(s.body=await t.arrayBuffer()),[t.url,s]}var ft=new WeakMap;function gt(r){return ft.get(r)}function Mt(r,e){let t=r.headers.get("PAYMENT-RESPONSE"),n;if(t)try{let a=lt(t);a&&typeof a=="object"&&!Array.isArray(a)&&(n={...a})}catch{}n??={},n.settlementStatus="unconfirmed";let s=n.network===e.network,o=[n.errorReason,n.errorCode,n.errorMessage].every(a=>a===void 0||typeof a=="string"),i=[n.errorReason,n.errorCode].filter(a=>typeof a=="string"&&a.length>0);return i.some(a=>/pending|unknown|unconfirmed|timeout|temporar/i.test(a))?n.settlementStatus="pending":n.success===!0&&s&&o&&i.length===0&&typeof n.transaction=="string"&&n.transaction.trim().length>0?n.settlementStatus="settled":n.success===!1&&(s||n.network===void 0)&&i.length>0&&(n.settlementStatus="failed"),n.attemptedAmountAtomic=e.amountAtomic,n.settlementStatus==="settled"?n.amountAtomic=e.amountAtomic:delete n.amountAtomic,n.assetDecimals=e.assetDecimals,ft.set(r,n),n}function ht(r){let{adapters:e=[xe({verbose:r.verbose}),Te({verbose:r.verbose})],wallets:t,wallet:n,preferredNetwork:s,rpcUrls:o={},maxAmountAtomic:i,fetch:a=globalThis.fetch,verbose:c=!1,accessPass:p,onPaymentRequired:y,onPaymentDispatched:w,maxRetries:S=0,retryDelayMs:b=500}=r,l=c?console.log.bind(console,"[x402]"):()=>{};async function R(g,A){let x;for(let f=0;f<=S;f++)try{let u=await a(g,A);if(u.status>=502&&u.status<=504&&f<S){l(`Retry ${f+1}/${S}: server returned ${u.status}`),await new Promise(h=>setTimeout(h,b*Math.pow(2,f)));continue}return u}catch(u){x=u,f<S&&(l(`Retry ${f+1}/${S}: ${u instanceof Error?u.message:"network error"}`),await new Promise(h=>setTimeout(h,b*Math.pow(2,f))))}throw x}let M=new Map;function q(g){try{let A=new URL(g).host,x=M.get(A);if(x&&x.expiresAt>Date.now()/1e3+10)return x.jwt;x&&M.delete(A)}catch{}return null}function W(g,A){try{let x=new URL(g).host,f=A.split(".");if(f.length===3){let u=JSON.parse(atob(f[1].replace(/-/g,"+").replace(/_/g,"/"))),h=Math.floor(Date.now()/1e3),d=h+86400,v=Math.min(typeof u.exp=="number"?u.exp:h,d);M.set(x,{jwt:A,expiresAt:v}),l("Access pass cached for",x,"| expires:",new Date(v*1e3).toISOString())}}catch{l("Failed to cache access pass")}}let P=t||{};n&&!P.solana&&V(n)&&(P.solana=n),n&&!P.evm&&X(n)&&(P.evm=n);function C(g){let A=[];for(let x of g){let f=e.find(d=>d.canHandle(x.network));if(!f)continue;let u=f.name==="Solana"?"svm":"evm";if(Se(x,u))continue;let h;f.name==="Solana"?h=P.solana:f.name==="EVM"&&(h=P.evm),h&&f.isConnected(h)&&A.push({accept:x,adapter:f,wallet:h})}if(A.length===0)return null;if(s){let x=A.find(f=>f.accept.network===s);if(x)return x}return A[0]}function T(g,A){return ut(g,A)}function $(g,A){return o[g]||A.getDefaultRpcUrl(g)}async function K(g,A,x,f,u){let h="";if(p?.preferTier&&f.tiers){let m=f.tiers.find(G=>G.id===p.preferTier);if(m){if(p.maxSpend&&parseFloat(m.price)>parseFloat(p.maxSpend))throw new _("access_pass_exceeds_max_spend",`Access pass tier "${m.id}" costs $${m.price}, exceeds max spend $${p.maxSpend}`);h=`tier=${m.id}`}}else if(p?.preferDuration&&f.ratePerHour)h=`duration=${p.preferDuration}`;else if(f.tiers&&f.tiers.length>0){let m=f.tiers[0];if(p?.maxSpend&&parseFloat(m.price)>parseFloat(p.maxSpend))throw new _("access_pass_exceeds_max_spend",`Cheapest access pass costs $${m.price}, exceeds max spend $${p?.maxSpend}`);h=`tier=${m.id}`}let d=h?u.includes("?")?`${u}&${h}`:`${u}?${h}`:u;l("Purchasing access pass:",h||"default tier");let v=x.headers.get("PAYMENT-REQUIRED");if(!v)return null;let k;try{k=JSON.parse(atob(v))}catch{return null}let N=C(k.accepts);if(!N)return null;if(ot(k.extensions))throw new _("unsupported_required_payment_identifier","Required payment identifiers are not supported by this client");let{accept:O,adapter:J,wallet:le}=N;if(J.name==="Solana"&&!O.extra?.feePayer)return null;let Y=O.extra?.decimals??(at(O.asset)?6:void 0);if(typeof Y!="number")return null;let we=O.amount??O.maxAmountRequired;if(!we)return null;let z=$(O.network,J);try{let m=await J.getBalance(O,le,z),G=Number(we)/Math.pow(10,Y);if(m<G){let Et=T(O.network,J.name);throw new _("insufficient_balance",`Insufficient balance for access pass on ${Et}. Have $${m.toFixed(4)}, need $${G.toFixed(4)}`)}}catch(m){if(m instanceof _)throw m}let Q=await J.buildTransaction(O,le,z),de;J.name==="EVM"?de=JSON.parse(Q.serialized):de={transaction:Q.serialized};let ee=typeof g=="string"?g:g instanceof URL?g.href:g.url,ue=k.resource;if(typeof k.resource=="string")try{let m=new URL(k.resource,ee);["http:","https:"].includes(m.protocol)&&(ue=m.toString())}catch{}else if(k.resource&&typeof k.resource=="object"&&"url"in k.resource){let m=k.resource;try{let G=new URL(m.url,ee);["http:","https:"].includes(G.protocol)&&(ue={...m,url:G.toString()})}catch{}}let qe={x402Version:O.x402Version??2,resource:ue,accepted:O,payload:de};Q.extensions&&(qe.extensions=Q.extensions);let be=btoa(JSON.stringify(qe)),te=await a(d,{...A,method:"POST",headers:{...A?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":be}});if(!te.ok)return l("Pass purchase failed:",te.status),null;let E=te.headers.get("ACCESS-PASS");return E&&(W(u,E),l("Access pass purchased and cached")),te}async function F(g,A){let x=g;if(l("Making request:",x),p){let E=q(x);if(E){l("Using cached access pass");let m=await a(g,{...A,headers:{...A?.headers||{},Authorization:`Bearer ${E}`}});if(m.status!==401&&m.status!==402)return m;l("Cached pass rejected (status",m.status,"), purchasing new pass");try{M.delete(new URL(x).host)}catch{}}}let f=await R(g,A);if(f.status!==402)return f;l("Received 402 Payment Required");let u=f.headers.get("X-ACCESS-PASS-TIERS");if(p&&u){l("Server offers access passes, purchasing...");try{let E=JSON.parse(atob(u)),m=await K(g,A,f,E,x);if(m)return m}catch(E){l("Access pass purchase failed, falling back to per-request payment:",E)}}let h=f.headers.get("PAYMENT-REQUIRED");if(!h)throw new _("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let d;try{let E=atob(h);d=JSON.parse(E)}catch{throw new _("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}if(l("Payment requirements:",d),ot(d.extensions))throw new _("unsupported_required_payment_identifier","Required payment identifiers are not supported by this client");let v=f.headers.get("X-Quote-Hash");v&&l("Quote hash received:",v);let k=C(d.accepts);if(!k){let E=d.accepts.map(m=>m.network).join(", ");throw new _("no_matching_payment_option",`No supported payment option with a connected wallet for: ${E}`)}let{accept:N,adapter:O,wallet:J}=k;if(l(`Using ${O.name} for ${N.network}`),O.name==="Solana"&&!N.extra?.feePayer)throw new _("missing_fee_payer","Solana payment option missing feePayer in extra");let le=N.extra?.decimals??(at(N.asset)?6:void 0);if(typeof le!="number")throw new _("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let Y=N.amount??N.maxAmountRequired;if(!Y)throw new _("missing_amount","Payment option missing amount");if(i&&BigInt(Y)>BigInt(i))throw new _("amount_exceeds_max",`Payment amount ${Y} exceeds maximum ${i}`);let we=$(N.network,O);l("Checking balance...");try{let E=await O.getBalance(N,J,we),m=Number(Y)/Math.pow(10,le);if(E<m){let G=T(N.network,O.name);throw new _("insufficient_balance",`Insufficient balance on ${G}. Have $${E.toFixed(4)}, need $${m.toFixed(4)}`)}l(`Balance OK: $${E.toFixed(4)} >= $${m.toFixed(4)}`)}catch(E){if(E instanceof _)throw E;l("Balance check failed (RPC error), proceeding with transaction attempt")}if(y&&!await y(N))throw new _("payment_rejected","Payment rejected by onPaymentRequired callback");l("Building transaction...");let z=await O.buildTransaction(N,J,we);l("Transaction signed");let Q;O.name==="EVM"?Q=JSON.parse(z.serialized):Q={transaction:z.serialized};let de=g,ee=d.resource;if(typeof d.resource=="string")try{let E=new URL(d.resource,de).toString();E!==d.resource&&l("Resolved relative resource URL:",d.resource,"\u2192",E),ee=E}catch{ee=d.resource}else if(d.resource&&typeof d.resource=="object"&&"url"in d.resource){let E=d.resource;try{let m=new URL(E.url,de).toString();m!==E.url&&(l("Resolved relative resource URL:",E.url,"\u2192",m),ee={...E,url:m})}catch{}}let ue={x402Version:N.x402Version??2,resource:ee,accepted:N,payload:Q};z.extensions&&(ue.extensions=z.extensions);let qe=btoa(JSON.stringify(ue));if(w)try{w(N,z.settlementProbe)}catch{}l("Retrying request with payment...");let be=await R(g,{...A,headers:{...A?.headers||{},"PAYMENT-SIGNATURE":qe,...v?{"X-Quote-Hash":v}:{}}});l("Retry response status:",be.status);let te=Mt(be,{network:N.network,amountAtomic:Y,assetDecimals:le});return te.extensions&&l("Settlement extensions:",Object.keys(te.extensions).join(", ")),be}async function U(g,A){let[x,f]=await Bt(g,A);return F(x,f)}return{fetch:U}}function yt(r){let e=gt(r);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function et(r){let e=yt(r);if(e?.recommendations?.length)return e.recommendations}async function tt(r){let t=yt(r)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function At(r){let{wallets:e,wallet:t,preferredNetwork:n,rpcUrls:s={},verbose:o=!1}=r,[i,a]=(0,I.useState)(!1),[c,p]=(0,I.useState)("idle"),[y,w]=(0,I.useState)(null),[S,b]=(0,I.useState)(null),[l,R]=(0,I.useState)(null),[M,q]=(0,I.useState)([]),[W,P]=(0,I.useState)(null),C=(0,I.useCallback)((...u)=>{o&&console.log("[useX402Payment]",...u)},[o]),T=(0,I.useMemo)(()=>{let u={...e};return t&&!u.solana&&V(t)&&(u.solana=t),t&&!u.evm&&X(t)&&(u.evm=t),u},[e,t]),$=(0,I.useMemo)(()=>[xe({verbose:o,rpcUrls:s}),Te({verbose:o,rpcUrls:s})],[o,s]),K=(0,I.useMemo)(()=>({solana:T.solana?V(T.solana)&&$[0].isConnected(T.solana):!1,evm:T.evm?X(T.evm)&&$[1].isConnected(T.evm):!1}),[T,$]),F=K.solana||K.evm,U=(0,I.useCallback)(async()=>{let u=[];if(K.solana&&T.solana)try{let h=$.find(d=>d.name==="Solana");if(h){let d={scheme:"exact",network:H,amount:"0",asset:We,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},v=await h.getBalance(d,T.solana);u.push({network:H,chainName:Ze(H),balance:v,asset:"USDC"})}}catch(h){C("Failed to fetch Solana balance:",h)}if(K.evm&&T.evm)try{let h=$.find(d=>d.name==="EVM");if(h){let d={scheme:"exact",network:j,amount:"0",asset:Ve,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},v=await h.getBalance(d,T.evm);u.push({network:j,chainName:Ze(j),balance:v,asset:"USDC"})}}catch(h){C("Failed to fetch Base balance:",h)}q(u)},[K,T,$,C]);(0,I.useEffect)(()=>{U();let u=setInterval(U,3e4);return()=>clearInterval(u)},[U]);let g=(0,I.useCallback)(()=>{a(!1),p("idle"),w(null),b(null),R(null),P(null)},[]),A=(0,I.useMemo)(()=>ht({adapters:$,wallets:T,preferredNetwork:n,rpcUrls:s,verbose:o}),[$,T,n,s,o]),x=(0,I.useCallback)(async(u,h)=>{if(a(!0),p("pending"),w(null),b(null),R(null),!F){let d=new _("wallet_not_connected","No wallet connected");throw w(d),p("error"),a(!1),d}try{let d=await A.fetch(u,h),v=d.headers.get("PAYMENT-RESPONSE");if(v)try{let N=JSON.parse(atob(v));N.transaction&&b(N.transaction),N.network&&R(N.network)}catch{C("Could not parse PAYMENT-RESPONSE header")}let k=et(d);return P(k??null),k&&(C("Sponsored recommendations received:",k.length),tt(d).catch(()=>{})),p("success"),d}catch(d){let v=d instanceof Error?d:new Error(String(d));throw w(v),p("error"),d}finally{a(!1),setTimeout(U,2e3)}},[A,F,C,U]),f=(0,I.useMemo)(()=>S?mt(S,l||n||H):null,[S,l,n]);return{fetch:x,isLoading:i,status:c,error:y,transactionId:S,transactionNetwork:l,transactionUrl:f,balances:M,connectedChains:K,isAnyWalletConnected:F,reset:g,refreshBalances:U,accessPass:null,sponsoredRecommendations:W}}0&&(module.exports={X402Error,fireImpressionBeacon,getSponsoredRecommendations,useX402Payment});
1
+ "use strict";var Et=Object.create;var Ke=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var Tt=Object.getOwnPropertyNames;var bt=Object.getPrototypeOf,wt=Object.prototype.hasOwnProperty;var Rt=(n,e)=>{for(var t in e)Ke(n,t,{get:e[t],enumerable:!0})},it=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Tt(e))!wt.call(n,s)&&s!==t&&Ke(n,s,{get:()=>e[s],enumerable:!(r=xt(e,s))||r.enumerable});return n};var Fe=(n,e,t)=>(t=n!=null?Et(bt(n)):{},it(e||!n||!n.__esModule?Ke(t,"default",{value:n,enumerable:!0}):t,n)),_t=n=>it(Ke({},"__esModule",{value:!0}),n);var kt={};Rt(kt,{X402Error:()=>_,fireImpressionBeacon:()=>tt,getSponsoredRecommendations:()=>et,useX402Payment:()=>At});module.exports=_t(kt);var I=require("react");var j="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Re="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",He="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",ne=j,_e=Re,Ne=He,H="eip155:8453",me="eip155:84532",fe="eip155:42161",ge="eip155:137",he="eip155:10",ye="eip155:43114",Ae="eip155:56",re="eip155:480",se="eip155:143",oe="eip155:4663",ae="eip155:1187947933",ie="eip155:324705682",Se="eip155:1",ce=H,je=me,Pe=fe,Ce=ge,Ie=he,ve=ye,Oe=Ae,De=re,Be=se,Me=oe,Ue=ae,ke=ie,Le=Se,We="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",ct="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",Ve="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",nt="0x55d398326f99059fF775485246999027B3197955",Xe="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",rt="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",Je={[Ae]:Xe,[H]:Ve,[me]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[fe]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[ge]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[he]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[ye]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[re]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[se]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[oe]:rt,[ae]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[ie]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[Se]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},Ge={[nt]:{symbol:"USDT",decimals:18},[Xe]:{symbol:"USDC",decimals:18}};var Ye={[re]:{name:"USDC",version:"2"},[se]:{name:"USDC",version:"2"},[oe]:{name:"Global Dollar",version:"1"},[ae]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[ie]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}},Z="0x000000000022D473030F116dDEE9F6B43aC78BA3",$e="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",st={[Ae]:56,[H]:8453,[me]:84532,[fe]:42161,[ge]:137,[he]:10,[ye]:43114,[re]:480,[se]:143,[oe]:4663,[ae]:1187947933,[ie]:324705682,[Se]:1},pe={[j]:"https://api.dexter.cash/api/solana/rpc",[Re]:"https://api.devnet.solana.com",[He]:"https://api.testnet.solana.com"},L={[Ae]:"https://api.dexter.cash/api/evm/bsc/rpc",[H]:"https://api.dexter.cash/api/base/rpc",[me]:"https://sepolia.base.org",[fe]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[ge]:"https://api.dexter.cash/api/evm/polygon/rpc",[he]:"https://api.dexter.cash/api/evm/optimism/rpc",[ye]:"https://api.dexter.cash/api/evm/avalanche/rpc",[re]:"https://worldchain-mainnet.g.alchemy.com/public",[se]:"https://rpc.monad.xyz",[oe]:"https://rpc.mainnet.chain.robinhood.com",[ae]:"https://skale-base.skalenodes.com/v1/base",[ie]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[Se]:"https://eth.llamarpc.com"};var _=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)}};function Ee(n,e){let t=n.scheme??"exact";if(t!=="exact"&&!(e==="evm"&&t==="exact-approval"))return`Unsupported payment scheme: ${t}`;let r=n.extra?.paymentFlow;if(r!==void 0&&r!=="authorization")return`Unsupported payment flow: ${String(r)}`;let s=n.extra?.assetTransferMethod;if(s!==void 0&&(typeof s!="string"||!(t==="exact-approval"?[]:e==="evm"?["eip3009","permit2"]:["default"]).includes(s)))return`Unsupported payment asset transfer method: ${String(s)}`}function ot(n){let e=n?.["payment-identifier"];if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.info;return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.required===!0}var pt=[{caip2:"eip155:8453",bare:"base",family:"evm"},{caip2:"eip155:1",bare:"ethereum",family:"evm"},{caip2:"eip155:137",bare:"polygon",family:"evm"},{caip2:"eip155:42161",bare:"arbitrum",family:"evm"},{caip2:"eip155:10",bare:"optimism",family:"evm"},{caip2:"eip155:43114",bare:"avalanche",family:"evm"},{caip2:"eip155:56",bare:"bsc",family:"evm"},{caip2:"eip155:480",bare:"world",family:"evm"},{caip2:"eip155:143",bare:"monad",family:"evm"},{caip2:"eip155:4663",bare:"robinhood",family:"evm"},{caip2:"eip155:1187947933",bare:"skale-base",family:"evm"},{caip2:"eip155:324705682",bare:"skale-base-sepolia",family:"evm"},{caip2:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",bare:"solana",family:"svm"}],Ht=new Map(pt.map(n=>[n.caip2.toLowerCase(),n])),jt=new Map(pt.map(n=>[n.bare.toLowerCase(),n]));function lt(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-(e.length%4||4))%4);return JSON.parse(Buffer.from(t,"base64").toString("utf8"))}var B=require("@solana/web3.js"),M=require("@solana/spl-token");var Nt=12e3,Pt=1;function V(n){if(!n||typeof n!="object")return!1;let e=n;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var ze=class{name="Solana";networks=[ne,_e,Ne];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]:pe[e]?pe[e]:e==="solana"?pe[ne]:e==="solana-devnet"?pe[_e]:e==="solana-testnet"?pe[Ne]:pe[ne]}getAddress(e){return V(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return V(e)?e.publicKey!==null:!1}async getBalance(e,t,r){if(!V(t)||!t.publicKey)return 0;let s=r||this.getDefaultRpcUrl(e.network),o=new B.Connection(s,"confirmed"),i=new B.PublicKey(t.publicKey.toBase58()),a=new B.PublicKey(e.asset);try{let p=(await o.getAccountInfo(a,"confirmed"))?.owner.toBase58()===M.TOKEN_2022_PROGRAM_ID.toBase58()?M.TOKEN_2022_PROGRAM_ID:M.TOKEN_PROGRAM_ID,y=await(0,M.getAssociatedTokenAddress)(a,i,!1,p),b=await(0,M.getAccount)(o,y,void 0,p),E=e.extra?.decimals??6;return Number(b.amount)/Math.pow(10,E)}catch(c){if(c&&typeof c=="object"&&"name"in c&&(c.name==="TokenAccountNotFoundError"||c.name==="TokenInvalidAccountOwnerError"))return 0;throw c}}async buildTransaction(e,t,r){let s=Ee(e,"svm");if(s)throw new Error(s);if(!V(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let o=r||this.getDefaultRpcUrl(e.network),i=new B.Connection(o,"confirmed"),a=new B.PublicKey(t.publicKey.toBase58()),{payTo:c,asset:p,extra:y}=e,b=e.amount??e.maxAmountRequired;if(!b)throw new Error("Missing amount in payment requirements");if(!y?.feePayer)throw new Error("Missing feePayer in payment requirements");let E=new B.PublicKey(y.feePayer),w=new B.PublicKey(p),l=new B.PublicKey(c);this.log("Building transaction:",{from:a.toBase58(),to:c,amount:b,asset:p,feePayer:y.feePayer});let R=[];R.push(B.ComputeBudgetProgram.setComputeUnitLimit({units:Nt})),R.push(B.ComputeBudgetProgram.setComputeUnitPrice({microLamports:Pt}));let v=await i.getAccountInfo(w,"confirmed");if(!v)throw new Error(`Token mint ${p} not found`);let q=v.owner.toBase58()===M.TOKEN_2022_PROGRAM_ID.toBase58()?M.TOKEN_2022_PROGRAM_ID:M.TOKEN_PROGRAM_ID,W=await(0,M.getMint)(i,w,void 0,q);typeof y?.decimals=="number"&&W.decimals!==y.decimals&&this.log(`Decimals mismatch: requirements say ${y.decimals}, mint says ${W.decimals}`);let P=await(0,M.getAssociatedTokenAddress)(w,a,!1,q),C=await(0,M.getAssociatedTokenAddress)(w,l,!0,q);if(!await i.getAccountInfo(P,"confirmed"))throw new Error(`No token account found for ${p}. Please ensure you have USDC in your wallet.`);if(!await i.getAccountInfo(C,"confirmed"))throw new Error(`Seller token account not found. The seller (${c}) must have a USDC account.`);let K=BigInt(b);R.push((0,M.createTransferCheckedInstruction)(P,w,C,a,K,W.decimals,[],q));let{blockhash:F}=await i.getLatestBlockhash("confirmed"),U=new B.TransactionMessage({payerKey:E,recentBlockhash:F,instructions:R}).compileToV0Message(),g=new B.VersionedTransaction(U),A=await t.signTransaction(g);return this.log("Transaction signed successfully"),{serialized:Buffer.from(A.serialize()).toString("base64"),settlementProbe:{kind:"solana",sourceAta:P.toBase58(),destinationAta:C.toBase58(),asset:p,amount:b,blockhash:F}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let r=new B.Connection(t,"confirmed"),s=new B.PublicKey(e.destinationAta),o=await r.getSignaturesForAddress(s,{limit:25});if(o.length===0)return{settled:!1};let i=BigInt(e.amount);for(let a of o){if(a.err)continue;let c=await r.getTransaction(a.signature,{commitment:"confirmed",maxSupportedTransactionVersion:0});if(!c?.meta)continue;let p=c.transaction.message.getAccountKeys().keySegments().flat(),y=c.meta.preTokenBalances??[],b=c.meta.postTokenBalances??[];for(let E of b){if(E.mint!==e.asset)continue;let w=p[E.accountIndex];if(!w||!w.equals(s))continue;let l=y.find(q=>q.accountIndex===E.accountIndex),R=BigInt(l?.uiTokenAmount.amount??"0");if(BigInt(E.uiTokenAmount.amount??"0")-R===i)return{settled:!0,txSignature:a.signature}}}return{settled:!1}}};function xe(n){return new ze(n)}var Ct={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"validAfter",type:"uint256"}]},dt=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function X(n){if(!n||typeof n!="object")return!1;let e=n;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var Qe=class{name="EVM";networks=[Oe,ce,je,Le,Pe,Ce,Ie,ve,De,Be,Me,Ue,ke];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:evm]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="base"||e==="bsc"||e==="ethereum"||e==="arbitrum"||e==="polygon"||e==="optimism"||e==="avalanche"||e==="world"||e==="monad"||e==="robinhood"||e==="skale-base"||e==="skale-base-sepolia"||e.startsWith("eip155:"))}getDefaultRpcUrl(e){return this.config.rpcUrls?.[e]?this.config.rpcUrls[e]:L[e]?L[e]:e==="base"?L[ce]:e==="bsc"?L[Oe]:e==="ethereum"?L[Le]:e==="arbitrum"?L[Pe]:e==="polygon"?L[Ce]:e==="optimism"?L[Ie]:e==="avalanche"?L[ve]:e==="world"?L[De]:e==="monad"?L[Be]:e==="robinhood"?L[Me]:e==="skale-base"?L[Ue]:e==="skale-base-sepolia"?L[ke]:L[ce]}getAddress(e){return X(e)?e.address:null}isConnected(e){return X(e)?!!e.address:!1}getChainId(e){if(st[e])return st[e];if(e.startsWith("eip155:")){let t=e.split(":")[1];return parseInt(t,10)}return e==="base"?8453:e==="bsc"?56:e==="ethereum"?1:e==="arbitrum"?42161:e==="polygon"?137:e==="optimism"?10:e==="avalanche"?43114:e==="world"?480:e==="monad"?143:e==="robinhood"?4663:e==="skale-base"?1187947933:e==="skale-base-sepolia"?324705682:8453}async getBalance(e,t,r){if(!X(t)||!t.address)return 0;let s=r||this.getDefaultRpcUrl(e.network);try{let o=this.encodeBalanceOf(t.address),i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:e.asset,data:o},"latest"]})});if(!i.ok)throw new Error(`RPC request failed: ${i.status}`);let a=await i.json();if(a.error)throw new Error(`RPC error: ${JSON.stringify(a.error)}`);if(!a.result||a.result==="0x")return 0;let c=BigInt(a.result),p=e.extra?.decimals??6;return Number(c)/Math.pow(10,p)}catch(o){throw o}}encodeBalanceOf(e){let t="0x70a08231",r=e.slice(2).toLowerCase().padStart(64,"0");return t+r}async confirmSettlement(e,t){if(e.kind==="eip3009"){let r="0xe94a0102",s=e.from.slice(2).toLowerCase().padStart(64,"0"),o=e.nonce.slice(2).toLowerCase().padStart(64,"0"),i=r+s+o,a=await this.ethCall(t,e.asset,i);return{settled:BigInt(a)!==0n}}if(e.kind==="permit2"){let r="0x4fe02b44",s=BigInt(e.nonce),o=s>>8n,i=s&0xffn,a=e.from.slice(2).toLowerCase().padStart(64,"0"),c=o.toString(16).padStart(64,"0"),p=r+a+c,y=await this.ethCall(t,Z,p);return{settled:(BigInt(y)>>i&1n)===1n}}throw new Error(`EvmAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`)}async ethCall(e,t,r){let s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:r},"latest"]})});if(!s.ok)throw new Error(`RPC request failed: ${s.status}`);let o=await s.json();if(o.error)throw new Error(`RPC error: ${JSON.stringify(o.error)}`);if(!o.result||o.result==="0x")throw new Error("RPC returned an empty result");return o.result}async buildTransaction(e,t,r){let s=Ee(e,"evm");if(s)throw new Error(s);if(!X(t))throw new Error("Invalid EVM wallet");if(!t.address)throw new Error("Wallet not connected");if(e.scheme==="exact-approval")return this.buildApprovalTransaction(e,t,r);if(e.extra?.assetTransferMethod==="permit2")return this.buildPermit2Transaction(e,t,r);let{payTo:o,asset:i,extra:a}=e,c=e.amount??e.maxAmountRequired;if(!c)throw new Error("Missing amount in payment requirements");this.log("Building EVM transaction:",{from:t.address,to:o,amount:c,asset:i,network:e.network});let p=this.getChainId(e.network),y=Ye[`eip155:${p}`],b={name:a?.name??y?.name??"USD Coin",version:a?.version??y?.version??"2",chainId:BigInt(p),verifyingContract:i},E={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},w=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(w);let l="0x"+[...w].map(C=>C.toString(16).padStart(2,"0")).join(""),R=Math.floor(Date.now()/1e3),v={from:t.address,to:o,value:c,validAfter:String(R-600),validBefore:String(R+(e.maxTimeoutSeconds||60)),nonce:l},q={from:t.address,to:o,value:BigInt(c),validAfter:BigInt(R-600),validBefore:BigInt(R+(e.maxTimeoutSeconds||60)),nonce:l};if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let W=await t.signTypedData({domain:b,types:E,primaryType:"TransferWithAuthorization",message:q});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:v,signature:W}),signature:W,settlementProbe:{kind:"eip3009",from:v.from,to:v.to,amount:v.value,nonce:l,asset:i,chainId:p}}}async buildApprovalTransaction(e,t,r){let{payTo:s,asset:o,extra:i}=e,a=e.amount??e.maxAmountRequired;if(!a)throw new Error("Missing amount in payment requirements");let c=i?.facilitatorContract;if(!c)throw new Error("exact-approval scheme requires extra.facilitatorContract from the facilitator. The /supported endpoint should provide this.");if(!t.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building approval-based transaction:",{from:t.address,to:s,amount:a,asset:o,network:e.network,facilitatorContract:c});let p=r||this.getDefaultRpcUrl(e.network),y=i?.fee??"0",b=BigInt(a)+BigInt(y),E=await this.readAllowance(p,o,t.address,c);if(E<b){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 U=this.calculateApprovalAmount(a,y,i?.approvalStrategy);this.log(`Approving ${U} for ${c} (current allowance: ${E})`);let g=await t.sendTransaction({to:o,data:this.encodeApprove(c,U),value:0n});this.log(`Approval tx sent: ${g}`),await this.waitForReceipt(p,g),this.log("Approval confirmed")}else this.log("Sufficient allowance, skipping approval");let w=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(w);let l=[...w].reduce((U,g)=>U*256n+BigInt(g),0n).toString(),R=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(R);let v="0x"+[...R].map(U=>U.toString(16).padStart(2,"0")).join(""),W=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),P=i?.eip712Domain,C=P?{name:P.name,version:P.version,chainId:BigInt(P.chainId),verifyingContract:P.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(e.network)),verifyingContract:c},T=i?.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:s,token:o,amount:BigInt(a),fee:BigInt(y),nonce:BigInt(l),deadline:BigInt(W),paymentId:v},K=await t.signTypedData({domain:C,types:T,primaryType:"Payment",message:$});this.log("EIP-712 Payment signature obtained");let F={from:t.address,to:s,token:o,amount:a,fee:y,nonce:l,deadline:W,paymentId:v,signature:K};return{serialized:JSON.stringify(F),signature:K}}async buildPermit2Transaction(e,t,r){let{payTo:s,asset:o}=e,i=e.amount??e.maxAmountRequired;if(!i)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:s,amount:i,asset:o,network:e.network});let a=r||this.getDefaultRpcUrl(e.network),c=await this.readAllowance(a,o,t.address,Z),p;if(c<BigInt(i)){let C=this.encodeApprove(Z,dt);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${c})`);let T=this.getChainId(e.network),$=await this.readGasPrice(a),K=await this.readNonce(a,t.address),F=await t.signTransaction({to:o,data:C,chainId:T,gas:50000n,gasPrice:$,nonce:K});p={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:o,spender:Z,amount:dt.toString(),signedTransaction:F,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${c})`);let T=await t.sendTransaction({to:o,data:C,value:0n});this.log(`Permit2 approval tx sent: ${T}`),await this.waitForReceipt(a,T),this.log("Permit2 approval confirmed")}else throw new Error("Permit2 payments require a wallet that supports signTransaction or sendTransaction for the one-time Permit2 approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.")}else this.log("Sufficient Permit2 allowance, skipping approval");let y=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(y);let b=[...y].reduce((C,T)=>C*256n+BigInt(T),0n),E=Math.floor(Date.now()/1e3),w=E-600,l=E+(e.maxTimeoutSeconds||300),R=this.getChainId(e.network),v={name:"Permit2",chainId:BigInt(R),verifyingContract:Z},q={permitted:{token:o,amount:BigInt(i)},spender:$e,nonce:b,deadline:BigInt(l),witness:{to:s,validAfter:BigInt(w)}},W=await t.signTypedData({domain:v,types:Ct,primaryType:"PermitWitnessTransferFrom",message:q});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let P={signature:W,permit2Authorization:{from:t.address,permitted:{token:o,amount:i},spender:$e,nonce:b.toString(),deadline:String(l),witness:{to:s,validAfter:String(w)}}};return{serialized:JSON.stringify(P),signature:W,extensions:p,settlementProbe:{kind:"permit2",from:t.address,nonce:b.toString(),chainId:R}}}async readAllowance(e,t,r,s){let o="0xdd62ed3e",i=r.slice(2).toLowerCase().padStart(64,"0"),a=s.slice(2).toLowerCase().padStart(64,"0"),c=o+i+a;try{let y=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t,data:c},"latest"]})})).json();return y.error||!y.result||y.result==="0x"?0n:BigInt(y.result)}catch{return 0n}}encodeApprove(e,t){let r="0x095ea7b3",s=e.slice(2).toLowerCase().padStart(64,"0"),o=t.toString(16).padStart(64,"0");return r+s+o}async waitForReceipt(e,t,r=3e4){let s=Date.now();for(;Date.now()-s<r;){try{let i=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(i.result){if(i.result.status==="0x0")throw new Error(`Approval transaction reverted: ${t}`);return}}catch(o){if(o instanceof Error&&o.message.includes("reverted"))throw o}await new Promise(o=>setTimeout(o,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 s=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 s.result?parseInt(s.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,r){let s=BigInt(e)+BigInt(t);if(!r||r.mode==="exact")return s;let o=BigInt(r.defaultMultiple??10),i=s*o;if(r.maxCapUsd){let a=this.inferDecimals(e),c=BigInt(Math.floor(r.maxCapUsd*Math.pow(10,a)));if(i>c)return c}if(r.exactAboveUsd){let a=this.inferDecimals(e),c=BigInt(Math.floor(r.exactAboveUsd*Math.pow(10,a)));if(BigInt(e)>c)return s}return i}inferDecimals(e){return e.length>12?18:6}};function Te(n){return new Qe(n)}function at(n){if(n===We||n===ct)return!0;let e=n.toLowerCase();for(let t of Object.values(Je))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(Ge))if(t.toLowerCase()===e)return!0;return!1}function It(n){return n.startsWith("solana:")||n==="solana"}var vt=["base","base-sepolia","ethereum","arbitrum","polygon","optimism","avalanche","bsc","world","monad","robinhood","skale-base","skale-base-sepolia"];function Ot(n){return n.startsWith("eip155:")||vt.includes(n)}function Dt(n){return It(n)?"solana":Ot(n)?"evm":"unknown"}function Ze(n){return{[j]:"Solana",[Re]:"Solana Devnet",[He]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[H]:"Base",[me]:"Base Sepolia",[Se]:"Ethereum",[fe]:"Arbitrum",[ge]:"Polygon",[he]:"Optimism",[ye]:"Avalanche",[Ae]:"BSC",[re]:"World Chain",[se]:"Monad",[oe]:"Robinhood Chain",[ae]:"SKALE Base",[ie]:"SKALE Base Sepolia",base:"Base","base-sepolia":"Base Sepolia",ethereum:"Ethereum",arbitrum:"Arbitrum",polygon:"Polygon",optimism:"Optimism",avalanche:"Avalanche",bsc:"BSC",world:"World Chain",monad:"Monad",robinhood:"Robinhood Chain","skale-base":"SKALE Base","skale-base-sepolia":"SKALE Base Sepolia"}[n]||n}function ut(n,e){let t=Ze(n);return t===n?e:t}function mt(n,e){let t=Dt(e);if(t==="solana")return e.includes("devnet")||e===Re?`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==="world"?r="480":e==="monad"?r="143":e==="robinhood"?r="4663":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"480":return`https://worldscan.org/tx/${n}`;case"143":return`https://monadvision.com/tx/${n}`;case"4663":return`https://robinhoodchain.blockscout.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 Bt(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((i,a)=>r.set(a,i));let s={method:e?.method??t.method,headers:r,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},o=(s.method??"GET").toUpperCase();return e&&"body"in e?s.body=e.body:o!=="GET"&&o!=="HEAD"&&t.body&&(s.body=await t.arrayBuffer()),[t.url,s]}var ft=new WeakMap;function gt(n){return ft.get(n)}function Mt(n){if(!(n.length>16384))try{let e=n.trimStart().startsWith("{")?JSON.parse(n):lt(n);return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}catch{return}}function Ut(n,e){let t=n.headers.get("PAYMENT-RESPONSE")??n.headers.get("X-PAYMENT-RESPONSE"),r;if(t)try{let a=Mt(t);a&&typeof a=="object"&&!Array.isArray(a)&&(r={...a})}catch{}r??={},delete r.chainConfirmation,r.settlementStatus="unconfirmed";let s=r.network===e.network,o=[r.errorReason,r.errorCode,r.errorMessage].every(a=>a===void 0||typeof a=="string"),i=[r.errorReason,r.errorCode].filter(a=>typeof a=="string"&&a.length>0);return i.some(a=>/pending|unknown|unconfirmed|timeout|temporar/i.test(a))?r.settlementStatus="pending":r.success===!0&&s&&o&&i.length===0&&typeof r.transaction=="string"&&r.transaction.trim().length>0?r.settlementStatus="settled":r.success===!1&&(s||r.network===void 0)&&i.length>0&&(r.settlementStatus="failed"),r.attemptedAmountAtomic=e.amountAtomic,r.settlementStatus==="settled"?r.amountAtomic=e.amountAtomic:delete r.amountAtomic,r.assetDecimals=e.assetDecimals,ft.set(n,r),r}function ht(n){let{adapters:e=[xe({verbose:n.verbose}),Te({verbose:n.verbose})],wallets:t,wallet:r,preferredNetwork:s,rpcUrls:o={},maxAmountAtomic:i,fetch:a=globalThis.fetch,verbose:c=!1,accessPass:p,onPaymentRequired:y,onPaymentDispatched:b,maxRetries:E=0,retryDelayMs:w=500}=n,l=c?console.log.bind(console,"[x402]"):()=>{};async function R(g,A){let x;for(let f=0;f<=E;f++)try{let u=await a(g,A);if(u.status>=502&&u.status<=504&&f<E){l(`Retry ${f+1}/${E}: server returned ${u.status}`),await new Promise(h=>setTimeout(h,w*Math.pow(2,f)));continue}return u}catch(u){x=u,f<E&&(l(`Retry ${f+1}/${E}: ${u instanceof Error?u.message:"network error"}`),await new Promise(h=>setTimeout(h,w*Math.pow(2,f))))}throw x}let v=new Map;function q(g){try{let A=new URL(g).host,x=v.get(A);if(x&&x.expiresAt>Date.now()/1e3+10)return x.jwt;x&&v.delete(A)}catch{}return null}function W(g,A){try{let x=new URL(g).host,f=A.split(".");if(f.length===3){let u=JSON.parse(atob(f[1].replace(/-/g,"+").replace(/_/g,"/"))),h=Math.floor(Date.now()/1e3),d=h+86400,O=Math.min(typeof u.exp=="number"?u.exp:h,d);v.set(x,{jwt:A,expiresAt:O}),l("Access pass cached for",x,"| expires:",new Date(O*1e3).toISOString())}}catch{l("Failed to cache access pass")}}let P=t||{};r&&!P.solana&&V(r)&&(P.solana=r),r&&!P.evm&&X(r)&&(P.evm=r);function C(g){let A=[];for(let x of g){let f=e.find(d=>d.canHandle(x.network));if(!f)continue;let u=f.name==="Solana"?"svm":"evm";if(Ee(x,u))continue;let h;f.name==="Solana"?h=P.solana:f.name==="EVM"&&(h=P.evm),h&&f.isConnected(h)&&A.push({accept:x,adapter:f,wallet:h})}if(A.length===0)return null;if(s){let x=A.find(f=>f.accept.network===s);if(x)return x}return A[0]}function T(g,A){return ut(g,A)}function $(g,A){return o[g]||A.getDefaultRpcUrl(g)}async function K(g,A,x,f,u){let h="";if(p?.preferTier&&f.tiers){let m=f.tiers.find(G=>G.id===p.preferTier);if(m){if(p.maxSpend&&parseFloat(m.price)>parseFloat(p.maxSpend))throw new _("access_pass_exceeds_max_spend",`Access pass tier "${m.id}" costs $${m.price}, exceeds max spend $${p.maxSpend}`);h=`tier=${m.id}`}}else if(p?.preferDuration&&f.ratePerHour)h=`duration=${p.preferDuration}`;else if(f.tiers&&f.tiers.length>0){let m=f.tiers[0];if(p?.maxSpend&&parseFloat(m.price)>parseFloat(p.maxSpend))throw new _("access_pass_exceeds_max_spend",`Cheapest access pass costs $${m.price}, exceeds max spend $${p?.maxSpend}`);h=`tier=${m.id}`}let d=h?u.includes("?")?`${u}&${h}`:`${u}?${h}`:u;l("Purchasing access pass:",h||"default tier");let O=x.headers.get("PAYMENT-REQUIRED");if(!O)return null;let k;try{k=JSON.parse(atob(O))}catch{return null}let N=C(k.accepts);if(!N)return null;if(ot(k.extensions))throw new _("unsupported_required_payment_identifier","Required payment identifiers are not supported by this client");let{accept:D,adapter:J,wallet:le}=N;if(J.name==="Solana"&&!D.extra?.feePayer)return null;let Y=D.extra?.decimals??(at(D.asset)?6:void 0);if(typeof Y!="number")return null;let be=D.amount??D.maxAmountRequired;if(!be)return null;let z=$(D.network,J);try{let m=await J.getBalance(D,le,z),G=Number(be)/Math.pow(10,Y);if(m<G){let St=T(D.network,J.name);throw new _("insufficient_balance",`Insufficient balance for access pass on ${St}. Have $${m.toFixed(4)}, need $${G.toFixed(4)}`)}}catch(m){if(m instanceof _)throw m}let Q=await J.buildTransaction(D,le,z),de;J.name==="EVM"?de=JSON.parse(Q.serialized):de={transaction:Q.serialized};let ee=typeof g=="string"?g:g instanceof URL?g.href:g.url,ue=k.resource;if(typeof k.resource=="string")try{let m=new URL(k.resource,ee);["http:","https:"].includes(m.protocol)&&(ue=m.toString())}catch{}else if(k.resource&&typeof k.resource=="object"&&"url"in k.resource){let m=k.resource;try{let G=new URL(m.url,ee);["http:","https:"].includes(G.protocol)&&(ue={...m,url:G.toString()})}catch{}}let qe={x402Version:D.x402Version??2,resource:ue,accepted:D,payload:de};Q.extensions&&(qe.extensions=Q.extensions);let we=btoa(JSON.stringify(qe)),te=await a(d,{...A,method:"POST",headers:{...A?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":we}});if(!te.ok)return l("Pass purchase failed:",te.status),null;let S=te.headers.get("ACCESS-PASS");return S&&(W(u,S),l("Access pass purchased and cached")),te}async function F(g,A){let x=g;if(l("Making request:",x),p){let S=q(x);if(S){l("Using cached access pass");let m=await a(g,{...A,headers:{...A?.headers||{},Authorization:`Bearer ${S}`}});if(m.status!==401&&m.status!==402)return m;l("Cached pass rejected (status",m.status,"), purchasing new pass");try{v.delete(new URL(x).host)}catch{}}}let f=await R(g,A);if(f.status!==402)return f;l("Received 402 Payment Required");let u=f.headers.get("X-ACCESS-PASS-TIERS");if(p&&u){l("Server offers access passes, purchasing...");try{let S=JSON.parse(atob(u)),m=await K(g,A,f,S,x);if(m)return m}catch(S){l("Access pass purchase failed, falling back to per-request payment:",S)}}let h=f.headers.get("PAYMENT-REQUIRED");if(!h)throw new _("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let d;try{let S=atob(h);d=JSON.parse(S)}catch{throw new _("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}if(l("Payment requirements:",d),ot(d.extensions))throw new _("unsupported_required_payment_identifier","Required payment identifiers are not supported by this client");let O=f.headers.get("X-Quote-Hash");O&&l("Quote hash received:",O);let k=C(d.accepts);if(!k){let S=d.accepts.map(m=>m.network).join(", ");throw new _("no_matching_payment_option",`No supported payment option with a connected wallet for: ${S}`)}let{accept:N,adapter:D,wallet:J}=k;if(l(`Using ${D.name} for ${N.network}`),D.name==="Solana"&&!N.extra?.feePayer)throw new _("missing_fee_payer","Solana payment option missing feePayer in extra");let le=N.extra?.decimals??(at(N.asset)?6:void 0);if(typeof le!="number")throw new _("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let Y=N.amount??N.maxAmountRequired;if(!Y)throw new _("missing_amount","Payment option missing amount");if(i&&BigInt(Y)>BigInt(i))throw new _("amount_exceeds_max",`Payment amount ${Y} exceeds maximum ${i}`);let be=$(N.network,D);l("Checking balance...");try{let S=await D.getBalance(N,J,be),m=Number(Y)/Math.pow(10,le);if(S<m){let G=T(N.network,D.name);throw new _("insufficient_balance",`Insufficient balance on ${G}. Have $${S.toFixed(4)}, need $${m.toFixed(4)}`)}l(`Balance OK: $${S.toFixed(4)} >= $${m.toFixed(4)}`)}catch(S){if(S instanceof _)throw S;l("Balance check failed (RPC error), proceeding with transaction attempt")}if(y&&!await y(N))throw new _("payment_rejected","Payment rejected by onPaymentRequired callback");l("Building transaction...");let z=await D.buildTransaction(N,J,be);l("Transaction signed");let Q;D.name==="EVM"?Q=JSON.parse(z.serialized):Q={transaction:z.serialized};let de=g,ee=d.resource;if(typeof d.resource=="string")try{let S=new URL(d.resource,de).toString();S!==d.resource&&l("Resolved relative resource URL:",d.resource,"\u2192",S),ee=S}catch{ee=d.resource}else if(d.resource&&typeof d.resource=="object"&&"url"in d.resource){let S=d.resource;try{let m=new URL(S.url,de).toString();m!==S.url&&(l("Resolved relative resource URL:",S.url,"\u2192",m),ee={...S,url:m})}catch{}}let ue={x402Version:N.x402Version??2,resource:ee,accepted:N,payload:Q};z.extensions&&(ue.extensions=z.extensions);let qe=btoa(JSON.stringify(ue));if(b)try{b(N,z.settlementProbe)}catch{}l("Retrying request with payment...");let we=await R(g,{...A,headers:{...A?.headers||{},"PAYMENT-SIGNATURE":qe,...O?{"X-Quote-Hash":O}:{}}});l("Retry response status:",we.status);let te=Ut(we,{network:N.network,amountAtomic:Y,assetDecimals:le});return te.extensions&&l("Settlement extensions:",Object.keys(te.extensions).join(", ")),we}async function U(g,A){let[x,f]=await Bt(g,A);return F(x,f)}return{fetch:U}}function yt(n){let e=gt(n);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function et(n){let e=yt(n);if(e?.recommendations?.length)return e.recommendations}async function tt(n){let t=yt(n)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function At(n){let{wallets:e,wallet:t,preferredNetwork:r,rpcUrls:s={},verbose:o=!1}=n,[i,a]=(0,I.useState)(!1),[c,p]=(0,I.useState)("idle"),[y,b]=(0,I.useState)(null),[E,w]=(0,I.useState)(null),[l,R]=(0,I.useState)(null),[v,q]=(0,I.useState)([]),[W,P]=(0,I.useState)(null),C=(0,I.useCallback)((...u)=>{o&&console.log("[useX402Payment]",...u)},[o]),T=(0,I.useMemo)(()=>{let u={...e};return t&&!u.solana&&V(t)&&(u.solana=t),t&&!u.evm&&X(t)&&(u.evm=t),u},[e,t]),$=(0,I.useMemo)(()=>[xe({verbose:o,rpcUrls:s}),Te({verbose:o,rpcUrls:s})],[o,s]),K=(0,I.useMemo)(()=>({solana:T.solana?V(T.solana)&&$[0].isConnected(T.solana):!1,evm:T.evm?X(T.evm)&&$[1].isConnected(T.evm):!1}),[T,$]),F=K.solana||K.evm,U=(0,I.useCallback)(async()=>{let u=[];if(K.solana&&T.solana)try{let h=$.find(d=>d.name==="Solana");if(h){let d={scheme:"exact",network:j,amount:"0",asset:We,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},O=await h.getBalance(d,T.solana);u.push({network:j,chainName:Ze(j),balance:O,asset:"USDC"})}}catch(h){C("Failed to fetch Solana balance:",h)}if(K.evm&&T.evm)try{let h=$.find(d=>d.name==="EVM");if(h){let d={scheme:"exact",network:H,amount:"0",asset:Ve,payTo:"",maxTimeoutSeconds:60,extra:{feePayer:"",decimals:6}},O=await h.getBalance(d,T.evm);u.push({network:H,chainName:Ze(H),balance:O,asset:"USDC"})}}catch(h){C("Failed to fetch Base balance:",h)}q(u)},[K,T,$,C]);(0,I.useEffect)(()=>{U();let u=setInterval(U,3e4);return()=>clearInterval(u)},[U]);let g=(0,I.useCallback)(()=>{a(!1),p("idle"),b(null),w(null),R(null),P(null)},[]),A=(0,I.useMemo)(()=>ht({adapters:$,wallets:T,preferredNetwork:r,rpcUrls:s,verbose:o}),[$,T,r,s,o]),x=(0,I.useCallback)(async(u,h)=>{if(a(!0),p("pending"),b(null),w(null),R(null),!F){let d=new _("wallet_not_connected","No wallet connected");throw b(d),p("error"),a(!1),d}try{let d=await A.fetch(u,h),O=d.headers.get("PAYMENT-RESPONSE");if(O)try{let N=JSON.parse(atob(O));N.transaction&&w(N.transaction),N.network&&R(N.network)}catch{C("Could not parse PAYMENT-RESPONSE header")}let k=et(d);return P(k??null),k&&(C("Sponsored recommendations received:",k.length),tt(d).catch(()=>{})),p("success"),d}catch(d){let O=d instanceof Error?d:new Error(String(d));throw b(O),p("error"),d}finally{a(!1),setTimeout(U,2e3)}},[A,F,C,U]),f=(0,I.useMemo)(()=>E?mt(E,l||r||j):null,[E,l,r]);return{fetch:x,isLoading:i,status:c,error:y,transactionId:E,transactionNetwork:l,transactionUrl:f,balances:v,connectedChains:K,isAnyWalletConnected:F,reset:g,refreshBalances:U,accessPass:null,sponsoredRecommendations:W}}0&&(module.exports={X402Error,fireImpressionBeacon,getSponsoredRecommendations,useX402Payment});
@@ -1,5 +1,5 @@
1
- import { X as X402Client } from '../x402-client-Cil4Tmqy.cjs';
2
- import { W as WalletSet, B as BalanceInfo } from '../types-B4JCwkHH.cjs';
1
+ import { X as X402Client } from '../x402-client-zC0XNdb_.cjs';
2
+ import { W as WalletSet, B as BalanceInfo } from '../types-CEOJ9sFp.cjs';
3
3
  import { SponsoredRecommendation } from '@dexterai/x402-ads-types';
4
4
  export { SponsoredRecommendation } from '@dexterai/x402-ads-types';
5
5
  export { A as AccessPassClientConfig, a as AccessPassInfo, b as AccessPassTier, X as X402Error } from '../types-8Q38sHOi.cjs';
@@ -1,5 +1,5 @@
1
- import { X as X402Client } from '../x402-client-Cil4Tmqy.js';
2
- import { W as WalletSet, B as BalanceInfo } from '../types-Ds9IUnXG.js';
1
+ import { X as X402Client } from '../x402-client-zC0XNdb_.js';
2
+ import { W as WalletSet, B as BalanceInfo } from '../types-Bm6-yPwi.js';
3
3
  import { SponsoredRecommendation } from '@dexterai/x402-ads-types';
4
4
  export { SponsoredRecommendation } from '@dexterai/x402-ads-types';
5
5
  export { A as AccessPassClientConfig, a as AccessPassInfo, b as AccessPassTier, X as X402Error } from '../types-8Q38sHOi.js';