@dexterai/x402 6.0.1 → 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.
- package/CHANGELOG.md +9 -0
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.js +1 -1
- package/dist/tab/index.cjs +5 -5
- package/dist/tab/index.js +5 -5
- package/package.json +2 -2
package/dist/client/index.js
CHANGED
|
@@ -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};
|