@dexterai/x402 6.0.2 → 6.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "use strict";var Gt=Object.create;var Ze=Object.defineProperty;var Zt=Object.getOwnPropertyDescriptor;var Qt=Object.getOwnPropertyNames;var en=Object.getPrototypeOf,tn=Object.prototype.hasOwnProperty;var nn=(n,e)=>{for(var t in e)Ze(n,t,{get:e[t],enumerable:!0})},Tt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qt(e))!tn.call(n,o)&&o!==t&&Ze(n,o,{get:()=>e[o],enumerable:!(r=Zt(e,o))||r.enumerable});return n};var H=(n,e,t)=>(t=n!=null?Gt(en(n)):{},Tt(e||!n||!n.__esModule?Ze(t,"default",{value:n,enumerable:!0}):t,n)),rn=n=>Tt(Ze({},"__esModule",{value:!0}),n);var kn={};nn(kn,{BASE_MAINNET:()=>z,DEXTER_FACILITATOR_URL:()=>St,KEYPAIR_SYMBOL:()=>he,SOLANA_MAINNET:()=>j,USDC_MINT:()=>qe,X402Error:()=>_,buildV1PaymentHeader:()=>Je,capabilitySearch:()=>Pt.capabilitySearch,capturePaymentReceipt:()=>xt,createBudgetAccount:()=>Jt,createEvmAdapter:()=>re,createEvmKeypairWallet:()=>ht,createKeypairWallet:()=>gt,createSolanaAdapter:()=>F,detectStrategy:()=>_t,fireImpressionBeacon:()=>zt,getPaymentReceipt:()=>Pe,getSponsoredAccessInfo:()=>yt,getSponsoredRecommendations:()=>jt,isEvmKeypairWallet:()=>Ht,isKeypairWallet:()=>Lt,payAndFetch:()=>Et,toNetworkRef:()=>J,toSiwxSigner:()=>Ye});module.exports=rn(kn);var Ne="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Qe="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",et="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",j=Ne,Ce=Qe,ke=et,ie="eip155:8453",Se="eip155:84532",we="eip155:42161",ve="eip155:137",xe="eip155:10",Re="eip155:43114",_e="eip155:56",ce="eip155:480",ue="eip155:143",le="eip155:4663",me="eip155:1187947933",de="eip155:324705682",Ee="eip155:1",z=ie,tt=Se,Oe=we,Ve=ve,Be=xe,De=Re,Ue=_e,Me=ce,$e=ue,Ke=le,Fe=me,Le=de,We=Ee,qe="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",It="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",Nt="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",At="0x55d398326f99059fF775485246999027B3197955",nt="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",bt="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",rt={[_e]:nt,[ie]:Nt,[Se]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[we]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[ve]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[xe]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[Re]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[ce]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[ue]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[le]:bt,[me]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[de]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[Ee]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},ot={[At]:{symbol:"USDT",decimals:18},[nt]:{symbol:"USDC",decimals:18}};var st={[ce]:{name:"USDC",version:"2"},[ue]:{name:"USDC",version:"2"},[le]:{name:"Global Dollar",version:"1"},[me]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[de]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}},ne="0x000000000022D473030F116dDEE9F6B43aC78BA3",He="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",je={[_e]:56,[ie]:8453,[Se]:84532,[we]:42161,[ve]:137,[xe]:10,[Re]:43114,[ce]:480,[ue]:143,[le]:4663,[me]:1187947933,[de]:324705682,[Ee]:1},pe={[Ne]:"https://api.dexter.cash/api/solana/rpc",[Qe]:"https://api.devnet.solana.com",[et]:"https://api.testnet.solana.com"},B={[_e]:"https://api.dexter.cash/api/evm/bsc/rpc",[ie]:"https://api.dexter.cash/api/base/rpc",[Se]:"https://sepolia.base.org",[we]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[ve]:"https://api.dexter.cash/api/evm/polygon/rpc",[xe]:"https://api.dexter.cash/api/evm/optimism/rpc",[Re]:"https://api.dexter.cash/api/evm/avalanche/rpc",[ce]:"https://worldchain-mainnet.g.alchemy.com/public",[ue]:"https://rpc.monad.xyz",[le]:"https://rpc.mainnet.chain.robinhood.com",[me]:"https://skale-base.skalenodes.com/v1/base",[de]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[Ee]:"https://eth.llamarpc.com"},St="https://x402.dexter.cash";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 X(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 o=n.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 ze(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 Ct=[{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"}],on=new Map(Ct.map(n=>[n.caip2.toLowerCase(),n])),sn=new Map(Ct.map(n=>[n.bare.toLowerCase(),n]));function J(n){if(!n)return null;let e=n.toLowerCase(),t=on.get(e)||sn.get(e);return t?{caip2:t.caip2,bare:t.bare,family:t.family}:null}function wt(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"))}function an(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,o=J(String(r.network??""));o&&e.push({scheme:String(r.scheme??"exact"),network:o,amount:String(r.amount??r.maxAmountRequired??"0"),asset:String(r.asset??""),payTo:String(r.payTo??""),maxTimeoutSeconds:typeof r.maxTimeoutSeconds=="number"?r.maxTimeoutSeconds:void 0,extra:r.extra&&typeof r.extra=="object"?r.extra:void 0})}return e}async function kt(n){let e=n.headers.get("payment-required");if(!e)return null;let t;try{t=wt(e)}catch{return null}let r=Array.isArray(t.accepts)?t.accepts:[];return r.length===0?null:{x402Version:2,options:an(r),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}}var k=require("@solana/web3.js"),V=require("@solana/spl-token");var cn=12e3,un=1;function fe(n){if(!n||typeof n!="object")return!1;let e=n;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var at=class{name="Solana";networks=[j,Ce,ke];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[j]:e==="solana-devnet"?pe[Ce]:e==="solana-testnet"?pe[ke]:pe[j]}getAddress(e){return fe(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return fe(e)?e.publicKey!==null:!1}async getBalance(e,t,r){if(!fe(t)||!t.publicKey)return 0;let o=r||this.getDefaultRpcUrl(e.network),s=new k.Connection(o,"confirmed"),a=new k.PublicKey(t.publicKey.toBase58()),i=new k.PublicKey(e.asset);try{let u=(await s.getAccountInfo(i,"confirmed"))?.owner.toBase58()===V.TOKEN_2022_PROGRAM_ID.toBase58()?V.TOKEN_2022_PROGRAM_ID:V.TOKEN_PROGRAM_ID,d=await(0,V.getAssociatedTokenAddress)(i,a,!1,u),f=await(0,V.getAccount)(s,d,void 0,u),S=e.extra?.decimals??6;return Number(f.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,r){let o=X(e,"svm");if(o)throw new Error(o);if(!fe(t))throw new Error("Invalid Solana wallet");if(!t.publicKey)throw new Error("Wallet not connected");let s=r||this.getDefaultRpcUrl(e.network),a=new k.Connection(s,"confirmed"),i=new k.PublicKey(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 S=new k.PublicKey(d.feePayer),w=new k.PublicKey(u),l=new k.PublicKey(c);this.log("Building transaction:",{from:i.toBase58(),to:c,amount:f,asset:u,feePayer:d.feePayer});let y=[];y.push(k.ComputeBudgetProgram.setComputeUnitLimit({units:cn})),y.push(k.ComputeBudgetProgram.setComputeUnitPrice({microLamports:un}));let g=await a.getAccountInfo(w,"confirmed");if(!g)throw new Error(`Token mint ${u} not found`);let R=g.owner.toBase58()===V.TOKEN_2022_PROGRAM_ID.toBase58()?V.TOKEN_2022_PROGRAM_ID:V.TOKEN_PROGRAM_ID,m=await(0,V.getMint)(a,w,void 0,R);typeof d?.decimals=="number"&&m.decimals!==d.decimals&&this.log(`Decimals mismatch: requirements say ${d.decimals}, mint says ${m.decimals}`);let p=await(0,V.getAssociatedTokenAddress)(w,i,!1,R),E=await(0,V.getAssociatedTokenAddress)(w,l,!0,R);if(!await a.getAccountInfo(p,"confirmed"))throw new Error(`No token account found for ${u}. Please ensure you have USDC in your wallet.`);if(!await a.getAccountInfo(E,"confirmed"))throw new Error(`Seller token account not found. The seller (${c}) must have a USDC account.`);let G=BigInt(f);y.push((0,V.createTransferCheckedInstruction)(p,w,E,i,G,m.decimals,[],R));let{blockhash:Z}=await a.getLatestBlockhash("confirmed"),$=new k.TransactionMessage({payerKey:S,recentBlockhash:Z,instructions:y}).compileToV0Message(),b=new k.VersionedTransaction($),v=await t.signTransaction(b);return this.log("Transaction signed successfully"),{serialized:Buffer.from(v.serialize()).toString("base64"),settlementProbe:{kind:"solana",sourceAta:p.toBase58(),destinationAta:E.toBase58(),asset:u,amount:f,blockhash:Z}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let r=new k.Connection(t,"confirmed"),o=new k.PublicKey(e.destinationAta),s=await r.getSignaturesForAddress(o,{limit:25});if(s.length===0)return{settled:!1};let a=BigInt(e.amount);for(let i of s){if(i.err)continue;let c=await r.getTransaction(i.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 S of f){if(S.mint!==e.asset)continue;let w=u[S.accountIndex];if(!w||!w.equals(o))continue;let l=d.find(R=>R.accountIndex===S.accountIndex),y=BigInt(l?.uiTokenAmount.amount??"0");if(BigInt(S.uiTokenAmount.amount??"0")-y===a)return{settled:!0,txSignature:i.signature}}}return{settled:!1}}};function F(n){return new at(n)}var ln={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"validAfter",type:"uint256"}]},Ot=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function ge(n){if(!n||typeof n!="object")return!1;let e=n;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var it=class{name="EVM";networks=[Ue,z,tt,We,Oe,Ve,Be,De,Me,$e,Ke,Fe,Le];config;log;constructor(e={}){this.config=e,this.log=e.verbose?console.log.bind(console,"[x402:evm]"):()=>{}}canHandle(e){return!!(this.networks.includes(e)||e==="base"||e==="bsc"||e==="ethereum"||e==="arbitrum"||e==="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]:B[e]?B[e]:e==="base"?B[z]:e==="bsc"?B[Ue]:e==="ethereum"?B[We]:e==="arbitrum"?B[Oe]:e==="polygon"?B[Ve]:e==="optimism"?B[Be]:e==="avalanche"?B[De]:e==="world"?B[Me]:e==="monad"?B[$e]:e==="robinhood"?B[Ke]:e==="skale-base"?B[Fe]:e==="skale-base-sepolia"?B[Le]:B[z]}getAddress(e){return ge(e)?e.address:null}isConnected(e){return ge(e)?!!e.address:!1}getChainId(e){if(je[e])return je[e];if(e.startsWith("eip155:")){let t=e.split(":")[1];return parseInt(t,10)}return e==="base"?8453:e==="bsc"?56:e==="ethereum"?1:e==="arbitrum"?42161: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(!ge(t)||!t.address)return 0;let o=r||this.getDefaultRpcUrl(e.network);try{let s=this.encodeBalanceOf(t.address),a=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(!a.ok)throw new Error(`RPC request failed: ${a.status}`);let i=await a.json();if(i.error)throw new Error(`RPC error: ${JSON.stringify(i.error)}`);if(!i.result||i.result==="0x")return 0;let c=BigInt(i.result),u=e.extra?.decimals??6;return Number(c)/Math.pow(10,u)}catch(s){throw s}}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",o=e.from.slice(2).toLowerCase().padStart(64,"0"),s=e.nonce.slice(2).toLowerCase().padStart(64,"0"),a=r+o+s,i=await this.ethCall(t,e.asset,a);return{settled:BigInt(i)!==0n}}if(e.kind==="permit2"){let r="0x4fe02b44",o=BigInt(e.nonce),s=o>>8n,a=o&0xffn,i=e.from.slice(2).toLowerCase().padStart(64,"0"),c=s.toString(16).padStart(64,"0"),u=r+i+c,d=await this.ethCall(t,ne,u);return{settled:(BigInt(d)>>a&1n)===1n}}throw new Error(`EvmAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`)}async ethCall(e,t,r){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:r},"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,r){let o=X(e,"evm");if(o)throw new Error(o);if(!ge(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:s,asset:a,extra:i}=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:a,network:e.network});let u=this.getChainId(e.network),d=st[`eip155:${u}`],f={name:i?.name??d?.name??"USD Coin",version:i?.version??d?.version??"2",chainId:BigInt(u),verifyingContract:a},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"}]},w=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(w);let l="0x"+[...w].map(E=>E.toString(16).padStart(2,"0")).join(""),y=Math.floor(Date.now()/1e3),g={from:t.address,to:s,value:c,validAfter:String(y-600),validBefore:String(y+(e.maxTimeoutSeconds||60)),nonce:l},R={from:t.address,to:s,value:BigInt(c),validAfter:BigInt(y-600),validBefore:BigInt(y+(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:S,primaryType:"TransferWithAuthorization",message:R});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:a,chainId:u}}}async buildApprovalTransaction(e,t,r){let{payTo:o,asset:s,extra:a}=e,i=e.amount??e.maxAmountRequired;if(!i)throw new Error("Missing amount in payment requirements");let c=a?.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:i,asset:s,network:e.network,facilitatorContract:c});let u=r||this.getDefaultRpcUrl(e.network),d=a?.fee??"0",f=BigInt(i)+BigInt(d),S=await this.readAllowance(u,s,t.address,c);if(S<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 $=this.calculateApprovalAmount(i,d,a?.approvalStrategy);this.log(`Approving ${$} for ${c} (current allowance: ${S})`);let b=await t.sendTransaction({to:s,data:this.encodeApprove(c,$),value:0n});this.log(`Approval tx sent: ${b}`),await this.waitForReceipt(u,b),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(($,b)=>$*256n+BigInt(b),0n).toString(),y=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(y);let g="0x"+[...y].map($=>$.toString(16).padStart(2,"0")).join(""),m=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),p=a?.eip712Domain,E=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},D=a?.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"}]},oe={from:t.address,to:o,token:s,amount:BigInt(i),fee:BigInt(d),nonce:BigInt(l),deadline:BigInt(m),paymentId:g},G=await t.signTypedData({domain:E,types:D,primaryType:"Payment",message:oe});this.log("EIP-712 Payment signature obtained");let Z={from:t.address,to:o,token:s,amount:i,fee:d,nonce:l,deadline:m,paymentId:g,signature:G};return{serialized:JSON.stringify(Z),signature:G}}async buildPermit2Transaction(e,t,r){let{payTo:o,asset:s}=e,a=e.amount??e.maxAmountRequired;if(!a)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:a,asset:s,network:e.network});let i=r||this.getDefaultRpcUrl(e.network),c=await this.readAllowance(i,s,t.address,ne),u;if(c<BigInt(a)){let E=this.encodeApprove(ne,Ot);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${c})`);let D=this.getChainId(e.network),oe=await this.readGasPrice(i),G=await this.readNonce(i,t.address),Z=await t.signTransaction({to:s,data:E,chainId:D,gas:50000n,gasPrice:oe,nonce:G});u={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:s,spender:ne,amount:Ot.toString(),signedTransaction:Z,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${c})`);let D=await t.sendTransaction({to:s,data:E,value:0n});this.log(`Permit2 approval tx sent: ${D}`),await this.waitForReceipt(i,D),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((E,D)=>E*256n+BigInt(D),0n),S=Math.floor(Date.now()/1e3),w=S-600,l=S+(e.maxTimeoutSeconds||300),y=this.getChainId(e.network),g={name:"Permit2",chainId:BigInt(y),verifyingContract:ne},R={permitted:{token:s,amount:BigInt(a)},spender:He,nonce:f,deadline:BigInt(l),witness:{to:o,validAfter:BigInt(w)}},m=await t.signTypedData({domain:g,types:ln,primaryType:"PermitWitnessTransferFrom",message:R});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let p={signature:m,permit2Authorization:{from:t.address,permitted:{token:s,amount:a},spender:He,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:y}}}async readAllowance(e,t,r,o){let s="0xdd62ed3e",a=r.slice(2).toLowerCase().padStart(64,"0"),i=o.slice(2).toLowerCase().padStart(64,"0"),c=s+a+i;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 r="0x095ea7b3",o=e.slice(2).toLowerCase().padStart(64,"0"),s=t.toString(16).padStart(64,"0");return r+o+s}async waitForReceipt(e,t,r=3e4){let o=Date.now();for(;Date.now()-o<r;){try{let a=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(a.result){if(a.result.status==="0x0")throw new Error(`Approval transaction reverted: ${t}`);return}}catch(s){if(s instanceof Error&&s.message.includes("reverted"))throw s}await new Promise(s=>setTimeout(s,2e3))}throw new Error(`Approval transaction receipt timeout after ${r}ms: ${t}`)}async readGasPrice(e){try{let r=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_gasPrice",params:[]})})).json();return r.result?BigInt(r.result):50000000n}catch{return 50000000n}}async readNonce(e,t){try{let o=await(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionCount",params:[t,"latest"]})})).json();return o.result?parseInt(o.result,16):0}catch{return 0}}calculateApprovalAmount(e,t,r){let o=BigInt(e)+BigInt(t);if(!r||r.mode==="exact")return o;let s=BigInt(r.defaultMultiple??10),a=o*s;if(r.maxCapUsd){let i=this.inferDecimals(e),c=BigInt(Math.floor(r.maxCapUsd*Math.pow(10,i)));if(a>c)return c}if(r.exactAboveUsd){let i=this.inferDecimals(e),c=BigInt(Math.floor(r.exactAboveUsd*Math.pow(10,i)));if(BigInt(e)>c)return o}return a}inferDecimals(e){return e.length>12?18:6}};function re(n){return new it(n)}function vt(n){if(n===qe||n===It)return!0;let e=n.toLowerCase();for(let t of Object.values(rt))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(ot))if(t.toLowerCase()===e)return!0;return!1}function mn(n){return{[Ne]:"Solana",[Qe]:"Solana Devnet",[et]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[ie]:"Base",[Se]:"Base Sepolia",[Ee]:"Ethereum",[we]:"Arbitrum",[ve]:"Polygon",[xe]:"Optimism",[Re]:"Avalanche",[_e]:"BSC",[ce]:"World Chain",[ue]:"Monad",[le]:"Robinhood Chain",[me]:"SKALE Base",[de]:"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 Vt(n,e){let t=mn(n);return t===n?e:t}async function dn(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((a,i)=>r.set(i,a));let o={method:e?.method??t.method,headers:r,signal:e?.signal??t.signal,redirect:e?.redirect??t.redirect,credentials:e?.credentials??t.credentials},s=(o.method??"GET").toUpperCase();return e&&"body"in e?o.body=e.body:s!=="GET"&&s!=="HEAD"&&t.body&&(o.body=await t.arrayBuffer()),[t.url,o]}var Bt=new WeakMap;function Pe(n){return Bt.get(n)}function xt(n,e){let t=n.headers.get("PAYMENT-RESPONSE"),r;if(t)try{let i=wt(t);i&&typeof i=="object"&&!Array.isArray(i)&&(r={...i})}catch{}r??={},r.settlementStatus="unconfirmed";let o=r.network===e.network,s=[r.errorReason,r.errorCode,r.errorMessage].every(i=>i===void 0||typeof i=="string"),a=[r.errorReason,r.errorCode].filter(i=>typeof i=="string"&&i.length>0);return a.some(i=>/pending|unknown|unconfirmed|timeout|temporar/i.test(i))?r.settlementStatus="pending":r.success===!0&&o&&s&&a.length===0&&typeof r.transaction=="string"&&r.transaction.trim().length>0?r.settlementStatus="settled":r.success===!1&&(o||r.network===void 0)&&a.length>0&&(r.settlementStatus="failed"),r.attemptedAmountAtomic=e.amountAtomic,r.settlementStatus==="settled"?r.amountAtomic=e.amountAtomic:delete r.amountAtomic,r.assetDecimals=e.assetDecimals,Bt.set(n,r),r}function ct(n){let{adapters:e=[F({verbose:n.verbose}),re({verbose:n.verbose})],wallets:t,wallet:r,preferredNetwork:o,rpcUrls:s={},maxAmountAtomic:a,fetch:i=globalThis.fetch,verbose:c=!1,accessPass:u,onPaymentRequired:d,onPaymentDispatched:f,maxRetries:S=0,retryDelayMs:w=500}=n,l=c?console.log.bind(console,"[x402]"):()=>{};async function y(b,v){let P;for(let A=0;A<=S;A++)try{let I=await i(b,v);if(I.status>=502&&I.status<=504&&A<S){l(`Retry ${A+1}/${S}: server returned ${I.status}`),await new Promise(T=>setTimeout(T,w*Math.pow(2,A)));continue}return I}catch(I){P=I,A<S&&(l(`Retry ${A+1}/${S}: ${I instanceof Error?I.message:"network error"}`),await new Promise(T=>setTimeout(T,w*Math.pow(2,A))))}throw P}let g=new Map;function R(b){try{let v=new URL(b).host,P=g.get(v);if(P&&P.expiresAt>Date.now()/1e3+10)return P.jwt;P&&g.delete(v)}catch{}return null}function m(b,v){try{let P=new URL(b).host,A=v.split(".");if(A.length===3){let I=JSON.parse(atob(A[1].replace(/-/g,"+").replace(/_/g,"/"))),T=Math.floor(Date.now()/1e3),N=T+86400,K=Math.min(typeof I.exp=="number"?I.exp:T,N);g.set(P,{jwt:v,expiresAt:K}),l("Access pass cached for",P,"| expires:",new Date(K*1e3).toISOString())}}catch{l("Failed to cache access pass")}}let p=t||{};r&&!p.solana&&fe(r)&&(p.solana=r),r&&!p.evm&&ge(r)&&(p.evm=r);function E(b){let v=[];for(let P of b){let A=e.find(N=>N.canHandle(P.network));if(!A)continue;let I=A.name==="Solana"?"svm":"evm";if(X(P,I))continue;let T;A.name==="Solana"?T=p.solana:A.name==="EVM"&&(T=p.evm),T&&A.isConnected(T)&&v.push({accept:P,adapter:A,wallet:T})}if(v.length===0)return null;if(o){let P=v.find(A=>A.accept.network===o);if(P)return P}return v[0]}function D(b,v){return Vt(b,v)}function oe(b,v){return s[b]||v.getDefaultRpcUrl(b)}async function G(b,v,P,A,I){let T="";if(u?.preferTier&&A.tiers){let h=A.tiers.find(q=>q.id===u.preferTier);if(h){if(u.maxSpend&&parseFloat(h.price)>parseFloat(u.maxSpend))throw new _("access_pass_exceeds_max_spend",`Access pass tier "${h.id}" costs $${h.price}, exceeds max spend $${u.maxSpend}`);T=`tier=${h.id}`}}else if(u?.preferDuration&&A.ratePerHour)T=`duration=${u.preferDuration}`;else if(A.tiers&&A.tiers.length>0){let h=A.tiers[0];if(u?.maxSpend&&parseFloat(h.price)>parseFloat(u.maxSpend))throw new _("access_pass_exceeds_max_spend",`Cheapest access pass costs $${h.price}, exceeds max spend $${u?.maxSpend}`);T=`tier=${h.id}`}let N=T?I.includes("?")?`${I}&${T}`:`${I}?${T}`:I;l("Purchasing access pass:",T||"default tier");let K=P.headers.get("PAYMENT-REQUIRED");if(!K)return null;let U;try{U=JSON.parse(atob(K))}catch{return null}let O=E(U.accepts);if(!O)return null;if(ze(U.extensions))throw new _("unsupported_required_payment_identifier","Required payment identifiers are not supported by this client");let{accept:C,adapter:W,wallet:ye}=O;if(W.name==="Solana"&&!C.extra?.feePayer)return null;let Q=C.extra?.decimals??(vt(C.asset)?6:void 0);if(typeof Q!="number")return null;let Te=C.amount??C.maxAmountRequired;if(!Te)return null;let ee=oe(C.network,W);try{let h=await W.getBalance(C,ye,ee),q=Number(Te)/Math.pow(10,Q);if(h<q){let Yt=D(C.network,W.name);throw new _("insufficient_balance",`Insufficient balance for access pass on ${Yt}. Have $${h.toFixed(4)}, need $${q.toFixed(4)}`)}}catch(h){if(h instanceof _)throw h}let te=await W.buildTransaction(C,ye,ee),Ae;W.name==="EVM"?Ae=JSON.parse(te.serialized):Ae={transaction:te.serialized};let se=typeof b=="string"?b:b instanceof URL?b.href:b.url,be=U.resource;if(typeof U.resource=="string")try{let h=new URL(U.resource,se);["http:","https:"].includes(h.protocol)&&(be=h.toString())}catch{}else if(U.resource&&typeof U.resource=="object"&&"url"in U.resource){let h=U.resource;try{let q=new URL(h.url,se);["http:","https:"].includes(q.protocol)&&(be={...h,url:q.toString()})}catch{}}let Ge={x402Version:C.x402Version??2,resource:be,accepted:C,payload:Ae};te.extensions&&(Ge.extensions=te.extensions);let Ie=btoa(JSON.stringify(Ge)),ae=await i(N,{...v,method:"POST",headers:{...v?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":Ie}});if(!ae.ok)return l("Pass purchase failed:",ae.status),null;let x=ae.headers.get("ACCESS-PASS");return x&&(m(I,x),l("Access pass purchased and cached")),ae}async function Z(b,v){let P=b;if(l("Making request:",P),u){let x=R(P);if(x){l("Using cached access pass");let h=await i(b,{...v,headers:{...v?.headers||{},Authorization:`Bearer ${x}`}});if(h.status!==401&&h.status!==402)return h;l("Cached pass rejected (status",h.status,"), purchasing new pass");try{g.delete(new URL(P).host)}catch{}}}let A=await y(b,v);if(A.status!==402)return A;l("Received 402 Payment Required");let I=A.headers.get("X-ACCESS-PASS-TIERS");if(u&&I){l("Server offers access passes, purchasing...");try{let x=JSON.parse(atob(I)),h=await G(b,v,A,x,P);if(h)return h}catch(x){l("Access pass purchase failed, falling back to per-request payment:",x)}}let T=A.headers.get("PAYMENT-REQUIRED");if(!T)throw new _("missing_payment_required_header","Server returned 402 but no PAYMENT-REQUIRED header");let N;try{let x=atob(T);N=JSON.parse(x)}catch{throw new _("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}if(l("Payment requirements:",N),ze(N.extensions))throw new _("unsupported_required_payment_identifier","Required payment identifiers are not supported by this client");let K=A.headers.get("X-Quote-Hash");K&&l("Quote hash received:",K);let U=E(N.accepts);if(!U){let x=N.accepts.map(h=>h.network).join(", ");throw new _("no_matching_payment_option",`No supported payment option with a connected wallet for: ${x}`)}let{accept:O,adapter:C,wallet:W}=U;if(l(`Using ${C.name} for ${O.network}`),C.name==="Solana"&&!O.extra?.feePayer)throw new _("missing_fee_payer","Solana payment option missing feePayer in extra");let ye=O.extra?.decimals??(vt(O.asset)?6:void 0);if(typeof ye!="number")throw new _("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let Q=O.amount??O.maxAmountRequired;if(!Q)throw new _("missing_amount","Payment option missing amount");if(a&&BigInt(Q)>BigInt(a))throw new _("amount_exceeds_max",`Payment amount ${Q} exceeds maximum ${a}`);let Te=oe(O.network,C);l("Checking balance...");try{let x=await C.getBalance(O,W,Te),h=Number(Q)/Math.pow(10,ye);if(x<h){let q=D(O.network,C.name);throw new _("insufficient_balance",`Insufficient balance on ${q}. Have $${x.toFixed(4)}, need $${h.toFixed(4)}`)}l(`Balance OK: $${x.toFixed(4)} >= $${h.toFixed(4)}`)}catch(x){if(x instanceof _)throw x;l("Balance check failed (RPC error), proceeding with transaction attempt")}if(d&&!await d(O))throw new _("payment_rejected","Payment rejected by onPaymentRequired callback");l("Building transaction...");let ee=await C.buildTransaction(O,W,Te);l("Transaction signed");let te;C.name==="EVM"?te=JSON.parse(ee.serialized):te={transaction:ee.serialized};let Ae=b,se=N.resource;if(typeof N.resource=="string")try{let x=new URL(N.resource,Ae).toString();x!==N.resource&&l("Resolved relative resource URL:",N.resource,"\u2192",x),se=x}catch{se=N.resource}else if(N.resource&&typeof N.resource=="object"&&"url"in N.resource){let x=N.resource;try{let h=new URL(x.url,Ae).toString();h!==x.url&&(l("Resolved relative resource URL:",x.url,"\u2192",h),se={...x,url:h})}catch{}}let be={x402Version:O.x402Version??2,resource:se,accepted:O,payload:te};ee.extensions&&(be.extensions=ee.extensions);let Ge=btoa(JSON.stringify(be));if(f)try{f(O,ee.settlementProbe)}catch{}l("Retrying request with payment...");let Ie=await y(b,{...v,headers:{...v?.headers||{},"PAYMENT-SIGNATURE":Ge,...K?{"X-Quote-Hash":K}:{}}});l("Retry response status:",Ie.status);let ae=xt(Ie,{network:O.network,amountAtomic:Q,assetDecimals:ye});return ae.extensions&&l("Settlement extensions:",Object.keys(ae.extensions).join(", ")),Ie}async function $(b,v){let[P,A]=await dn(b,v);return Z(P,A)}return{fetch:$}}var wn=require("@solana/web3.js"),mt=require("@noble/hashes/utils");var pn=H(require("tweetnacl"),1),fn=require("@solana/web3.js"),ut=require("@dexterai/vault/messages"),gn=require("@dexterai/vault/session");var M=require("@dexterai/vault/messages");var hn=require("@noble/hashes/sha256");var pr=(1n<<64n)-1n;var yn=require("@noble/hashes/sha256"),An=require("@noble/hashes/utils");var bn="dexter-native-tab-v2-reservation/v1",gr=`${bn}:`;var vn=require("@dexterai/vault/session");var Rt=require("@dexterai/vault/instructions"),Sn=require("@dexterai/vault/precompile"),lt=require("@dexterai/vault/constants");function Dt(n,e){let t=e??n.reservationReceipt;if((n.payload.sequenceNumber&2147483648)!==0&&!t)throw new Error("native_tab_v2_reservation_receipt_required");return Buffer.from(JSON.stringify({payload:n.payload,sessionPublicKey:(0,mt.bytesToHex)(n.sessionPublicKey),sessionRegistration:(0,mt.bytesToHex)(n.sessionRegistration),sessionSignature:(0,mt.bytesToHex)(n.sessionSignature),...t?{reservationReceipt:t}:{}}),"utf8").toString("base64")}function Y(n){if(n instanceof Error){if(n.message&&n.message.length>0)return n.message;if(n.name&&n.name.length>0)return n.name}let e=String(n);return e.length>0?e:"unknown error"}async function Xe(n){let e="";try{e=(await n.clone().text()).slice(0,600)}catch{}let t=e.toLowerCase(),r=t.includes("settle")||t.includes("facilitator"),o=e;try{let s=JSON.parse(e),a=[s.error,s.detail,s.message].filter(i=>typeof i=="string"&&i.length>0);a.length>0&&(o=a.join(" \u2014 "))}catch{}return o||(o=`HTTP ${n.status}`),{reason:r?"settlement_failed":"merchant_rejected",detail:`merchant HTTP ${n.status}: ${o}`}}var dt="Payment authorization was sent, but the merchant did not respond within the timeout. ",pt=" Do not retry without checking \u2014 inspect the funding wallet for a transfer to the merchant before attempting payment again.";async function ft(n,e,t){if(!n)return{confirmed:!1,detail:dt+"This payment scheme has no on-chain confirmation check, so the SDK cannot verify whether it settled."+pt};try{if(n.kind==="solana"){let a=F(),i=t??a.getDefaultRpcUrl(e.caip2);if(!a.confirmSettlement)return Mt();let c=await a.confirmSettlement(n,i);return c.settled?{confirmed:!0,txSignature:c.txSignature}:Ut()}let r=re(),o=r.getDefaultRpcUrl(e.caip2);if(!r.confirmSettlement)return Mt();let s=await r.confirmSettlement(n,o);return s.settled?{confirmed:!0,txSignature:s.txSignature}:Ut()}catch(r){return{confirmed:!1,detail:dt+`On-chain confirmation could not be completed (${Y(r)}).`+pt}}}function Ut(){return{confirmed:!1,detail:dt+"On-chain confirmation found no matching settlement yet \u2014 the payment may still be pending, or may not have settled."+pt}}function Mt(){return{confirmed:!1,detail:dt+"The chain adapter does not support on-chain confirmation."+pt}}async function xn(n,e,t,r){let o;try{o=await r.signNextVoucher(t.amount)}catch(c){return r.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",Dt(o));let a={method:e.method??"GET",headers:s};e.signal&&(a.signal=e.signal),typeof e.body=="string"&&(a.body=e.body);let i;try{i=await fetch(n,a)}catch(c){return{ok:!1,reason:"error",detail:c?.message??String(c)}}return i.status===402?r.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"}:r.rollbackVoucher?.call(r,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:i.ok?{ok:!0,paid:!0,response:i,amountPaid:t.amount,network:t.network}:{ok:!1,...await Xe(i)}}var $t={version:2,async parseChallenge(n){return kt(n)},async pay(n,e,t,r,o){if(ze(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 xn(n,e,m,o.tab);if(p)return p}}let s=t.options.filter(m=>!X(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=>X(m,m.network.family)).join("; ")}`};let a=s.find(m=>m.network.family==="evm"?!!r.evm:m.network.family==="svm"?!!r.solana:!1);if(!a)return{ok:!1,reason:"unsupported_network"};let i=o.timeoutMs??15e3,c=o.responseTimeoutMs??12e4,u=new AbortController,d=setTimeout(()=>u.abort(),i),f=!1,S,w,l=(m,p)=>{f=!0,w=m,S=p,clearTimeout(d),d=setTimeout(()=>u.abort(),c)},y=ct({wallets:r,preferredNetwork:a.network.caip2,maxAmountAtomic:o.maxAmountAtomic,fetch:globalThis.fetch,onPaymentDispatched:l}),g=e.signal?AbortSignal.any([e.signal,u.signal]):u.signal,R={method:e.method??"GET",headers:e.headers,signal:g};typeof e.body=="string"&&(R.body=e.body);try{let m=await y.fetch(n,R);if(clearTimeout(d),!f)return m.ok?{ok:!0,paid:!1,response:m}:{ok:!1,response:m,...await Xe(m)};let p=Pe(m),E=typeof p?.transaction=="string"?p.transaction:void 0;if(p?.settlementStatus!=="settled"){let D=p?.settlementStatus==="failed";return{ok:!1,reason:D?"settlement_failed":"payment_unconfirmed",detail:`${D?"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:E,paymentReceipt:p}}return m.ok?{ok:!0,paid:!0,response:m,amountPaid:w?.amount??w?.maxAmountRequired??a.amount,network:J(w?.network??"")??a.network,txSignature:E,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:E,paymentReceipt:p}}catch(m){clearTimeout(d);let p=m;if(p?.name==="AbortError"){if(!f)return{ok:!1,reason:"timeout"};let E=await ft(S,a.network,o.solanaRpcUrl);return E.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:a.amount,network:a.network,txSignature:E.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:E.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)}}}};var Kt=require("viem");var Rn={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 _n(){let n=globalThis.crypto??(await import("crypto")).webcrypto,e=new Uint8Array(32);return n.getRandomValues(e),"0x"+Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}async function En(n,e,t){if(typeof n.signTypedData!="function")throw new Error("EVM wallet does not support signTypedData");let r=Math.floor(Date.now()/1e3),o=String(r-600),s=String(r+(e.maxTimeoutSeconds??60)),a={from:n.address,to:e.payTo,value:e.amount,validAfter:o,validBefore:s,nonce:await _n()},i=je[e.network.caip2];if(i===void 0)throw new Error(`unknown chain id for network ${e.network.caip2}`);let c=e.extra,u=await n.signTypedData({domain:{name:c.name,version:c.version,chainId:i,verifyingContract:(0,Kt.getAddress)(e.asset)},types:Rn,primaryType:"TransferWithAuthorization",message:a});return{payment:{x402Version:1,scheme:e.scheme,network:t,payload:{signature:u,authorization:a}},settlementProbe:{kind:"eip3009",from:a.from,nonce:a.nonce,asset:e.asset,chainId:i}}}async function Je(n,e,t){try{let r;for(let o of n.options){let s=o.network.family==="evm"&&!!e.evm||o.network.family==="svm"&&!!e.solana;if(o.scheme!=="exact"){s&&(r=o.scheme);continue}if(o.network.family==="evm"&&e.evm){let a=await e.evm;return await Pn(o,a,t)}if(o.network.family==="svm"&&e.solana){let a=await e.solana;return await Tn(o,a,t)}}return r!==void 0?{ok:!1,reason:"merchant_rejected",detail:`v1 supports only the 'exact' scheme, got '${r}'`}:{ok:!1,reason:"unsupported_network"}}catch(r){return{ok:!1,reason:"error",detail:Y(r)}}}async function Pn(n,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(n.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};let r=n.extra??{},o=r.name,s=r.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 a=n.network.bare,{payment:i,settlementProbe:c}=await En(e,n,a);return{ok:!0,headerValue:Buffer.from(JSON.stringify(i),"utf8").toString("base64"),option:n,settlementProbe:c}}async function Tn(n,e,t){if(t.maxAmountAtomic!==void 0&&BigInt(n.amount)>BigInt(t.maxAmountAtomic))return{ok:!1,reason:"budget_exceeded"};if(n.scheme!=="exact")return{ok:!1,reason:"merchant_rejected",detail:`v1 SVM supports only the 'exact' scheme, got '${n.scheme}'`};let r=n.extra??{};if(typeof r.feePayer!="string"||r.feePayer.length===0)return{ok:!1,reason:"merchant_rejected",detail:"v1 SVM challenge missing extra.feePayer (required as the transaction fee payer)"};let o=n.network.bare,s={x402Version:1,scheme:n.scheme,network:o,asset:n.asset,payTo:n.payTo,amount:n.amount,maxAmountRequired:n.amount,maxTimeoutSeconds:n.maxTimeoutSeconds??60,extra:r},i=await F().buildTransaction(s,e,t.solanaRpcUrl),c={x402Version:1,scheme:n.scheme,network:o,payload:{transaction:i.serialized}};return{ok:!0,headerValue:Buffer.from(JSON.stringify(c),"utf8").toString("base64"),option:n,settlementProbe:i.settlementProbe}}function In(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let r=t,o=J(String(r.network??""));o&&e.push({scheme:String(r.scheme??"exact"),network:o,amount:String(r.maxAmountRequired??r.amount??"0"),asset:String(r.asset??""),payTo:String(r.payTo??""),maxTimeoutSeconds:typeof r.maxTimeoutSeconds=="number"?r.maxTimeoutSeconds:void 0,extra:r.extra&&typeof r.extra=="object"?r.extra:void 0})}return e}var Ft={version:1,async parseChallenge(n){if(n.headers.get("payment-required"))return null;let e;try{e=await n.clone().json()}catch{return null}let t=Array.isArray(e.accepts)?e.accepts:[];if(t.length===0)return null;let r=In(t);return r.length===0?null:{x402Version:1,options:r}},async pay(n,e,t,r,o){let s,a=new AbortController,i=!1,c,u;try{let d=o.timeoutMs??15e3;s=setTimeout(()=>a.abort(),d);let f=await Je(t,r,o);if(!f.ok)return{ok:!1,reason:f.reason,detail:f.detail};let S=f.headerValue,w=f.option;u=w,c=f.settlementProbe;let l=new Headers(e.headers??void 0);l.set("X-PAYMENT",S);let y=e.signal!=null?AbortSignal.any([e.signal,a.signal]):a.signal,g={method:e.method,headers:l,signal:y};typeof e.body=="string"&&(g.body=e.body),i=!0,clearTimeout(s);let R=o.responseTimeoutMs??12e4;s=setTimeout(()=>a.abort(),R);let m=await fetch(n,g);return m.ok?{ok:!0,paid:!0,response:m,amountPaid:w.amount,network:w.network,txSignature:Nn(m)}:{ok:!1,...await Xe(m)}}catch(d){if(d instanceof Error&&d.name==="AbortError"){if(!i)return{ok:!1,reason:"timeout"};let f=await ft(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:Y(d)}}finally{s!==void 0&&clearTimeout(s)}}};function Nn(n){let e=n.headers.get("x-payment-response")??n.headers.get("X-PAYMENT-RESPONSE");if(e)try{let t=JSON.parse(Buffer.from(e,"base64").toString("utf8")),r=t.transaction??t.txHash??t.transactionHash;return typeof r=="string"?r:void 0}catch{return}}var Wt=H(require("tweetnacl"),1);var L=require("@solana/web3.js"),he=Symbol.for("x402:keypair");async function gt(n){let e;if(typeof n=="string"){let t;try{let r=await import("bs58"),o=r.decode??r.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 r=t(n);e=L.Keypair.fromSecretKey(r)}catch{try{let o=JSON.parse(n);if(Array.isArray(o))e=L.Keypair.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(n))e=L.Keypair.fromSecretKey(Uint8Array.from(n));else if(n instanceof Uint8Array)e=L.Keypair.fromSecretKey(n);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 L.VersionedTransaction)return t.sign([e]),t;if(t instanceof L.Transaction)return t.sign(e),t;throw new Error("Unknown transaction type")},[he]:e}}function Lt(n){if(!n||typeof n!="object")return!1;let e=n;return he in e&&e[he]instanceof L.Keypair&&"publicKey"in e&&"signTransaction"in e}function Ye(n){let e=n.evm;if(e&&typeof e.signMessage=="function"&&typeof e.address=="string")return{address:e.address,signMessage:e.signMessage};let t=n.solana;if(t){let r=t[he];if(r&&r.secretKey&&r.publicKey)return{publicKey:r.publicKey,signMessage:async o=>Wt.sign.detached(o,r.secretKey)}}return null}var qt=[$t,Ft];async function _t(n){for(let e of qt)if(await e.parseChallenge(n.clone()))return e;return null}async function Cn(n){let e=Ye(n);if(!e)return fetch;try{return(await import("@x402/extensions/sign-in-with-x")).wrapFetchWithSIWx(fetch,e)}catch(t){return console.warn(`[x402] SIW-X unavailable \u2014 @x402/extensions failed to load; SIW-X merchants will not authenticate. ${Y(t)}`),fetch}}async function Et(n,e,t,r){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;try{o=await(await Cn(t))(n,{...e})}catch(s){return{ok:!1,reason:"error",detail:Y(s)}}if(o.status!==402)return{ok:!0,paid:!1,response:o};for(let s of qt){let a=await s.parseChallenge(o.clone());if(a)return s.pay(n,e,a,t,r)}return{ok:!1,reason:"no_payment_options"}}async function ht(n){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=n.startsWith("0x")?n:`0x${n}`,r=e(t);return{address:r.address,signTypedData:o=>r.signTypedData(o),signTransaction:o=>r.signTransaction({to:o.to,data:o.data,chainId:o.chainId,gas:o.gas,gasPrice:o.gasPrice,nonce:o.nonce,type:"legacy"}),signMessage:o=>r.signMessage({message:o.message})}}function Ht(n){if(!n||typeof n!="object")return!1;let e=n;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")&&"signTypedData"in e&&typeof e.signTypedData=="function"}function yt(n){let e=Pe(n);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function jt(n){let e=yt(n);if(e?.recommendations?.length)return e.recommendations}async function zt(n){let t=yt(n)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function Xt(n,e){let{walletPrivateKey:t,evmPrivateKey:r,preferredNetwork:o,rpcUrls:s,maxAmountAtomic:a,verbose:i,accessPass:c,onPaymentRequired:u}=e;if(!t&&!r)throw new Error("At least one wallet private key is required (walletPrivateKey or evmPrivateKey)");let d={},f=[];t&&f.push(gt(t).then(g=>{d.solana=g}).catch(g=>{console.warn(`[x402] Solana wallet init failed: ${g.message}`)})),r&&f.push(ht(r).then(g=>{d.evm=g}).catch(g=>{console.warn(`[x402] EVM wallet init failed: ${g.message}`)}));let S=f.length>0?Promise.all(f):null,l=ct({wallets:d,preferredNetwork:o,rpcUrls:s,maxAmountAtomic:a,fetch:n,verbose:i,accessPass:c,onPaymentRequired:u}),y=l.fetch.bind(l);return S?(async(g,R)=>(await S,y(g,R))):y}function Jt(n){let{budget:e,allowedDomains:t,onPaymentRequired:r,...o}=n,s=parseFloat(e.total),a=e.perRequest?parseFloat(e.perRequest):1/0,i=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,y)=>l+y.amount,0)}function f(){let l=Date.now()-36e5;return c.filter(y=>y.timestamp>=l).reduce((y,g)=>y+g.amount,0)}let S=Xt(fetch,{...o,onPaymentRequired:async l=>{let y=l.extra?.decimals??6,g=Number(l.amount)/Math.pow(10,y);if(g>a)throw new _("amount_exceeds_max",`$${g.toFixed(4)} exceeds per-request limit of $${a.toFixed(2)}`);let R=d();if(R+g>s)throw new _("amount_exceeds_max",`Budget exceeded. Spent $${R.toFixed(2)} of $${s.toFixed(2)}, payment: $${g.toFixed(4)}`);let m=f();if(m+g>i)throw new _("amount_exceeds_max",`Hourly limit ($${i.toFixed(2)}) exceeded. Spent $${m.toFixed(2)} this hour`);return u=g,r?r(l):!0}});return{fetch:(async(l,y)=>{let g=typeof l=="string"?l:l instanceof URL?l.href:l.url,R="unknown";try{R=new URL(g).hostname}catch{}if(t&&!t.some(p=>R===p||R.endsWith(`.${p}`)))throw new _("payment_rejected",`Domain "${R}" not in allowed domains`);u=0;let m=await S(l,y);if(u>0){let p="unknown",E=m.headers.get("PAYMENT-RESPONSE");if(E)try{p=JSON.parse(atob(E)).network||p}catch{}c.push({amount:u,domain:R,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=[]}}}var Pt=require("@dexterai/x402-core");0&&(module.exports={BASE_MAINNET,DEXTER_FACILITATOR_URL,KEYPAIR_SYMBOL,SOLANA_MAINNET,USDC_MINT,X402Error,buildV1PaymentHeader,capabilitySearch,capturePaymentReceipt,createBudgetAccount,createEvmAdapter,createEvmKeypairWallet,createKeypairWallet,createSolanaAdapter,detectStrategy,fireImpressionBeacon,getPaymentReceipt,getSponsoredAccessInfo,getSponsoredRecommendations,isEvmKeypairWallet,isKeypairWallet,payAndFetch,toNetworkRef,toSiwxSigner});
1
+ "use strict";var Zt=Object.create;var Ze=Object.defineProperty;var Qt=Object.getOwnPropertyDescriptor;var en=Object.getOwnPropertyNames;var tn=Object.getPrototypeOf,nn=Object.prototype.hasOwnProperty;var rn=(r,e)=>{for(var t in e)Ze(r,t,{get:e[t],enumerable:!0})},Tt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of en(e))!nn.call(r,o)&&o!==t&&Ze(r,o,{get:()=>e[o],enumerable:!(n=Qt(e,o))||n.enumerable});return r};var H=(r,e,t)=>(t=r!=null?Zt(tn(r)):{},Tt(e||!r||!r.__esModule?Ze(t,"default",{value:r,enumerable:!0}):t,r)),on=r=>Tt(Ze({},"__esModule",{value:!0}),r);var On={};rn(On,{BASE_MAINNET:()=>X,DEXTER_FACILITATOR_URL:()=>St,KEYPAIR_SYMBOL:()=>he,SOLANA_MAINNET:()=>j,USDC_MINT:()=>qe,X402Error:()=>_,buildV1PaymentHeader:()=>Je,capabilitySearch:()=>Pt.capabilitySearch,capturePaymentReceipt:()=>xt,createBudgetAccount:()=>Gt,createEvmAdapter:()=>re,createEvmKeypairWallet:()=>ht,createKeypairWallet:()=>gt,createSolanaAdapter:()=>L,detectStrategy:()=>Et,fireImpressionBeacon:()=>zt,getPaymentReceipt:()=>Pe,getSponsoredAccessInfo:()=>yt,getSponsoredRecommendations:()=>Xt,isEvmKeypairWallet:()=>jt,isKeypairWallet:()=>Ft,payAndFetch:()=>_t,toNetworkRef:()=>J,toSiwxSigner:()=>Ge});module.exports=on(On);var Ne="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Qe="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",et="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",j=Ne,Ce=Qe,ke=et,ie="eip155:8453",Se="eip155:84532",we="eip155:42161",ve="eip155:137",xe="eip155:10",Re="eip155:43114",Ee="eip155:56",ce="eip155:480",ue="eip155:143",le="eip155:4663",me="eip155:1187947933",de="eip155:324705682",_e="eip155:1",X=ie,tt=Se,Oe=we,Ve=ve,Be=xe,De=Re,Ue=Ee,Me=ce,$e=ue,Ke=le,Le=me,Fe=de,We=_e,qe="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",It="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",Nt="0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",At="0x55d398326f99059fF775485246999027B3197955",nt="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",bt="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",rt={[Ee]:nt,[ie]:Nt,[Se]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[we]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[ve]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[xe]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[Re]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[ce]:"0x79A02482A880bCE3F13e09Da970dC34db4CD24d1",[ue]:"0x754704Bc059F8C67012fEd69BC8A327a5aafb603",[le]:bt,[me]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[de]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[_e]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},ot={[At]:{symbol:"USDT",decimals:18},[nt]:{symbol:"USDC",decimals:18}};var st={[ce]:{name:"USDC",version:"2"},[ue]:{name:"USDC",version:"2"},[le]:{name:"Global Dollar",version:"1"},[me]:{name:"Bridged USDC (SKALE Bridge)",version:"2"},[de]:{name:"Bridged USDC (SKALE Bridge)",version:"2"}},ne="0x000000000022D473030F116dDEE9F6B43aC78BA3",He="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",je={[Ee]:56,[ie]:8453,[Se]:84532,[we]:42161,[ve]:137,[xe]:10,[Re]:43114,[ce]:480,[ue]:143,[le]:4663,[me]:1187947933,[de]:324705682,[_e]:1},pe={[Ne]:"https://api.dexter.cash/api/solana/rpc",[Qe]:"https://api.devnet.solana.com",[et]:"https://api.testnet.solana.com"},B={[Ee]:"https://api.dexter.cash/api/evm/bsc/rpc",[ie]:"https://api.dexter.cash/api/base/rpc",[Se]:"https://sepolia.base.org",[we]:"https://api.dexter.cash/api/evm/arbitrum/rpc",[ve]:"https://api.dexter.cash/api/evm/polygon/rpc",[xe]:"https://api.dexter.cash/api/evm/optimism/rpc",[Re]:"https://api.dexter.cash/api/evm/avalanche/rpc",[ce]:"https://worldchain-mainnet.g.alchemy.com/public",[ue]:"https://rpc.monad.xyz",[le]:"https://rpc.mainnet.chain.robinhood.com",[me]:"https://skale-base.skalenodes.com/v1/base",[de]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[_e]:"https://eth.llamarpc.com"},St="https://x402.dexter.cash";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 z(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 Xe(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 Ct=[{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"}],sn=new Map(Ct.map(r=>[r.caip2.toLowerCase(),r])),an=new Map(Ct.map(r=>[r.bare.toLowerCase(),r]));function J(r){if(!r)return null;let e=r.toLowerCase(),t=sn.get(e)||an.get(e);return t?{caip2:t.caip2,bare:t.bare,family:t.family}:null}function wt(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 cn(r){let e=[];for(let t of r){if(!t||typeof t!="object")continue;let n=t,o=J(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 kt(r){let e=r.headers.get("payment-required");if(!e)return null;let t;try{t=wt(e)}catch{return null}let n=Array.isArray(t.accepts)?t.accepts:[];return n.length===0?null:{x402Version:2,options:cn(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}}var k=require("@solana/web3.js"),V=require("@solana/spl-token");var un=12e3,ln=1;function fe(r){if(!r||typeof r!="object")return!1;let e=r;return"publicKey"in e&&"signTransaction"in e&&typeof e.signTransaction=="function"}var at=class{name="Solana";networks=[j,Ce,ke];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[j]:e==="solana-devnet"?pe[Ce]:e==="solana-testnet"?pe[ke]:pe[j]}getAddress(e){return fe(e)?e.publicKey?.toBase58()??null:null}isConnected(e){return fe(e)?e.publicKey!==null:!1}async getBalance(e,t,n){if(!fe(t)||!t.publicKey)return 0;let o=n||this.getDefaultRpcUrl(e.network),s=new k.Connection(o,"confirmed"),i=new k.PublicKey(t.publicKey.toBase58()),a=new k.PublicKey(e.asset);try{let u=(await s.getAccountInfo(a,"confirmed"))?.owner.toBase58()===V.TOKEN_2022_PROGRAM_ID.toBase58()?V.TOKEN_2022_PROGRAM_ID:V.TOKEN_PROGRAM_ID,d=await(0,V.getAssociatedTokenAddress)(a,i,!1,u),f=await(0,V.getAccount)(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=z(e,"svm");if(o)throw new Error(o);if(!fe(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 k.Connection(s,"confirmed"),a=new k.PublicKey(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 k.PublicKey(d.feePayer),w=new k.PublicKey(u),l=new k.PublicKey(c);this.log("Building transaction:",{from:a.toBase58(),to:c,amount:f,asset:u,feePayer:d.feePayer});let h=[];h.push(k.ComputeBudgetProgram.setComputeUnitLimit({units:un})),h.push(k.ComputeBudgetProgram.setComputeUnitPrice({microLamports:ln}));let g=await i.getAccountInfo(w,"confirmed");if(!g)throw new Error(`Token mint ${u} not found`);let x=g.owner.toBase58()===V.TOKEN_2022_PROGRAM_ID.toBase58()?V.TOKEN_2022_PROGRAM_ID:V.TOKEN_PROGRAM_ID,m=await(0,V.getMint)(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(0,V.getAssociatedTokenAddress)(w,a,!1,x),v=await(0,V.getAssociatedTokenAddress)(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 Y=BigInt(f);h.push((0,V.createTransferCheckedInstruction)(p,w,v,a,Y,m.decimals,[],x));let{blockhash:Z}=await i.getLatestBlockhash("confirmed"),$=new k.TransactionMessage({payerKey:A,recentBlockhash:Z,instructions:h}).compileToV0Message(),S=new k.VersionedTransaction($),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:Z}}}async confirmSettlement(e,t){if(e.kind!=="solana")throw new Error(`SolanaAdapter.confirmSettlement cannot handle probe kind "${e.kind}"`);let n=new k.Connection(t,"confirmed"),o=new k.PublicKey(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 at(r)}var mn={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"validAfter",type:"uint256"}]},Ot=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function ge(r){if(!r||typeof r!="object")return!1;let e=r;return"address"in e&&typeof e.address=="string"&&e.address.startsWith("0x")}var it=class{name="EVM";networks=[Ue,X,tt,We,Oe,Ve,Be,De,Me,$e,Ke,Le,Fe];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]:B[e]?B[e]:e==="base"?B[X]:e==="bsc"?B[Ue]:e==="ethereum"?B[We]:e==="arbitrum"?B[Oe]:e==="polygon"?B[Ve]:e==="optimism"?B[Be]:e==="avalanche"?B[De]:e==="world"?B[Me]:e==="monad"?B[$e]:e==="robinhood"?B[Ke]:e==="skale-base"?B[Le]:e==="skale-base-sepolia"?B[Fe]:B[X]}getAddress(e){return ge(e)?e.address:null}isConnected(e){return ge(e)?!!e.address:!1}getChainId(e){if(je[e])return je[e];if(e.startsWith("eip155:")){let t=e.split(":")[1];return parseInt(t,10)}return e==="base"?8453:e==="bsc"?56:e==="ethereum"?1:e==="arbitrum"?42161: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(!ge(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,ne,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=z(e,"evm");if(o)throw new Error(o);if(!ge(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=st[`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 $=this.calculateApprovalAmount(a,d,i?.approvalStrategy);this.log(`Approving ${$} for ${c} (current allowance: ${A})`);let S=await t.sendTransaction({to:s,data:this.encodeApprove(c,$),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(($,S)=>$*256n+BigInt(S),0n).toString(),h=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(h);let g="0x"+[...h].map($=>$.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},D=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"}]},oe={from:t.address,to:o,token:s,amount:BigInt(a),fee:BigInt(d),nonce:BigInt(l),deadline:BigInt(m),paymentId:g},Y=await t.signTypedData({domain:v,types:D,primaryType:"Payment",message:oe});this.log("EIP-712 Payment signature obtained");let Z={from:t.address,to:o,token:s,amount:a,fee:d,nonce:l,deadline:m,paymentId:g,signature:Y};return{serialized:JSON.stringify(Z),signature:Y}}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,ne),u;if(c<BigInt(i)){let v=this.encodeApprove(ne,Ot);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${c})`);let D=this.getChainId(e.network),oe=await this.readGasPrice(a),Y=await this.readNonce(a,t.address),Z=await t.signTransaction({to:s,data:v,chainId:D,gas:50000n,gasPrice:oe,nonce:Y});u={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:s,spender:ne,amount:Ot.toString(),signedTransaction:Z,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(t.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${c})`);let D=await t.sendTransaction({to:s,data:v,value:0n});this.log(`Permit2 approval tx sent: ${D}`),await this.waitForReceipt(a,D),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,D)=>v*256n+BigInt(D),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:ne},x={permitted:{token:s,amount:BigInt(i)},spender:He,nonce:f,deadline:BigInt(l),witness:{to:o,validAfter:BigInt(w)}},m=await t.signTypedData({domain:g,types:mn,primaryType:"PermitWitnessTransferFrom",message:x});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let p={signature:m,permit2Authorization:{from:t.address,permitted:{token:s,amount:i},spender:He,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 re(r){return new it(r)}function vt(r){if(r===qe||r===It)return!0;let e=r.toLowerCase();for(let t of Object.values(rt))if(t.toLowerCase()===e)return!0;for(let t of Object.keys(ot))if(t.toLowerCase()===e)return!0;return!1}function dn(r){return{[Ne]:"Solana",[Qe]:"Solana Devnet",[et]:"Solana Testnet",solana:"Solana","solana-devnet":"Solana Devnet","solana-testnet":"Solana Testnet",[ie]:"Base",[Se]:"Base Sepolia",[_e]:"Ethereum",[we]:"Arbitrum",[ve]:"Polygon",[xe]:"Optimism",[Re]:"Avalanche",[Ee]:"BSC",[ce]:"World Chain",[ue]:"Monad",[le]:"Robinhood Chain",[me]:"SKALE Base",[de]:"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 Vt(r,e){let t=dn(r);return t===r?e:t}async function pn(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 Bt=new WeakMap;function Pe(r){return Bt.get(r)}function xt(r,e){let t=r.headers.get("PAYMENT-RESPONSE"),n;if(t)try{let a=wt(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,Bt.set(r,n),n}function ct(r){let{adapters:e=[L({verbose:r.verbose}),re({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 P;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){P=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 P}let g=new Map;function x(S){try{let R=new URL(S).host,P=g.get(R);if(P&&P.expiresAt>Date.now()/1e3+10)return P.jwt;P&&g.delete(R)}catch{}return null}function m(S,R){try{let P=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,K=Math.min(typeof I.exp=="number"?I.exp:T,N);g.set(P,{jwt:R,expiresAt:K}),l("Access pass cached for",P,"| expires:",new Date(K*1e3).toISOString())}}catch{l("Failed to cache access pass")}}let p=t||{};n&&!p.solana&&fe(n)&&(p.solana=n),n&&!p.evm&&ge(n)&&(p.evm=n);function v(S){let R=[];for(let P of S){let b=e.find(N=>N.canHandle(P.network));if(!b)continue;let I=b.name==="Solana"?"svm":"evm";if(z(P,I))continue;let T;b.name==="Solana"?T=p.solana:b.name==="EVM"&&(T=p.evm),T&&b.isConnected(T)&&R.push({accept:P,adapter:b,wallet:T})}if(R.length===0)return null;if(o){let P=R.find(b=>b.accept.network===o);if(P)return P}return R[0]}function D(S,R){return Vt(S,R)}function oe(S,R){return s[S]||R.getDefaultRpcUrl(S)}async function Y(S,R,P,b,I){let T="";if(u?.preferTier&&b.tiers){let y=b.tiers.find(q=>q.id===u.preferTier);if(y){if(u.maxSpend&&parseFloat(y.price)>parseFloat(u.maxSpend))throw new _("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 _("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 K=P.headers.get("PAYMENT-REQUIRED");if(!K)return null;let U;try{U=JSON.parse(atob(K))}catch{return null}let O=v(U.accepts);if(!O)return null;if(Xe(U.extensions))throw new _("unsupported_required_payment_identifier","Required payment identifiers are not supported by this client");let{accept:C,adapter:W,wallet:ye}=O;if(W.name==="Solana"&&!C.extra?.feePayer)return null;let Q=C.extra?.decimals??(vt(C.asset)?6:void 0);if(typeof Q!="number")return null;let Te=C.amount??C.maxAmountRequired;if(!Te)return null;let ee=oe(C.network,W);try{let y=await W.getBalance(C,ye,ee),q=Number(Te)/Math.pow(10,Q);if(y<q){let Yt=D(C.network,W.name);throw new _("insufficient_balance",`Insufficient balance for access pass on ${Yt}. Have $${y.toFixed(4)}, need $${q.toFixed(4)}`)}}catch(y){if(y instanceof _)throw y}let te=await W.buildTransaction(C,ye,ee),Ae;W.name==="EVM"?Ae=JSON.parse(te.serialized):Ae={transaction:te.serialized};let se=typeof S=="string"?S:S instanceof URL?S.href:S.url,be=U.resource;if(typeof U.resource=="string")try{let y=new URL(U.resource,se);["http:","https:"].includes(y.protocol)&&(be=y.toString())}catch{}else if(U.resource&&typeof U.resource=="object"&&"url"in U.resource){let y=U.resource;try{let q=new URL(y.url,se);["http:","https:"].includes(q.protocol)&&(be={...y,url:q.toString()})}catch{}}let Ye={x402Version:C.x402Version??2,resource:be,accepted:C,payload:Ae};te.extensions&&(Ye.extensions=te.extensions);let Ie=btoa(JSON.stringify(Ye)),ae=await a(N,{...R,method:"POST",headers:{...R?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":Ie}});if(!ae.ok)return l("Pass purchase failed:",ae.status),null;let E=ae.headers.get("ACCESS-PASS");return E&&(m(I,E),l("Access pass purchased and cached")),ae}async function Z(S,R){let P=S;if(l("Making request:",P),u){let E=x(P);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(P).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 Y(S,R,b,E,P);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 _("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 _("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}if(l("Payment requirements:",N),Xe(N.extensions))throw new _("unsupported_required_payment_identifier","Required payment identifiers are not supported by this client");let K=b.headers.get("X-Quote-Hash");K&&l("Quote hash received:",K);let U=v(N.accepts);if(!U){let E=N.accepts.map(y=>y.network).join(", ");throw new _("no_matching_payment_option",`No supported payment option with a connected wallet for: ${E}`)}let{accept:O,adapter:C,wallet:W}=U;if(l(`Using ${C.name} for ${O.network}`),C.name==="Solana"&&!O.extra?.feePayer)throw new _("missing_fee_payer","Solana payment option missing feePayer in extra");let ye=O.extra?.decimals??(vt(O.asset)?6:void 0);if(typeof ye!="number")throw new _("missing_decimals","Payment option missing decimals - provide in extra or use a known stablecoin");let Q=O.amount??O.maxAmountRequired;if(!Q)throw new _("missing_amount","Payment option missing amount");if(i&&BigInt(Q)>BigInt(i))throw new _("amount_exceeds_max",`Payment amount ${Q} exceeds maximum ${i}`);let Te=oe(O.network,C);l("Checking balance...");try{let E=await C.getBalance(O,W,Te),y=Number(Q)/Math.pow(10,ye);if(E<y){let q=D(O.network,C.name);throw new _("insufficient_balance",`Insufficient balance on ${q}. Have $${E.toFixed(4)}, need $${y.toFixed(4)}`)}l(`Balance OK: $${E.toFixed(4)} >= $${y.toFixed(4)}`)}catch(E){if(E instanceof _)throw E;l("Balance check failed (RPC error), proceeding with transaction attempt")}if(d&&!await d(O))throw new _("payment_rejected","Payment rejected by onPaymentRequired callback");l("Building transaction...");let ee=await C.buildTransaction(O,W,Te);l("Transaction signed");let te;C.name==="EVM"?te=JSON.parse(ee.serialized):te={transaction:ee.serialized};let Ae=S,se=N.resource;if(typeof N.resource=="string")try{let E=new URL(N.resource,Ae).toString();E!==N.resource&&l("Resolved relative resource URL:",N.resource,"\u2192",E),se=E}catch{se=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,Ae).toString();y!==E.url&&(l("Resolved relative resource URL:",E.url,"\u2192",y),se={...E,url:y})}catch{}}let be={x402Version:O.x402Version??2,resource:se,accepted:O,payload:te};ee.extensions&&(be.extensions=ee.extensions);let Ye=btoa(JSON.stringify(be));if(f)try{f(O,ee.settlementProbe)}catch{}l("Retrying request with payment...");let Ie=await h(S,{...R,headers:{...R?.headers||{},"PAYMENT-SIGNATURE":Ye,...K?{"X-Quote-Hash":K}:{}}});l("Retry response status:",Ie.status);let ae=xt(Ie,{network:O.network,amountAtomic:Q,assetDecimals:ye});return ae.extensions&&l("Settlement extensions:",Object.keys(ae.extensions).join(", ")),Ie}async function $(S,R){let[P,b]=await pn(S,R);return Z(P,b)}return{fetch:$}}var vn=require("@solana/web3.js"),mt=require("@noble/hashes/utils");var fn=H(require("tweetnacl"),1),gn=require("@solana/web3.js"),ut=require("@dexterai/vault/messages"),hn=require("@dexterai/vault/session");var M=require("@dexterai/vault/messages");var yn=require("@noble/hashes/sha256");var fr=(1n<<64n)-1n;var An=require("@noble/hashes/sha256"),bn=require("@noble/hashes/utils");var Sn="dexter-native-tab-v2-reservation/v1",hr=`${Sn}:`;var xn=require("@dexterai/vault/session");var Rt=require("@dexterai/vault/instructions"),wn=require("@dexterai/vault/precompile"),lt=require("@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:(0,mt.bytesToHex)(r.sessionPublicKey),sessionRegistration:(0,mt.bytesToHex)(r.sessionRegistration),sessionSignature:(0,mt.bytesToHex)(r.sessionSignature),...t?{reservationReceipt:t}:{}}),"utf8").toString("base64")}function G(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 ze(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 dt="Payment authorization was sent, but the merchant did not respond within the timeout. ",pt=" Do not retry without checking \u2014 inspect the funding wallet for a transfer to the merchant before attempting payment again.";async function ft(r,e,t){if(!r)return{confirmed:!1,detail:dt+"This payment scheme has no on-chain confirmation check, so the SDK cannot verify whether it settled."+pt};try{if(r.kind==="solana"){let i=L(),a=t??i.getDefaultRpcUrl(e.caip2);if(!i.confirmSettlement)return Mt();let c=await i.confirmSettlement(r,a);return c.settled?{confirmed:!0,txSignature:c.txSignature}:Ut()}let n=re(),o=n.getDefaultRpcUrl(e.caip2);if(!n.confirmSettlement)return Mt();let s=await n.confirmSettlement(r,o);return s.settled?{confirmed:!0,txSignature:s.txSignature}:Ut()}catch(n){return{confirmed:!1,detail:dt+`On-chain confirmation could not be completed (${G(n)}).`+pt}}}function Ut(){return{confirmed:!1,detail:dt+"On-chain confirmation found no matching settlement yet \u2014 the payment may still be pending, or may not have settled."+pt}}function Mt(){return{confirmed:!1,detail:dt+"The chain adapter does not support on-chain confirmation."+pt}}async function Rn(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",Dt(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 ze(a)}}var $t={version:2,async parseChallenge(r){return kt(r)},async pay(r,e,t,n,o){if(Xe(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 Rn(r,e,m,o.tab);if(p)return p}}let s=t.options.filter(m=>!z(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=>z(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=ct({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 ze(m)};let p=Pe(m),v=typeof p?.transaction=="string"?p.transaction:void 0;if(p?.settlementStatus!=="settled"){let D=p?.settlementStatus==="failed";return{ok:!1,reason:D?"settlement_failed":"payment_unconfirmed",detail:`${D?"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:J(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 ft(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)}}}};var Kt=require("viem");var En={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 _n(){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 Pn(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 _n()},a=je[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:(0,Kt.getAddress)(e.asset)},types:En,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 Je(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 Tn(o,i,t)}if(o.network.family==="svm"&&e.solana){let i=await e.solana;return await In(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:G(n)}}}async function Tn(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 Pn(e,r,i);return{ok:!0,headerValue:Buffer.from(JSON.stringify(a),"utf8").toString("base64"),option:r,settlementProbe:c}}async function In(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 Nn(r){let e=[];for(let t of r){if(!t||typeof t!="object")continue;let n=t,o=J(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 Lt={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=Nn(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 Je(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:Cn(m)}:{ok:!1,...await ze(m)}}catch(d){if(d instanceof Error&&d.name==="AbortError"){if(!a)return{ok:!1,reason:"timeout"};let f=await ft(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:G(d)}}finally{s!==void 0&&clearTimeout(s)}}};function Cn(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}}var Wt=H(require("tweetnacl"),1);var F=require("@solana/web3.js"),he=Symbol.for("x402:keypair");async function gt(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=F.Keypair.fromSecretKey(n)}catch{try{let o=JSON.parse(r);if(Array.isArray(o))e=F.Keypair.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=F.Keypair.fromSecretKey(Uint8Array.from(r));else if(r instanceof Uint8Array)e=F.Keypair.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 F.VersionedTransaction)return t.sign([e]),t;if(t instanceof F.Transaction)return t.sign(e),t;throw new Error("Unknown transaction type")},[he]:e}}function Ft(r){if(!r||typeof r!="object")return!1;let e=r;return he in e&&e[he]instanceof F.Keypair&&"publicKey"in e&&"signTransaction"in e}function Ge(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[he];if(n&&n.secretKey&&n.publicKey)return{publicKey:n.publicKey,signMessage:async o=>Wt.sign.detached(o,n.secretKey)}}return null}var qt=require("@x402/core/http"),Ht=[$t,Lt];async function Et(r){for(let e of Ht)if(await e.parseChallenge(r.clone()))return e;return null}async function kn(r){let e=async(o,s)=>({response:await fetch(o,s),paymentUrl:o,paymentInit:s}),t=Ge(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. ${G(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=(0,qt.decodePaymentRequiredHeader)(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 _t(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 kn(t))(r,{...e});o=c.response,s=c.paymentUrl,i=c.paymentInit}catch(a){return{ok:!1,reason:"error",detail:G(a)}}if(o.status!==402)return{ok:!0,paid:!1,response:o};for(let a of Ht){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 ht(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 jt(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 yt(r){let e=Pe(r);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function Xt(r){let e=yt(r);if(e?.recommendations?.length)return e.recommendations}async function zt(r){let t=yt(r)?.tracking?.impressionBeacon;if(!t)return!1;try{await fetch(t,{method:"GET"})}catch{}return!0}function Jt(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(gt(t).then(g=>{d.solana=g}).catch(g=>{console.warn(`[x402] Solana wallet init failed: ${g.message}`)})),n&&f.push(ht(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=ct({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 Gt(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=Jt(fetch,{...o,onPaymentRequired:async l=>{let h=l.extra?.decimals??6,g=Number(l.amount)/Math.pow(10,h);if(g>i)throw new _("amount_exceeds_max",`$${g.toFixed(4)} exceeds per-request limit of $${i.toFixed(2)}`);let x=d();if(x+g>s)throw new _("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 _("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 _("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=[]}}}var Pt=require("@dexterai/x402-core");0&&(module.exports={BASE_MAINNET,DEXTER_FACILITATOR_URL,KEYPAIR_SYMBOL,SOLANA_MAINNET,USDC_MINT,X402Error,buildV1PaymentHeader,capabilitySearch,capturePaymentReceipt,createBudgetAccount,createEvmAdapter,createEvmKeypairWallet,createKeypairWallet,createSolanaAdapter,detectStrategy,fireImpressionBeacon,getPaymentReceipt,getSponsoredAccessInfo,getSponsoredRecommendations,isEvmKeypairWallet,isKeypairWallet,payAndFetch,toNetworkRef,toSiwxSigner});
@@ -52,7 +52,7 @@ declare function payAndFetch(url: string, requestInit: RequestInit, wallets: Wal
52
52
  declare function toNetworkRef(network: string): NetworkRef | null;
53
53
 
54
54
  /**
55
- * Map a WalletSet to a SIWxSigner for wrapFetchWithSIWx, or null when
55
+ * Map a WalletSet to a SIWxSigner for createSIWxPayload, or null when
56
56
  * neither wallet can sign SIW-X proofs.
57
57
  */
58
58
  declare function toSiwxSigner(wallets: WalletSet): SIWxSigner | null;
@@ -52,7 +52,7 @@ declare function payAndFetch(url: string, requestInit: RequestInit, wallets: Wal
52
52
  declare function toNetworkRef(network: string): NetworkRef | null;
53
53
 
54
54
  /**
55
- * Map a WalletSet to a SIWxSigner for wrapFetchWithSIWx, or null when
55
+ * Map a WalletSet to a SIWxSigner for createSIWxPayload, or null when
56
56
  * neither wallet can sign SIW-X proofs.
57
57
  */
58
58
  declare function toSiwxSigner(wallets: WalletSet): SIWxSigner | null;
@@ -1 +1 @@
1
- var _e="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",je="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",ze="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",X=_e,Ee=je,Pe=ze,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,Xe=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",Ye="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",lt="0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168",Ge={[Se]:Ye,[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},[Ye]:{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"}},Y="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={[_e]:"https://api.dexter.cash/api/solana/rpc",[je]:"https://api.devnet.solana.com",[ze]:"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 Fe(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"}],Ft=new Map(vt.map(r=>[r.caip2.toLowerCase(),r])),Lt=new Map(vt.map(r=>[r.bare.toLowerCase(),r]));function G(r){if(!r)return null;let e=r.toLowerCase(),t=Ft.get(e)||Lt.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=G(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 zt,getMint as Xt,TOKEN_PROGRAM_ID as _t,TOKEN_2022_PROGRAM_ID as et}from"@solana/spl-token";var Jt=12e3,Yt=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=[X,Ee,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[X]:e==="solana-devnet"?ie[Ee]:e==="solana-testnet"?ie[Pe]:ie[X]}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"),a=new ce(t.publicKey.toBase58()),i=new ce(e.asset);try{let u=(await s.getAccountInfo(i,"confirmed"))?.owner.toBase58()===et.toBase58()?et:_t,d=await pt(i,a,!1,u),f=await jt(s,d,void 0,u),S=e.extra?.decimals??6;return Number(f.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 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),a=new dt(s,"confirmed"),i=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 S=new ce(d.feePayer),w=new ce(u),l=new ce(c);this.log("Building transaction:",{from:i.toBase58(),to:c,amount:f,asset:u,feePayer:d.feePayer});let y=[];y.push(Rt.setComputeUnitLimit({units:Jt})),y.push(Rt.setComputeUnitPrice({microLamports:Yt}));let g=await a.getAccountInfo(w,"confirmed");if(!g)throw new Error(`Token mint ${u} not found`);let R=g.owner.toBase58()===et.toBase58()?et:_t,m=await Xt(a,w,void 0,R);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,i,!1,R),_=await pt(w,l,!0,R);if(!await a.getAccountInfo(p,"confirmed"))throw new Error(`No token account found for ${u}. Please ensure you have USDC in your wallet.`);if(!await a.getAccountInfo(_,"confirmed"))throw new Error(`Seller token account not found. The seller (${c}) must have a USDC account.`);let W=BigInt(f);y.push(zt(p,w,_,i,W,m.decimals,[],R));let{blockhash:q}=await a.getLatestBlockhash("confirmed"),D=new qt({payerKey:S,recentBlockhash:q,instructions:y}).compileToV0Message(),b=new Ht(D),v=await t.signTransaction(b);return this.log("Transaction signed successfully"),{serialized:Buffer.from(v.serialize()).toString("base64"),settlementProbe:{kind:"solana",sourceAta:p.toBase58(),destinationAta:_.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 a=BigInt(e.amount);for(let i of s){if(i.err)continue;let c=await n.getTransaction(i.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 S of f){if(S.mint!==e.asset)continue;let w=u[S.accountIndex];if(!w||!w.equals(o))continue;let l=d.find(R=>R.accountIndex===S.accountIndex),y=BigInt(l?.uiTokenAmount.amount??"0");if(BigInt(S.uiTokenAmount.amount??"0")-y===a)return{settled:!0,txSignature:i.signature}}}return{settled:!1}}};function F(r){return new tt(r)}var Gt={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"validAfter",type:"uint256"}]},Et=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function 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,Xe,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),a=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(!a.ok)throw new Error(`RPC request failed: ${a.status}`);let i=await a.json();if(i.error)throw new Error(`RPC error: ${JSON.stringify(i.error)}`);if(!i.result||i.result==="0x")return 0;let c=BigInt(i.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"),a=n+o+s,i=await this.ethCall(t,e.asset,a);return{settled:BigInt(i)!==0n}}if(e.kind==="permit2"){let n="0x4fe02b44",o=BigInt(e.nonce),s=o>>8n,a=o&0xffn,i=e.from.slice(2).toLowerCase().padStart(64,"0"),c=s.toString(16).padStart(64,"0"),u=n+i+c,d=await this.ethCall(t,Y,u);return{settled:(BigInt(d)>>a&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:a,extra:i}=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:a,network:e.network});let u=this.getChainId(e.network),d=Qe[`eip155:${u}`],f={name:i?.name??d?.name??"USD Coin",version:i?.version??d?.version??"2",chainId:BigInt(u),verifyingContract:a},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"}]},w=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(w);let l="0x"+[...w].map(_=>_.toString(16).padStart(2,"0")).join(""),y=Math.floor(Date.now()/1e3),g={from:t.address,to:s,value:c,validAfter:String(y-600),validBefore:String(y+(e.maxTimeoutSeconds||60)),nonce:l},R={from:t.address,to:s,value:BigInt(c),validAfter:BigInt(y-600),validBefore:BigInt(y+(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:S,primaryType:"TransferWithAuthorization",message:R});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:a,chainId:u}}}async buildApprovalTransaction(e,t,n){let{payTo:o,asset:s,extra:a}=e,i=e.amount??e.maxAmountRequired;if(!i)throw new Error("Missing amount in payment requirements");let c=a?.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:i,asset:s,network:e.network,facilitatorContract:c});let u=n||this.getDefaultRpcUrl(e.network),d=a?.fee??"0",f=BigInt(i)+BigInt(d),S=await this.readAllowance(u,s,t.address,c);if(S<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(i,d,a?.approvalStrategy);this.log(`Approving ${D} for ${c} (current allowance: ${S})`);let b=await t.sendTransaction({to:s,data:this.encodeApprove(c,D),value:0n});this.log(`Approval tx sent: ${b}`),await this.waitForReceipt(u,b),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,b)=>D*256n+BigInt(b),0n).toString(),y=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(y);let g="0x"+[...y].map(D=>D.toString(16).padStart(2,"0")).join(""),m=Math.floor(Date.now()/1e3)+(e.maxTimeoutSeconds||300),p=a?.eip712Domain,_=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=a?.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(i),fee:BigInt(d),nonce:BigInt(l),deadline:BigInt(m),paymentId:g},W=await t.signTypedData({domain:_,types:V,primaryType:"Payment",message:Z});this.log("EIP-712 Payment signature obtained");let q={from:t.address,to:o,token:s,amount:i,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,a=e.amount??e.maxAmountRequired;if(!a)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:a,asset:s,network:e.network});let i=n||this.getDefaultRpcUrl(e.network),c=await this.readAllowance(i,s,t.address,Y),u;if(c<BigInt(a)){let _=this.encodeApprove(Y,Et);if(t.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${c})`);let V=this.getChainId(e.network),Z=await this.readGasPrice(i),W=await this.readNonce(i,t.address),q=await t.signTransaction({to:s,data:_,chainId:V,gas:50000n,gasPrice:Z,nonce:W});u={erc20ApprovalGasSponsoring:{info:{from:t.address,asset:s,spender:Y,amount:Et.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:_,value:0n});this.log(`Permit2 approval tx sent: ${V}`),await this.waitForReceipt(i,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)=>_*256n+BigInt(V),0n),S=Math.floor(Date.now()/1e3),w=S-600,l=S+(e.maxTimeoutSeconds||300),y=this.getChainId(e.network),g={name:"Permit2",chainId:BigInt(y),verifyingContract:Y},R={permitted:{token:s,amount:BigInt(a)},spender:$e,nonce:f,deadline:BigInt(l),witness:{to:o,validAfter:BigInt(w)}},m=await t.signTypedData({domain:g,types:Gt,primaryType:"PermitWitnessTransferFrom",message:R});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let p={signature:m,permit2Authorization:{from:t.address,permitted:{token:s,amount:a},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:y}}}async readAllowance(e,t,n,o){let s="0xdd62ed3e",a=n.slice(2).toLowerCase().padStart(64,"0"),i=o.slice(2).toLowerCase().padStart(64,"0"),c=s+a+i;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 a=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(a.result){if(a.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),a=o*s;if(n.maxCapUsd){let i=this.inferDecimals(e),c=BigInt(Math.floor(n.maxCapUsd*Math.pow(10,i)));if(a>c)return c}if(n.exactAboveUsd){let i=this.inferDecimals(e),c=BigInt(Math.floor(n.exactAboveUsd*Math.pow(10,i)));if(BigInt(e)>c)return o}return a}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(Ge))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{[_e]:"Solana",[je]:"Solana Devnet",[ze]:"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((a,i)=>n.set(i,a));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 Le(r){return Tt.get(r)}function It(r,e){let t=r.headers.get("PAYMENT-RESPONSE"),n;if(t)try{let i=mt(t);i&&typeof i=="object"&&!Array.isArray(i)&&(n={...i})}catch{}n??={},n.settlementStatus="unconfirmed";let o=n.network===e.network,s=[n.errorReason,n.errorCode,n.errorMessage].every(i=>i===void 0||typeof i=="string"),a=[n.errorReason,n.errorCode].filter(i=>typeof i=="string"&&i.length>0);return a.some(i=>/pending|unknown|unconfirmed|timeout|temporar/i.test(i))?n.settlementStatus="pending":n.success===!0&&o&&s&&a.length===0&&typeof n.transaction=="string"&&n.transaction.trim().length>0?n.settlementStatus="settled":n.success===!1&&(o||n.network===void 0)&&a.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=[F({verbose:r.verbose}),me({verbose:r.verbose})],wallets:t,wallet:n,preferredNetwork:o,rpcUrls:s={},maxAmountAtomic:a,fetch:i=globalThis.fetch,verbose:c=!1,accessPass:u,onPaymentRequired:d,onPaymentDispatched:f,maxRetries:S=0,retryDelayMs:w=500}=r,l=c?console.log.bind(console,"[x402]"):()=>{};async function y(b,v){let E;for(let A=0;A<=S;A++)try{let I=await i(b,v);if(I.status>=502&&I.status<=504&&A<S){l(`Retry ${A+1}/${S}: server returned ${I.status}`),await new Promise(T=>setTimeout(T,w*Math.pow(2,A)));continue}return I}catch(I){E=I,A<S&&(l(`Retry ${A+1}/${S}: ${I instanceof Error?I.message:"network error"}`),await new Promise(T=>setTimeout(T,w*Math.pow(2,A))))}throw E}let g=new Map;function R(b){try{let v=new URL(b).host,E=g.get(v);if(E&&E.expiresAt>Date.now()/1e3+10)return E.jwt;E&&g.delete(v)}catch{}return null}function m(b,v){try{let E=new URL(b).host,A=v.split(".");if(A.length===3){let I=JSON.parse(atob(A[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(E,{jwt:v,expiresAt:U}),l("Access pass cached for",E,"| 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 _(b){let v=[];for(let E of b){let A=e.find(N=>N.canHandle(E.network));if(!A)continue;let I=A.name==="Solana"?"svm":"evm";if(K(E,I))continue;let T;A.name==="Solana"?T=p.solana:A.name==="EVM"&&(T=p.evm),T&&A.isConnected(T)&&v.push({accept:E,adapter:A,wallet:T})}if(v.length===0)return null;if(o){let E=v.find(A=>A.accept.network===o);if(E)return E}return v[0]}function V(b,v){return Pt(b,v)}function Z(b,v){return s[b]||v.getDefaultRpcUrl(b)}async function W(b,v,E,A,I){let T="";if(u?.preferTier&&A.tiers){let h=A.tiers.find($=>$.id===u.preferTier);if(h){if(u.maxSpend&&parseFloat(h.price)>parseFloat(u.maxSpend))throw new P("access_pass_exceeds_max_spend",`Access pass tier "${h.id}" costs $${h.price}, exceeds max spend $${u.maxSpend}`);T=`tier=${h.id}`}}else if(u?.preferDuration&&A.ratePerHour)T=`duration=${u.preferDuration}`;else if(A.tiers&&A.tiers.length>0){let h=A.tiers[0];if(u?.maxSpend&&parseFloat(h.price)>parseFloat(u.maxSpend))throw new P("access_pass_exceeds_max_spend",`Cheapest access pass costs $${h.price}, exceeds max spend $${u?.maxSpend}`);T=`tier=${h.id}`}let N=T?I.includes("?")?`${I}&${T}`:`${I}?${T}`:I;l("Purchasing access pass:",T||"default tier");let U=E.headers.get("PAYMENT-REQUIRED");if(!U)return null;let B;try{B=JSON.parse(atob(U))}catch{return null}let k=_(B.accepts);if(!k)return null;if(Fe(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 h=await M.getBalance(C,de,j),$=Number(xe)/Math.pow(10,H);if(h<$){let Kt=V(C.network,M.name);throw new P("insufficient_balance",`Insufficient balance for access pass on ${Kt}. Have $${h.toFixed(4)}, need $${$.toFixed(4)}`)}}catch(h){if(h instanceof P)throw h}let z=await M.buildTransaction(C,de,j),pe;M.name==="EVM"?pe=JSON.parse(z.serialized):pe={transaction:z.serialized};let Q=typeof b=="string"?b:b instanceof URL?b.href:b.url,fe=B.resource;if(typeof B.resource=="string")try{let h=new URL(B.resource,Q);["http:","https:"].includes(h.protocol)&&(fe=h.toString())}catch{}else if(B.resource&&typeof B.resource=="object"&&"url"in B.resource){let h=B.resource;try{let $=new URL(h.url,Q);["http:","https:"].includes($.protocol)&&(fe={...h,url:$.toString()})}catch{}}let He={x402Version:C.x402Version??2,resource:fe,accepted:C,payload:pe};z.extensions&&(He.extensions=z.extensions);let Re=btoa(JSON.stringify(He)),ee=await i(N,{...v,method:"POST",headers:{...v?.headers||{},"Content-Type":"application/json","PAYMENT-SIGNATURE":Re}});if(!ee.ok)return l("Pass purchase failed:",ee.status),null;let x=ee.headers.get("ACCESS-PASS");return x&&(m(I,x),l("Access pass purchased and cached")),ee}async function q(b,v){let E=b;if(l("Making request:",E),u){let x=R(E);if(x){l("Using cached access pass");let h=await i(b,{...v,headers:{...v?.headers||{},Authorization:`Bearer ${x}`}});if(h.status!==401&&h.status!==402)return h;l("Cached pass rejected (status",h.status,"), purchasing new pass");try{g.delete(new URL(E).host)}catch{}}}let A=await y(b,v);if(A.status!==402)return A;l("Received 402 Payment Required");let I=A.headers.get("X-ACCESS-PASS-TIERS");if(u&&I){l("Server offers access passes, purchasing...");try{let x=JSON.parse(atob(I)),h=await W(b,v,A,x,E);if(h)return h}catch(x){l("Access pass purchase failed, falling back to per-request payment:",x)}}let T=A.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 x=atob(T);N=JSON.parse(x)}catch{throw new P("invalid_payment_required","Failed to decode PAYMENT-REQUIRED header")}if(l("Payment requirements:",N),Fe(N.extensions))throw new P("unsupported_required_payment_identifier","Required payment identifiers are not supported by this client");let U=A.headers.get("X-Quote-Hash");U&&l("Quote hash received:",U);let B=_(N.accepts);if(!B){let x=N.accepts.map(h=>h.network).join(", ");throw new P("no_matching_payment_option",`No supported payment option with a connected wallet for: ${x}`)}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(a&&BigInt(H)>BigInt(a))throw new P("amount_exceeds_max",`Payment amount ${H} exceeds maximum ${a}`);let xe=Z(k.network,C);l("Checking balance...");try{let x=await C.getBalance(k,M,xe),h=Number(H)/Math.pow(10,de);if(x<h){let $=V(k.network,C.name);throw new P("insufficient_balance",`Insufficient balance on ${$}. Have $${x.toFixed(4)}, need $${h.toFixed(4)}`)}l(`Balance OK: $${x.toFixed(4)} >= $${h.toFixed(4)}`)}catch(x){if(x instanceof P)throw x;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 z;C.name==="EVM"?z=JSON.parse(j.serialized):z={transaction:j.serialized};let pe=b,Q=N.resource;if(typeof N.resource=="string")try{let x=new URL(N.resource,pe).toString();x!==N.resource&&l("Resolved relative resource URL:",N.resource,"\u2192",x),Q=x}catch{Q=N.resource}else if(N.resource&&typeof N.resource=="object"&&"url"in N.resource){let x=N.resource;try{let h=new URL(x.url,pe).toString();h!==x.url&&(l("Resolved relative resource URL:",x.url,"\u2192",h),Q={...x,url:h})}catch{}}let fe={x402Version:k.x402Version??2,resource:Q,accepted:k,payload:z};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 y(b,{...v,headers:{...v?.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(b,v){let[E,A]=await Qt(b,v);return q(E,A)}return{fetch:D}}import{PublicKey as Gr}from"@solana/web3.js";import{bytesToHex as gt}from"@noble/hashes/utils";import dr from"tweetnacl";import{PublicKey as fr}from"@solana/web3.js";import{contextBoundVoucherV2Message as hr,finalVoucherV2Sequence as yr,sessionRegisterMessage as Ar,sessionVoucherV2AuthorizationNonce as br}from"@dexterai/vault/messages";import{deriveSessionPda as wr}from"@dexterai/vault/session";import{sessionRegisterMessage as en,sessionReplaceV1Message as or,sessionRevokeMessage as sr,sessionVoucherV2Nonce as ar,sessionVoucherV2AuthorizationNonce as ir,finalVoucherV2Sequence as cr,voucherV2SequenceOrdinal as ur,voucherPayloadMessage as tn,buildVoucherMessage as lr}from"@dexterai/vault/messages";import{sha256 as _r}from"@noble/hashes/sha256";var xr=(1n<<64n)-1n;import{sha256 as Tr}from"@noble/hashes/sha256";import{bytesToHex as Nr}from"@noble/hashes/utils";var nn="dexter-native-tab-v2-reservation/v1",Cr=`${nn}:`;import{deriveSessionPda as ro}from"@dexterai/vault/session";import{buildRegisterSessionKeyInstruction as Br,buildRevokeSessionKeyInstruction as Dr,deriveSwigWalletAddress as Ur}from"@dexterai/vault/instructions";import{buildSecp256r1VerifyInstruction as $r}from"@dexterai/vault/precompile";import{DEXTER_VAULT_PROGRAM_ID as rn,SECP256R1_PROGRAM_ID as Fr,INSTRUCTIONS_SYSVAR_ID as Lr}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 L(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),a=[s.error,s.detail,s.message].filter(i=>typeof i=="string"&&i.length>0);a.length>0&&(o=a.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 a=F(),i=t??a.getDefaultRpcUrl(e.caip2);if(!a.confirmSettlement)return kt();let c=await a.confirmSettlement(r,i);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 (${L(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 a={method:e.method??"GET",headers:s};e.signal&&(a.signal=e.signal),typeof e.body=="string"&&(a.body=e.body);let i;try{i=await fetch(r,a)}catch(c){return{ok:!1,reason:"error",detail:c?.message??String(c)}}return i.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:i.ok?{ok:!0,paid:!0,response:i,amountPaid:t.amount,network:t.network}:{ok:!1,...await We(i)}}var Ot={version:2,async parseChallenge(r){return xt(r)},async pay(r,e,t,n,o){if(Fe(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 a=s.find(m=>m.network.family==="evm"?!!n.evm:m.network.family==="svm"?!!n.solana:!1);if(!a)return{ok:!1,reason:"unsupported_network"};let i=o.timeoutMs??15e3,c=o.responseTimeoutMs??12e4,u=new AbortController,d=setTimeout(()=>u.abort(),i),f=!1,S,w,l=(m,p)=>{f=!0,w=m,S=p,clearTimeout(d),d=setTimeout(()=>u.abort(),c)},y=rt({wallets:n,preferredNetwork:a.network.caip2,maxAmountAtomic:o.maxAmountAtomic,fetch:globalThis.fetch,onPaymentDispatched:l}),g=e.signal?AbortSignal.any([e.signal,u.signal]):u.signal,R={method:e.method??"GET",headers:e.headers,signal:g};typeof e.body=="string"&&(R.body=e.body);try{let m=await y.fetch(r,R);if(clearTimeout(d),!f)return m.ok?{ok:!0,paid:!1,response:m}:{ok:!1,response:m,...await We(m)};let p=Le(m),_=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:_,paymentReceipt:p}}return m.ok?{ok:!0,paid:!0,response:m,amountPaid:w?.amount??w?.maxAmountRequired??a.amount,network:G(w?.network??"")??a.network,txSignature:_,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:_,paymentReceipt:p}}catch(m){clearTimeout(d);let p=m;if(p?.name==="AbortError"){if(!f)return{ok:!1,reason:"timeout"};let _=await at(S,a.network,o.solanaRpcUrl);return _.confirmed?{ok:!0,paid:!0,response:void 0,amountPaid:a.amount,network:a.network,txSignature:_.txSignature}:{ok:!1,reason:"payment_unconfirmed",detail:_.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)),a={from:r.address,to:e.payTo,value:e.amount,validAfter:o,validBefore:s,nonce:await cn()},i=Ke[e.network.caip2];if(i===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:i,verifyingContract:sn(e.asset)},types:an,primaryType:"TransferWithAuthorization",message:a});return{payment:{x402Version:1,scheme:e.scheme,network:t,payload:{signature:u,authorization:a}},settlementProbe:{kind:"eip3009",from:a.from,nonce:a.nonce,asset:e.asset,chainId:i}}}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 a=await e.evm;return await ln(o,a,t)}if(o.network.family==="svm"&&e.solana){let a=await e.solana;return await mn(o,a,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:L(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 a=r.network.bare,{payment:i,settlementProbe:c}=await un(e,r,a);return{ok:!0,headerValue:Buffer.from(JSON.stringify(i),"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},i=await F().buildTransaction(s,e,t.solanaRpcUrl),c={x402Version:1,scheme:r.scheme,network:o,payload:{transaction:i.serialized}};return{ok:!0,headerValue:Buffer.from(JSON.stringify(c),"utf8").toString("base64"),option:r,settlementProbe:i.settlementProbe}}function dn(r){let e=[];for(let t of r){if(!t||typeof t!="object")continue;let n=t,o=G(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,a=new AbortController,i=!1,c,u;try{let d=o.timeoutMs??15e3;s=setTimeout(()=>a.abort(),d);let f=await it(t,n,o);if(!f.ok)return{ok:!1,reason:f.reason,detail:f.detail};let S=f.headerValue,w=f.option;u=w,c=f.settlementProbe;let l=new Headers(e.headers??void 0);l.set("X-PAYMENT",S);let y=e.signal!=null?AbortSignal.any([e.signal,a.signal]):a.signal,g={method:e.method,headers:l,signal:y};typeof e.body=="string"&&(g.body=e.body),i=!0,clearTimeout(s);let R=o.responseTimeoutMs??12e4;s=setTimeout(()=>a.abort(),R);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(!i)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:L(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}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 yn(r){let e=ct(r);if(!e)return fetch;try{return(await import("@x402/extensions/sign-in-with-x")).wrapFetchWithSIWx(fetch,e)}catch(t){return console.warn(`[x402] SIW-X unavailable \u2014 @x402/extensions failed to load; SIW-X merchants will not authenticate. ${L(t)}`),fetch}}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;try{o=await(await yn(t))(r,{...e})}catch(s){return{ok:!1,reason:"error",detail:L(s)}}if(o.status!==402)return{ok:!0,paid:!1,response:o};for(let s of Dt){let a=await s.parseChallenge(o.clone());if(a)return s.pay(r,e,a,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 An(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=Le(r);if(e?.extensions?.["sponsored-access"])return e.extensions["sponsored-access"]}function bn(r){let e=At(r);if(e?.recommendations?.length)return e.recommendations}async function Sn(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:a,verbose:i,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 S=f.length>0?Promise.all(f):null,l=rt({wallets:d,preferredNetwork:o,rpcUrls:s,maxAmountAtomic:a,fetch:r,verbose:i,accessPass:c,onPaymentRequired:u}),y=l.fetch.bind(l);return S?(async(g,R)=>(await S,y(g,R))):y}function wn(r){let{budget:e,allowedDomains:t,onPaymentRequired:n,...o}=r,s=parseFloat(e.total),a=e.perRequest?parseFloat(e.perRequest):1/0,i=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,y)=>l+y.amount,0)}function f(){let l=Date.now()-36e5;return c.filter(y=>y.timestamp>=l).reduce((y,g)=>y+g.amount,0)}let S=$t(fetch,{...o,onPaymentRequired:async l=>{let y=l.extra?.decimals??6,g=Number(l.amount)/Math.pow(10,y);if(g>a)throw new P("amount_exceeds_max",`$${g.toFixed(4)} exceeds per-request limit of $${a.toFixed(2)}`);let R=d();if(R+g>s)throw new P("amount_exceeds_max",`Budget exceeded. Spent $${R.toFixed(2)} of $${s.toFixed(2)}, payment: $${g.toFixed(4)}`);let m=f();if(m+g>i)throw new P("amount_exceeds_max",`Hourly limit ($${i.toFixed(2)}) exceeded. Spent $${m.toFixed(2)} this hour`);return u=g,n?n(l):!0}});return{fetch:(async(l,y)=>{let g=typeof l=="string"?l:l instanceof URL?l.href:l.url,R="unknown";try{R=new URL(g).hostname}catch{}if(t&&!t.some(p=>R===p||R.endsWith(`.${p}`)))throw new P("payment_rejected",`Domain "${R}" not in allowed domains`);u=0;let m=await S(l,y);if(u>0){let p="unknown",_=m.headers.get("PAYMENT-RESPONSE");if(_)try{p=JSON.parse(atob(_)).network||p}catch{}c.push({amount:u,domain:R,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 vn}from"@dexterai/x402-core";export{J as BASE_MAINNET,wt as DEXTER_FACILITATOR_URL,ve as KEYPAIR_SYMBOL,X as SOLANA_MAINNET,Je as USDC_MINT,P as X402Error,it as buildV1PaymentHeader,vn as capabilitySearch,It as capturePaymentReceipt,wn as createBudgetAccount,me as createEvmAdapter,yt as createEvmKeypairWallet,ht as createKeypairWallet,F as createSolanaAdapter,Ut as detectStrategy,Sn as fireImpressionBeacon,Le as getPaymentReceipt,At as getSponsoredAccessInfo,bn as getSponsoredRecommendations,An as isEvmKeypairWallet,hn as isKeypairWallet,Mt as payAndFetch,G as toNetworkRef,ct as toSiwxSigner};
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};